gclient_utils.py 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309
  1. # Copyright (c) 2012 The Chromium Authors. All rights reserved.
  2. # Use of this source code is governed by a BSD-style license that can be
  3. # found in the LICENSE file.
  4. """Generic utils."""
  5. from __future__ import print_function
  6. import codecs
  7. import collections
  8. import contextlib
  9. import datetime
  10. import errno
  11. import functools
  12. import io
  13. import logging
  14. import operator
  15. import os
  16. import pipes
  17. import platform
  18. import re
  19. import stat
  20. import subprocess
  21. import sys
  22. import tempfile
  23. import threading
  24. import time
  25. import subprocess2
  26. if sys.version_info.major == 2:
  27. from cStringIO import StringIO
  28. import collections as collections_abc
  29. import Queue as queue
  30. import urlparse
  31. else:
  32. from collections import abc as collections_abc
  33. from io import StringIO
  34. import queue
  35. import urllib.parse as urlparse
  36. RETRY_MAX = 3
  37. RETRY_INITIAL_SLEEP = 0.5
  38. START = datetime.datetime.now()
  39. _WARNINGS = []
  40. # These repos are known to cause OOM errors on 32-bit platforms, due the the
  41. # very large objects they contain. It is not safe to use threaded index-pack
  42. # when cloning/fetching them.
  43. THREADED_INDEX_PACK_BLOCKLIST = [
  44. 'https://chromium.googlesource.com/chromium/reference_builds/chrome_win.git'
  45. ]
  46. """To support rethrowing exceptions with tracebacks on both Py2 and 3."""
  47. if sys.version_info.major == 2:
  48. # We have to use exec to avoid a SyntaxError in Python 3.
  49. exec("def reraise(typ, value, tb=None):\n raise typ, value, tb\n")
  50. else:
  51. def reraise(typ, value, tb=None):
  52. if value is None:
  53. value = typ()
  54. if value.__traceback__ is not tb:
  55. raise value.with_traceback(tb)
  56. raise value
  57. class Error(Exception):
  58. """gclient exception class."""
  59. def __init__(self, msg, *args, **kwargs):
  60. index = getattr(threading.currentThread(), 'index', 0)
  61. if index:
  62. msg = '\n'.join('%d> %s' % (index, l) for l in msg.splitlines())
  63. super(Error, self).__init__(msg, *args, **kwargs)
  64. def Elapsed(until=None):
  65. if until is None:
  66. until = datetime.datetime.now()
  67. return str(until - START).partition('.')[0]
  68. def PrintWarnings():
  69. """Prints any accumulated warnings."""
  70. if _WARNINGS:
  71. print('\n\nWarnings:', file=sys.stderr)
  72. for warning in _WARNINGS:
  73. print(warning, file=sys.stderr)
  74. def AddWarning(msg):
  75. """Adds the given warning message to the list of accumulated warnings."""
  76. _WARNINGS.append(msg)
  77. def SplitUrlRevision(url):
  78. """Splits url and returns a two-tuple: url, rev"""
  79. if url.startswith('ssh:'):
  80. # Make sure ssh://user-name@example.com/~/test.git@stable works
  81. regex = r'(ssh://(?:[-.\w]+@)?[-\w:\.]+/[-~\w\./]+)(?:@(.+))?'
  82. components = re.search(regex, url).groups()
  83. else:
  84. components = url.rsplit('@', 1)
  85. if re.match(r'^\w+\@', url) and '@' not in components[0]:
  86. components = [url]
  87. if len(components) == 1:
  88. components += [None]
  89. return tuple(components)
  90. def IsGitSha(revision):
  91. """Returns true if the given string is a valid hex-encoded sha"""
  92. return re.match('^[a-fA-F0-9]{6,40}$', revision) is not None
  93. def IsFullGitSha(revision):
  94. """Returns true if the given string is a valid hex-encoded full sha"""
  95. return re.match('^[a-fA-F0-9]{40}$', revision) is not None
  96. def IsDateRevision(revision):
  97. """Returns true if the given revision is of the form "{ ... }"."""
  98. return bool(revision and re.match(r'^\{.+\}$', str(revision)))
  99. def MakeDateRevision(date):
  100. """Returns a revision representing the latest revision before the given
  101. date."""
  102. return "{" + date + "}"
  103. def SyntaxErrorToError(filename, e):
  104. """Raises a gclient_utils.Error exception with the human readable message"""
  105. try:
  106. # Try to construct a human readable error message
  107. if filename:
  108. error_message = 'There is a syntax error in %s\n' % filename
  109. else:
  110. error_message = 'There is a syntax error\n'
  111. error_message += 'Line #%s, character %s: "%s"' % (
  112. e.lineno, e.offset, re.sub(r'[\r\n]*$', '', e.text))
  113. except:
  114. # Something went wrong, re-raise the original exception
  115. raise e
  116. else:
  117. raise Error(error_message)
  118. class PrintableObject(object):
  119. def __str__(self):
  120. output = ''
  121. for i in dir(self):
  122. if i.startswith('__'):
  123. continue
  124. output += '%s = %s\n' % (i, str(getattr(self, i, '')))
  125. return output
  126. def AskForData(message):
  127. # Try to load the readline module, so that "elaborate line editing" features
  128. # such as backspace work for `raw_input` / `input`.
  129. try:
  130. import readline
  131. except ImportError:
  132. # The readline module does not exist in all Python distributions, e.g. on
  133. # Windows. Fall back to simple input handling.
  134. pass
  135. # Use this so that it can be mocked in tests on Python 2 and 3.
  136. try:
  137. if sys.version_info.major == 2:
  138. return raw_input(message)
  139. return input(message)
  140. except KeyboardInterrupt:
  141. # Hide the exception.
  142. sys.exit(1)
  143. def FileRead(filename, mode='rbU'):
  144. # mode is ignored now; we always return unicode strings.
  145. with open(filename, mode='rb') as f:
  146. s = f.read()
  147. try:
  148. return s.decode('utf-8', 'replace')
  149. except (UnicodeDecodeError, AttributeError):
  150. return s
  151. def FileWrite(filename, content, mode='w', encoding='utf-8'):
  152. with codecs.open(filename, mode=mode, encoding=encoding) as f:
  153. f.write(content)
  154. @contextlib.contextmanager
  155. def temporary_directory(**kwargs):
  156. tdir = tempfile.mkdtemp(**kwargs)
  157. try:
  158. yield tdir
  159. finally:
  160. if tdir:
  161. rmtree(tdir)
  162. @contextlib.contextmanager
  163. def temporary_file():
  164. """Creates a temporary file.
  165. On Windows, a file must be closed before it can be opened again. This function
  166. allows to write something like:
  167. with gclient_utils.temporary_file() as tmp:
  168. gclient_utils.FileWrite(tmp, foo)
  169. useful_stuff(tmp)
  170. Instead of something like:
  171. with tempfile.NamedTemporaryFile(delete=False) as tmp:
  172. tmp.write(foo)
  173. tmp.close()
  174. try:
  175. useful_stuff(tmp)
  176. finally:
  177. os.remove(tmp.name)
  178. """
  179. handle, name = tempfile.mkstemp()
  180. os.close(handle)
  181. try:
  182. yield name
  183. finally:
  184. os.remove(name)
  185. def safe_rename(old, new):
  186. """Renames a file reliably.
  187. Sometimes os.rename does not work because a dying git process keeps a handle
  188. on it for a few seconds. An exception is then thrown, which make the program
  189. give up what it was doing and remove what was deleted.
  190. The only solution is to catch the exception and try again until it works.
  191. """
  192. # roughly 10s
  193. retries = 100
  194. for i in range(retries):
  195. try:
  196. os.rename(old, new)
  197. break
  198. except OSError:
  199. if i == (retries - 1):
  200. # Give up.
  201. raise
  202. # retry
  203. logging.debug("Renaming failed from %s to %s. Retrying ..." % (old, new))
  204. time.sleep(0.1)
  205. def rm_file_or_tree(path):
  206. if os.path.isfile(path) or os.path.islink(path):
  207. os.remove(path)
  208. else:
  209. rmtree(path)
  210. def rmtree(path):
  211. """shutil.rmtree() on steroids.
  212. Recursively removes a directory, even if it's marked read-only.
  213. shutil.rmtree() doesn't work on Windows if any of the files or directories
  214. are read-only. We need to be able to force the files to be writable (i.e.,
  215. deletable) as we traverse the tree.
  216. Even with all this, Windows still sometimes fails to delete a file, citing
  217. a permission error (maybe something to do with antivirus scans or disk
  218. indexing). The best suggestion any of the user forums had was to wait a
  219. bit and try again, so we do that too. It's hand-waving, but sometimes it
  220. works. :/
  221. On POSIX systems, things are a little bit simpler. The modes of the files
  222. to be deleted doesn't matter, only the modes of the directories containing
  223. them are significant. As the directory tree is traversed, each directory
  224. has its mode set appropriately before descending into it. This should
  225. result in the entire tree being removed, with the possible exception of
  226. *path itself, because nothing attempts to change the mode of its parent.
  227. Doing so would be hazardous, as it's not a directory slated for removal.
  228. In the ordinary case, this is not a problem: for our purposes, the user
  229. will never lack write permission on *path's parent.
  230. """
  231. if not os.path.exists(path):
  232. return
  233. if os.path.islink(path) or not os.path.isdir(path):
  234. raise Error('Called rmtree(%s) in non-directory' % path)
  235. if sys.platform == 'win32':
  236. # Give up and use cmd.exe's rd command.
  237. path = os.path.normcase(path)
  238. for _ in range(3):
  239. exitcode = subprocess.call(['cmd.exe', '/c', 'rd', '/q', '/s', path])
  240. if exitcode == 0:
  241. return
  242. else:
  243. print('rd exited with code %d' % exitcode, file=sys.stderr)
  244. time.sleep(3)
  245. raise Exception('Failed to remove path %s' % path)
  246. # On POSIX systems, we need the x-bit set on the directory to access it,
  247. # the r-bit to see its contents, and the w-bit to remove files from it.
  248. # The actual modes of the files within the directory is irrelevant.
  249. os.chmod(path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
  250. def remove(func, subpath):
  251. func(subpath)
  252. for fn in os.listdir(path):
  253. # If fullpath is a symbolic link that points to a directory, isdir will
  254. # be True, but we don't want to descend into that as a directory, we just
  255. # want to remove the link. Check islink and treat links as ordinary files
  256. # would be treated regardless of what they reference.
  257. fullpath = os.path.join(path, fn)
  258. if os.path.islink(fullpath) or not os.path.isdir(fullpath):
  259. remove(os.remove, fullpath)
  260. else:
  261. # Recurse.
  262. rmtree(fullpath)
  263. remove(os.rmdir, path)
  264. def safe_makedirs(tree):
  265. """Creates the directory in a safe manner.
  266. Because multiple threads can create these directories concurrently, trap the
  267. exception and pass on.
  268. """
  269. count = 0
  270. while not os.path.exists(tree):
  271. count += 1
  272. try:
  273. os.makedirs(tree)
  274. except OSError as e:
  275. # 17 POSIX, 183 Windows
  276. if e.errno not in (17, 183):
  277. raise
  278. if count > 40:
  279. # Give up.
  280. raise
  281. def CommandToStr(args):
  282. """Converts an arg list into a shell escaped string."""
  283. return ' '.join(pipes.quote(arg) for arg in args)
  284. class Wrapper(object):
  285. """Wraps an object, acting as a transparent proxy for all properties by
  286. default.
  287. """
  288. def __init__(self, wrapped):
  289. self._wrapped = wrapped
  290. def __getattr__(self, name):
  291. return getattr(self._wrapped, name)
  292. class AutoFlush(Wrapper):
  293. """Creates a file object clone to automatically flush after N seconds."""
  294. def __init__(self, wrapped, delay):
  295. super(AutoFlush, self).__init__(wrapped)
  296. if not hasattr(self, 'lock'):
  297. self.lock = threading.Lock()
  298. self.__last_flushed_at = time.time()
  299. self.delay = delay
  300. @property
  301. def autoflush(self):
  302. return self
  303. def write(self, out, *args, **kwargs):
  304. self._wrapped.write(out, *args, **kwargs)
  305. should_flush = False
  306. self.lock.acquire()
  307. try:
  308. if self.delay and (time.time() - self.__last_flushed_at) > self.delay:
  309. should_flush = True
  310. self.__last_flushed_at = time.time()
  311. finally:
  312. self.lock.release()
  313. if should_flush:
  314. self.flush()
  315. class Annotated(Wrapper):
  316. """Creates a file object clone to automatically prepends every line in worker
  317. threads with a NN> prefix.
  318. """
  319. def __init__(self, wrapped, include_zero=False):
  320. super(Annotated, self).__init__(wrapped)
  321. if not hasattr(self, 'lock'):
  322. self.lock = threading.Lock()
  323. self.__output_buffers = {}
  324. self.__include_zero = include_zero
  325. self._wrapped_write = getattr(self._wrapped, 'buffer', self._wrapped).write
  326. @property
  327. def annotated(self):
  328. return self
  329. def write(self, out):
  330. # Store as bytes to ensure Unicode characters get output correctly.
  331. if not isinstance(out, bytes):
  332. out = out.encode('utf-8')
  333. index = getattr(threading.currentThread(), 'index', 0)
  334. if not index and not self.__include_zero:
  335. # Unindexed threads aren't buffered.
  336. return self._wrapped_write(out)
  337. self.lock.acquire()
  338. try:
  339. # Use a dummy array to hold the string so the code can be lockless.
  340. # Strings are immutable, requiring to keep a lock for the whole dictionary
  341. # otherwise. Using an array is faster than using a dummy object.
  342. if not index in self.__output_buffers:
  343. obj = self.__output_buffers[index] = [b'']
  344. else:
  345. obj = self.__output_buffers[index]
  346. finally:
  347. self.lock.release()
  348. # Continue lockless.
  349. obj[0] += out
  350. while True:
  351. cr_loc = obj[0].find(b'\r')
  352. lf_loc = obj[0].find(b'\n')
  353. if cr_loc == lf_loc == -1:
  354. break
  355. elif cr_loc == -1 or (lf_loc >= 0 and lf_loc < cr_loc):
  356. line, remaining = obj[0].split(b'\n', 1)
  357. if line:
  358. self._wrapped_write(b'%d>%s\n' % (index, line))
  359. elif lf_loc == -1 or (cr_loc >= 0 and cr_loc < lf_loc):
  360. line, remaining = obj[0].split(b'\r', 1)
  361. if line:
  362. self._wrapped_write(b'%d>%s\r' % (index, line))
  363. obj[0] = remaining
  364. def flush(self):
  365. """Flush buffered output."""
  366. orphans = []
  367. self.lock.acquire()
  368. try:
  369. # Detect threads no longer existing.
  370. indexes = (getattr(t, 'index', None) for t in threading.enumerate())
  371. indexes = filter(None, indexes)
  372. for index in self.__output_buffers:
  373. if not index in indexes:
  374. orphans.append((index, self.__output_buffers[index][0]))
  375. for orphan in orphans:
  376. del self.__output_buffers[orphan[0]]
  377. finally:
  378. self.lock.release()
  379. # Don't keep the lock while writing. Will append \n when it shouldn't.
  380. for orphan in orphans:
  381. if orphan[1]:
  382. self._wrapped_write(b'%d>%s\n' % (orphan[0], orphan[1]))
  383. return self._wrapped.flush()
  384. def MakeFileAutoFlush(fileobj, delay=10):
  385. autoflush = getattr(fileobj, 'autoflush', None)
  386. if autoflush:
  387. autoflush.delay = delay
  388. return fileobj
  389. return AutoFlush(fileobj, delay)
  390. def MakeFileAnnotated(fileobj, include_zero=False):
  391. if getattr(fileobj, 'annotated', None):
  392. return fileobj
  393. return Annotated(fileobj, include_zero)
  394. GCLIENT_CHILDREN = []
  395. GCLIENT_CHILDREN_LOCK = threading.Lock()
  396. class GClientChildren(object):
  397. @staticmethod
  398. def add(popen_obj):
  399. with GCLIENT_CHILDREN_LOCK:
  400. GCLIENT_CHILDREN.append(popen_obj)
  401. @staticmethod
  402. def remove(popen_obj):
  403. with GCLIENT_CHILDREN_LOCK:
  404. GCLIENT_CHILDREN.remove(popen_obj)
  405. @staticmethod
  406. def _attemptToKillChildren():
  407. global GCLIENT_CHILDREN
  408. with GCLIENT_CHILDREN_LOCK:
  409. zombies = [c for c in GCLIENT_CHILDREN if c.poll() is None]
  410. for zombie in zombies:
  411. try:
  412. zombie.kill()
  413. except OSError:
  414. pass
  415. with GCLIENT_CHILDREN_LOCK:
  416. GCLIENT_CHILDREN = [k for k in GCLIENT_CHILDREN if k.poll() is not None]
  417. @staticmethod
  418. def _areZombies():
  419. with GCLIENT_CHILDREN_LOCK:
  420. return bool(GCLIENT_CHILDREN)
  421. @staticmethod
  422. def KillAllRemainingChildren():
  423. GClientChildren._attemptToKillChildren()
  424. if GClientChildren._areZombies():
  425. time.sleep(0.5)
  426. GClientChildren._attemptToKillChildren()
  427. with GCLIENT_CHILDREN_LOCK:
  428. if GCLIENT_CHILDREN:
  429. print('Could not kill the following subprocesses:', file=sys.stderr)
  430. for zombie in GCLIENT_CHILDREN:
  431. print(' ', zombie.pid, file=sys.stderr)
  432. def CheckCallAndFilter(args, print_stdout=False, filter_fn=None,
  433. show_header=False, always_show_header=False, retry=False,
  434. **kwargs):
  435. """Runs a command and calls back a filter function if needed.
  436. Accepts all subprocess2.Popen() parameters plus:
  437. print_stdout: If True, the command's stdout is forwarded to stdout.
  438. filter_fn: A function taking a single string argument called with each line
  439. of the subprocess2's output. Each line has the trailing newline
  440. character trimmed.
  441. show_header: Whether to display a header before the command output.
  442. always_show_header: Show header even when the command produced no output.
  443. retry: If the process exits non-zero, sleep for a brief interval and try
  444. again, up to RETRY_MAX times.
  445. stderr is always redirected to stdout.
  446. Returns the output of the command as a binary string.
  447. """
  448. def show_header_if_necessary(needs_header, attempt):
  449. """Show the header at most once."""
  450. if not needs_header[0]:
  451. return
  452. needs_header[0] = False
  453. # Automatically generated header. We only prepend a newline if
  454. # always_show_header is false, since it usually indicates there's an
  455. # external progress display, and it's better not to clobber it in that case.
  456. header = '' if always_show_header else '\n'
  457. header += '________ running \'%s\' in \'%s\'' % (
  458. ' '.join(args), kwargs.get('cwd', '.'))
  459. if attempt:
  460. header += ' attempt %s / %s' % (attempt + 1, RETRY_MAX + 1)
  461. header += '\n'
  462. if print_stdout:
  463. stdout_write = getattr(sys.stdout, 'buffer', sys.stdout).write
  464. stdout_write(header.encode())
  465. if filter_fn:
  466. filter_fn(header)
  467. def filter_line(command_output, line_start):
  468. """Extract the last line from command output and filter it."""
  469. if not filter_fn or line_start is None:
  470. return
  471. command_output.seek(line_start)
  472. filter_fn(command_output.read().decode('utf-8'))
  473. # Initialize stdout writer if needed. On Python 3, sys.stdout does not accept
  474. # byte inputs and sys.stdout.buffer must be used instead.
  475. if print_stdout:
  476. sys.stdout.flush()
  477. stdout_write = getattr(sys.stdout, 'buffer', sys.stdout).write
  478. else:
  479. stdout_write = lambda _: None
  480. sleep_interval = RETRY_INITIAL_SLEEP
  481. run_cwd = kwargs.get('cwd', os.getcwd())
  482. # Store the output of the command regardless of the value of print_stdout or
  483. # filter_fn.
  484. command_output = io.BytesIO()
  485. for attempt in range(RETRY_MAX + 1):
  486. # If our stdout is a terminal, then pass in a psuedo-tty pipe to our
  487. # subprocess when filtering its output. This makes the subproc believe
  488. # it was launched from a terminal, which will preserve ANSI color codes.
  489. os_type = GetMacWinAixOrLinux()
  490. if sys.stdout.isatty() and os_type != 'win' and os_type != 'aix':
  491. pipe_reader, pipe_writer = os.openpty()
  492. else:
  493. pipe_reader, pipe_writer = os.pipe()
  494. kid = subprocess2.Popen(
  495. args, bufsize=0, stdout=pipe_writer, stderr=subprocess2.STDOUT,
  496. **kwargs)
  497. # Close the write end of the pipe once we hand it off to the child proc.
  498. os.close(pipe_writer)
  499. GClientChildren.add(kid)
  500. # Passed as a list for "by ref" semantics.
  501. needs_header = [show_header]
  502. if always_show_header:
  503. show_header_if_necessary(needs_header, attempt)
  504. # Also, we need to forward stdout to prevent weird re-ordering of output.
  505. # This has to be done on a per byte basis to make sure it is not buffered:
  506. # normally buffering is done for each line, but if the process requests
  507. # input, no end-of-line character is output after the prompt and it would
  508. # not show up.
  509. try:
  510. line_start = None
  511. while True:
  512. try:
  513. in_byte = os.read(pipe_reader, 1)
  514. except (IOError, OSError) as e:
  515. if e.errno == errno.EIO:
  516. # An errno.EIO means EOF?
  517. in_byte = None
  518. else:
  519. raise e
  520. is_newline = in_byte in (b'\n', b'\r')
  521. if not in_byte:
  522. break
  523. show_header_if_necessary(needs_header, attempt)
  524. if is_newline:
  525. filter_line(command_output, line_start)
  526. line_start = None
  527. elif line_start is None:
  528. line_start = command_output.tell()
  529. stdout_write(in_byte)
  530. command_output.write(in_byte)
  531. # Flush the rest of buffered output.
  532. sys.stdout.flush()
  533. if line_start is not None:
  534. filter_line(command_output, line_start)
  535. os.close(pipe_reader)
  536. rv = kid.wait()
  537. # Don't put this in a 'finally,' since the child may still run if we get
  538. # an exception.
  539. GClientChildren.remove(kid)
  540. except KeyboardInterrupt:
  541. print('Failed while running "%s"' % ' '.join(args), file=sys.stderr)
  542. raise
  543. if rv == 0:
  544. return command_output.getvalue()
  545. if not retry:
  546. break
  547. print("WARNING: subprocess '%s' in %s failed; will retry after a short "
  548. 'nap...' % (' '.join('"%s"' % x for x in args), run_cwd))
  549. command_output = io.BytesIO()
  550. time.sleep(sleep_interval)
  551. sleep_interval *= 2
  552. raise subprocess2.CalledProcessError(
  553. rv, args, kwargs.get('cwd', None), command_output.getvalue(), None)
  554. class GitFilter(object):
  555. """A filter_fn implementation for quieting down git output messages.
  556. Allows a custom function to skip certain lines (predicate), and will throttle
  557. the output of percentage completed lines to only output every X seconds.
  558. """
  559. PERCENT_RE = re.compile('(.*) ([0-9]{1,3})% .*')
  560. def __init__(self, time_throttle=0, predicate=None, out_fh=None):
  561. """
  562. Args:
  563. time_throttle (int): GitFilter will throttle 'noisy' output (such as the
  564. XX% complete messages) to only be printed at least |time_throttle|
  565. seconds apart.
  566. predicate (f(line)): An optional function which is invoked for every line.
  567. The line will be skipped if predicate(line) returns False.
  568. out_fh: File handle to write output to.
  569. """
  570. self.first_line = True
  571. self.last_time = 0
  572. self.time_throttle = time_throttle
  573. self.predicate = predicate
  574. self.out_fh = out_fh or sys.stdout
  575. self.progress_prefix = None
  576. def __call__(self, line):
  577. # git uses an escape sequence to clear the line; elide it.
  578. esc = line.find(chr(0o33))
  579. if esc > -1:
  580. line = line[:esc]
  581. if self.predicate and not self.predicate(line):
  582. return
  583. now = time.time()
  584. match = self.PERCENT_RE.match(line)
  585. if match:
  586. if match.group(1) != self.progress_prefix:
  587. self.progress_prefix = match.group(1)
  588. elif now - self.last_time < self.time_throttle:
  589. return
  590. self.last_time = now
  591. if not self.first_line:
  592. self.out_fh.write('[%s] ' % Elapsed())
  593. self.first_line = False
  594. print(line, file=self.out_fh)
  595. def FindFileUpwards(filename, path=None):
  596. """Search upwards from the a directory (default: current) to find a file.
  597. Returns nearest upper-level directory with the passed in file.
  598. """
  599. if not path:
  600. path = os.getcwd()
  601. path = os.path.realpath(path)
  602. while True:
  603. file_path = os.path.join(path, filename)
  604. if os.path.exists(file_path):
  605. return path
  606. (new_path, _) = os.path.split(path)
  607. if new_path == path:
  608. return None
  609. path = new_path
  610. def GetMacWinAixOrLinux():
  611. """Returns 'mac', 'win', or 'linux', matching the current platform."""
  612. if sys.platform.startswith(('cygwin', 'win')):
  613. return 'win'
  614. elif sys.platform.startswith('linux'):
  615. return 'linux'
  616. elif sys.platform == 'darwin':
  617. return 'mac'
  618. elif sys.platform.startswith('aix'):
  619. return 'aix'
  620. raise Error('Unknown platform: ' + sys.platform)
  621. def GetGClientRootAndEntries(path=None):
  622. """Returns the gclient root and the dict of entries."""
  623. config_file = '.gclient_entries'
  624. root = FindFileUpwards(config_file, path)
  625. if not root:
  626. print("Can't find %s" % config_file)
  627. return None
  628. config_path = os.path.join(root, config_file)
  629. env = {}
  630. with open(config_path) as config:
  631. exec(config.read(), env)
  632. config_dir = os.path.dirname(config_path)
  633. return config_dir, env['entries']
  634. def lockedmethod(method):
  635. """Method decorator that holds self.lock for the duration of the call."""
  636. def inner(self, *args, **kwargs):
  637. try:
  638. try:
  639. self.lock.acquire()
  640. except KeyboardInterrupt:
  641. print('Was deadlocked', file=sys.stderr)
  642. raise
  643. return method(self, *args, **kwargs)
  644. finally:
  645. self.lock.release()
  646. return inner
  647. class WorkItem(object):
  648. """One work item."""
  649. # On cygwin, creating a lock throwing randomly when nearing ~100 locks.
  650. # As a workaround, use a single lock. Yep you read it right. Single lock for
  651. # all the 100 objects.
  652. lock = threading.Lock()
  653. def __init__(self, name):
  654. # A unique string representing this work item.
  655. self._name = name
  656. self.outbuf = StringIO()
  657. self.start = self.finish = None
  658. self.resources = [] # List of resources this work item requires.
  659. def run(self, work_queue):
  660. """work_queue is passed as keyword argument so it should be
  661. the last parameters of the function when you override it."""
  662. pass
  663. @property
  664. def name(self):
  665. return self._name
  666. class ExecutionQueue(object):
  667. """Runs a set of WorkItem that have interdependencies and were WorkItem are
  668. added as they are processed.
  669. This class manages that all the required dependencies are run
  670. before running each one.
  671. Methods of this class are thread safe.
  672. """
  673. def __init__(self, jobs, progress, ignore_requirements, verbose=False):
  674. """jobs specifies the number of concurrent tasks to allow. progress is a
  675. Progress instance."""
  676. # Set when a thread is done or a new item is enqueued.
  677. self.ready_cond = threading.Condition()
  678. # Maximum number of concurrent tasks.
  679. self.jobs = jobs
  680. # List of WorkItem, for gclient, these are Dependency instances.
  681. self.queued = []
  682. # List of strings representing each Dependency.name that was run.
  683. self.ran = []
  684. # List of items currently running.
  685. self.running = []
  686. # Exceptions thrown if any.
  687. self.exceptions = queue.Queue()
  688. # Progress status
  689. self.progress = progress
  690. if self.progress:
  691. self.progress.update(0)
  692. self.ignore_requirements = ignore_requirements
  693. self.verbose = verbose
  694. self.last_join = None
  695. self.last_subproc_output = None
  696. def enqueue(self, d):
  697. """Enqueue one Dependency to be executed later once its requirements are
  698. satisfied.
  699. """
  700. assert isinstance(d, WorkItem)
  701. self.ready_cond.acquire()
  702. try:
  703. self.queued.append(d)
  704. total = len(self.queued) + len(self.ran) + len(self.running)
  705. if self.jobs == 1:
  706. total += 1
  707. logging.debug('enqueued(%s)' % d.name)
  708. if self.progress:
  709. self.progress._total = total
  710. self.progress.update(0)
  711. self.ready_cond.notifyAll()
  712. finally:
  713. self.ready_cond.release()
  714. def out_cb(self, _):
  715. self.last_subproc_output = datetime.datetime.now()
  716. return True
  717. @staticmethod
  718. def format_task_output(task, comment=''):
  719. if comment:
  720. comment = ' (%s)' % comment
  721. if task.start and task.finish:
  722. elapsed = ' (Elapsed: %s)' % (
  723. str(task.finish - task.start).partition('.')[0])
  724. else:
  725. elapsed = ''
  726. return """
  727. %s%s%s
  728. ----------------------------------------
  729. %s
  730. ----------------------------------------""" % (
  731. task.name, comment, elapsed, task.outbuf.getvalue().strip())
  732. def _is_conflict(self, job):
  733. """Checks to see if a job will conflict with another running job."""
  734. for running_job in self.running:
  735. for used_resource in running_job.item.resources:
  736. logging.debug('Checking resource %s' % used_resource)
  737. if used_resource in job.resources:
  738. return True
  739. return False
  740. def flush(self, *args, **kwargs):
  741. """Runs all enqueued items until all are executed."""
  742. kwargs['work_queue'] = self
  743. self.last_subproc_output = self.last_join = datetime.datetime.now()
  744. self.ready_cond.acquire()
  745. try:
  746. while True:
  747. # Check for task to run first, then wait.
  748. while True:
  749. if not self.exceptions.empty():
  750. # Systematically flush the queue when an exception logged.
  751. self.queued = []
  752. self._flush_terminated_threads()
  753. if (not self.queued and not self.running or
  754. self.jobs == len(self.running)):
  755. logging.debug('No more worker threads or can\'t queue anything.')
  756. break
  757. # Check for new tasks to start.
  758. for i in range(len(self.queued)):
  759. # Verify its requirements.
  760. if (self.ignore_requirements or
  761. not (set(self.queued[i].requirements) - set(self.ran))):
  762. if not self._is_conflict(self.queued[i]):
  763. # Start one work item: all its requirements are satisfied.
  764. self._run_one_task(self.queued.pop(i), args, kwargs)
  765. break
  766. else:
  767. # Couldn't find an item that could run. Break out the outher loop.
  768. break
  769. if not self.queued and not self.running:
  770. # We're done.
  771. break
  772. # We need to poll here otherwise Ctrl-C isn't processed.
  773. try:
  774. self.ready_cond.wait(10)
  775. # If we haven't printed to terminal for a while, but we have received
  776. # spew from a suprocess, let the user know we're still progressing.
  777. now = datetime.datetime.now()
  778. if (now - self.last_join > datetime.timedelta(seconds=60) and
  779. self.last_subproc_output > self.last_join):
  780. if self.progress:
  781. print('')
  782. sys.stdout.flush()
  783. elapsed = Elapsed()
  784. print('[%s] Still working on:' % elapsed)
  785. sys.stdout.flush()
  786. for task in self.running:
  787. print('[%s] %s' % (elapsed, task.item.name))
  788. sys.stdout.flush()
  789. except KeyboardInterrupt:
  790. # Help debugging by printing some information:
  791. print(
  792. ('\nAllowed parallel jobs: %d\n# queued: %d\nRan: %s\n'
  793. 'Running: %d') % (self.jobs, len(self.queued), ', '.join(
  794. self.ran), len(self.running)),
  795. file=sys.stderr)
  796. for i in self.queued:
  797. print(
  798. '%s (not started): %s' % (i.name, ', '.join(i.requirements)),
  799. file=sys.stderr)
  800. for i in self.running:
  801. print(
  802. self.format_task_output(i.item, 'interrupted'), file=sys.stderr)
  803. raise
  804. # Something happened: self.enqueue() or a thread terminated. Loop again.
  805. finally:
  806. self.ready_cond.release()
  807. assert not self.running, 'Now guaranteed to be single-threaded'
  808. if not self.exceptions.empty():
  809. if self.progress:
  810. print('')
  811. # To get back the stack location correctly, the raise a, b, c form must be
  812. # used, passing a tuple as the first argument doesn't work.
  813. e, task = self.exceptions.get()
  814. print(self.format_task_output(task.item, 'ERROR'), file=sys.stderr)
  815. reraise(e[0], e[1], e[2])
  816. elif self.progress:
  817. self.progress.end()
  818. def _flush_terminated_threads(self):
  819. """Flush threads that have terminated."""
  820. running = self.running
  821. self.running = []
  822. for t in running:
  823. if t.is_alive():
  824. self.running.append(t)
  825. else:
  826. t.join()
  827. self.last_join = datetime.datetime.now()
  828. sys.stdout.flush()
  829. if self.verbose:
  830. print(self.format_task_output(t.item))
  831. if self.progress:
  832. self.progress.update(1, t.item.name)
  833. if t.item.name in self.ran:
  834. raise Error(
  835. 'gclient is confused, "%s" is already in "%s"' % (
  836. t.item.name, ', '.join(self.ran)))
  837. if not t.item.name in self.ran:
  838. self.ran.append(t.item.name)
  839. def _run_one_task(self, task_item, args, kwargs):
  840. if self.jobs > 1:
  841. # Start the thread.
  842. index = len(self.ran) + len(self.running) + 1
  843. new_thread = self._Worker(task_item, index, args, kwargs)
  844. self.running.append(new_thread)
  845. new_thread.start()
  846. else:
  847. # Run the 'thread' inside the main thread. Don't try to catch any
  848. # exception.
  849. try:
  850. task_item.start = datetime.datetime.now()
  851. print('[%s] Started.' % Elapsed(task_item.start), file=task_item.outbuf)
  852. task_item.run(*args, **kwargs)
  853. task_item.finish = datetime.datetime.now()
  854. print(
  855. '[%s] Finished.' % Elapsed(task_item.finish), file=task_item.outbuf)
  856. self.ran.append(task_item.name)
  857. if self.verbose:
  858. if self.progress:
  859. print('')
  860. print(self.format_task_output(task_item))
  861. if self.progress:
  862. self.progress.update(1, ', '.join(t.item.name for t in self.running))
  863. except KeyboardInterrupt:
  864. print(
  865. self.format_task_output(task_item, 'interrupted'), file=sys.stderr)
  866. raise
  867. except Exception:
  868. print(self.format_task_output(task_item, 'ERROR'), file=sys.stderr)
  869. raise
  870. class _Worker(threading.Thread):
  871. """One thread to execute one WorkItem."""
  872. def __init__(self, item, index, args, kwargs):
  873. threading.Thread.__init__(self, name=item.name or 'Worker')
  874. logging.info('_Worker(%s) reqs:%s' % (item.name, item.requirements))
  875. self.item = item
  876. self.index = index
  877. self.args = args
  878. self.kwargs = kwargs
  879. self.daemon = True
  880. def run(self):
  881. """Runs in its own thread."""
  882. logging.debug('_Worker.run(%s)' % self.item.name)
  883. work_queue = self.kwargs['work_queue']
  884. try:
  885. self.item.start = datetime.datetime.now()
  886. print('[%s] Started.' % Elapsed(self.item.start), file=self.item.outbuf)
  887. self.item.run(*self.args, **self.kwargs)
  888. self.item.finish = datetime.datetime.now()
  889. print(
  890. '[%s] Finished.' % Elapsed(self.item.finish), file=self.item.outbuf)
  891. except KeyboardInterrupt:
  892. logging.info('Caught KeyboardInterrupt in thread %s', self.item.name)
  893. logging.info(str(sys.exc_info()))
  894. work_queue.exceptions.put((sys.exc_info(), self))
  895. raise
  896. except Exception:
  897. # Catch exception location.
  898. logging.info('Caught exception in thread %s', self.item.name)
  899. logging.info(str(sys.exc_info()))
  900. work_queue.exceptions.put((sys.exc_info(), self))
  901. finally:
  902. logging.info('_Worker.run(%s) done', self.item.name)
  903. work_queue.ready_cond.acquire()
  904. try:
  905. work_queue.ready_cond.notifyAll()
  906. finally:
  907. work_queue.ready_cond.release()
  908. def GetEditor(git_editor=None):
  909. """Returns the most plausible editor to use.
  910. In order of preference:
  911. - GIT_EDITOR environment variable
  912. - core.editor git configuration variable (if supplied by git-cl)
  913. - VISUAL environment variable
  914. - EDITOR environment variable
  915. - vi (non-Windows) or notepad (Windows)
  916. In the case of git-cl, this matches git's behaviour, except that it does not
  917. include dumb terminal detection.
  918. """
  919. editor = os.environ.get('GIT_EDITOR') or git_editor
  920. if not editor:
  921. editor = os.environ.get('VISUAL')
  922. if not editor:
  923. editor = os.environ.get('EDITOR')
  924. if not editor:
  925. if sys.platform.startswith('win'):
  926. editor = 'notepad'
  927. else:
  928. editor = 'vi'
  929. return editor
  930. def RunEditor(content, git, git_editor=None):
  931. """Opens up the default editor in the system to get the CL description."""
  932. file_handle, filename = tempfile.mkstemp(text=True, prefix='cl_description')
  933. # Make sure CRLF is handled properly by requiring none.
  934. if '\r' in content:
  935. print(
  936. '!! Please remove \\r from your change description !!', file=sys.stderr)
  937. fileobj = os.fdopen(file_handle, 'wb')
  938. # Still remove \r if present.
  939. content = re.sub('\r?\n', '\n', content)
  940. # Some editors complain when the file doesn't end in \n.
  941. if not content.endswith('\n'):
  942. content += '\n'
  943. fileobj.write(content.encode('utf-8'))
  944. fileobj.close()
  945. try:
  946. editor = GetEditor(git_editor=git_editor)
  947. if not editor:
  948. return None
  949. cmd = '%s %s' % (editor, filename)
  950. if sys.platform == 'win32' and os.environ.get('TERM') == 'msys':
  951. # Msysgit requires the usage of 'env' to be present.
  952. cmd = 'env ' + cmd
  953. try:
  954. # shell=True to allow the shell to handle all forms of quotes in
  955. # $EDITOR.
  956. subprocess2.check_call(cmd, shell=True)
  957. except subprocess2.CalledProcessError:
  958. return None
  959. return FileRead(filename)
  960. finally:
  961. os.remove(filename)
  962. def UpgradeToHttps(url):
  963. """Upgrades random urls to https://.
  964. Do not touch unknown urls like ssh:// or git://.
  965. Do not touch http:// urls with a port number,
  966. Fixes invalid GAE url.
  967. """
  968. if not url:
  969. return url
  970. if not re.match(r'[a-z\-]+\://.*', url):
  971. # Make sure it is a valid uri. Otherwise, urlparse() will consider it a
  972. # relative url and will use http:///foo. Note that it defaults to http://
  973. # for compatibility with naked url like "localhost:8080".
  974. url = 'http://%s' % url
  975. parsed = list(urlparse.urlparse(url))
  976. # Do not automatically upgrade http to https if a port number is provided.
  977. if parsed[0] == 'http' and not re.match(r'^.+?\:\d+$', parsed[1]):
  978. parsed[0] = 'https'
  979. return urlparse.urlunparse(parsed)
  980. def ParseCodereviewSettingsContent(content):
  981. """Process a codereview.settings file properly."""
  982. lines = (l for l in content.splitlines() if not l.strip().startswith("#"))
  983. try:
  984. keyvals = dict([x.strip() for x in l.split(':', 1)] for l in lines if l)
  985. except ValueError:
  986. raise Error(
  987. 'Failed to process settings, please fix. Content:\n\n%s' % content)
  988. def fix_url(key):
  989. if keyvals.get(key):
  990. keyvals[key] = UpgradeToHttps(keyvals[key])
  991. fix_url('CODE_REVIEW_SERVER')
  992. fix_url('VIEW_VC')
  993. return keyvals
  994. def NumLocalCpus():
  995. """Returns the number of processors.
  996. multiprocessing.cpu_count() is permitted to raise NotImplementedError, and
  997. is known to do this on some Windows systems and OSX 10.6. If we can't get the
  998. CPU count, we will fall back to '1'.
  999. """
  1000. # Surround the entire thing in try/except; no failure here should stop gclient
  1001. # from working.
  1002. try:
  1003. # Use multiprocessing to get CPU count. This may raise
  1004. # NotImplementedError.
  1005. try:
  1006. import multiprocessing
  1007. return multiprocessing.cpu_count()
  1008. except NotImplementedError: # pylint: disable=bare-except
  1009. # (UNIX) Query 'os.sysconf'.
  1010. # pylint: disable=no-member
  1011. if hasattr(os, 'sysconf') and 'SC_NPROCESSORS_ONLN' in os.sysconf_names:
  1012. return int(os.sysconf('SC_NPROCESSORS_ONLN'))
  1013. # (Windows) Query 'NUMBER_OF_PROCESSORS' environment variable.
  1014. if 'NUMBER_OF_PROCESSORS' in os.environ:
  1015. return int(os.environ['NUMBER_OF_PROCESSORS'])
  1016. except Exception as e:
  1017. logging.exception("Exception raised while probing CPU count: %s", e)
  1018. logging.debug('Failed to get CPU count. Defaulting to 1.')
  1019. return 1
  1020. def DefaultDeltaBaseCacheLimit():
  1021. """Return a reasonable default for the git config core.deltaBaseCacheLimit.
  1022. The primary constraint is the address space of virtual memory. The cache
  1023. size limit is per-thread, and 32-bit systems can hit OOM errors if this
  1024. parameter is set too high.
  1025. """
  1026. if platform.architecture()[0].startswith('64'):
  1027. return '2g'
  1028. else:
  1029. return '512m'
  1030. def DefaultIndexPackConfig(url=''):
  1031. """Return reasonable default values for configuring git-index-pack.
  1032. Experiments suggest that higher values for pack.threads don't improve
  1033. performance."""
  1034. cache_limit = DefaultDeltaBaseCacheLimit()
  1035. result = ['-c', 'core.deltaBaseCacheLimit=%s' % cache_limit]
  1036. if url in THREADED_INDEX_PACK_BLOCKLIST:
  1037. result.extend(['-c', 'pack.threads=1'])
  1038. return result
  1039. def FindExecutable(executable):
  1040. """This mimics the "which" utility."""
  1041. path_folders = os.environ.get('PATH').split(os.pathsep)
  1042. for path_folder in path_folders:
  1043. target = os.path.join(path_folder, executable)
  1044. # Just in case we have some ~/blah paths.
  1045. target = os.path.abspath(os.path.expanduser(target))
  1046. if os.path.isfile(target) and os.access(target, os.X_OK):
  1047. return target
  1048. if sys.platform.startswith('win'):
  1049. for suffix in ('.bat', '.cmd', '.exe'):
  1050. alt_target = target + suffix
  1051. if os.path.isfile(alt_target) and os.access(alt_target, os.X_OK):
  1052. return alt_target
  1053. return None
  1054. def freeze(obj):
  1055. """Takes a generic object ``obj``, and returns an immutable version of it.
  1056. Supported types:
  1057. * dict / OrderedDict -> FrozenDict
  1058. * list -> tuple
  1059. * set -> frozenset
  1060. * any object with a working __hash__ implementation (assumes that hashable
  1061. means immutable)
  1062. Will raise TypeError if you pass an object which is not hashable.
  1063. """
  1064. if isinstance(obj, collections_abc.Mapping):
  1065. return FrozenDict((freeze(k), freeze(v)) for k, v in obj.items())
  1066. elif isinstance(obj, (list, tuple)):
  1067. return tuple(freeze(i) for i in obj)
  1068. elif isinstance(obj, set):
  1069. return frozenset(freeze(i) for i in obj)
  1070. else:
  1071. hash(obj)
  1072. return obj
  1073. class FrozenDict(collections_abc.Mapping):
  1074. """An immutable OrderedDict.
  1075. Modified From: http://stackoverflow.com/a/2704866
  1076. """
  1077. def __init__(self, *args, **kwargs):
  1078. self._d = collections.OrderedDict(*args, **kwargs)
  1079. # Calculate the hash immediately so that we know all the items are
  1080. # hashable too.
  1081. self._hash = functools.reduce(
  1082. operator.xor, (hash(i) for i in enumerate(self._d.items())), 0)
  1083. def __eq__(self, other):
  1084. if not isinstance(other, collections_abc.Mapping):
  1085. return NotImplemented
  1086. if self is other:
  1087. return True
  1088. if len(self) != len(other):
  1089. return False
  1090. for k, v in self.items():
  1091. if k not in other or other[k] != v:
  1092. return False
  1093. return True
  1094. def __iter__(self):
  1095. return iter(self._d)
  1096. def __len__(self):
  1097. return len(self._d)
  1098. def __getitem__(self, key):
  1099. return self._d[key]
  1100. def __hash__(self):
  1101. return self._hash
  1102. def __repr__(self):
  1103. return 'FrozenDict(%r)' % (self._d.items(),)