sync.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  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
  37. from project import HEAD
  38. from project import Project
  39. from project import RemoteSpec
  40. from command import Command, MirrorSafeCommand
  41. from error import RepoChangedException, GitError
  42. from project import R_HEADS
  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(quiet=opt.quiet,
  203. current_branch_only=opt.current_branch_only):
  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. threads.add(t)
  231. t.start()
  232. for t in threads:
  233. t.join()
  234. # If we saw an error, exit with code 1 so that other scripts can check.
  235. if err_event.isSet():
  236. print >>sys.stderr, '\nerror: Exited sync due to fetch errors'
  237. sys.exit(1)
  238. pm.end()
  239. for project in projects:
  240. project.bare_git.gc('--auto')
  241. return fetched
  242. def UpdateProjectList(self):
  243. new_project_paths = []
  244. for project in self.GetProjects(None, missing_ok=True):
  245. if project.relpath:
  246. new_project_paths.append(project.relpath)
  247. file_name = 'project.list'
  248. file_path = os.path.join(self.manifest.repodir, file_name)
  249. old_project_paths = []
  250. if os.path.exists(file_path):
  251. fd = open(file_path, 'r')
  252. try:
  253. old_project_paths = fd.read().split('\n')
  254. finally:
  255. fd.close()
  256. for path in old_project_paths:
  257. if not path:
  258. continue
  259. if path not in new_project_paths:
  260. """If the path has already been deleted, we don't need to do it
  261. """
  262. if os.path.exists(self.manifest.topdir + '/' + path):
  263. project = Project(
  264. manifest = self.manifest,
  265. name = path,
  266. remote = RemoteSpec('origin'),
  267. gitdir = os.path.join(self.manifest.topdir,
  268. path, '.git'),
  269. worktree = os.path.join(self.manifest.topdir, path),
  270. relpath = path,
  271. revisionExpr = 'HEAD',
  272. revisionId = None,
  273. groups = None)
  274. if project.IsDirty():
  275. print >>sys.stderr, 'error: Cannot remove project "%s": \
  276. uncommitted changes are present' % project.relpath
  277. print >>sys.stderr, ' commit changes, then run sync again'
  278. return -1
  279. else:
  280. print >>sys.stderr, 'Deleting obsolete path %s' % project.worktree
  281. shutil.rmtree(project.worktree)
  282. # Try deleting parent subdirs if they are empty
  283. dir = os.path.dirname(project.worktree)
  284. while dir != self.manifest.topdir:
  285. try:
  286. os.rmdir(dir)
  287. except OSError:
  288. break
  289. dir = os.path.dirname(dir)
  290. new_project_paths.sort()
  291. fd = open(file_path, 'w')
  292. try:
  293. fd.write('\n'.join(new_project_paths))
  294. fd.write('\n')
  295. finally:
  296. fd.close()
  297. return 0
  298. def Execute(self, opt, args):
  299. if opt.jobs:
  300. self.jobs = opt.jobs
  301. if self.jobs > 1:
  302. soft_limit, _ = _rlimit_nofile()
  303. self.jobs = min(self.jobs, (soft_limit - 5) / 3)
  304. if opt.network_only and opt.detach_head:
  305. print >>sys.stderr, 'error: cannot combine -n and -d'
  306. sys.exit(1)
  307. if opt.network_only and opt.local_only:
  308. print >>sys.stderr, 'error: cannot combine -n and -l'
  309. sys.exit(1)
  310. if opt.manifest_name and opt.smart_sync:
  311. print >>sys.stderr, 'error: cannot combine -m and -s'
  312. sys.exit(1)
  313. if opt.manifest_name and opt.smart_tag:
  314. print >>sys.stderr, 'error: cannot combine -m and -t'
  315. sys.exit(1)
  316. if opt.manifest_name:
  317. self.manifest.Override(opt.manifest_name)
  318. if opt.smart_sync or opt.smart_tag:
  319. if not self.manifest.manifest_server:
  320. print >>sys.stderr, \
  321. 'error: cannot smart sync: no manifest server defined in manifest'
  322. sys.exit(1)
  323. try:
  324. server = xmlrpclib.Server(self.manifest.manifest_server)
  325. if opt.smart_sync:
  326. p = self.manifest.manifestProject
  327. b = p.GetBranch(p.CurrentBranch)
  328. branch = b.merge
  329. if branch.startswith(R_HEADS):
  330. branch = branch[len(R_HEADS):]
  331. env = os.environ.copy()
  332. if (env.has_key('TARGET_PRODUCT') and
  333. env.has_key('TARGET_BUILD_VARIANT')):
  334. target = '%s-%s' % (env['TARGET_PRODUCT'],
  335. env['TARGET_BUILD_VARIANT'])
  336. [success, manifest_str] = server.GetApprovedManifest(branch, target)
  337. else:
  338. [success, manifest_str] = server.GetApprovedManifest(branch)
  339. else:
  340. assert(opt.smart_tag)
  341. [success, manifest_str] = server.GetManifest(opt.smart_tag)
  342. if success:
  343. manifest_name = "smart_sync_override.xml"
  344. manifest_path = os.path.join(self.manifest.manifestProject.worktree,
  345. manifest_name)
  346. try:
  347. f = open(manifest_path, 'w')
  348. try:
  349. f.write(manifest_str)
  350. finally:
  351. f.close()
  352. except IOError:
  353. print >>sys.stderr, 'error: cannot write manifest to %s' % \
  354. manifest_path
  355. sys.exit(1)
  356. self.manifest.Override(manifest_name)
  357. else:
  358. print >>sys.stderr, 'error: %s' % manifest_str
  359. sys.exit(1)
  360. except socket.error:
  361. print >>sys.stderr, 'error: cannot connect to manifest server %s' % (
  362. self.manifest.manifest_server)
  363. sys.exit(1)
  364. rp = self.manifest.repoProject
  365. rp.PreSync()
  366. mp = self.manifest.manifestProject
  367. mp.PreSync()
  368. if opt.repo_upgraded:
  369. _PostRepoUpgrade(self.manifest)
  370. if not opt.local_only:
  371. mp.Sync_NetworkHalf(quiet=opt.quiet,
  372. current_branch_only=opt.current_branch_only)
  373. if mp.HasChanges:
  374. syncbuf = SyncBuffer(mp.config)
  375. mp.Sync_LocalHalf(syncbuf)
  376. if not syncbuf.Finish():
  377. sys.exit(1)
  378. self.manifest._Unload()
  379. if opt.jobs is None:
  380. self.jobs = self.manifest.default.sync_j
  381. all = self.GetProjects(args, missing_ok=True)
  382. if not opt.local_only:
  383. to_fetch = []
  384. now = time.time()
  385. if (24 * 60 * 60) <= (now - rp.LastFetch):
  386. to_fetch.append(rp)
  387. to_fetch.extend(all)
  388. fetched = self._Fetch(to_fetch, opt)
  389. _PostRepoFetch(rp, opt.no_repo_verify)
  390. if opt.network_only:
  391. # bail out now; the rest touches the working tree
  392. return
  393. self.manifest._Unload()
  394. all = self.GetProjects(args, missing_ok=True)
  395. missing = []
  396. for project in all:
  397. if project.gitdir not in fetched:
  398. missing.append(project)
  399. self._Fetch(missing, opt)
  400. if self.manifest.IsMirror:
  401. # bail out now, we have no working tree
  402. return
  403. if self.UpdateProjectList():
  404. sys.exit(1)
  405. syncbuf = SyncBuffer(mp.config,
  406. detach_head = opt.detach_head)
  407. pm = Progress('Syncing work tree', len(all))
  408. for project in all:
  409. pm.update()
  410. if project.worktree:
  411. project.Sync_LocalHalf(syncbuf)
  412. pm.end()
  413. print >>sys.stderr
  414. if not syncbuf.Finish():
  415. sys.exit(1)
  416. # If there's a notice that's supposed to print at the end of the sync, print
  417. # it now...
  418. if self.manifest.notice:
  419. print self.manifest.notice
  420. def _PostRepoUpgrade(manifest):
  421. for project in manifest.projects.values():
  422. if project.Exists:
  423. project.PostRepoUpgrade()
  424. def _PostRepoFetch(rp, no_repo_verify=False, verbose=False):
  425. if rp.HasChanges:
  426. print >>sys.stderr, 'info: A new version of repo is available'
  427. print >>sys.stderr, ''
  428. if no_repo_verify or _VerifyTag(rp):
  429. syncbuf = SyncBuffer(rp.config)
  430. rp.Sync_LocalHalf(syncbuf)
  431. if not syncbuf.Finish():
  432. sys.exit(1)
  433. print >>sys.stderr, 'info: Restarting repo with latest version'
  434. raise RepoChangedException(['--repo-upgraded'])
  435. else:
  436. print >>sys.stderr, 'warning: Skipped upgrade to unverified version'
  437. else:
  438. if verbose:
  439. print >>sys.stderr, 'repo version %s is current' % rp.work_git.describe(HEAD)
  440. def _VerifyTag(project):
  441. gpg_dir = os.path.expanduser('~/.repoconfig/gnupg')
  442. if not os.path.exists(gpg_dir):
  443. print >>sys.stderr,\
  444. """warning: GnuPG was not available during last "repo init"
  445. warning: Cannot automatically authenticate repo."""
  446. return True
  447. try:
  448. cur = project.bare_git.describe(project.GetRevisionId())
  449. except GitError:
  450. cur = None
  451. if not cur \
  452. or re.compile(r'^.*-[0-9]{1,}-g[0-9a-f]{1,}$').match(cur):
  453. rev = project.revisionExpr
  454. if rev.startswith(R_HEADS):
  455. rev = rev[len(R_HEADS):]
  456. print >>sys.stderr
  457. print >>sys.stderr,\
  458. "warning: project '%s' branch '%s' is not signed" \
  459. % (project.name, rev)
  460. return False
  461. env = os.environ.copy()
  462. env['GIT_DIR'] = project.gitdir.encode()
  463. env['GNUPGHOME'] = gpg_dir.encode()
  464. cmd = [GIT, 'tag', '-v', cur]
  465. proc = subprocess.Popen(cmd,
  466. stdout = subprocess.PIPE,
  467. stderr = subprocess.PIPE,
  468. env = env)
  469. out = proc.stdout.read()
  470. proc.stdout.close()
  471. err = proc.stderr.read()
  472. proc.stderr.close()
  473. if proc.wait() != 0:
  474. print >>sys.stderr
  475. print >>sys.stderr, out
  476. print >>sys.stderr, err
  477. print >>sys.stderr
  478. return False
  479. return True