sync.py 38 KB

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