sync.py 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082
  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 __future__ import print_function
  16. import json
  17. import netrc
  18. from optparse import SUPPRESS_HELP
  19. import os
  20. import re
  21. import socket
  22. import subprocess
  23. import sys
  24. import tempfile
  25. import time
  26. from pyversion import is_python3
  27. if is_python3():
  28. import http.cookiejar as cookielib
  29. import urllib.error
  30. import urllib.parse
  31. import urllib.request
  32. import xmlrpc.client
  33. else:
  34. import cookielib
  35. import imp
  36. import urllib2
  37. import urlparse
  38. import xmlrpclib
  39. urllib = imp.new_module('urllib')
  40. urllib.error = urllib2
  41. urllib.parse = urlparse
  42. urllib.request = urllib2
  43. xmlrpc = imp.new_module('xmlrpc')
  44. xmlrpc.client = xmlrpclib
  45. try:
  46. import threading as _threading
  47. except ImportError:
  48. import dummy_threading as _threading
  49. try:
  50. import resource
  51. def _rlimit_nofile():
  52. return resource.getrlimit(resource.RLIMIT_NOFILE)
  53. except ImportError:
  54. def _rlimit_nofile():
  55. return (256, 256)
  56. try:
  57. import multiprocessing
  58. except ImportError:
  59. multiprocessing = None
  60. import event_log
  61. from git_command import GIT, git_require
  62. from git_config import GetUrlCookieFile
  63. from git_refs import R_HEADS, HEAD
  64. import gitc_utils
  65. from project import Project
  66. from project import RemoteSpec
  67. from command import Command, MirrorSafeCommand
  68. from error import RepoChangedException, GitError, ManifestParseError
  69. import platform_utils
  70. from project import SyncBuffer
  71. from progress import Progress
  72. from wrapper import Wrapper
  73. from manifest_xml import GitcManifest
  74. _ONE_DAY_S = 24 * 60 * 60
  75. class _FetchError(Exception):
  76. """Internal error thrown in _FetchHelper() when we don't want stack trace."""
  77. pass
  78. class Sync(Command, MirrorSafeCommand):
  79. jobs = 1
  80. common = True
  81. helpSummary = "Update working tree to the latest revision"
  82. helpUsage = """
  83. %prog [<project>...]
  84. """
  85. helpDescription = """
  86. The '%prog' command synchronizes local project directories
  87. with the remote repositories specified in the manifest. If a local
  88. project does not yet exist, it will clone a new local directory from
  89. the remote repository and set up tracking branches as specified in
  90. the manifest. If the local project already exists, '%prog'
  91. will update the remote branches and rebase any new local changes
  92. on top of the new remote changes.
  93. '%prog' will synchronize all projects listed at the command
  94. line. Projects can be specified either by name, or by a relative
  95. or absolute path to the project's local directory. If no projects
  96. are specified, '%prog' will synchronize all projects listed in
  97. the manifest.
  98. The -d/--detach option can be used to switch specified projects
  99. back to the manifest revision. This option is especially helpful
  100. if the project is currently on a topic branch, but the manifest
  101. revision is temporarily needed.
  102. The -s/--smart-sync option can be used to sync to a known good
  103. build as specified by the manifest-server element in the current
  104. manifest. The -t/--smart-tag option is similar and allows you to
  105. specify a custom tag/label.
  106. The -u/--manifest-server-username and -p/--manifest-server-password
  107. options can be used to specify a username and password to authenticate
  108. with the manifest server when using the -s or -t option.
  109. If -u and -p are not specified when using the -s or -t option, '%prog'
  110. will attempt to read authentication credentials for the manifest server
  111. from the user's .netrc file.
  112. '%prog' will not use authentication credentials from -u/-p or .netrc
  113. if the manifest server specified in the manifest file already includes
  114. credentials.
  115. The -f/--force-broken option can be used to proceed with syncing
  116. other projects if a project sync fails.
  117. The --force-sync option can be used to overwrite existing git
  118. directories if they have previously been linked to a different
  119. object direcotry. WARNING: This may cause data to be lost since
  120. refs may be removed when overwriting.
  121. The --no-clone-bundle option disables any attempt to use
  122. $URL/clone.bundle to bootstrap a new Git repository from a
  123. resumeable bundle file on a content delivery network. This
  124. may be necessary if there are problems with the local Python
  125. HTTP client or proxy configuration, but the Git binary works.
  126. The --fetch-submodules option enables fetching Git submodules
  127. of a project from server.
  128. The -c/--current-branch option can be used to only fetch objects that
  129. are on the branch specified by a project's revision.
  130. The --optimized-fetch option can be used to only fetch projects that
  131. are fixed to a sha1 revision if the sha1 revision does not already
  132. exist locally.
  133. The --prune option can be used to remove any refs that no longer
  134. exist on the remote.
  135. SSH Connections
  136. ---------------
  137. If at least one project remote URL uses an SSH connection (ssh://,
  138. git+ssh://, or user@host:path syntax) repo will automatically
  139. enable the SSH ControlMaster option when connecting to that host.
  140. This feature permits other projects in the same '%prog' session to
  141. reuse the same SSH tunnel, saving connection setup overheads.
  142. To disable this behavior on UNIX platforms, set the GIT_SSH
  143. environment variable to 'ssh'. For example:
  144. export GIT_SSH=ssh
  145. %prog
  146. Compatibility
  147. ~~~~~~~~~~~~~
  148. This feature is automatically disabled on Windows, due to the lack
  149. of UNIX domain socket support.
  150. This feature is not compatible with url.insteadof rewrites in the
  151. user's ~/.gitconfig. '%prog' is currently not able to perform the
  152. rewrite early enough to establish the ControlMaster tunnel.
  153. If the remote SSH daemon is Gerrit Code Review, version 2.0.10 or
  154. later is required to fix a server side protocol bug.
  155. """
  156. def _Options(self, p, show_smart=True):
  157. try:
  158. self.jobs = self.manifest.default.sync_j
  159. except ManifestParseError:
  160. self.jobs = 1
  161. p.add_option('-f', '--force-broken',
  162. dest='force_broken', action='store_true',
  163. help="continue sync even if a project fails to sync")
  164. p.add_option('--force-sync',
  165. dest='force_sync', action='store_true',
  166. help="overwrite an existing git directory if it needs to "
  167. "point to a different object directory. WARNING: this "
  168. "may cause loss of data")
  169. p.add_option('-l', '--local-only',
  170. dest='local_only', action='store_true',
  171. help="only update working tree, don't fetch")
  172. p.add_option('-n', '--network-only',
  173. dest='network_only', action='store_true',
  174. help="fetch only, don't update working tree")
  175. p.add_option('-d', '--detach',
  176. dest='detach_head', action='store_true',
  177. help='detach projects back to manifest revision')
  178. p.add_option('-c', '--current-branch',
  179. dest='current_branch_only', action='store_true',
  180. help='fetch only current branch from server')
  181. p.add_option('-q', '--quiet',
  182. dest='quiet', action='store_true',
  183. help='be more quiet')
  184. p.add_option('-j', '--jobs',
  185. dest='jobs', action='store', type='int',
  186. help="projects to fetch simultaneously (default %d)" % self.jobs)
  187. p.add_option('-m', '--manifest-name',
  188. dest='manifest_name',
  189. help='temporary manifest to use for this sync', metavar='NAME.xml')
  190. p.add_option('--no-clone-bundle',
  191. dest='no_clone_bundle', action='store_true',
  192. help='disable use of /clone.bundle on HTTP/HTTPS')
  193. p.add_option('-u', '--manifest-server-username', action='store',
  194. dest='manifest_server_username',
  195. help='username to authenticate with the manifest server')
  196. p.add_option('-p', '--manifest-server-password', action='store',
  197. dest='manifest_server_password',
  198. help='password to authenticate with the manifest server')
  199. p.add_option('--fetch-submodules',
  200. dest='fetch_submodules', action='store_true',
  201. help='fetch submodules from server')
  202. p.add_option('--no-tags',
  203. dest='no_tags', action='store_true',
  204. help="don't fetch tags")
  205. p.add_option('--optimized-fetch',
  206. dest='optimized_fetch', action='store_true',
  207. help='only fetch projects fixed to sha1 if revision does not exist locally')
  208. p.add_option('--prune', dest='prune', action='store_true',
  209. help='delete refs that no longer exist on the remote')
  210. if show_smart:
  211. p.add_option('-s', '--smart-sync',
  212. dest='smart_sync', action='store_true',
  213. help='smart sync using manifest from the latest known good build')
  214. p.add_option('-t', '--smart-tag',
  215. dest='smart_tag', action='store',
  216. help='smart sync using manifest from a known tag')
  217. g = p.add_option_group('repo Version options')
  218. g.add_option('--no-repo-verify',
  219. dest='no_repo_verify', action='store_true',
  220. help='do not verify repo source code')
  221. g.add_option('--repo-upgraded',
  222. dest='repo_upgraded', action='store_true',
  223. help=SUPPRESS_HELP)
  224. def _FetchProjectList(self, opt, projects, sem, *args, **kwargs):
  225. """Main function of the fetch threads when jobs are > 1.
  226. Delegates most of the work to _FetchHelper.
  227. Args:
  228. opt: Program options returned from optparse. See _Options().
  229. projects: Projects to fetch.
  230. sem: We'll release() this semaphore when we exit so that another thread
  231. can be started up.
  232. *args, **kwargs: Remaining arguments to pass to _FetchHelper. See the
  233. _FetchHelper docstring for details.
  234. """
  235. try:
  236. for project in projects:
  237. success = self._FetchHelper(opt, project, *args, **kwargs)
  238. if not success and not opt.force_broken:
  239. break
  240. finally:
  241. sem.release()
  242. def _FetchHelper(self, opt, project, lock, fetched, pm, err_event):
  243. """Fetch git objects for a single project.
  244. Args:
  245. opt: Program options returned from optparse. See _Options().
  246. project: Project object for the project to fetch.
  247. lock: Lock for accessing objects that are shared amongst multiple
  248. _FetchHelper() threads.
  249. fetched: set object that we will add project.gitdir to when we're done
  250. (with our lock held).
  251. pm: Instance of a Project object. We will call pm.update() (with our
  252. lock held).
  253. err_event: We'll set this event in the case of an error (after printing
  254. out info about the error).
  255. Returns:
  256. Whether the fetch was successful.
  257. """
  258. # We'll set to true once we've locked the lock.
  259. did_lock = False
  260. if not opt.quiet:
  261. print('Fetching project %s' % project.name)
  262. # Encapsulate everything in a try/except/finally so that:
  263. # - We always set err_event in the case of an exception.
  264. # - We always make sure we call sem.release().
  265. # - We always make sure we unlock the lock if we locked it.
  266. start = time.time()
  267. success = False
  268. try:
  269. try:
  270. success = project.Sync_NetworkHalf(
  271. quiet=opt.quiet,
  272. current_branch_only=opt.current_branch_only,
  273. force_sync=opt.force_sync,
  274. clone_bundle=not opt.no_clone_bundle,
  275. no_tags=opt.no_tags, archive=self.manifest.IsArchive,
  276. optimized_fetch=opt.optimized_fetch,
  277. prune=opt.prune)
  278. self._fetch_times.Set(project, time.time() - start)
  279. # Lock around all the rest of the code, since printing, updating a set
  280. # and Progress.update() are not thread safe.
  281. lock.acquire()
  282. did_lock = True
  283. if not success:
  284. err_event.set()
  285. print('error: Cannot fetch %s from %s'
  286. % (project.name, project.remote.url),
  287. file=sys.stderr)
  288. if opt.force_broken:
  289. print('warn: --force-broken, continuing to sync',
  290. file=sys.stderr)
  291. else:
  292. raise _FetchError()
  293. fetched.add(project.gitdir)
  294. pm.update()
  295. except _FetchError:
  296. pass
  297. except Exception as e:
  298. print('error: Cannot fetch %s (%s: %s)' \
  299. % (project.name, type(e).__name__, str(e)), file=sys.stderr)
  300. err_event.set()
  301. raise
  302. finally:
  303. if did_lock:
  304. lock.release()
  305. finish = time.time()
  306. self.event_log.AddSync(project, event_log.TASK_SYNC_NETWORK,
  307. start, finish, success)
  308. return success
  309. def _Fetch(self, projects, opt):
  310. fetched = set()
  311. lock = _threading.Lock()
  312. pm = Progress('Fetching projects', len(projects),
  313. print_newline=not(opt.quiet),
  314. always_print_percentage=opt.quiet)
  315. objdir_project_map = dict()
  316. for project in projects:
  317. objdir_project_map.setdefault(project.objdir, []).append(project)
  318. threads = set()
  319. sem = _threading.Semaphore(self.jobs)
  320. err_event = _threading.Event()
  321. for project_list in objdir_project_map.values():
  322. # Check for any errors before running any more tasks.
  323. # ...we'll let existing threads finish, though.
  324. if err_event.isSet() and not opt.force_broken:
  325. break
  326. sem.acquire()
  327. kwargs = dict(opt=opt,
  328. projects=project_list,
  329. sem=sem,
  330. lock=lock,
  331. fetched=fetched,
  332. pm=pm,
  333. err_event=err_event)
  334. if self.jobs > 1:
  335. t = _threading.Thread(target = self._FetchProjectList,
  336. kwargs = kwargs)
  337. # Ensure that Ctrl-C will not freeze the repo process.
  338. t.daemon = True
  339. threads.add(t)
  340. t.start()
  341. else:
  342. self._FetchProjectList(**kwargs)
  343. for t in threads:
  344. t.join()
  345. # If we saw an error, exit with code 1 so that other scripts can check.
  346. if err_event.isSet() and not opt.force_broken:
  347. print('\nerror: Exited sync due to fetch errors', file=sys.stderr)
  348. sys.exit(1)
  349. pm.end()
  350. self._fetch_times.Save()
  351. if not self.manifest.IsArchive:
  352. self._GCProjects(projects)
  353. return fetched
  354. def _GCProjects(self, projects):
  355. gc_gitdirs = {}
  356. for project in projects:
  357. if len(project.manifest.GetProjectsWithName(project.name)) > 1:
  358. print('Shared project %s found, disabling pruning.' % project.name)
  359. project.bare_git.config('--replace-all', 'gc.pruneExpire', 'never')
  360. gc_gitdirs[project.gitdir] = project.bare_git
  361. has_dash_c = git_require((1, 7, 2))
  362. if multiprocessing and has_dash_c:
  363. cpu_count = multiprocessing.cpu_count()
  364. else:
  365. cpu_count = 1
  366. jobs = min(self.jobs, cpu_count)
  367. if jobs < 2:
  368. for bare_git in gc_gitdirs.values():
  369. bare_git.gc('--auto')
  370. return
  371. config = {'pack.threads': cpu_count / jobs if cpu_count > jobs else 1}
  372. threads = set()
  373. sem = _threading.Semaphore(jobs)
  374. err_event = _threading.Event()
  375. def GC(bare_git):
  376. try:
  377. try:
  378. bare_git.gc('--auto', config=config)
  379. except GitError:
  380. err_event.set()
  381. except:
  382. err_event.set()
  383. raise
  384. finally:
  385. sem.release()
  386. for bare_git in gc_gitdirs.values():
  387. if err_event.isSet():
  388. break
  389. sem.acquire()
  390. t = _threading.Thread(target=GC, args=(bare_git,))
  391. t.daemon = True
  392. threads.add(t)
  393. t.start()
  394. for t in threads:
  395. t.join()
  396. if err_event.isSet():
  397. print('\nerror: Exited sync due to gc errors', file=sys.stderr)
  398. sys.exit(1)
  399. def _ReloadManifest(self, manifest_name=None):
  400. if manifest_name:
  401. # Override calls _Unload already
  402. self.manifest.Override(manifest_name)
  403. else:
  404. self.manifest._Unload()
  405. def _DeleteProject(self, path):
  406. print('Deleting obsolete path %s' % path, file=sys.stderr)
  407. # Delete the .git directory first, so we're less likely to have a partially
  408. # working git repository around. There shouldn't be any git projects here,
  409. # so rmtree works.
  410. try:
  411. platform_utils.rmtree(os.path.join(path, '.git'))
  412. except OSError:
  413. print('Failed to remove %s' % os.path.join(path, '.git'), file=sys.stderr)
  414. print('error: Failed to delete obsolete path %s' % path, file=sys.stderr)
  415. print(' remove manually, then run sync again', file=sys.stderr)
  416. return -1
  417. # Delete everything under the worktree, except for directories that contain
  418. # another git project
  419. dirs_to_remove = []
  420. failed = False
  421. for root, dirs, files in os.walk(path):
  422. for f in files:
  423. try:
  424. platform_utils.remove(os.path.join(root, f))
  425. except OSError:
  426. print('Failed to remove %s' % os.path.join(root, f), file=sys.stderr)
  427. failed = True
  428. dirs[:] = [d for d in dirs
  429. if not os.path.lexists(os.path.join(root, d, '.git'))]
  430. dirs_to_remove += [os.path.join(root, d) for d in dirs
  431. if os.path.join(root, d) not in dirs_to_remove]
  432. for d in reversed(dirs_to_remove):
  433. if platform_utils.islink(d):
  434. try:
  435. platform_utils.remove(d)
  436. except OSError:
  437. print('Failed to remove %s' % os.path.join(root, d), file=sys.stderr)
  438. failed = True
  439. elif len(os.listdir(d)) == 0:
  440. try:
  441. os.rmdir(d)
  442. except OSError:
  443. print('Failed to remove %s' % os.path.join(root, d), file=sys.stderr)
  444. failed = True
  445. continue
  446. if failed:
  447. print('error: Failed to delete obsolete path %s' % path, file=sys.stderr)
  448. print(' remove manually, then run sync again', file=sys.stderr)
  449. return -1
  450. # Try deleting parent dirs if they are empty
  451. project_dir = path
  452. while project_dir != self.manifest.topdir:
  453. if len(os.listdir(project_dir)) == 0:
  454. os.rmdir(project_dir)
  455. else:
  456. break
  457. project_dir = os.path.dirname(project_dir)
  458. return 0
  459. def UpdateProjectList(self):
  460. new_project_paths = []
  461. for project in self.GetProjects(None, missing_ok=True):
  462. if project.relpath:
  463. new_project_paths.append(project.relpath)
  464. file_name = 'project.list'
  465. file_path = os.path.join(self.manifest.repodir, file_name)
  466. old_project_paths = []
  467. if os.path.exists(file_path):
  468. fd = open(file_path, 'r')
  469. try:
  470. old_project_paths = fd.read().split('\n')
  471. finally:
  472. fd.close()
  473. for path in old_project_paths:
  474. if not path:
  475. continue
  476. if path not in new_project_paths:
  477. # If the path has already been deleted, we don't need to do it
  478. gitdir = os.path.join(self.manifest.topdir, path, '.git')
  479. if os.path.exists(gitdir):
  480. project = Project(
  481. manifest = self.manifest,
  482. name = path,
  483. remote = RemoteSpec('origin'),
  484. gitdir = gitdir,
  485. objdir = gitdir,
  486. worktree = os.path.join(self.manifest.topdir, path),
  487. relpath = path,
  488. revisionExpr = 'HEAD',
  489. revisionId = None,
  490. groups = None)
  491. if project.IsDirty():
  492. print('error: Cannot remove project "%s": uncommitted changes '
  493. 'are present' % project.relpath, file=sys.stderr)
  494. print(' commit changes, then run sync again',
  495. file=sys.stderr)
  496. return -1
  497. elif self._DeleteProject(project.worktree):
  498. return -1
  499. new_project_paths.sort()
  500. fd = open(file_path, 'w')
  501. try:
  502. fd.write('\n'.join(new_project_paths))
  503. fd.write('\n')
  504. finally:
  505. fd.close()
  506. return 0
  507. def Execute(self, opt, args):
  508. if opt.jobs:
  509. self.jobs = opt.jobs
  510. if self.jobs > 1:
  511. soft_limit, _ = _rlimit_nofile()
  512. self.jobs = min(self.jobs, (soft_limit - 5) / 3)
  513. if opt.network_only and opt.detach_head:
  514. print('error: cannot combine -n and -d', file=sys.stderr)
  515. sys.exit(1)
  516. if opt.network_only and opt.local_only:
  517. print('error: cannot combine -n and -l', file=sys.stderr)
  518. sys.exit(1)
  519. if opt.manifest_name and opt.smart_sync:
  520. print('error: cannot combine -m and -s', file=sys.stderr)
  521. sys.exit(1)
  522. if opt.manifest_name and opt.smart_tag:
  523. print('error: cannot combine -m and -t', file=sys.stderr)
  524. sys.exit(1)
  525. if opt.manifest_server_username or opt.manifest_server_password:
  526. if not (opt.smart_sync or opt.smart_tag):
  527. print('error: -u and -p may only be combined with -s or -t',
  528. file=sys.stderr)
  529. sys.exit(1)
  530. if None in [opt.manifest_server_username, opt.manifest_server_password]:
  531. print('error: both -u and -p must be given', file=sys.stderr)
  532. sys.exit(1)
  533. if opt.manifest_name:
  534. self.manifest.Override(opt.manifest_name)
  535. manifest_name = opt.manifest_name
  536. smart_sync_manifest_name = "smart_sync_override.xml"
  537. smart_sync_manifest_path = os.path.join(
  538. self.manifest.manifestProject.worktree, smart_sync_manifest_name)
  539. if opt.smart_sync or opt.smart_tag:
  540. if not self.manifest.manifest_server:
  541. print('error: cannot smart sync: no manifest server defined in '
  542. 'manifest', file=sys.stderr)
  543. sys.exit(1)
  544. manifest_server = self.manifest.manifest_server
  545. if not opt.quiet:
  546. print('Using manifest server %s' % manifest_server)
  547. if not '@' in manifest_server:
  548. username = None
  549. password = None
  550. if opt.manifest_server_username and opt.manifest_server_password:
  551. username = opt.manifest_server_username
  552. password = opt.manifest_server_password
  553. else:
  554. try:
  555. info = netrc.netrc()
  556. except IOError:
  557. # .netrc file does not exist or could not be opened
  558. pass
  559. else:
  560. try:
  561. parse_result = urllib.parse.urlparse(manifest_server)
  562. if parse_result.hostname:
  563. auth = info.authenticators(parse_result.hostname)
  564. if auth:
  565. username, _account, password = auth
  566. else:
  567. print('No credentials found for %s in .netrc'
  568. % parse_result.hostname, file=sys.stderr)
  569. except netrc.NetrcParseError as e:
  570. print('Error parsing .netrc file: %s' % e, file=sys.stderr)
  571. if (username and password):
  572. manifest_server = manifest_server.replace('://', '://%s:%s@' %
  573. (username, password),
  574. 1)
  575. transport = PersistentTransport(manifest_server)
  576. if manifest_server.startswith('persistent-'):
  577. manifest_server = manifest_server[len('persistent-'):]
  578. try:
  579. server = xmlrpc.client.Server(manifest_server, transport=transport)
  580. if opt.smart_sync:
  581. p = self.manifest.manifestProject
  582. b = p.GetBranch(p.CurrentBranch)
  583. branch = b.merge
  584. if branch.startswith(R_HEADS):
  585. branch = branch[len(R_HEADS):]
  586. env = os.environ.copy()
  587. if 'SYNC_TARGET' in env:
  588. target = env['SYNC_TARGET']
  589. [success, manifest_str] = server.GetApprovedManifest(branch, target)
  590. elif 'TARGET_PRODUCT' in env and 'TARGET_BUILD_VARIANT' in env:
  591. target = '%s-%s' % (env['TARGET_PRODUCT'],
  592. env['TARGET_BUILD_VARIANT'])
  593. [success, manifest_str] = server.GetApprovedManifest(branch, target)
  594. else:
  595. [success, manifest_str] = server.GetApprovedManifest(branch)
  596. else:
  597. assert(opt.smart_tag)
  598. [success, manifest_str] = server.GetManifest(opt.smart_tag)
  599. if success:
  600. manifest_name = smart_sync_manifest_name
  601. try:
  602. f = open(smart_sync_manifest_path, 'w')
  603. try:
  604. f.write(manifest_str)
  605. finally:
  606. f.close()
  607. except IOError as e:
  608. print('error: cannot write manifest to %s:\n%s'
  609. % (smart_sync_manifest_path, e),
  610. file=sys.stderr)
  611. sys.exit(1)
  612. self._ReloadManifest(manifest_name)
  613. else:
  614. print('error: manifest server RPC call failed: %s' %
  615. manifest_str, file=sys.stderr)
  616. sys.exit(1)
  617. except (socket.error, IOError, xmlrpc.client.Fault) as e:
  618. print('error: cannot connect to manifest server %s:\n%s'
  619. % (self.manifest.manifest_server, e), file=sys.stderr)
  620. sys.exit(1)
  621. except xmlrpc.client.ProtocolError as e:
  622. print('error: cannot connect to manifest server %s:\n%d %s'
  623. % (self.manifest.manifest_server, e.errcode, e.errmsg),
  624. file=sys.stderr)
  625. sys.exit(1)
  626. else: # Not smart sync or smart tag mode
  627. if os.path.isfile(smart_sync_manifest_path):
  628. try:
  629. platform_utils.remove(smart_sync_manifest_path)
  630. except OSError as e:
  631. print('error: failed to remove existing smart sync override manifest: %s' %
  632. e, file=sys.stderr)
  633. rp = self.manifest.repoProject
  634. rp.PreSync()
  635. mp = self.manifest.manifestProject
  636. mp.PreSync()
  637. if opt.repo_upgraded:
  638. _PostRepoUpgrade(self.manifest, quiet=opt.quiet)
  639. if not opt.local_only:
  640. start = time.time()
  641. success = mp.Sync_NetworkHalf(quiet=opt.quiet,
  642. current_branch_only=opt.current_branch_only,
  643. no_tags=opt.no_tags,
  644. optimized_fetch=opt.optimized_fetch,
  645. submodules=self.manifest.HasSubmodules)
  646. finish = time.time()
  647. self.event_log.AddSync(mp, event_log.TASK_SYNC_NETWORK,
  648. start, finish, success)
  649. if mp.HasChanges:
  650. syncbuf = SyncBuffer(mp.config)
  651. start = time.time()
  652. mp.Sync_LocalHalf(syncbuf, submodules=self.manifest.HasSubmodules)
  653. clean = syncbuf.Finish()
  654. self.event_log.AddSync(mp, event_log.TASK_SYNC_LOCAL,
  655. start, time.time(), clean)
  656. if not clean:
  657. sys.exit(1)
  658. self._ReloadManifest(manifest_name)
  659. if opt.jobs is None:
  660. self.jobs = self.manifest.default.sync_j
  661. if self.gitc_manifest:
  662. gitc_manifest_projects = self.GetProjects(args,
  663. missing_ok=True)
  664. gitc_projects = []
  665. opened_projects = []
  666. for project in gitc_manifest_projects:
  667. if project.relpath in self.gitc_manifest.paths and \
  668. self.gitc_manifest.paths[project.relpath].old_revision:
  669. opened_projects.append(project.relpath)
  670. else:
  671. gitc_projects.append(project.relpath)
  672. if not args:
  673. gitc_projects = None
  674. if gitc_projects != [] and not opt.local_only:
  675. print('Updating GITC client: %s' % self.gitc_manifest.gitc_client_name)
  676. manifest = GitcManifest(self.repodir, self.gitc_manifest.gitc_client_name)
  677. if manifest_name:
  678. manifest.Override(manifest_name)
  679. else:
  680. manifest.Override(self.manifest.manifestFile)
  681. gitc_utils.generate_gitc_manifest(self.gitc_manifest,
  682. manifest,
  683. gitc_projects)
  684. print('GITC client successfully synced.')
  685. # The opened projects need to be synced as normal, therefore we
  686. # generate a new args list to represent the opened projects.
  687. # TODO: make this more reliable -- if there's a project name/path overlap,
  688. # this may choose the wrong project.
  689. args = [os.path.relpath(self.manifest.paths[path].worktree, os.getcwd())
  690. for path in opened_projects]
  691. if not args:
  692. return
  693. all_projects = self.GetProjects(args,
  694. missing_ok=True,
  695. submodules_ok=opt.fetch_submodules)
  696. self._fetch_times = _FetchTimes(self.manifest)
  697. if not opt.local_only:
  698. to_fetch = []
  699. now = time.time()
  700. if _ONE_DAY_S <= (now - rp.LastFetch):
  701. to_fetch.append(rp)
  702. to_fetch.extend(all_projects)
  703. to_fetch.sort(key=self._fetch_times.Get, reverse=True)
  704. fetched = self._Fetch(to_fetch, opt)
  705. _PostRepoFetch(rp, opt.no_repo_verify)
  706. if opt.network_only:
  707. # bail out now; the rest touches the working tree
  708. return
  709. # Iteratively fetch missing and/or nested unregistered submodules
  710. previously_missing_set = set()
  711. while True:
  712. self._ReloadManifest(manifest_name)
  713. all_projects = self.GetProjects(args,
  714. missing_ok=True,
  715. submodules_ok=opt.fetch_submodules)
  716. missing = []
  717. for project in all_projects:
  718. if project.gitdir not in fetched:
  719. missing.append(project)
  720. if not missing:
  721. break
  722. # Stop us from non-stopped fetching actually-missing repos: If set of
  723. # missing repos has not been changed from last fetch, we break.
  724. missing_set = set(p.name for p in missing)
  725. if previously_missing_set == missing_set:
  726. break
  727. previously_missing_set = missing_set
  728. fetched.update(self._Fetch(missing, opt))
  729. if self.manifest.IsMirror or self.manifest.IsArchive:
  730. # bail out now, we have no working tree
  731. return
  732. if self.UpdateProjectList():
  733. sys.exit(1)
  734. syncbuf = SyncBuffer(mp.config,
  735. detach_head = opt.detach_head)
  736. pm = Progress('Syncing work tree', len(all_projects))
  737. for project in all_projects:
  738. pm.update()
  739. if project.worktree:
  740. start = time.time()
  741. project.Sync_LocalHalf(syncbuf, force_sync=opt.force_sync)
  742. self.event_log.AddSync(project, event_log.TASK_SYNC_LOCAL,
  743. start, time.time(), syncbuf.Recently())
  744. pm.end()
  745. print(file=sys.stderr)
  746. if not syncbuf.Finish():
  747. sys.exit(1)
  748. # If there's a notice that's supposed to print at the end of the sync, print
  749. # it now...
  750. if self.manifest.notice:
  751. print(self.manifest.notice)
  752. def _PostRepoUpgrade(manifest, quiet=False):
  753. wrapper = Wrapper()
  754. if wrapper.NeedSetupGnuPG():
  755. wrapper.SetupGnuPG(quiet)
  756. for project in manifest.projects:
  757. if project.Exists:
  758. project.PostRepoUpgrade()
  759. def _PostRepoFetch(rp, no_repo_verify=False, verbose=False):
  760. if rp.HasChanges:
  761. print('info: A new version of repo is available', file=sys.stderr)
  762. print(file=sys.stderr)
  763. if no_repo_verify or _VerifyTag(rp):
  764. syncbuf = SyncBuffer(rp.config)
  765. rp.Sync_LocalHalf(syncbuf)
  766. if not syncbuf.Finish():
  767. sys.exit(1)
  768. print('info: Restarting repo with latest version', file=sys.stderr)
  769. raise RepoChangedException(['--repo-upgraded'])
  770. else:
  771. print('warning: Skipped upgrade to unverified version', file=sys.stderr)
  772. else:
  773. if verbose:
  774. print('repo version %s is current' % rp.work_git.describe(HEAD),
  775. file=sys.stderr)
  776. def _VerifyTag(project):
  777. gpg_dir = os.path.expanduser('~/.repoconfig/gnupg')
  778. if not os.path.exists(gpg_dir):
  779. print('warning: GnuPG was not available during last "repo init"\n'
  780. 'warning: Cannot automatically authenticate repo."""',
  781. file=sys.stderr)
  782. return True
  783. try:
  784. cur = project.bare_git.describe(project.GetRevisionId())
  785. except GitError:
  786. cur = None
  787. if not cur \
  788. or re.compile(r'^.*-[0-9]{1,}-g[0-9a-f]{1,}$').match(cur):
  789. rev = project.revisionExpr
  790. if rev.startswith(R_HEADS):
  791. rev = rev[len(R_HEADS):]
  792. print(file=sys.stderr)
  793. print("warning: project '%s' branch '%s' is not signed"
  794. % (project.name, rev), file=sys.stderr)
  795. return False
  796. env = os.environ.copy()
  797. env['GIT_DIR'] = project.gitdir.encode()
  798. env['GNUPGHOME'] = gpg_dir.encode()
  799. cmd = [GIT, 'tag', '-v', cur]
  800. proc = subprocess.Popen(cmd,
  801. stdout = subprocess.PIPE,
  802. stderr = subprocess.PIPE,
  803. env = env)
  804. out = proc.stdout.read()
  805. proc.stdout.close()
  806. err = proc.stderr.read()
  807. proc.stderr.close()
  808. if proc.wait() != 0:
  809. print(file=sys.stderr)
  810. print(out, file=sys.stderr)
  811. print(err, file=sys.stderr)
  812. print(file=sys.stderr)
  813. return False
  814. return True
  815. class _FetchTimes(object):
  816. _ALPHA = 0.5
  817. def __init__(self, manifest):
  818. self._path = os.path.join(manifest.repodir, '.repo_fetchtimes.json')
  819. self._times = None
  820. self._seen = set()
  821. def Get(self, project):
  822. self._Load()
  823. return self._times.get(project.name, _ONE_DAY_S)
  824. def Set(self, project, t):
  825. self._Load()
  826. name = project.name
  827. old = self._times.get(name, t)
  828. self._seen.add(name)
  829. a = self._ALPHA
  830. self._times[name] = (a*t) + ((1-a) * old)
  831. def _Load(self):
  832. if self._times is None:
  833. try:
  834. f = open(self._path)
  835. try:
  836. self._times = json.load(f)
  837. finally:
  838. f.close()
  839. except (IOError, ValueError):
  840. try:
  841. platform_utils.remove(self._path)
  842. except OSError:
  843. pass
  844. self._times = {}
  845. def Save(self):
  846. if self._times is None:
  847. return
  848. to_delete = []
  849. for name in self._times:
  850. if name not in self._seen:
  851. to_delete.append(name)
  852. for name in to_delete:
  853. del self._times[name]
  854. try:
  855. f = open(self._path, 'w')
  856. try:
  857. json.dump(self._times, f, indent=2)
  858. finally:
  859. f.close()
  860. except (IOError, TypeError):
  861. try:
  862. platform_utils.remove(self._path)
  863. except OSError:
  864. pass
  865. # This is a replacement for xmlrpc.client.Transport using urllib2
  866. # and supporting persistent-http[s]. It cannot change hosts from
  867. # request to request like the normal transport, the real url
  868. # is passed during initialization.
  869. class PersistentTransport(xmlrpc.client.Transport):
  870. def __init__(self, orig_host):
  871. self.orig_host = orig_host
  872. def request(self, host, handler, request_body, verbose=False):
  873. with GetUrlCookieFile(self.orig_host, not verbose) as (cookiefile, proxy):
  874. # Python doesn't understand cookies with the #HttpOnly_ prefix
  875. # Since we're only using them for HTTP, copy the file temporarily,
  876. # stripping those prefixes away.
  877. if cookiefile:
  878. tmpcookiefile = tempfile.NamedTemporaryFile()
  879. tmpcookiefile.write("# HTTP Cookie File")
  880. try:
  881. with open(cookiefile) as f:
  882. for line in f:
  883. if line.startswith("#HttpOnly_"):
  884. line = line[len("#HttpOnly_"):]
  885. tmpcookiefile.write(line)
  886. tmpcookiefile.flush()
  887. cookiejar = cookielib.MozillaCookieJar(tmpcookiefile.name)
  888. try:
  889. cookiejar.load()
  890. except cookielib.LoadError:
  891. cookiejar = cookielib.CookieJar()
  892. finally:
  893. tmpcookiefile.close()
  894. else:
  895. cookiejar = cookielib.CookieJar()
  896. proxyhandler = urllib.request.ProxyHandler
  897. if proxy:
  898. proxyhandler = urllib.request.ProxyHandler({
  899. "http": proxy,
  900. "https": proxy })
  901. opener = urllib.request.build_opener(
  902. urllib.request.HTTPCookieProcessor(cookiejar),
  903. proxyhandler)
  904. url = urllib.parse.urljoin(self.orig_host, handler)
  905. parse_results = urllib.parse.urlparse(url)
  906. scheme = parse_results.scheme
  907. if scheme == 'persistent-http':
  908. scheme = 'http'
  909. if scheme == 'persistent-https':
  910. # If we're proxying through persistent-https, use http. The
  911. # proxy itself will do the https.
  912. if proxy:
  913. scheme = 'http'
  914. else:
  915. scheme = 'https'
  916. # Parse out any authentication information using the base class
  917. host, extra_headers, _ = self.get_host_info(parse_results.netloc)
  918. url = urllib.parse.urlunparse((
  919. scheme,
  920. host,
  921. parse_results.path,
  922. parse_results.params,
  923. parse_results.query,
  924. parse_results.fragment))
  925. request = urllib.request.Request(url, request_body)
  926. if extra_headers is not None:
  927. for (name, header) in extra_headers:
  928. request.add_header(name, header)
  929. request.add_header('Content-Type', 'text/xml')
  930. try:
  931. response = opener.open(request)
  932. except urllib.error.HTTPError as e:
  933. if e.code == 501:
  934. # We may have been redirected through a login process
  935. # but our POST turned into a GET. Retry.
  936. response = opener.open(request)
  937. else:
  938. raise
  939. p, u = xmlrpc.client.getparser()
  940. while 1:
  941. data = response.read(1024)
  942. if not data:
  943. break
  944. p.feed(data)
  945. p.close()
  946. return u.close()
  947. def close(self):
  948. pass