sync.py 17 KB

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