sync.py 36 KB

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