sync.py 38 KB

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