sync.py 14 KB

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