gclient_utils.py 39 KB

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