sync.py 32 KB

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