sync.py 17 KB

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