sync.py 45 KB

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