gclient_utils.py 39 KB

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