sync.py 33 KB

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