sync.py 43 KB

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