sync.py 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255
  1. # Copyright (C) 2008 The Android Open Source Project
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import http.cookiejar as cookielib
  15. import json
  16. import netrc
  17. from optparse import SUPPRESS_HELP
  18. import os
  19. import re
  20. import socket
  21. import subprocess
  22. import sys
  23. import tempfile
  24. import time
  25. import urllib.error
  26. import urllib.parse
  27. import urllib.request
  28. import xmlrpc.client
  29. try:
  30. import threading as _threading
  31. except ImportError:
  32. import dummy_threading as _threading
  33. try:
  34. import resource
  35. def _rlimit_nofile():
  36. return resource.getrlimit(resource.RLIMIT_NOFILE)
  37. except ImportError:
  38. def _rlimit_nofile():
  39. return (256, 256)
  40. try:
  41. import multiprocessing
  42. except ImportError:
  43. multiprocessing = None
  44. import event_log
  45. from git_command import GIT, git_require
  46. from git_config import GetUrlCookieFile
  47. from git_refs import R_HEADS, HEAD
  48. import git_superproject
  49. import gitc_utils
  50. from project import Project
  51. from project import RemoteSpec
  52. from command import Command, MirrorSafeCommand
  53. from error import BUG_REPORT_URL, RepoChangedException, GitError, ManifestParseError
  54. import platform_utils
  55. from project import SyncBuffer
  56. from progress import Progress
  57. from wrapper import Wrapper
  58. from manifest_xml import GitcManifest
  59. _ONE_DAY_S = 24 * 60 * 60
  60. class _FetchError(Exception):
  61. """Internal error thrown in _FetchHelper() when we don't want stack trace."""
  62. pass
  63. class _CheckoutError(Exception):
  64. """Internal error thrown in _CheckoutOne() when we don't want stack trace."""
  65. class Sync(Command, MirrorSafeCommand):
  66. jobs = 1
  67. common = True
  68. helpSummary = "Update working tree to the latest revision"
  69. helpUsage = """
  70. %prog [<project>...]
  71. """
  72. helpDescription = """
  73. The '%prog' command synchronizes local project directories
  74. with the remote repositories specified in the manifest. If a local
  75. project does not yet exist, it will clone a new local directory from
  76. the remote repository and set up tracking branches as specified in
  77. the manifest. If the local project already exists, '%prog'
  78. will update the remote branches and rebase any new local changes
  79. on top of the new remote changes.
  80. '%prog' will synchronize all projects listed at the command
  81. line. Projects can be specified either by name, or by a relative
  82. or absolute path to the project's local directory. If no projects
  83. are specified, '%prog' will synchronize all projects listed in
  84. the manifest.
  85. The -d/--detach option can be used to switch specified projects
  86. back to the manifest revision. This option is especially helpful
  87. if the project is currently on a topic branch, but the manifest
  88. revision is temporarily needed.
  89. The -s/--smart-sync option can be used to sync to a known good
  90. build as specified by the manifest-server element in the current
  91. manifest. The -t/--smart-tag option is similar and allows you to
  92. specify a custom tag/label.
  93. The -u/--manifest-server-username and -p/--manifest-server-password
  94. options can be used to specify a username and password to authenticate
  95. with the manifest server when using the -s or -t option.
  96. If -u and -p are not specified when using the -s or -t option, '%prog'
  97. will attempt to read authentication credentials for the manifest server
  98. from the user's .netrc file.
  99. '%prog' will not use authentication credentials from -u/-p or .netrc
  100. if the manifest server specified in the manifest file already includes
  101. credentials.
  102. By default, all projects will be synced. The --fail-fast option can be used
  103. to halt syncing as soon as possible when the first project fails to sync.
  104. The --force-sync option can be used to overwrite existing git
  105. directories if they have previously been linked to a different
  106. object directory. WARNING: This may cause data to be lost since
  107. refs may be removed when overwriting.
  108. The --force-remove-dirty option can be used to remove previously used
  109. projects with uncommitted changes. WARNING: This may cause data to be
  110. lost since uncommitted changes may be removed with projects that no longer
  111. exist in the manifest.
  112. The --no-clone-bundle option disables any attempt to use
  113. $URL/clone.bundle to bootstrap a new Git repository from a
  114. resumeable bundle file on a content delivery network. This
  115. may be necessary if there are problems with the local Python
  116. HTTP client or proxy configuration, but the Git binary works.
  117. The --fetch-submodules option enables fetching Git submodules
  118. of a project from server.
  119. The -c/--current-branch option can be used to only fetch objects that
  120. are on the branch specified by a project's revision.
  121. The --optimized-fetch option can be used to only fetch projects that
  122. are fixed to a sha1 revision if the sha1 revision does not already
  123. exist locally.
  124. The --prune option can be used to remove any refs that no longer
  125. exist on the remote.
  126. # SSH Connections
  127. If at least one project remote URL uses an SSH connection (ssh://,
  128. git+ssh://, or user@host:path syntax) repo will automatically
  129. enable the SSH ControlMaster option when connecting to that host.
  130. This feature permits other projects in the same '%prog' session to
  131. reuse the same SSH tunnel, saving connection setup overheads.
  132. To disable this behavior on UNIX platforms, set the GIT_SSH
  133. environment variable to 'ssh'. For example:
  134. export GIT_SSH=ssh
  135. %prog
  136. # Compatibility
  137. This feature is automatically disabled on Windows, due to the lack
  138. of UNIX domain socket support.
  139. This feature is not compatible with url.insteadof rewrites in the
  140. user's ~/.gitconfig. '%prog' is currently not able to perform the
  141. rewrite early enough to establish the ControlMaster tunnel.
  142. If the remote SSH daemon is Gerrit Code Review, version 2.0.10 or
  143. later is required to fix a server side protocol bug.
  144. """
  145. def _Options(self, p, show_smart=True):
  146. try:
  147. self.jobs = self.manifest.default.sync_j
  148. except ManifestParseError:
  149. self.jobs = 1
  150. p.add_option('-f', '--force-broken',
  151. dest='force_broken', action='store_true',
  152. help='obsolete option (to be deleted in the future)')
  153. p.add_option('--fail-fast',
  154. dest='fail_fast', action='store_true',
  155. help='stop syncing after first error is hit')
  156. p.add_option('--force-sync',
  157. dest='force_sync', action='store_true',
  158. help="overwrite an existing git directory if it needs to "
  159. "point to a different object directory. WARNING: this "
  160. "may cause loss of data")
  161. p.add_option('--force-remove-dirty',
  162. dest='force_remove_dirty', action='store_true',
  163. help="force remove projects with uncommitted modifications if "
  164. "projects no longer exist in the manifest. "
  165. "WARNING: this may cause loss of data")
  166. p.add_option('-l', '--local-only',
  167. dest='local_only', action='store_true',
  168. help="only update working tree, don't fetch")
  169. p.add_option('--no-manifest-update', '--nmu',
  170. dest='mp_update', action='store_false', default='true',
  171. help='use the existing manifest checkout as-is. '
  172. '(do not update to the latest revision)')
  173. p.add_option('-n', '--network-only',
  174. dest='network_only', action='store_true',
  175. help="fetch only, don't update working tree")
  176. p.add_option('-d', '--detach',
  177. dest='detach_head', action='store_true',
  178. help='detach projects back to manifest revision')
  179. p.add_option('-c', '--current-branch',
  180. dest='current_branch_only', action='store_true',
  181. help='fetch only current branch from server')
  182. p.add_option('-v', '--verbose',
  183. dest='output_mode', action='store_true',
  184. help='show all sync output')
  185. p.add_option('-q', '--quiet',
  186. dest='output_mode', action='store_false',
  187. help='only show errors')
  188. p.add_option('-j', '--jobs',
  189. dest='jobs', action='store', type='int',
  190. help="projects to fetch simultaneously (default %d)" % self.jobs)
  191. p.add_option('-m', '--manifest-name',
  192. dest='manifest_name',
  193. help='temporary manifest to use for this sync', metavar='NAME.xml')
  194. p.add_option('--clone-bundle', action='store_true',
  195. help='enable use of /clone.bundle on HTTP/HTTPS')
  196. p.add_option('--no-clone-bundle', dest='clone_bundle', action='store_false',
  197. help='disable use of /clone.bundle on HTTP/HTTPS')
  198. p.add_option('-u', '--manifest-server-username', action='store',
  199. dest='manifest_server_username',
  200. help='username to authenticate with the manifest server')
  201. p.add_option('-p', '--manifest-server-password', action='store',
  202. dest='manifest_server_password',
  203. help='password to authenticate with the manifest server')
  204. p.add_option('--fetch-submodules',
  205. dest='fetch_submodules', action='store_true',
  206. help='fetch submodules from server')
  207. p.add_option('--use-superproject', action='store_true',
  208. help='use the manifest superproject to sync projects')
  209. p.add_option('--no-tags',
  210. dest='tags', default=True, action='store_false',
  211. help="don't fetch tags")
  212. p.add_option('--optimized-fetch',
  213. dest='optimized_fetch', action='store_true',
  214. help='only fetch projects fixed to sha1 if revision does not exist locally')
  215. p.add_option('--retry-fetches',
  216. default=0, action='store', type='int',
  217. help='number of times to retry fetches on transient errors')
  218. p.add_option('--prune', dest='prune', action='store_true',
  219. help='delete refs that no longer exist on the remote')
  220. if show_smart:
  221. p.add_option('-s', '--smart-sync',
  222. dest='smart_sync', action='store_true',
  223. help='smart sync using manifest from the latest known good build')
  224. p.add_option('-t', '--smart-tag',
  225. dest='smart_tag', action='store',
  226. help='smart sync using manifest from a known tag')
  227. g = p.add_option_group('repo Version options')
  228. g.add_option('--no-repo-verify',
  229. dest='repo_verify', default=True, action='store_false',
  230. help='do not verify repo source code')
  231. g.add_option('--repo-upgraded',
  232. dest='repo_upgraded', action='store_true',
  233. help=SUPPRESS_HELP)
  234. def _FetchProjectList(self, opt, projects, sem, *args, **kwargs):
  235. """Main function of the fetch threads.
  236. Delegates most of the work to _FetchHelper.
  237. Args:
  238. opt: Program options returned from optparse. See _Options().
  239. projects: Projects to fetch.
  240. sem: We'll release() this semaphore when we exit so that another thread
  241. can be started up.
  242. *args, **kwargs: Remaining arguments to pass to _FetchHelper. See the
  243. _FetchHelper docstring for details.
  244. """
  245. try:
  246. for project in projects:
  247. success = self._FetchHelper(opt, project, *args, **kwargs)
  248. if not success and opt.fail_fast:
  249. break
  250. finally:
  251. sem.release()
  252. def _FetchHelper(self, opt, project, lock, fetched, pm, err_event,
  253. clone_filter):
  254. """Fetch git objects for a single project.
  255. Args:
  256. opt: Program options returned from optparse. See _Options().
  257. project: Project object for the project to fetch.
  258. lock: Lock for accessing objects that are shared amongst multiple
  259. _FetchHelper() threads.
  260. fetched: set object that we will add project.gitdir to when we're done
  261. (with our lock held).
  262. pm: Instance of a Project object. We will call pm.update() (with our
  263. lock held).
  264. err_event: We'll set this event in the case of an error (after printing
  265. out info about the error).
  266. clone_filter: Filter for use in a partial clone.
  267. Returns:
  268. Whether the fetch was successful.
  269. """
  270. # We'll set to true once we've locked the lock.
  271. did_lock = False
  272. # Encapsulate everything in a try/except/finally so that:
  273. # - We always set err_event in the case of an exception.
  274. # - We always make sure we unlock the lock if we locked it.
  275. start = time.time()
  276. success = False
  277. try:
  278. try:
  279. success = project.Sync_NetworkHalf(
  280. quiet=opt.quiet,
  281. verbose=opt.verbose,
  282. current_branch_only=opt.current_branch_only,
  283. force_sync=opt.force_sync,
  284. clone_bundle=opt.clone_bundle,
  285. tags=opt.tags, archive=self.manifest.IsArchive,
  286. optimized_fetch=opt.optimized_fetch,
  287. retry_fetches=opt.retry_fetches,
  288. prune=opt.prune,
  289. clone_filter=clone_filter)
  290. self._fetch_times.Set(project, time.time() - start)
  291. # Lock around all the rest of the code, since printing, updating a set
  292. # and Progress.update() are not thread safe.
  293. lock.acquire()
  294. did_lock = True
  295. if not success:
  296. err_event.set()
  297. print('error: Cannot fetch %s from %s'
  298. % (project.name, project.remote.url),
  299. file=sys.stderr)
  300. if opt.fail_fast:
  301. raise _FetchError()
  302. fetched.add(project.gitdir)
  303. pm.update(msg=project.name)
  304. except _FetchError:
  305. pass
  306. except Exception as e:
  307. print('error: Cannot fetch %s (%s: %s)'
  308. % (project.name, type(e).__name__, str(e)), file=sys.stderr)
  309. err_event.set()
  310. raise
  311. finally:
  312. if did_lock:
  313. lock.release()
  314. finish = time.time()
  315. self.event_log.AddSync(project, event_log.TASK_SYNC_NETWORK,
  316. start, finish, success)
  317. return success
  318. def _Fetch(self, projects, opt, err_event):
  319. fetched = set()
  320. lock = _threading.Lock()
  321. pm = Progress('Fetching projects', len(projects),
  322. always_print_percentage=opt.quiet)
  323. objdir_project_map = dict()
  324. for project in projects:
  325. objdir_project_map.setdefault(project.objdir, []).append(project)
  326. threads = set()
  327. sem = _threading.Semaphore(self.jobs)
  328. for project_list in objdir_project_map.values():
  329. # Check for any errors before running any more tasks.
  330. # ...we'll let existing threads finish, though.
  331. if err_event.isSet() and opt.fail_fast:
  332. break
  333. sem.acquire()
  334. kwargs = dict(opt=opt,
  335. projects=project_list,
  336. sem=sem,
  337. lock=lock,
  338. fetched=fetched,
  339. pm=pm,
  340. err_event=err_event,
  341. clone_filter=self.manifest.CloneFilter)
  342. if self.jobs > 1:
  343. t = _threading.Thread(target=self._FetchProjectList,
  344. kwargs=kwargs)
  345. # Ensure that Ctrl-C will not freeze the repo process.
  346. t.daemon = True
  347. threads.add(t)
  348. t.start()
  349. else:
  350. self._FetchProjectList(**kwargs)
  351. for t in threads:
  352. t.join()
  353. pm.end()
  354. self._fetch_times.Save()
  355. if not self.manifest.IsArchive:
  356. self._GCProjects(projects, opt, err_event)
  357. return fetched
  358. def _CheckoutWorker(self, opt, sem, project, *args, **kwargs):
  359. """Main function of the fetch threads.
  360. Delegates most of the work to _CheckoutOne.
  361. Args:
  362. opt: Program options returned from optparse. See _Options().
  363. projects: Projects to fetch.
  364. sem: We'll release() this semaphore when we exit so that another thread
  365. can be started up.
  366. *args, **kwargs: Remaining arguments to pass to _CheckoutOne. See the
  367. _CheckoutOne docstring for details.
  368. """
  369. try:
  370. return self._CheckoutOne(opt, project, *args, **kwargs)
  371. finally:
  372. sem.release()
  373. def _CheckoutOne(self, opt, project, lock, pm, err_event, err_results):
  374. """Checkout work tree for one project
  375. Args:
  376. opt: Program options returned from optparse. See _Options().
  377. project: Project object for the project to checkout.
  378. lock: Lock for accessing objects that are shared amongst multiple
  379. _CheckoutWorker() threads.
  380. pm: Instance of a Project object. We will call pm.update() (with our
  381. lock held).
  382. err_event: We'll set this event in the case of an error (after printing
  383. out info about the error).
  384. err_results: A list of strings, paths to git repos where checkout
  385. failed.
  386. Returns:
  387. Whether the fetch was successful.
  388. """
  389. # We'll set to true once we've locked the lock.
  390. did_lock = False
  391. # Encapsulate everything in a try/except/finally so that:
  392. # - We always set err_event in the case of an exception.
  393. # - We always make sure we unlock the lock if we locked it.
  394. start = time.time()
  395. syncbuf = SyncBuffer(self.manifest.manifestProject.config,
  396. detach_head=opt.detach_head)
  397. success = False
  398. try:
  399. try:
  400. project.Sync_LocalHalf(syncbuf, force_sync=opt.force_sync)
  401. # Lock around all the rest of the code, since printing, updating a set
  402. # and Progress.update() are not thread safe.
  403. lock.acquire()
  404. success = syncbuf.Finish()
  405. did_lock = True
  406. if not success:
  407. err_event.set()
  408. print('error: Cannot checkout %s' % (project.name),
  409. file=sys.stderr)
  410. raise _CheckoutError()
  411. pm.update(msg=project.name)
  412. except _CheckoutError:
  413. pass
  414. except Exception as e:
  415. print('error: Cannot checkout %s: %s: %s' %
  416. (project.name, type(e).__name__, str(e)),
  417. file=sys.stderr)
  418. err_event.set()
  419. raise
  420. finally:
  421. if did_lock:
  422. if not success:
  423. err_results.append(project.relpath)
  424. lock.release()
  425. finish = time.time()
  426. self.event_log.AddSync(project, event_log.TASK_SYNC_LOCAL,
  427. start, finish, success)
  428. return success
  429. def _Checkout(self, all_projects, opt, err_event, err_results):
  430. """Checkout projects listed in all_projects
  431. Args:
  432. all_projects: List of all projects that should be checked out.
  433. opt: Program options returned from optparse. See _Options().
  434. err_event: We'll set this event in the case of an error (after printing
  435. out info about the error).
  436. err_results: A list of strings, paths to git repos where checkout
  437. failed.
  438. """
  439. # Perform checkouts in multiple threads when we are using partial clone.
  440. # Without partial clone, all needed git objects are already downloaded,
  441. # in this situation it's better to use only one process because the checkout
  442. # would be mostly disk I/O; with partial clone, the objects are only
  443. # downloaded when demanded (at checkout time), which is similar to the
  444. # Sync_NetworkHalf case and parallelism would be helpful.
  445. if self.manifest.CloneFilter:
  446. syncjobs = self.jobs
  447. else:
  448. syncjobs = 1
  449. lock = _threading.Lock()
  450. pm = Progress('Checking out projects', len(all_projects))
  451. threads = set()
  452. sem = _threading.Semaphore(syncjobs)
  453. for project in all_projects:
  454. # Check for any errors before running any more tasks.
  455. # ...we'll let existing threads finish, though.
  456. if err_event.isSet() and opt.fail_fast:
  457. break
  458. sem.acquire()
  459. if project.worktree:
  460. kwargs = dict(opt=opt,
  461. sem=sem,
  462. project=project,
  463. lock=lock,
  464. pm=pm,
  465. err_event=err_event,
  466. err_results=err_results)
  467. if syncjobs > 1:
  468. t = _threading.Thread(target=self._CheckoutWorker,
  469. kwargs=kwargs)
  470. # Ensure that Ctrl-C will not freeze the repo process.
  471. t.daemon = True
  472. threads.add(t)
  473. t.start()
  474. else:
  475. self._CheckoutWorker(**kwargs)
  476. for t in threads:
  477. t.join()
  478. pm.end()
  479. def _GCProjects(self, projects, opt, err_event):
  480. gc_gitdirs = {}
  481. for project in projects:
  482. # Make sure pruning never kicks in with shared projects.
  483. if (not project.use_git_worktrees and
  484. len(project.manifest.GetProjectsWithName(project.name)) > 1):
  485. print('%s: Shared project %s found, disabling pruning.' %
  486. (project.relpath, project.name))
  487. if git_require((2, 7, 0)):
  488. project.EnableRepositoryExtension('preciousObjects')
  489. else:
  490. # This isn't perfect, but it's the best we can do with old git.
  491. print('%s: WARNING: shared projects are unreliable when using old '
  492. 'versions of git; please upgrade to git-2.7.0+.'
  493. % (project.relpath,),
  494. file=sys.stderr)
  495. project.config.SetString('gc.pruneExpire', 'never')
  496. gc_gitdirs[project.gitdir] = project.bare_git
  497. if multiprocessing:
  498. cpu_count = multiprocessing.cpu_count()
  499. else:
  500. cpu_count = 1
  501. jobs = min(self.jobs, cpu_count)
  502. if jobs < 2:
  503. for bare_git in gc_gitdirs.values():
  504. bare_git.gc('--auto')
  505. return
  506. config = {'pack.threads': cpu_count // jobs if cpu_count > jobs else 1}
  507. threads = set()
  508. sem = _threading.Semaphore(jobs)
  509. def GC(bare_git):
  510. try:
  511. try:
  512. bare_git.gc('--auto', config=config)
  513. except GitError:
  514. err_event.set()
  515. except Exception:
  516. err_event.set()
  517. raise
  518. finally:
  519. sem.release()
  520. for bare_git in gc_gitdirs.values():
  521. if err_event.isSet() and opt.fail_fast:
  522. break
  523. sem.acquire()
  524. t = _threading.Thread(target=GC, args=(bare_git,))
  525. t.daemon = True
  526. threads.add(t)
  527. t.start()
  528. for t in threads:
  529. t.join()
  530. def _ReloadManifest(self, manifest_name=None):
  531. if manifest_name:
  532. # Override calls _Unload already
  533. self.manifest.Override(manifest_name)
  534. else:
  535. self.manifest._Unload()
  536. def UpdateProjectList(self, opt):
  537. new_project_paths = []
  538. for project in self.GetProjects(None, missing_ok=True):
  539. if project.relpath:
  540. new_project_paths.append(project.relpath)
  541. file_name = 'project.list'
  542. file_path = os.path.join(self.manifest.repodir, file_name)
  543. old_project_paths = []
  544. if os.path.exists(file_path):
  545. with open(file_path, 'r') as fd:
  546. old_project_paths = fd.read().split('\n')
  547. # In reversed order, so subfolders are deleted before parent folder.
  548. for path in sorted(old_project_paths, reverse=True):
  549. if not path:
  550. continue
  551. if path not in new_project_paths:
  552. # If the path has already been deleted, we don't need to do it
  553. gitdir = os.path.join(self.manifest.topdir, path, '.git')
  554. if os.path.exists(gitdir):
  555. project = Project(
  556. manifest=self.manifest,
  557. name=path,
  558. remote=RemoteSpec('origin'),
  559. gitdir=gitdir,
  560. objdir=gitdir,
  561. use_git_worktrees=os.path.isfile(gitdir),
  562. worktree=os.path.join(self.manifest.topdir, path),
  563. relpath=path,
  564. revisionExpr='HEAD',
  565. revisionId=None,
  566. groups=None)
  567. if not project.DeleteWorktree(
  568. quiet=opt.quiet,
  569. force=opt.force_remove_dirty):
  570. return 1
  571. new_project_paths.sort()
  572. with open(file_path, 'w') as fd:
  573. fd.write('\n'.join(new_project_paths))
  574. fd.write('\n')
  575. return 0
  576. def _SmartSyncSetup(self, opt, smart_sync_manifest_path):
  577. if not self.manifest.manifest_server:
  578. print('error: cannot smart sync: no manifest server defined in '
  579. 'manifest', file=sys.stderr)
  580. sys.exit(1)
  581. manifest_server = self.manifest.manifest_server
  582. if not opt.quiet:
  583. print('Using manifest server %s' % manifest_server)
  584. if '@' not in manifest_server:
  585. username = None
  586. password = None
  587. if opt.manifest_server_username and opt.manifest_server_password:
  588. username = opt.manifest_server_username
  589. password = opt.manifest_server_password
  590. else:
  591. try:
  592. info = netrc.netrc()
  593. except IOError:
  594. # .netrc file does not exist or could not be opened
  595. pass
  596. else:
  597. try:
  598. parse_result = urllib.parse.urlparse(manifest_server)
  599. if parse_result.hostname:
  600. auth = info.authenticators(parse_result.hostname)
  601. if auth:
  602. username, _account, password = auth
  603. else:
  604. print('No credentials found for %s in .netrc'
  605. % parse_result.hostname, file=sys.stderr)
  606. except netrc.NetrcParseError as e:
  607. print('Error parsing .netrc file: %s' % e, file=sys.stderr)
  608. if (username and password):
  609. manifest_server = manifest_server.replace('://', '://%s:%s@' %
  610. (username, password),
  611. 1)
  612. transport = PersistentTransport(manifest_server)
  613. if manifest_server.startswith('persistent-'):
  614. manifest_server = manifest_server[len('persistent-'):]
  615. try:
  616. server = xmlrpc.client.Server(manifest_server, transport=transport)
  617. if opt.smart_sync:
  618. p = self.manifest.manifestProject
  619. b = p.GetBranch(p.CurrentBranch)
  620. branch = b.merge
  621. if branch.startswith(R_HEADS):
  622. branch = branch[len(R_HEADS):]
  623. if 'SYNC_TARGET' in os.environ:
  624. target = os.environ['SYNC_TARGET']
  625. [success, manifest_str] = server.GetApprovedManifest(branch, target)
  626. elif ('TARGET_PRODUCT' in os.environ and
  627. 'TARGET_BUILD_VARIANT' in os.environ):
  628. target = '%s-%s' % (os.environ['TARGET_PRODUCT'],
  629. os.environ['TARGET_BUILD_VARIANT'])
  630. [success, manifest_str] = server.GetApprovedManifest(branch, target)
  631. else:
  632. [success, manifest_str] = server.GetApprovedManifest(branch)
  633. else:
  634. assert(opt.smart_tag)
  635. [success, manifest_str] = server.GetManifest(opt.smart_tag)
  636. if success:
  637. manifest_name = os.path.basename(smart_sync_manifest_path)
  638. try:
  639. with open(smart_sync_manifest_path, 'w') as f:
  640. f.write(manifest_str)
  641. except IOError as e:
  642. print('error: cannot write manifest to %s:\n%s'
  643. % (smart_sync_manifest_path, e),
  644. file=sys.stderr)
  645. sys.exit(1)
  646. self._ReloadManifest(manifest_name)
  647. else:
  648. print('error: manifest server RPC call failed: %s' %
  649. manifest_str, file=sys.stderr)
  650. sys.exit(1)
  651. except (socket.error, IOError, xmlrpc.client.Fault) as e:
  652. print('error: cannot connect to manifest server %s:\n%s'
  653. % (self.manifest.manifest_server, e), file=sys.stderr)
  654. sys.exit(1)
  655. except xmlrpc.client.ProtocolError as e:
  656. print('error: cannot connect to manifest server %s:\n%d %s'
  657. % (self.manifest.manifest_server, e.errcode, e.errmsg),
  658. file=sys.stderr)
  659. sys.exit(1)
  660. return manifest_name
  661. def _UpdateManifestProject(self, opt, mp, manifest_name):
  662. """Fetch & update the local manifest project."""
  663. if not opt.local_only:
  664. start = time.time()
  665. success = mp.Sync_NetworkHalf(quiet=opt.quiet, verbose=opt.verbose,
  666. current_branch_only=opt.current_branch_only,
  667. force_sync=opt.force_sync,
  668. tags=opt.tags,
  669. optimized_fetch=opt.optimized_fetch,
  670. retry_fetches=opt.retry_fetches,
  671. submodules=self.manifest.HasSubmodules,
  672. clone_filter=self.manifest.CloneFilter)
  673. finish = time.time()
  674. self.event_log.AddSync(mp, event_log.TASK_SYNC_NETWORK,
  675. start, finish, success)
  676. if mp.HasChanges:
  677. syncbuf = SyncBuffer(mp.config)
  678. start = time.time()
  679. mp.Sync_LocalHalf(syncbuf, submodules=self.manifest.HasSubmodules)
  680. clean = syncbuf.Finish()
  681. self.event_log.AddSync(mp, event_log.TASK_SYNC_LOCAL,
  682. start, time.time(), clean)
  683. if not clean:
  684. sys.exit(1)
  685. self._ReloadManifest(opt.manifest_name)
  686. if opt.jobs is None:
  687. self.jobs = self.manifest.default.sync_j
  688. def ValidateOptions(self, opt, args):
  689. if opt.force_broken:
  690. print('warning: -f/--force-broken is now the default behavior, and the '
  691. 'options are deprecated', file=sys.stderr)
  692. if opt.network_only and opt.detach_head:
  693. self.OptionParser.error('cannot combine -n and -d')
  694. if opt.network_only and opt.local_only:
  695. self.OptionParser.error('cannot combine -n and -l')
  696. if opt.manifest_name and opt.smart_sync:
  697. self.OptionParser.error('cannot combine -m and -s')
  698. if opt.manifest_name and opt.smart_tag:
  699. self.OptionParser.error('cannot combine -m and -t')
  700. if opt.manifest_server_username or opt.manifest_server_password:
  701. if not (opt.smart_sync or opt.smart_tag):
  702. self.OptionParser.error('-u and -p may only be combined with -s or -t')
  703. if None in [opt.manifest_server_username, opt.manifest_server_password]:
  704. self.OptionParser.error('both -u and -p must be given')
  705. def Execute(self, opt, args):
  706. if opt.jobs:
  707. self.jobs = opt.jobs
  708. if self.jobs > 1:
  709. soft_limit, _ = _rlimit_nofile()
  710. self.jobs = min(self.jobs, (soft_limit - 5) // 3)
  711. opt.quiet = opt.output_mode is False
  712. opt.verbose = opt.output_mode is True
  713. if opt.manifest_name:
  714. self.manifest.Override(opt.manifest_name)
  715. manifest_name = opt.manifest_name
  716. smart_sync_manifest_path = os.path.join(
  717. self.manifest.manifestProject.worktree, 'smart_sync_override.xml')
  718. if opt.clone_bundle is None:
  719. opt.clone_bundle = self.manifest.CloneBundle
  720. if opt.smart_sync or opt.smart_tag:
  721. manifest_name = self._SmartSyncSetup(opt, smart_sync_manifest_path)
  722. else:
  723. if os.path.isfile(smart_sync_manifest_path):
  724. try:
  725. platform_utils.remove(smart_sync_manifest_path)
  726. except OSError as e:
  727. print('error: failed to remove existing smart sync override manifest: %s' %
  728. e, file=sys.stderr)
  729. err_event = _threading.Event()
  730. rp = self.manifest.repoProject
  731. rp.PreSync()
  732. cb = rp.CurrentBranch
  733. if cb:
  734. base = rp.GetBranch(cb).merge
  735. if not base or not base.startswith('refs/heads/'):
  736. print('warning: repo is not tracking a remote branch, so it will not '
  737. 'receive updates; run `repo init --repo-rev=stable` to fix.',
  738. file=sys.stderr)
  739. mp = self.manifest.manifestProject
  740. mp.PreSync()
  741. if opt.repo_upgraded:
  742. _PostRepoUpgrade(self.manifest, quiet=opt.quiet)
  743. if not opt.mp_update:
  744. print('Skipping update of local manifest project.')
  745. else:
  746. self._UpdateManifestProject(opt, mp, manifest_name)
  747. if self.gitc_manifest:
  748. gitc_manifest_projects = self.GetProjects(args,
  749. missing_ok=True)
  750. gitc_projects = []
  751. opened_projects = []
  752. for project in gitc_manifest_projects:
  753. if project.relpath in self.gitc_manifest.paths and \
  754. self.gitc_manifest.paths[project.relpath].old_revision:
  755. opened_projects.append(project.relpath)
  756. else:
  757. gitc_projects.append(project.relpath)
  758. if not args:
  759. gitc_projects = None
  760. if gitc_projects != [] and not opt.local_only:
  761. print('Updating GITC client: %s' % self.gitc_manifest.gitc_client_name)
  762. manifest = GitcManifest(self.repodir, self.gitc_manifest.gitc_client_name)
  763. if manifest_name:
  764. manifest.Override(manifest_name)
  765. else:
  766. manifest.Override(self.manifest.manifestFile)
  767. gitc_utils.generate_gitc_manifest(self.gitc_manifest,
  768. manifest,
  769. gitc_projects)
  770. print('GITC client successfully synced.')
  771. # The opened projects need to be synced as normal, therefore we
  772. # generate a new args list to represent the opened projects.
  773. # TODO: make this more reliable -- if there's a project name/path overlap,
  774. # this may choose the wrong project.
  775. args = [os.path.relpath(self.manifest.paths[path].worktree, os.getcwd())
  776. for path in opened_projects]
  777. if not args:
  778. return
  779. all_projects = self.GetProjects(args,
  780. missing_ok=True,
  781. submodules_ok=opt.fetch_submodules)
  782. if opt.use_superproject:
  783. if not self.manifest.superproject:
  784. print('error: superproject tag is not defined in manifest.xml',
  785. file=sys.stderr)
  786. sys.exit(1)
  787. print('WARNING: --use-superproject is experimental and not '
  788. 'for general use', file=sys.stderr)
  789. superproject_url = self.manifest.superproject['remote'].url
  790. if not superproject_url:
  791. print('error: superproject URL is not defined in manifest.xml',
  792. file=sys.stderr)
  793. sys.exit(1)
  794. superproject = git_superproject.Superproject(self.manifest.repodir)
  795. try:
  796. superproject_shas = superproject.GetAllProjectsSHAs(url=superproject_url)
  797. except Exception as e:
  798. print('error: Cannot get project SHAs for %s: %s: %s' %
  799. (superproject_url, type(e).__name__, str(e)),
  800. file=sys.stderr)
  801. sys.exit(1)
  802. projects_missing_shas = []
  803. for project in all_projects:
  804. path = project.relpath
  805. if not path:
  806. continue
  807. sha = superproject_shas.get(path)
  808. if sha:
  809. project.SetRevisionId(sha)
  810. else:
  811. projects_missing_shas.append(path)
  812. if projects_missing_shas:
  813. print('error: please file a bug using %s to report missing shas for: %s' %
  814. (BUG_REPORT_URL, projects_missing_shas), file=sys.stderr)
  815. sys.exit(1)
  816. err_network_sync = False
  817. err_update_projects = False
  818. err_checkout = False
  819. self._fetch_times = _FetchTimes(self.manifest)
  820. if not opt.local_only:
  821. to_fetch = []
  822. now = time.time()
  823. if _ONE_DAY_S <= (now - rp.LastFetch):
  824. to_fetch.append(rp)
  825. to_fetch.extend(all_projects)
  826. to_fetch.sort(key=self._fetch_times.Get, reverse=True)
  827. fetched = self._Fetch(to_fetch, opt, err_event)
  828. _PostRepoFetch(rp, opt.repo_verify)
  829. if opt.network_only:
  830. # bail out now; the rest touches the working tree
  831. if err_event.isSet():
  832. print('\nerror: Exited sync due to fetch errors.\n', file=sys.stderr)
  833. sys.exit(1)
  834. return
  835. # Iteratively fetch missing and/or nested unregistered submodules
  836. previously_missing_set = set()
  837. while True:
  838. self._ReloadManifest(manifest_name)
  839. all_projects = self.GetProjects(args,
  840. missing_ok=True,
  841. submodules_ok=opt.fetch_submodules)
  842. missing = []
  843. for project in all_projects:
  844. if project.gitdir not in fetched:
  845. missing.append(project)
  846. if not missing:
  847. break
  848. # Stop us from non-stopped fetching actually-missing repos: If set of
  849. # missing repos has not been changed from last fetch, we break.
  850. missing_set = set(p.name for p in missing)
  851. if previously_missing_set == missing_set:
  852. break
  853. previously_missing_set = missing_set
  854. fetched.update(self._Fetch(missing, opt, err_event))
  855. # If we saw an error, exit with code 1 so that other scripts can check.
  856. if err_event.isSet():
  857. err_network_sync = True
  858. if opt.fail_fast:
  859. print('\nerror: Exited sync due to fetch errors.\n'
  860. 'Local checkouts *not* updated. Resolve network issues & '
  861. 'retry.\n'
  862. '`repo sync -l` will update some local checkouts.',
  863. file=sys.stderr)
  864. sys.exit(1)
  865. if self.manifest.IsMirror or self.manifest.IsArchive:
  866. # bail out now, we have no working tree
  867. return
  868. if self.UpdateProjectList(opt):
  869. err_event.set()
  870. err_update_projects = True
  871. if opt.fail_fast:
  872. print('\nerror: Local checkouts *not* updated.', file=sys.stderr)
  873. sys.exit(1)
  874. err_results = []
  875. self._Checkout(all_projects, opt, err_event, err_results)
  876. if err_event.isSet():
  877. err_checkout = True
  878. # NB: We don't exit here because this is the last step.
  879. # If there's a notice that's supposed to print at the end of the sync, print
  880. # it now...
  881. if self.manifest.notice:
  882. print(self.manifest.notice)
  883. # If we saw an error, exit with code 1 so that other scripts can check.
  884. if err_event.isSet():
  885. print('\nerror: Unable to fully sync the tree.', file=sys.stderr)
  886. if err_network_sync:
  887. print('error: Downloading network changes failed.', file=sys.stderr)
  888. if err_update_projects:
  889. print('error: Updating local project lists failed.', file=sys.stderr)
  890. if err_checkout:
  891. print('error: Checking out local projects failed.', file=sys.stderr)
  892. if err_results:
  893. print('Failing repos:\n%s' % '\n'.join(err_results), file=sys.stderr)
  894. print('Try re-running with "-j1 --fail-fast" to exit at the first error.',
  895. file=sys.stderr)
  896. sys.exit(1)
  897. if not opt.quiet:
  898. print('repo sync has finished successfully.')
  899. def _PostRepoUpgrade(manifest, quiet=False):
  900. wrapper = Wrapper()
  901. if wrapper.NeedSetupGnuPG():
  902. wrapper.SetupGnuPG(quiet)
  903. for project in manifest.projects:
  904. if project.Exists:
  905. project.PostRepoUpgrade()
  906. def _PostRepoFetch(rp, repo_verify=True, verbose=False):
  907. if rp.HasChanges:
  908. print('info: A new version of repo is available', file=sys.stderr)
  909. print(file=sys.stderr)
  910. if not repo_verify or _VerifyTag(rp):
  911. syncbuf = SyncBuffer(rp.config)
  912. rp.Sync_LocalHalf(syncbuf)
  913. if not syncbuf.Finish():
  914. sys.exit(1)
  915. print('info: Restarting repo with latest version', file=sys.stderr)
  916. raise RepoChangedException(['--repo-upgraded'])
  917. else:
  918. print('warning: Skipped upgrade to unverified version', file=sys.stderr)
  919. else:
  920. if verbose:
  921. print('repo version %s is current' % rp.work_git.describe(HEAD),
  922. file=sys.stderr)
  923. def _VerifyTag(project):
  924. gpg_dir = os.path.expanduser('~/.repoconfig/gnupg')
  925. if not os.path.exists(gpg_dir):
  926. print('warning: GnuPG was not available during last "repo init"\n'
  927. 'warning: Cannot automatically authenticate repo."""',
  928. file=sys.stderr)
  929. return True
  930. try:
  931. cur = project.bare_git.describe(project.GetRevisionId())
  932. except GitError:
  933. cur = None
  934. if not cur \
  935. or re.compile(r'^.*-[0-9]{1,}-g[0-9a-f]{1,}$').match(cur):
  936. rev = project.revisionExpr
  937. if rev.startswith(R_HEADS):
  938. rev = rev[len(R_HEADS):]
  939. print(file=sys.stderr)
  940. print("warning: project '%s' branch '%s' is not signed"
  941. % (project.name, rev), file=sys.stderr)
  942. return False
  943. env = os.environ.copy()
  944. env['GIT_DIR'] = project.gitdir
  945. env['GNUPGHOME'] = gpg_dir
  946. cmd = [GIT, 'tag', '-v', cur]
  947. proc = subprocess.Popen(cmd,
  948. stdout=subprocess.PIPE,
  949. stderr=subprocess.PIPE,
  950. env=env)
  951. out = proc.stdout.read()
  952. proc.stdout.close()
  953. err = proc.stderr.read()
  954. proc.stderr.close()
  955. if proc.wait() != 0:
  956. print(file=sys.stderr)
  957. print(out, file=sys.stderr)
  958. print(err, file=sys.stderr)
  959. print(file=sys.stderr)
  960. return False
  961. return True
  962. class _FetchTimes(object):
  963. _ALPHA = 0.5
  964. def __init__(self, manifest):
  965. self._path = os.path.join(manifest.repodir, '.repo_fetchtimes.json')
  966. self._times = None
  967. self._seen = set()
  968. def Get(self, project):
  969. self._Load()
  970. return self._times.get(project.name, _ONE_DAY_S)
  971. def Set(self, project, t):
  972. self._Load()
  973. name = project.name
  974. old = self._times.get(name, t)
  975. self._seen.add(name)
  976. a = self._ALPHA
  977. self._times[name] = (a * t) + ((1 - a) * old)
  978. def _Load(self):
  979. if self._times is None:
  980. try:
  981. with open(self._path) as f:
  982. self._times = json.load(f)
  983. except (IOError, ValueError):
  984. try:
  985. platform_utils.remove(self._path)
  986. except OSError:
  987. pass
  988. self._times = {}
  989. def Save(self):
  990. if self._times is None:
  991. return
  992. to_delete = []
  993. for name in self._times:
  994. if name not in self._seen:
  995. to_delete.append(name)
  996. for name in to_delete:
  997. del self._times[name]
  998. try:
  999. with open(self._path, 'w') as f:
  1000. json.dump(self._times, f, indent=2)
  1001. except (IOError, TypeError):
  1002. try:
  1003. platform_utils.remove(self._path)
  1004. except OSError:
  1005. pass
  1006. # This is a replacement for xmlrpc.client.Transport using urllib2
  1007. # and supporting persistent-http[s]. It cannot change hosts from
  1008. # request to request like the normal transport, the real url
  1009. # is passed during initialization.
  1010. class PersistentTransport(xmlrpc.client.Transport):
  1011. def __init__(self, orig_host):
  1012. self.orig_host = orig_host
  1013. def request(self, host, handler, request_body, verbose=False):
  1014. with GetUrlCookieFile(self.orig_host, not verbose) as (cookiefile, proxy):
  1015. # Python doesn't understand cookies with the #HttpOnly_ prefix
  1016. # Since we're only using them for HTTP, copy the file temporarily,
  1017. # stripping those prefixes away.
  1018. if cookiefile:
  1019. tmpcookiefile = tempfile.NamedTemporaryFile(mode='w')
  1020. tmpcookiefile.write("# HTTP Cookie File")
  1021. try:
  1022. with open(cookiefile) as f:
  1023. for line in f:
  1024. if line.startswith("#HttpOnly_"):
  1025. line = line[len("#HttpOnly_"):]
  1026. tmpcookiefile.write(line)
  1027. tmpcookiefile.flush()
  1028. cookiejar = cookielib.MozillaCookieJar(tmpcookiefile.name)
  1029. try:
  1030. cookiejar.load()
  1031. except cookielib.LoadError:
  1032. cookiejar = cookielib.CookieJar()
  1033. finally:
  1034. tmpcookiefile.close()
  1035. else:
  1036. cookiejar = cookielib.CookieJar()
  1037. proxyhandler = urllib.request.ProxyHandler
  1038. if proxy:
  1039. proxyhandler = urllib.request.ProxyHandler({
  1040. "http": proxy,
  1041. "https": proxy})
  1042. opener = urllib.request.build_opener(
  1043. urllib.request.HTTPCookieProcessor(cookiejar),
  1044. proxyhandler)
  1045. url = urllib.parse.urljoin(self.orig_host, handler)
  1046. parse_results = urllib.parse.urlparse(url)
  1047. scheme = parse_results.scheme
  1048. if scheme == 'persistent-http':
  1049. scheme = 'http'
  1050. if scheme == 'persistent-https':
  1051. # If we're proxying through persistent-https, use http. The
  1052. # proxy itself will do the https.
  1053. if proxy:
  1054. scheme = 'http'
  1055. else:
  1056. scheme = 'https'
  1057. # Parse out any authentication information using the base class
  1058. host, extra_headers, _ = self.get_host_info(parse_results.netloc)
  1059. url = urllib.parse.urlunparse((
  1060. scheme,
  1061. host,
  1062. parse_results.path,
  1063. parse_results.params,
  1064. parse_results.query,
  1065. parse_results.fragment))
  1066. request = urllib.request.Request(url, request_body)
  1067. if extra_headers is not None:
  1068. for (name, header) in extra_headers:
  1069. request.add_header(name, header)
  1070. request.add_header('Content-Type', 'text/xml')
  1071. try:
  1072. response = opener.open(request)
  1073. except urllib.error.HTTPError as e:
  1074. if e.code == 501:
  1075. # We may have been redirected through a login process
  1076. # but our POST turned into a GET. Retry.
  1077. response = opener.open(request)
  1078. else:
  1079. raise
  1080. p, u = xmlrpc.client.getparser()
  1081. while 1:
  1082. data = response.read(1024)
  1083. if not data:
  1084. break
  1085. p.feed(data)
  1086. p.close()
  1087. return u.close()
  1088. def close(self):
  1089. pass