sync.py 43 KB

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