sync.py 17 KB

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