sync.py 33 KB

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