sync.py 13 KB

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