sync.py 19 KB

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