sync.py 44 KB

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