sync.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852
  1. #
  2. # Copyright (C) 2008 The Android Open Source Project
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. from __future__ import print_function
  16. import json
  17. import netrc
  18. from optparse import SUPPRESS_HELP
  19. import os
  20. import re
  21. import shutil
  22. import socket
  23. import subprocess
  24. import sys
  25. import time
  26. from pyversion import is_python3
  27. if is_python3():
  28. import urllib.parse
  29. import xmlrpc.client
  30. else:
  31. import imp
  32. import urlparse
  33. import xmlrpclib
  34. urllib = imp.new_module('urllib')
  35. urllib.parse = urlparse
  36. xmlrpc = imp.new_module('xmlrpc')
  37. xmlrpc.client = xmlrpclib
  38. try:
  39. import threading as _threading
  40. except ImportError:
  41. import dummy_threading as _threading
  42. try:
  43. import resource
  44. def _rlimit_nofile():
  45. return resource.getrlimit(resource.RLIMIT_NOFILE)
  46. except ImportError:
  47. def _rlimit_nofile():
  48. return (256, 256)
  49. try:
  50. import multiprocessing
  51. except ImportError:
  52. multiprocessing = None
  53. from git_command import GIT, git_require
  54. from git_refs import R_HEADS, HEAD
  55. from project import Project
  56. from project import RemoteSpec
  57. from command import Command, MirrorSafeCommand
  58. from error import RepoChangedException, GitError, ManifestParseError
  59. from project import SyncBuffer
  60. from progress import Progress
  61. from wrapper import Wrapper
  62. _ONE_DAY_S = 24 * 60 * 60
  63. class _FetchError(Exception):
  64. """Internal error thrown in _FetchHelper() when we don't want stack trace."""
  65. pass
  66. class Sync(Command, MirrorSafeCommand):
  67. jobs = 1
  68. common = True
  69. helpSummary = "Update working tree to the latest revision"
  70. helpUsage = """
  71. %prog [<project>...]
  72. """
  73. helpDescription = """
  74. The '%prog' command synchronizes local project directories
  75. with the remote repositories specified in the manifest. If a local
  76. project does not yet exist, it will clone a new local directory from
  77. the remote repository and set up tracking branches as specified in
  78. the manifest. If the local project already exists, '%prog'
  79. will update the remote branches and rebase any new local changes
  80. on top of the new remote changes.
  81. '%prog' will synchronize all projects listed at the command
  82. line. Projects can be specified either by name, or by a relative
  83. or absolute path to the project's local directory. If no projects
  84. are specified, '%prog' will synchronize all projects listed in
  85. the manifest.
  86. The -d/--detach option can be used to switch specified projects
  87. back to the manifest revision. This option is especially helpful
  88. if the project is currently on a topic branch, but the manifest
  89. revision is temporarily needed.
  90. The -s/--smart-sync option can be used to sync to a known good
  91. build as specified by the manifest-server element in the current
  92. manifest. The -t/--smart-tag option is similar and allows you to
  93. specify a custom tag/label.
  94. The -u/--manifest-server-username and -p/--manifest-server-password
  95. options can be used to specify a username and password to authenticate
  96. with the manifest server when using the -s or -t option.
  97. If -u and -p are not specified when using the -s or -t option, '%prog'
  98. will attempt to read authentication credentials for the manifest server
  99. from the user's .netrc file.
  100. '%prog' will not use authentication credentials from -u/-p or .netrc
  101. if the manifest server specified in the manifest file already includes
  102. credentials.
  103. The -f/--force-broken option can be used to proceed with syncing
  104. other projects if a project sync fails.
  105. The --force-sync option can be used to overwrite existing git
  106. directories if they have previously been linked to a different
  107. object direcotry. WARNING: This may cause data to be lost since
  108. refs may be removed when overwriting.
  109. The --no-clone-bundle option disables any attempt to use
  110. $URL/clone.bundle to bootstrap a new Git repository from a
  111. resumeable bundle file on a content delivery network. This
  112. may be necessary if there are problems with the local Python
  113. HTTP client or proxy configuration, but the Git binary works.
  114. The --fetch-submodules option enables fetching Git submodules
  115. of a project from server.
  116. The -c/--current-branch option can be used to only fetch objects that
  117. are on the branch specified by a project's revision.
  118. The --optimized-fetch option can be used to only fetch projects that
  119. are fixed to a sha1 revision if the sha1 revision does not already
  120. exist locally.
  121. SSH Connections
  122. ---------------
  123. If at least one project remote URL uses an SSH connection (ssh://,
  124. git+ssh://, or user@host:path syntax) repo will automatically
  125. enable the SSH ControlMaster option when connecting to that host.
  126. This feature permits other projects in the same '%prog' session to
  127. reuse the same SSH tunnel, saving connection setup overheads.
  128. To disable this behavior on UNIX platforms, set the GIT_SSH
  129. environment variable to 'ssh'. For example:
  130. export GIT_SSH=ssh
  131. %prog
  132. Compatibility
  133. ~~~~~~~~~~~~~
  134. This feature is automatically disabled on Windows, due to the lack
  135. of UNIX domain socket support.
  136. This feature is not compatible with url.insteadof rewrites in the
  137. user's ~/.gitconfig. '%prog' is currently not able to perform the
  138. rewrite early enough to establish the ControlMaster tunnel.
  139. If the remote SSH daemon is Gerrit Code Review, version 2.0.10 or
  140. later is required to fix a server side protocol bug.
  141. """
  142. def _Options(self, p, show_smart=True):
  143. try:
  144. self.jobs = self.manifest.default.sync_j
  145. except ManifestParseError:
  146. self.jobs = 1
  147. p.add_option('-f', '--force-broken',
  148. dest='force_broken', action='store_true',
  149. help="continue sync even if a project fails to sync")
  150. p.add_option('--force-sync',
  151. dest='force_sync', action='store_true',
  152. help="overwrite an existing git directory if it needs to "
  153. "point to a different object directory. WARNING: this "
  154. "may cause loss of data")
  155. p.add_option('-l', '--local-only',
  156. dest='local_only', action='store_true',
  157. help="only update working tree, don't fetch")
  158. p.add_option('-n', '--network-only',
  159. dest='network_only', action='store_true',
  160. help="fetch only, don't update working tree")
  161. p.add_option('-d', '--detach',
  162. dest='detach_head', action='store_true',
  163. help='detach projects back to manifest revision')
  164. p.add_option('-c', '--current-branch',
  165. dest='current_branch_only', action='store_true',
  166. help='fetch only current branch from server')
  167. p.add_option('-q', '--quiet',
  168. dest='quiet', action='store_true',
  169. help='be more quiet')
  170. p.add_option('-j', '--jobs',
  171. dest='jobs', action='store', type='int',
  172. help="projects to fetch simultaneously (default %d)" % self.jobs)
  173. p.add_option('-m', '--manifest-name',
  174. dest='manifest_name',
  175. help='temporary manifest to use for this sync', metavar='NAME.xml')
  176. p.add_option('--no-clone-bundle',
  177. dest='no_clone_bundle', action='store_true',
  178. help='disable use of /clone.bundle on HTTP/HTTPS')
  179. p.add_option('-u', '--manifest-server-username', action='store',
  180. dest='manifest_server_username',
  181. help='username to authenticate with the manifest server')
  182. p.add_option('-p', '--manifest-server-password', action='store',
  183. dest='manifest_server_password',
  184. help='password to authenticate with the manifest server')
  185. p.add_option('--fetch-submodules',
  186. dest='fetch_submodules', action='store_true',
  187. help='fetch submodules from server')
  188. p.add_option('--no-tags',
  189. dest='no_tags', action='store_true',
  190. help="don't fetch tags")
  191. p.add_option('--optimized-fetch',
  192. dest='optimized_fetch', action='store_true',
  193. help='only fetch projects fixed to sha1 if revision does not exist locally')
  194. if show_smart:
  195. p.add_option('-s', '--smart-sync',
  196. dest='smart_sync', action='store_true',
  197. help='smart sync using manifest from a known good build')
  198. p.add_option('-t', '--smart-tag',
  199. dest='smart_tag', action='store',
  200. help='smart sync using manifest from a known tag')
  201. g = p.add_option_group('repo Version options')
  202. g.add_option('--no-repo-verify',
  203. dest='no_repo_verify', action='store_true',
  204. help='do not verify repo source code')
  205. g.add_option('--repo-upgraded',
  206. dest='repo_upgraded', action='store_true',
  207. help=SUPPRESS_HELP)
  208. def _FetchProjectList(self, opt, projects, *args, **kwargs):
  209. """Main function of the fetch threads when jobs are > 1.
  210. Delegates most of the work to _FetchHelper.
  211. Args:
  212. opt: Program options returned from optparse. See _Options().
  213. projects: Projects to fetch.
  214. *args, **kwargs: Remaining arguments to pass to _FetchHelper. See the
  215. _FetchHelper docstring for details.
  216. """
  217. for project in projects:
  218. success = self._FetchHelper(opt, project, *args, **kwargs)
  219. if not success and not opt.force_broken:
  220. break
  221. def _FetchHelper(self, opt, project, lock, fetched, pm, sem, err_event):
  222. """Fetch git objects for a single project.
  223. Args:
  224. opt: Program options returned from optparse. See _Options().
  225. project: Project object for the project to fetch.
  226. lock: Lock for accessing objects that are shared amongst multiple
  227. _FetchHelper() threads.
  228. fetched: set object that we will add project.gitdir to when we're done
  229. (with our lock held).
  230. pm: Instance of a Project object. We will call pm.update() (with our
  231. lock held).
  232. sem: We'll release() this semaphore when we exit so that another thread
  233. can be started up.
  234. err_event: We'll set this event in the case of an error (after printing
  235. out info about the error).
  236. Returns:
  237. Whether the fetch was successful.
  238. """
  239. # We'll set to true once we've locked the lock.
  240. did_lock = False
  241. if not opt.quiet:
  242. print('Fetching project %s' % project.name)
  243. # Encapsulate everything in a try/except/finally so that:
  244. # - We always set err_event in the case of an exception.
  245. # - We always make sure we call sem.release().
  246. # - We always make sure we unlock the lock if we locked it.
  247. try:
  248. try:
  249. start = time.time()
  250. success = project.Sync_NetworkHalf(
  251. quiet=opt.quiet,
  252. current_branch_only=opt.current_branch_only,
  253. force_sync=opt.force_sync,
  254. clone_bundle=not opt.no_clone_bundle,
  255. no_tags=opt.no_tags, archive=self.manifest.IsArchive,
  256. optimized_fetch=opt.optimized_fetch)
  257. self._fetch_times.Set(project, time.time() - start)
  258. # Lock around all the rest of the code, since printing, updating a set
  259. # and Progress.update() are not thread safe.
  260. lock.acquire()
  261. did_lock = True
  262. if not success:
  263. print('error: Cannot fetch %s' % project.name, file=sys.stderr)
  264. if opt.force_broken:
  265. print('warn: --force-broken, continuing to sync',
  266. file=sys.stderr)
  267. else:
  268. raise _FetchError()
  269. fetched.add(project.gitdir)
  270. pm.update()
  271. except _FetchError:
  272. err_event.set()
  273. except Exception as e:
  274. print('error: Cannot fetch %s (%s: %s)' \
  275. % (project.name, type(e).__name__, str(e)), file=sys.stderr)
  276. err_event.set()
  277. raise
  278. finally:
  279. if did_lock:
  280. lock.release()
  281. sem.release()
  282. return success
  283. def _Fetch(self, projects, opt):
  284. fetched = set()
  285. lock = _threading.Lock()
  286. pm = Progress('Fetching projects', len(projects))
  287. objdir_project_map = dict()
  288. for project in projects:
  289. objdir_project_map.setdefault(project.objdir, []).append(project)
  290. threads = set()
  291. sem = _threading.Semaphore(self.jobs)
  292. err_event = _threading.Event()
  293. for project_list in objdir_project_map.values():
  294. # Check for any errors before running any more tasks.
  295. # ...we'll let existing threads finish, though.
  296. if err_event.isSet() and not opt.force_broken:
  297. break
  298. sem.acquire()
  299. kwargs = dict(opt=opt,
  300. projects=project_list,
  301. lock=lock,
  302. fetched=fetched,
  303. pm=pm,
  304. sem=sem,
  305. err_event=err_event)
  306. if self.jobs > 1:
  307. t = _threading.Thread(target = self._FetchProjectList,
  308. kwargs = kwargs)
  309. # Ensure that Ctrl-C will not freeze the repo process.
  310. t.daemon = True
  311. threads.add(t)
  312. t.start()
  313. else:
  314. self._FetchProjectList(**kwargs)
  315. for t in threads:
  316. t.join()
  317. # If we saw an error, exit with code 1 so that other scripts can check.
  318. if err_event.isSet():
  319. print('\nerror: Exited sync due to fetch errors', file=sys.stderr)
  320. sys.exit(1)
  321. pm.end()
  322. self._fetch_times.Save()
  323. if not self.manifest.IsArchive:
  324. self._GCProjects(projects)
  325. return fetched
  326. def _GCProjects(self, projects):
  327. gitdirs = {}
  328. for project in projects:
  329. gitdirs[project.gitdir] = project.bare_git
  330. has_dash_c = git_require((1, 7, 2))
  331. if multiprocessing and has_dash_c:
  332. cpu_count = multiprocessing.cpu_count()
  333. else:
  334. cpu_count = 1
  335. jobs = min(self.jobs, cpu_count)
  336. if jobs < 2:
  337. for bare_git in gitdirs.values():
  338. bare_git.gc('--auto')
  339. return
  340. config = {'pack.threads': cpu_count / jobs if cpu_count > jobs else 1}
  341. threads = set()
  342. sem = _threading.Semaphore(jobs)
  343. err_event = _threading.Event()
  344. def GC(bare_git):
  345. try:
  346. try:
  347. bare_git.gc('--auto', config=config)
  348. except GitError:
  349. err_event.set()
  350. except:
  351. err_event.set()
  352. raise
  353. finally:
  354. sem.release()
  355. for bare_git in gitdirs.values():
  356. if err_event.isSet():
  357. break
  358. sem.acquire()
  359. t = _threading.Thread(target=GC, args=(bare_git,))
  360. t.daemon = True
  361. threads.add(t)
  362. t.start()
  363. for t in threads:
  364. t.join()
  365. if err_event.isSet():
  366. print('\nerror: Exited sync due to gc errors', file=sys.stderr)
  367. sys.exit(1)
  368. def _ReloadManifest(self, manifest_name=None):
  369. if manifest_name:
  370. # Override calls _Unload already
  371. self.manifest.Override(manifest_name)
  372. else:
  373. self.manifest._Unload()
  374. def UpdateProjectList(self):
  375. new_project_paths = []
  376. for project in self.GetProjects(None, missing_ok=True):
  377. if project.relpath:
  378. new_project_paths.append(project.relpath)
  379. file_name = 'project.list'
  380. file_path = os.path.join(self.manifest.repodir, file_name)
  381. old_project_paths = []
  382. if os.path.exists(file_path):
  383. fd = open(file_path, 'r')
  384. try:
  385. old_project_paths = fd.read().split('\n')
  386. finally:
  387. fd.close()
  388. for path in old_project_paths:
  389. if not path:
  390. continue
  391. if path not in new_project_paths:
  392. # If the path has already been deleted, we don't need to do it
  393. if os.path.exists(self.manifest.topdir + '/' + path):
  394. gitdir = os.path.join(self.manifest.topdir, path, '.git')
  395. project = Project(
  396. manifest = self.manifest,
  397. name = path,
  398. remote = RemoteSpec('origin'),
  399. gitdir = gitdir,
  400. objdir = gitdir,
  401. worktree = os.path.join(self.manifest.topdir, path),
  402. relpath = path,
  403. revisionExpr = 'HEAD',
  404. revisionId = None,
  405. groups = None)
  406. if project.IsDirty():
  407. print('error: Cannot remove project "%s": uncommitted changes '
  408. 'are present' % project.relpath, file=sys.stderr)
  409. print(' commit changes, then run sync again',
  410. file=sys.stderr)
  411. return -1
  412. else:
  413. print('Deleting obsolete path %s' % project.worktree,
  414. file=sys.stderr)
  415. shutil.rmtree(project.worktree)
  416. # Try deleting parent subdirs if they are empty
  417. project_dir = os.path.dirname(project.worktree)
  418. while project_dir != self.manifest.topdir:
  419. try:
  420. os.rmdir(project_dir)
  421. except OSError:
  422. break
  423. project_dir = os.path.dirname(project_dir)
  424. new_project_paths.sort()
  425. fd = open(file_path, 'w')
  426. try:
  427. fd.write('\n'.join(new_project_paths))
  428. fd.write('\n')
  429. finally:
  430. fd.close()
  431. return 0
  432. def Execute(self, opt, args):
  433. if opt.jobs:
  434. self.jobs = opt.jobs
  435. if self.jobs > 1:
  436. soft_limit, _ = _rlimit_nofile()
  437. self.jobs = min(self.jobs, (soft_limit - 5) / 3)
  438. if opt.network_only and opt.detach_head:
  439. print('error: cannot combine -n and -d', file=sys.stderr)
  440. sys.exit(1)
  441. if opt.network_only and opt.local_only:
  442. print('error: cannot combine -n and -l', file=sys.stderr)
  443. sys.exit(1)
  444. if opt.manifest_name and opt.smart_sync:
  445. print('error: cannot combine -m and -s', file=sys.stderr)
  446. sys.exit(1)
  447. if opt.manifest_name and opt.smart_tag:
  448. print('error: cannot combine -m and -t', file=sys.stderr)
  449. sys.exit(1)
  450. if opt.manifest_server_username or opt.manifest_server_password:
  451. if not (opt.smart_sync or opt.smart_tag):
  452. print('error: -u and -p may only be combined with -s or -t',
  453. file=sys.stderr)
  454. sys.exit(1)
  455. if None in [opt.manifest_server_username, opt.manifest_server_password]:
  456. print('error: both -u and -p must be given', file=sys.stderr)
  457. sys.exit(1)
  458. if opt.manifest_name:
  459. self.manifest.Override(opt.manifest_name)
  460. manifest_name = opt.manifest_name
  461. smart_sync_manifest_name = "smart_sync_override.xml"
  462. smart_sync_manifest_path = os.path.join(
  463. self.manifest.manifestProject.worktree, smart_sync_manifest_name)
  464. if opt.smart_sync or opt.smart_tag:
  465. if not self.manifest.manifest_server:
  466. print('error: cannot smart sync: no manifest server defined in '
  467. 'manifest', file=sys.stderr)
  468. sys.exit(1)
  469. manifest_server = self.manifest.manifest_server
  470. if not opt.quiet:
  471. print('Using manifest server %s' % manifest_server)
  472. if not '@' in manifest_server:
  473. username = None
  474. password = None
  475. if opt.manifest_server_username and opt.manifest_server_password:
  476. username = opt.manifest_server_username
  477. password = opt.manifest_server_password
  478. else:
  479. try:
  480. info = netrc.netrc()
  481. except IOError:
  482. print('.netrc file does not exist or could not be opened',
  483. file=sys.stderr)
  484. else:
  485. try:
  486. parse_result = urllib.parse.urlparse(manifest_server)
  487. if parse_result.hostname:
  488. username, _account, password = \
  489. info.authenticators(parse_result.hostname)
  490. except TypeError:
  491. # TypeError is raised when the given hostname is not present
  492. # in the .netrc file.
  493. print('No credentials found for %s in .netrc'
  494. % parse_result.hostname, file=sys.stderr)
  495. except netrc.NetrcParseError as e:
  496. print('Error parsing .netrc file: %s' % e, file=sys.stderr)
  497. if (username and password):
  498. manifest_server = manifest_server.replace('://', '://%s:%s@' %
  499. (username, password),
  500. 1)
  501. try:
  502. server = xmlrpc.client.Server(manifest_server)
  503. if opt.smart_sync:
  504. p = self.manifest.manifestProject
  505. b = p.GetBranch(p.CurrentBranch)
  506. branch = b.merge
  507. if branch.startswith(R_HEADS):
  508. branch = branch[len(R_HEADS):]
  509. env = os.environ.copy()
  510. if 'SYNC_TARGET' in env:
  511. target = env['SYNC_TARGET']
  512. [success, manifest_str] = server.GetApprovedManifest(branch, target)
  513. elif 'TARGET_PRODUCT' in env and 'TARGET_BUILD_VARIANT' in env:
  514. target = '%s-%s' % (env['TARGET_PRODUCT'],
  515. env['TARGET_BUILD_VARIANT'])
  516. [success, manifest_str] = server.GetApprovedManifest(branch, target)
  517. else:
  518. [success, manifest_str] = server.GetApprovedManifest(branch)
  519. else:
  520. assert(opt.smart_tag)
  521. [success, manifest_str] = server.GetManifest(opt.smart_tag)
  522. if success:
  523. manifest_name = smart_sync_manifest_name
  524. try:
  525. f = open(smart_sync_manifest_path, 'w')
  526. try:
  527. f.write(manifest_str)
  528. finally:
  529. f.close()
  530. except IOError as e:
  531. print('error: cannot write manifest to %s:\n%s'
  532. % (smart_sync_manifest_path, e),
  533. file=sys.stderr)
  534. sys.exit(1)
  535. self._ReloadManifest(manifest_name)
  536. else:
  537. print('error: manifest server RPC call failed: %s' %
  538. manifest_str, file=sys.stderr)
  539. sys.exit(1)
  540. except (socket.error, IOError, xmlrpc.client.Fault) as e:
  541. print('error: cannot connect to manifest server %s:\n%s'
  542. % (self.manifest.manifest_server, e), file=sys.stderr)
  543. sys.exit(1)
  544. except xmlrpc.client.ProtocolError as e:
  545. print('error: cannot connect to manifest server %s:\n%d %s'
  546. % (self.manifest.manifest_server, e.errcode, e.errmsg),
  547. file=sys.stderr)
  548. sys.exit(1)
  549. else: # Not smart sync or smart tag mode
  550. if os.path.isfile(smart_sync_manifest_path):
  551. try:
  552. os.remove(smart_sync_manifest_path)
  553. except OSError as e:
  554. print('error: failed to remove existing smart sync override manifest: %s' %
  555. e, file=sys.stderr)
  556. rp = self.manifest.repoProject
  557. rp.PreSync()
  558. mp = self.manifest.manifestProject
  559. mp.PreSync()
  560. if opt.repo_upgraded:
  561. _PostRepoUpgrade(self.manifest, quiet=opt.quiet)
  562. if not opt.local_only:
  563. mp.Sync_NetworkHalf(quiet=opt.quiet,
  564. current_branch_only=opt.current_branch_only,
  565. no_tags=opt.no_tags,
  566. optimized_fetch=opt.optimized_fetch)
  567. if mp.HasChanges:
  568. syncbuf = SyncBuffer(mp.config)
  569. mp.Sync_LocalHalf(syncbuf)
  570. if not syncbuf.Finish():
  571. sys.exit(1)
  572. self._ReloadManifest(manifest_name)
  573. if opt.jobs is None:
  574. self.jobs = self.manifest.default.sync_j
  575. all_projects = self.GetProjects(args,
  576. missing_ok=True,
  577. submodules_ok=opt.fetch_submodules)
  578. self._fetch_times = _FetchTimes(self.manifest)
  579. if not opt.local_only:
  580. to_fetch = []
  581. now = time.time()
  582. if _ONE_DAY_S <= (now - rp.LastFetch):
  583. to_fetch.append(rp)
  584. to_fetch.extend(all_projects)
  585. to_fetch.sort(key=self._fetch_times.Get, reverse=True)
  586. fetched = self._Fetch(to_fetch, opt)
  587. _PostRepoFetch(rp, opt.no_repo_verify)
  588. if opt.network_only:
  589. # bail out now; the rest touches the working tree
  590. return
  591. # Iteratively fetch missing and/or nested unregistered submodules
  592. previously_missing_set = set()
  593. while True:
  594. self._ReloadManifest(manifest_name)
  595. all_projects = self.GetProjects(args,
  596. missing_ok=True,
  597. submodules_ok=opt.fetch_submodules)
  598. missing = []
  599. for project in all_projects:
  600. if project.gitdir not in fetched:
  601. missing.append(project)
  602. if not missing:
  603. break
  604. # Stop us from non-stopped fetching actually-missing repos: If set of
  605. # missing repos has not been changed from last fetch, we break.
  606. missing_set = set(p.name for p in missing)
  607. if previously_missing_set == missing_set:
  608. break
  609. previously_missing_set = missing_set
  610. fetched.update(self._Fetch(missing, opt))
  611. if self.manifest.IsMirror or self.manifest.IsArchive:
  612. # bail out now, we have no working tree
  613. return
  614. if self.UpdateProjectList():
  615. sys.exit(1)
  616. syncbuf = SyncBuffer(mp.config,
  617. detach_head = opt.detach_head)
  618. pm = Progress('Syncing work tree', len(all_projects))
  619. for project in all_projects:
  620. pm.update()
  621. if project.worktree:
  622. project.Sync_LocalHalf(syncbuf, force_sync=opt.force_sync)
  623. pm.end()
  624. print(file=sys.stderr)
  625. if not syncbuf.Finish():
  626. sys.exit(1)
  627. # If there's a notice that's supposed to print at the end of the sync, print
  628. # it now...
  629. if self.manifest.notice:
  630. print(self.manifest.notice)
  631. def _PostRepoUpgrade(manifest, quiet=False):
  632. wrapper = Wrapper()
  633. if wrapper.NeedSetupGnuPG():
  634. wrapper.SetupGnuPG(quiet)
  635. for project in manifest.projects:
  636. if project.Exists:
  637. project.PostRepoUpgrade()
  638. def _PostRepoFetch(rp, no_repo_verify=False, verbose=False):
  639. if rp.HasChanges:
  640. print('info: A new version of repo is available', file=sys.stderr)
  641. print(file=sys.stderr)
  642. if no_repo_verify or _VerifyTag(rp):
  643. syncbuf = SyncBuffer(rp.config)
  644. rp.Sync_LocalHalf(syncbuf)
  645. if not syncbuf.Finish():
  646. sys.exit(1)
  647. print('info: Restarting repo with latest version', file=sys.stderr)
  648. raise RepoChangedException(['--repo-upgraded'])
  649. else:
  650. print('warning: Skipped upgrade to unverified version', file=sys.stderr)
  651. else:
  652. if verbose:
  653. print('repo version %s is current' % rp.work_git.describe(HEAD),
  654. file=sys.stderr)
  655. def _VerifyTag(project):
  656. gpg_dir = os.path.expanduser('~/.repoconfig/gnupg')
  657. if not os.path.exists(gpg_dir):
  658. print('warning: GnuPG was not available during last "repo init"\n'
  659. 'warning: Cannot automatically authenticate repo."""',
  660. file=sys.stderr)
  661. return True
  662. try:
  663. cur = project.bare_git.describe(project.GetRevisionId())
  664. except GitError:
  665. cur = None
  666. if not cur \
  667. or re.compile(r'^.*-[0-9]{1,}-g[0-9a-f]{1,}$').match(cur):
  668. rev = project.revisionExpr
  669. if rev.startswith(R_HEADS):
  670. rev = rev[len(R_HEADS):]
  671. print(file=sys.stderr)
  672. print("warning: project '%s' branch '%s' is not signed"
  673. % (project.name, rev), file=sys.stderr)
  674. return False
  675. env = os.environ.copy()
  676. env['GIT_DIR'] = project.gitdir.encode()
  677. env['GNUPGHOME'] = gpg_dir.encode()
  678. cmd = [GIT, 'tag', '-v', cur]
  679. proc = subprocess.Popen(cmd,
  680. stdout = subprocess.PIPE,
  681. stderr = subprocess.PIPE,
  682. env = env)
  683. out = proc.stdout.read()
  684. proc.stdout.close()
  685. err = proc.stderr.read()
  686. proc.stderr.close()
  687. if proc.wait() != 0:
  688. print(file=sys.stderr)
  689. print(out, file=sys.stderr)
  690. print(err, file=sys.stderr)
  691. print(file=sys.stderr)
  692. return False
  693. return True
  694. class _FetchTimes(object):
  695. _ALPHA = 0.5
  696. def __init__(self, manifest):
  697. self._path = os.path.join(manifest.repodir, '.repo_fetchtimes.json')
  698. self._times = None
  699. self._seen = set()
  700. def Get(self, project):
  701. self._Load()
  702. return self._times.get(project.name, _ONE_DAY_S)
  703. def Set(self, project, t):
  704. self._Load()
  705. name = project.name
  706. old = self._times.get(name, t)
  707. self._seen.add(name)
  708. a = self._ALPHA
  709. self._times[name] = (a*t) + ((1-a) * old)
  710. def _Load(self):
  711. if self._times is None:
  712. try:
  713. f = open(self._path)
  714. try:
  715. self._times = json.load(f)
  716. finally:
  717. f.close()
  718. except (IOError, ValueError):
  719. try:
  720. os.remove(self._path)
  721. except OSError:
  722. pass
  723. self._times = {}
  724. def Save(self):
  725. if self._times is None:
  726. return
  727. to_delete = []
  728. for name in self._times:
  729. if name not in self._seen:
  730. to_delete.append(name)
  731. for name in to_delete:
  732. del self._times[name]
  733. try:
  734. f = open(self._path, 'w')
  735. try:
  736. json.dump(self._times, f, indent=2)
  737. finally:
  738. f.close()
  739. except (IOError, TypeError):
  740. try:
  741. os.remove(self._path)
  742. except OSError:
  743. pass