sync.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  1. #
  2. # Copyright (C) 2008 The Android Open Source Project
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import netrc
  16. from optparse import SUPPRESS_HELP
  17. import os
  18. import re
  19. import shutil
  20. import socket
  21. import subprocess
  22. import sys
  23. import time
  24. import urlparse
  25. import xmlrpclib
  26. try:
  27. import threading as _threading
  28. except ImportError:
  29. import dummy_threading as _threading
  30. try:
  31. import resource
  32. def _rlimit_nofile():
  33. return resource.getrlimit(resource.RLIMIT_NOFILE)
  34. except ImportError:
  35. def _rlimit_nofile():
  36. return (256, 256)
  37. from git_command import GIT
  38. from git_refs import R_HEADS, HEAD
  39. from project import Project
  40. from project import RemoteSpec
  41. from command import Command, MirrorSafeCommand
  42. from error import RepoChangedException, GitError
  43. from project import SyncBuffer
  44. from progress import Progress
  45. class _FetchError(Exception):
  46. """Internal error thrown in _FetchHelper() when we don't want stack trace."""
  47. pass
  48. class Sync(Command, MirrorSafeCommand):
  49. jobs = 1
  50. common = True
  51. helpSummary = "Update working tree to the latest revision"
  52. helpUsage = """
  53. %prog [<project>...]
  54. """
  55. helpDescription = """
  56. The '%prog' command synchronizes local project directories
  57. with the remote repositories specified in the manifest. If a local
  58. project does not yet exist, it will clone a new local directory from
  59. the remote repository and set up tracking branches as specified in
  60. the manifest. If the local project already exists, '%prog'
  61. will update the remote branches and rebase any new local changes
  62. on top of the new remote changes.
  63. '%prog' will synchronize all projects listed at the command
  64. line. Projects can be specified either by name, or by a relative
  65. or absolute path to the project's local directory. If no projects
  66. are specified, '%prog' will synchronize all projects listed in
  67. the manifest.
  68. The -d/--detach option can be used to switch specified projects
  69. back to the manifest revision. This option is especially helpful
  70. if the project is currently on a topic branch, but the manifest
  71. revision is temporarily needed.
  72. The -s/--smart-sync option can be used to sync to a known good
  73. build as specified by the manifest-server element in the current
  74. manifest. The -t/--smart-tag option is similar and allows you to
  75. specify a custom tag/label.
  76. The -f/--force-broken option can be used to proceed with syncing
  77. other projects if a project sync fails.
  78. The --no-clone-bundle option disables any attempt to use
  79. $URL/clone.bundle to bootstrap a new Git repository from a
  80. resumeable bundle file on a content delivery network. This
  81. may be necessary if there are problems with the local Python
  82. HTTP client or proxy configuration, but the Git binary works.
  83. SSH Connections
  84. ---------------
  85. If at least one project remote URL uses an SSH connection (ssh://,
  86. git+ssh://, or user@host:path syntax) repo will automatically
  87. enable the SSH ControlMaster option when connecting to that host.
  88. This feature permits other projects in the same '%prog' session to
  89. reuse the same SSH tunnel, saving connection setup overheads.
  90. To disable this behavior on UNIX platforms, set the GIT_SSH
  91. environment variable to 'ssh'. For example:
  92. export GIT_SSH=ssh
  93. %prog
  94. Compatibility
  95. ~~~~~~~~~~~~~
  96. This feature is automatically disabled on Windows, due to the lack
  97. of UNIX domain socket support.
  98. This feature is not compatible with url.insteadof rewrites in the
  99. user's ~/.gitconfig. '%prog' is currently not able to perform the
  100. rewrite early enough to establish the ControlMaster tunnel.
  101. If the remote SSH daemon is Gerrit Code Review, version 2.0.10 or
  102. later is required to fix a server side protocol bug.
  103. """
  104. def _Options(self, p, show_smart=True):
  105. self.jobs = self.manifest.default.sync_j
  106. p.add_option('-f', '--force-broken',
  107. dest='force_broken', action='store_true',
  108. help="continue sync even if a project fails to sync")
  109. p.add_option('-l','--local-only',
  110. dest='local_only', action='store_true',
  111. help="only update working tree, don't fetch")
  112. p.add_option('-n','--network-only',
  113. dest='network_only', action='store_true',
  114. help="fetch only, don't update working tree")
  115. p.add_option('-d','--detach',
  116. dest='detach_head', action='store_true',
  117. help='detach projects back to manifest revision')
  118. p.add_option('-c','--current-branch',
  119. dest='current_branch_only', action='store_true',
  120. help='fetch only current branch from server')
  121. p.add_option('-q','--quiet',
  122. dest='quiet', action='store_true',
  123. help='be more quiet')
  124. p.add_option('-j','--jobs',
  125. dest='jobs', action='store', type='int',
  126. help="projects to fetch simultaneously (default %d)" % self.jobs)
  127. p.add_option('-m', '--manifest-name',
  128. dest='manifest_name',
  129. help='temporary manifest to use for this sync', metavar='NAME.xml')
  130. p.add_option('--no-clone-bundle',
  131. dest='no_clone_bundle', action='store_true',
  132. help='disable use of /clone.bundle on HTTP/HTTPS')
  133. if show_smart:
  134. p.add_option('-s', '--smart-sync',
  135. dest='smart_sync', action='store_true',
  136. help='smart sync using manifest from a known good build')
  137. p.add_option('-t', '--smart-tag',
  138. dest='smart_tag', action='store',
  139. help='smart sync using manifest from a known tag')
  140. g = p.add_option_group('repo Version options')
  141. g.add_option('--no-repo-verify',
  142. dest='no_repo_verify', action='store_true',
  143. help='do not verify repo source code')
  144. g.add_option('--repo-upgraded',
  145. dest='repo_upgraded', action='store_true',
  146. help=SUPPRESS_HELP)
  147. def _FetchHelper(self, opt, project, lock, fetched, pm, sem, err_event):
  148. """Main function of the fetch threads when jobs are > 1.
  149. Args:
  150. opt: Program options returned from optparse. See _Options().
  151. project: Project object for the project to fetch.
  152. lock: Lock for accessing objects that are shared amongst multiple
  153. _FetchHelper() threads.
  154. fetched: set object that we will add project.gitdir to when we're done
  155. (with our lock held).
  156. pm: Instance of a Project object. We will call pm.update() (with our
  157. lock held).
  158. sem: We'll release() this semaphore when we exit so that another thread
  159. can be started up.
  160. err_event: We'll set this event in the case of an error (after printing
  161. out info about the error).
  162. """
  163. # We'll set to true once we've locked the lock.
  164. did_lock = False
  165. # Encapsulate everything in a try/except/finally so that:
  166. # - We always set err_event in the case of an exception.
  167. # - We always make sure we call sem.release().
  168. # - We always make sure we unlock the lock if we locked it.
  169. try:
  170. try:
  171. success = project.Sync_NetworkHalf(
  172. quiet=opt.quiet,
  173. current_branch_only=opt.current_branch_only,
  174. clone_bundle=not opt.no_clone_bundle)
  175. # Lock around all the rest of the code, since printing, updating a set
  176. # and Progress.update() are not thread safe.
  177. lock.acquire()
  178. did_lock = True
  179. if not success:
  180. print >>sys.stderr, 'error: Cannot fetch %s' % project.name
  181. if opt.force_broken:
  182. print >>sys.stderr, 'warn: --force-broken, continuing to sync'
  183. else:
  184. raise _FetchError()
  185. fetched.add(project.gitdir)
  186. pm.update()
  187. except _FetchError:
  188. err_event.set()
  189. except:
  190. err_event.set()
  191. raise
  192. finally:
  193. if did_lock:
  194. lock.release()
  195. sem.release()
  196. def _Fetch(self, projects, opt):
  197. fetched = set()
  198. pm = Progress('Fetching projects', len(projects))
  199. if self.jobs == 1:
  200. for project in projects:
  201. pm.update()
  202. if project.Sync_NetworkHalf(
  203. quiet=opt.quiet,
  204. current_branch_only=opt.current_branch_only,
  205. clone_bundle=not opt.no_clone_bundle):
  206. fetched.add(project.gitdir)
  207. else:
  208. print >>sys.stderr, 'error: Cannot fetch %s' % project.name
  209. if opt.force_broken:
  210. print >>sys.stderr, 'warn: --force-broken, continuing to sync'
  211. else:
  212. sys.exit(1)
  213. else:
  214. threads = set()
  215. lock = _threading.Lock()
  216. sem = _threading.Semaphore(self.jobs)
  217. err_event = _threading.Event()
  218. for project in projects:
  219. # Check for any errors before starting any new threads.
  220. # ...we'll let existing threads finish, though.
  221. if err_event.isSet():
  222. break
  223. sem.acquire()
  224. t = _threading.Thread(target = self._FetchHelper,
  225. args = (opt,
  226. project,
  227. lock,
  228. fetched,
  229. pm,
  230. sem,
  231. err_event))
  232. # Ensure that Ctrl-C will not freeze the repo process.
  233. t.daemon = True
  234. threads.add(t)
  235. t.start()
  236. for t in threads:
  237. t.join()
  238. # If we saw an error, exit with code 1 so that other scripts can check.
  239. if err_event.isSet():
  240. print >>sys.stderr, '\nerror: Exited sync due to fetch errors'
  241. sys.exit(1)
  242. pm.end()
  243. for project in projects:
  244. project.bare_git.gc('--auto')
  245. return fetched
  246. def UpdateProjectList(self):
  247. new_project_paths = []
  248. for project in self.GetProjects(None, missing_ok=True):
  249. if project.relpath:
  250. new_project_paths.append(project.relpath)
  251. file_name = 'project.list'
  252. file_path = os.path.join(self.manifest.repodir, file_name)
  253. old_project_paths = []
  254. if os.path.exists(file_path):
  255. fd = open(file_path, 'r')
  256. try:
  257. old_project_paths = fd.read().split('\n')
  258. finally:
  259. fd.close()
  260. for path in old_project_paths:
  261. if not path:
  262. continue
  263. if path not in new_project_paths:
  264. """If the path has already been deleted, we don't need to do it
  265. """
  266. if os.path.exists(self.manifest.topdir + '/' + path):
  267. project = Project(
  268. manifest = self.manifest,
  269. name = path,
  270. remote = RemoteSpec('origin'),
  271. gitdir = os.path.join(self.manifest.topdir,
  272. path, '.git'),
  273. worktree = os.path.join(self.manifest.topdir, path),
  274. relpath = path,
  275. revisionExpr = 'HEAD',
  276. revisionId = None,
  277. groups = None)
  278. if project.IsDirty():
  279. print >>sys.stderr, 'error: Cannot remove project "%s": \
  280. uncommitted changes are present' % project.relpath
  281. print >>sys.stderr, ' commit changes, then run sync again'
  282. return -1
  283. else:
  284. print >>sys.stderr, 'Deleting obsolete path %s' % project.worktree
  285. shutil.rmtree(project.worktree)
  286. # Try deleting parent subdirs if they are empty
  287. dir = os.path.dirname(project.worktree)
  288. while dir != self.manifest.topdir:
  289. try:
  290. os.rmdir(dir)
  291. except OSError:
  292. break
  293. dir = os.path.dirname(dir)
  294. new_project_paths.sort()
  295. fd = open(file_path, 'w')
  296. try:
  297. fd.write('\n'.join(new_project_paths))
  298. fd.write('\n')
  299. finally:
  300. fd.close()
  301. return 0
  302. def Execute(self, opt, args):
  303. if opt.jobs:
  304. self.jobs = opt.jobs
  305. if self.jobs > 1:
  306. soft_limit, _ = _rlimit_nofile()
  307. self.jobs = min(self.jobs, (soft_limit - 5) / 3)
  308. if opt.network_only and opt.detach_head:
  309. print >>sys.stderr, 'error: cannot combine -n and -d'
  310. sys.exit(1)
  311. if opt.network_only and opt.local_only:
  312. print >>sys.stderr, 'error: cannot combine -n and -l'
  313. sys.exit(1)
  314. if opt.manifest_name and opt.smart_sync:
  315. print >>sys.stderr, 'error: cannot combine -m and -s'
  316. sys.exit(1)
  317. if opt.manifest_name and opt.smart_tag:
  318. print >>sys.stderr, 'error: cannot combine -m and -t'
  319. sys.exit(1)
  320. if opt.manifest_name:
  321. self.manifest.Override(opt.manifest_name)
  322. if opt.smart_sync or opt.smart_tag:
  323. if not self.manifest.manifest_server:
  324. print >>sys.stderr, \
  325. 'error: cannot smart sync: no manifest server defined in manifest'
  326. sys.exit(1)
  327. manifest_server = self.manifest.manifest_server
  328. if not '@' in manifest_server:
  329. try:
  330. info = netrc.netrc()
  331. except IOError:
  332. print >>sys.stderr, '.netrc file does not exist or could not be opened'
  333. else:
  334. try:
  335. parse_result = urlparse.urlparse(manifest_server)
  336. if parse_result.hostname:
  337. username, _account, password = \
  338. info.authenticators(parse_result.hostname)
  339. except TypeError:
  340. # TypeError is raised when the given hostname is not present
  341. # in the .netrc file.
  342. print >>sys.stderr, 'No credentials found for %s in .netrc' % \
  343. parse_result.hostname
  344. except netrc.NetrcParseError as e:
  345. print >>sys.stderr, 'Error parsing .netrc file: %s' % e
  346. else:
  347. if (username and password):
  348. manifest_server = manifest_server.replace('://', '://%s:%s@' %
  349. (username, password),
  350. 1)
  351. try:
  352. server = xmlrpclib.Server(manifest_server)
  353. if opt.smart_sync:
  354. p = self.manifest.manifestProject
  355. b = p.GetBranch(p.CurrentBranch)
  356. branch = b.merge
  357. if branch.startswith(R_HEADS):
  358. branch = branch[len(R_HEADS):]
  359. env = os.environ.copy()
  360. if (env.has_key('TARGET_PRODUCT') and
  361. env.has_key('TARGET_BUILD_VARIANT')):
  362. target = '%s-%s' % (env['TARGET_PRODUCT'],
  363. env['TARGET_BUILD_VARIANT'])
  364. [success, manifest_str] = server.GetApprovedManifest(branch, target)
  365. else:
  366. [success, manifest_str] = server.GetApprovedManifest(branch)
  367. else:
  368. assert(opt.smart_tag)
  369. [success, manifest_str] = server.GetManifest(opt.smart_tag)
  370. if success:
  371. manifest_name = "smart_sync_override.xml"
  372. manifest_path = os.path.join(self.manifest.manifestProject.worktree,
  373. manifest_name)
  374. try:
  375. f = open(manifest_path, 'w')
  376. try:
  377. f.write(manifest_str)
  378. finally:
  379. f.close()
  380. except IOError:
  381. print >>sys.stderr, 'error: cannot write manifest to %s' % \
  382. manifest_path
  383. sys.exit(1)
  384. self.manifest.Override(manifest_name)
  385. else:
  386. print >>sys.stderr, 'error: %s' % manifest_str
  387. sys.exit(1)
  388. except (socket.error, IOError, xmlrpclib.Fault), e:
  389. print >>sys.stderr, 'error: cannot connect to manifest server %s:\n%s' % (
  390. self.manifest.manifest_server, e)
  391. sys.exit(1)
  392. except xmlrpclib.ProtocolError, e:
  393. print >>sys.stderr, 'error: cannot connect to manifest server %s:\n%d %s' % (
  394. self.manifest.manifest_server, e.errcode, e.errmsg)
  395. sys.exit(1)
  396. rp = self.manifest.repoProject
  397. rp.PreSync()
  398. mp = self.manifest.manifestProject
  399. mp.PreSync()
  400. if opt.repo_upgraded:
  401. _PostRepoUpgrade(self.manifest)
  402. if not opt.local_only:
  403. mp.Sync_NetworkHalf(quiet=opt.quiet,
  404. current_branch_only=opt.current_branch_only)
  405. if mp.HasChanges:
  406. syncbuf = SyncBuffer(mp.config)
  407. mp.Sync_LocalHalf(syncbuf)
  408. if not syncbuf.Finish():
  409. sys.exit(1)
  410. self.manifest._Unload()
  411. if opt.jobs is None:
  412. self.jobs = self.manifest.default.sync_j
  413. all = self.GetProjects(args, missing_ok=True)
  414. if not opt.local_only:
  415. to_fetch = []
  416. now = time.time()
  417. if (24 * 60 * 60) <= (now - rp.LastFetch):
  418. to_fetch.append(rp)
  419. to_fetch.extend(all)
  420. fetched = self._Fetch(to_fetch, opt)
  421. _PostRepoFetch(rp, opt.no_repo_verify)
  422. if opt.network_only:
  423. # bail out now; the rest touches the working tree
  424. return
  425. self.manifest._Unload()
  426. all = self.GetProjects(args, missing_ok=True)
  427. missing = []
  428. for project in all:
  429. if project.gitdir not in fetched:
  430. missing.append(project)
  431. self._Fetch(missing, opt)
  432. if self.manifest.IsMirror:
  433. # bail out now, we have no working tree
  434. return
  435. if self.UpdateProjectList():
  436. sys.exit(1)
  437. syncbuf = SyncBuffer(mp.config,
  438. detach_head = opt.detach_head)
  439. pm = Progress('Syncing work tree', len(all))
  440. for project in all:
  441. pm.update()
  442. if project.worktree:
  443. project.Sync_LocalHalf(syncbuf)
  444. pm.end()
  445. print >>sys.stderr
  446. if not syncbuf.Finish():
  447. sys.exit(1)
  448. # If there's a notice that's supposed to print at the end of the sync, print
  449. # it now...
  450. if self.manifest.notice:
  451. print self.manifest.notice
  452. def _PostRepoUpgrade(manifest):
  453. for project in manifest.projects.values():
  454. if project.Exists:
  455. project.PostRepoUpgrade()
  456. def _PostRepoFetch(rp, no_repo_verify=False, verbose=False):
  457. if rp.HasChanges:
  458. print >>sys.stderr, 'info: A new version of repo is available'
  459. print >>sys.stderr, ''
  460. if no_repo_verify or _VerifyTag(rp):
  461. syncbuf = SyncBuffer(rp.config)
  462. rp.Sync_LocalHalf(syncbuf)
  463. if not syncbuf.Finish():
  464. sys.exit(1)
  465. print >>sys.stderr, 'info: Restarting repo with latest version'
  466. raise RepoChangedException(['--repo-upgraded'])
  467. else:
  468. print >>sys.stderr, 'warning: Skipped upgrade to unverified version'
  469. else:
  470. if verbose:
  471. print >>sys.stderr, 'repo version %s is current' % rp.work_git.describe(HEAD)
  472. def _VerifyTag(project):
  473. gpg_dir = os.path.expanduser('~/.repoconfig/gnupg')
  474. if not os.path.exists(gpg_dir):
  475. print >>sys.stderr,\
  476. """warning: GnuPG was not available during last "repo init"
  477. warning: Cannot automatically authenticate repo."""
  478. return True
  479. try:
  480. cur = project.bare_git.describe(project.GetRevisionId())
  481. except GitError:
  482. cur = None
  483. if not cur \
  484. or re.compile(r'^.*-[0-9]{1,}-g[0-9a-f]{1,}$').match(cur):
  485. rev = project.revisionExpr
  486. if rev.startswith(R_HEADS):
  487. rev = rev[len(R_HEADS):]
  488. print >>sys.stderr
  489. print >>sys.stderr,\
  490. "warning: project '%s' branch '%s' is not signed" \
  491. % (project.name, rev)
  492. return False
  493. env = os.environ.copy()
  494. env['GIT_DIR'] = project.gitdir.encode()
  495. env['GNUPGHOME'] = gpg_dir.encode()
  496. cmd = [GIT, 'tag', '-v', cur]
  497. proc = subprocess.Popen(cmd,
  498. stdout = subprocess.PIPE,
  499. stderr = subprocess.PIPE,
  500. env = env)
  501. out = proc.stdout.read()
  502. proc.stdout.close()
  503. err = proc.stderr.read()
  504. proc.stderr.close()
  505. if proc.wait() != 0:
  506. print >>sys.stderr
  507. print >>sys.stderr, out
  508. print >>sys.stderr, err
  509. print >>sys.stderr
  510. return False
  511. return True