sync.py 43 KB

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