gclient_utils.py 40 KB

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