gclient_utils.py 40 KB

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