bisect-builds.py 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346
  1. #!/usr/bin/env python3
  2. # Copyright (c) 2012 The Chromium Authors. All rights reserved.
  3. # Use of this source code is governed by a BSD-style license that can be
  4. # found in the LICENSE file.
  5. """Snapshot Build Bisect Tool
  6. This script bisects a snapshot archive using binary search. It starts at
  7. a bad revision (it will try to guess HEAD) and asks for a last known-good
  8. revision. It will then binary search across this revision range by downloading,
  9. unzipping, and opening Chromium for you. After testing the specific revision,
  10. it will ask you whether it is good or bad before continuing the search.
  11. """
  12. from __future__ import print_function
  13. # The base URL for stored build archives.
  14. CHROMIUM_BASE_URL = ('http://commondatastorage.googleapis.com'
  15. '/chromium-browser-snapshots')
  16. WEBKIT_BASE_URL = ('http://commondatastorage.googleapis.com'
  17. '/chromium-webkit-snapshots')
  18. ASAN_BASE_URL = ('http://commondatastorage.googleapis.com'
  19. '/chromium-browser-asan')
  20. # URL template for viewing changelogs between revisions.
  21. CHANGELOG_URL = ('https://chromium.googlesource.com/chromium/src/+log/%s..%s')
  22. # URL to convert SVN revision to git hash.
  23. CRREV_URL = ('https://cr-rev.appspot.com/_ah/api/crrev/v1/redirect/')
  24. # DEPS file URL.
  25. DEPS_FILE = ('https://chromium.googlesource.com/chromium/src/+/%s/DEPS')
  26. # Blink changelogs URL.
  27. BLINK_CHANGELOG_URL = ('http://build.chromium.org'
  28. '/f/chromium/perf/dashboard/ui/changelog_blink.html'
  29. '?url=/trunk&range=%d%%3A%d')
  30. DONE_MESSAGE_GOOD_MIN = ('You are probably looking for a change made after %s ('
  31. 'known good), but no later than %s (first known bad).')
  32. DONE_MESSAGE_GOOD_MAX = ('You are probably looking for a change made after %s ('
  33. 'known bad), but no later than %s (first known good).')
  34. CHROMIUM_GITHASH_TO_SVN_URL = (
  35. 'https://chromium.googlesource.com/chromium/src/+/%s?format=json')
  36. BLINK_GITHASH_TO_SVN_URL = (
  37. 'https://chromium.googlesource.com/chromium/blink/+/%s?format=json')
  38. GITHASH_TO_SVN_URL = {
  39. 'chromium': CHROMIUM_GITHASH_TO_SVN_URL,
  40. 'blink': BLINK_GITHASH_TO_SVN_URL,
  41. }
  42. VERSION_HISTORY_URL = ('https://versionhistory.googleapis.com/v1/chrome'
  43. '/platforms/win/channels/stable/versions/all/releases')
  44. OMAHA_REVISIONS_URL = ('https://omahaproxy.appspot.com/deps.json?version=%s')
  45. CRDASH_REVISIONS_URL = (
  46. 'https://chromiumdash.appspot.com/fetch_version?version=%s')
  47. # Search pattern to be matched in the JSON output from
  48. # CHROMIUM_GITHASH_TO_SVN_URL to get the chromium revision (svn revision).
  49. CHROMIUM_SEARCH_PATTERN_OLD = (
  50. r'.*git-svn-id: svn://svn.chromium.org/chrome/trunk/src@(\d+) ')
  51. CHROMIUM_SEARCH_PATTERN = (
  52. r'Cr-Commit-Position: refs/heads/(?:master|main)@{#(\d+)}')
  53. # Search pattern to be matched in the json output from
  54. # BLINK_GITHASH_TO_SVN_URL to get the blink revision (svn revision).
  55. BLINK_SEARCH_PATTERN = (
  56. r'.*git-svn-id: svn://svn.chromium.org/blink/trunk@(\d+) ')
  57. SEARCH_PATTERN = {
  58. 'chromium': CHROMIUM_SEARCH_PATTERN,
  59. 'blink': BLINK_SEARCH_PATTERN,
  60. }
  61. CREDENTIAL_ERROR_MESSAGE = ('You are attempting to access protected data with '
  62. 'no configured credentials')
  63. ###############################################################################
  64. import glob
  65. import json
  66. import optparse
  67. import os
  68. import re
  69. import shlex
  70. import shutil
  71. import subprocess
  72. import sys
  73. import tempfile
  74. import threading
  75. from distutils.version import LooseVersion
  76. from xml.etree import ElementTree
  77. import zipfile
  78. if sys.version_info[0] == 3:
  79. import urllib.request as urllib
  80. else:
  81. import urllib
  82. class PathContext(object):
  83. """A PathContext is used to carry the information used to construct URLs and
  84. paths when dealing with the storage server and archives."""
  85. def __init__(self, base_url, platform, good_revision, bad_revision, is_asan,
  86. use_local_cache):
  87. super(PathContext, self).__init__()
  88. # Store off the input parameters.
  89. self.base_url = base_url
  90. self.platform = platform # What's passed in to the '-a/--archive' option.
  91. self.good_revision = good_revision
  92. self.bad_revision = bad_revision
  93. self.is_asan = is_asan
  94. self.build_type = 'release'
  95. # Dictionary which stores svn revision number as key and it's
  96. # corresponding git hash as value. This data is populated in
  97. # _FetchAndParse and used later in GetDownloadURL while downloading
  98. # the build.
  99. self.githash_svn_dict = {}
  100. # The name of the ZIP file in a revision directory on the server.
  101. self.archive_name = None
  102. # Whether to cache and use the list of known revisions in a local file to
  103. # speed up the initialization of the script at the next run.
  104. self.use_local_cache = use_local_cache
  105. # Locate the local checkout to speed up the script by using locally stored
  106. # metadata.
  107. abs_file_path = os.path.abspath(os.path.realpath(__file__))
  108. local_src_path = os.path.join(os.path.dirname(abs_file_path), '..')
  109. if abs_file_path.endswith(os.path.join('tools', 'bisect-builds.py')) and\
  110. os.path.exists(os.path.join(local_src_path, '.git')):
  111. self.local_src_path = os.path.normpath(local_src_path)
  112. else:
  113. self.local_src_path = None
  114. # Set some internal members:
  115. # _listing_platform_dir = Directory that holds revisions. Ends with a '/'.
  116. # _archive_extract_dir = Uncompressed directory in the archive_name file.
  117. # _binary_name = The name of the executable to run.
  118. if self.platform in ('linux', 'linux64', 'linux-arm', 'chromeos'):
  119. self._binary_name = 'chrome'
  120. elif self.platform in ('mac', 'mac64', 'mac-arm'):
  121. self.archive_name = 'chrome-mac.zip'
  122. self._archive_extract_dir = 'chrome-mac'
  123. elif self.platform in ('win', 'win64'):
  124. # Note: changed at revision 591483; see GetDownloadURL and GetLaunchPath
  125. # below where these are patched.
  126. self.archive_name = 'chrome-win32.zip'
  127. self._archive_extract_dir = 'chrome-win32'
  128. self._binary_name = 'chrome.exe'
  129. else:
  130. raise Exception('Invalid platform: %s' % self.platform)
  131. if self.platform in ('linux', 'linux64', 'linux-arm', 'chromeos'):
  132. # Note: changed at revision 591483; see GetDownloadURL and GetLaunchPath
  133. # below where these are patched.
  134. self.archive_name = 'chrome-linux.zip'
  135. self._archive_extract_dir = 'chrome-linux'
  136. if self.platform == 'linux':
  137. self._listing_platform_dir = 'Linux/'
  138. elif self.platform == 'linux64':
  139. self._listing_platform_dir = 'Linux_x64/'
  140. elif self.platform == 'linux-arm':
  141. self._listing_platform_dir = 'Linux_ARM_Cross-Compile/'
  142. elif self.platform == 'chromeos':
  143. self._listing_platform_dir = 'Linux_ChromiumOS_Full/'
  144. elif self.platform in ('mac', 'mac64'):
  145. self._listing_platform_dir = 'Mac/'
  146. self._binary_name = 'Chromium.app/Contents/MacOS/Chromium'
  147. elif self.platform in ('mac-arm'):
  148. self._listing_platform_dir = 'Mac_Arm/'
  149. self._binary_name = 'Chromium.app/Contents/MacOS/Chromium'
  150. elif self.platform == 'win':
  151. self._listing_platform_dir = 'Win/'
  152. elif self.platform == 'win64':
  153. self._listing_platform_dir = 'Win_x64/'
  154. def GetASANPlatformDir(self):
  155. """ASAN builds are in directories like "linux-release", or have filenames
  156. like "asan-win32-release-277079.zip". This aligns to our platform names
  157. except in the case of Windows where they use "win32" instead of "win"."""
  158. if self.platform == 'win':
  159. return 'win32'
  160. else:
  161. return self.platform
  162. def GetListingURL(self, marker=None):
  163. """Returns the URL for a directory listing, with an optional marker."""
  164. marker_param = ''
  165. if marker:
  166. marker_param = '&marker=' + str(marker)
  167. if self.is_asan:
  168. prefix = '%s-%s' % (self.GetASANPlatformDir(), self.build_type)
  169. return self.base_url + '/?delimiter=&prefix=' + prefix + marker_param
  170. else:
  171. return (self.base_url + '/?delimiter=/&prefix=' +
  172. self._listing_platform_dir + marker_param)
  173. def GetDownloadURL(self, revision):
  174. """Gets the download URL for a build archive of a specific revision."""
  175. if self.is_asan:
  176. return '%s/%s-%s/%s-%d.zip' % (
  177. ASAN_BASE_URL, self.GetASANPlatformDir(), self.build_type,
  178. self.GetASANBaseName(), revision)
  179. if str(revision) in self.githash_svn_dict:
  180. revision = self.githash_svn_dict[str(revision)]
  181. archive_name = self.archive_name
  182. # At revision 591483, the names of two of the archives changed
  183. # due to: https://chromium-review.googlesource.com/#/q/1226086
  184. # See: http://crbug.com/789612
  185. if revision >= 591483:
  186. if self.platform == 'chromeos':
  187. archive_name = 'chrome-chromeos.zip'
  188. elif self.platform in ('win', 'win64'):
  189. archive_name = 'chrome-win.zip'
  190. return '%s/%s%s/%s' % (self.base_url, self._listing_platform_dir,
  191. revision, archive_name)
  192. def GetLastChangeURL(self):
  193. """Returns a URL to the LAST_CHANGE file."""
  194. return self.base_url + '/' + self._listing_platform_dir + 'LAST_CHANGE'
  195. def GetASANBaseName(self):
  196. """Returns the base name of the ASAN zip file."""
  197. if 'linux' in self.platform:
  198. return 'asan-symbolized-%s-%s' % (self.GetASANPlatformDir(),
  199. self.build_type)
  200. else:
  201. return 'asan-%s-%s' % (self.GetASANPlatformDir(), self.build_type)
  202. def GetLaunchPath(self, revision):
  203. """Returns a relative path (presumably from the archive extraction location)
  204. that is used to run the executable."""
  205. if self.is_asan:
  206. extract_dir = '%s-%d' % (self.GetASANBaseName(), revision)
  207. else:
  208. extract_dir = self._archive_extract_dir
  209. # At revision 591483, the names of two of the archives changed
  210. # due to: https://chromium-review.googlesource.com/#/q/1226086
  211. # See: http://crbug.com/789612
  212. if revision >= 591483:
  213. if self.platform == 'chromeos':
  214. extract_dir = 'chrome-chromeos'
  215. elif self.platform in ('win', 'win64'):
  216. extract_dir = 'chrome-win'
  217. return os.path.join(extract_dir, self._binary_name)
  218. def ParseDirectoryIndex(self, last_known_rev):
  219. """Parses the Google Storage directory listing into a list of revision
  220. numbers."""
  221. def _GetMarkerForRev(revision):
  222. if self.is_asan:
  223. return '%s-%s/%s-%d.zip' % (
  224. self.GetASANPlatformDir(), self.build_type,
  225. self.GetASANBaseName(), revision)
  226. return '%s%d' % (self._listing_platform_dir, revision)
  227. def _FetchAndParse(url):
  228. """Fetches a URL and returns a 2-Tuple of ([revisions], next-marker). If
  229. next-marker is not None, then the listing is a partial listing and another
  230. fetch should be performed with next-marker being the marker= GET
  231. parameter."""
  232. handle = urllib.urlopen(url)
  233. document = ElementTree.parse(handle)
  234. # All nodes in the tree are namespaced. Get the root's tag name to extract
  235. # the namespace. Etree does namespaces as |{namespace}tag|.
  236. root_tag = document.getroot().tag
  237. end_ns_pos = root_tag.find('}')
  238. if end_ns_pos == -1:
  239. raise Exception('Could not locate end namespace for directory index')
  240. namespace = root_tag[:end_ns_pos + 1]
  241. # Find the prefix (_listing_platform_dir) and whether or not the list is
  242. # truncated.
  243. prefix_len = len(document.find(namespace + 'Prefix').text)
  244. next_marker = None
  245. is_truncated = document.find(namespace + 'IsTruncated')
  246. if is_truncated is not None and is_truncated.text.lower() == 'true':
  247. next_marker = document.find(namespace + 'NextMarker').text
  248. # Get a list of all the revisions.
  249. revisions = []
  250. githash_svn_dict = {}
  251. if self.is_asan:
  252. asan_regex = re.compile(r'.*%s-(\d+)\.zip$' % (self.GetASANBaseName()))
  253. # Non ASAN builds are in a <revision> directory. The ASAN builds are
  254. # flat
  255. all_prefixes = document.findall(namespace + 'Contents/' +
  256. namespace + 'Key')
  257. for prefix in all_prefixes:
  258. m = asan_regex.match(prefix.text)
  259. if m:
  260. try:
  261. revisions.append(int(m.group(1)))
  262. except ValueError:
  263. pass
  264. else:
  265. all_prefixes = document.findall(namespace + 'CommonPrefixes/' +
  266. namespace + 'Prefix')
  267. # The <Prefix> nodes have content of the form of
  268. # |_listing_platform_dir/revision/|. Strip off the platform dir and the
  269. # trailing slash to just have a number.
  270. for prefix in all_prefixes:
  271. revnum = prefix.text[prefix_len:-1]
  272. try:
  273. revnum = int(revnum)
  274. revisions.append(revnum)
  275. # Notes:
  276. # Ignore hash in chromium-browser-snapshots as they are invalid
  277. # Resulting in 404 error in fetching pages:
  278. # https://chromium.googlesource.com/chromium/src/+/[rev_hash]
  279. except ValueError:
  280. pass
  281. return (revisions, next_marker, githash_svn_dict)
  282. # Fetch the first list of revisions.
  283. if last_known_rev:
  284. revisions = []
  285. # Optimization: Start paging at the last known revision (local cache).
  286. next_marker = _GetMarkerForRev(last_known_rev)
  287. # Optimization: Stop paging at the last known revision (remote).
  288. last_change_rev = GetChromiumRevision(self, self.GetLastChangeURL())
  289. if last_known_rev == last_change_rev:
  290. return []
  291. else:
  292. (revisions, next_marker, new_dict) = _FetchAndParse(self.GetListingURL())
  293. self.githash_svn_dict.update(new_dict)
  294. last_change_rev = None
  295. # If the result list was truncated, refetch with the next marker. Do this
  296. # until an entire directory listing is done.
  297. while next_marker:
  298. sys.stdout.write('\rFetching revisions at marker %s' % next_marker)
  299. sys.stdout.flush()
  300. next_url = self.GetListingURL(next_marker)
  301. (new_revisions, next_marker, new_dict) = _FetchAndParse(next_url)
  302. revisions.extend(new_revisions)
  303. self.githash_svn_dict.update(new_dict)
  304. if last_change_rev and last_change_rev in new_revisions:
  305. break
  306. sys.stdout.write('\r')
  307. sys.stdout.flush()
  308. return revisions
  309. def _GetSVNRevisionFromGitHashWithoutGitCheckout(self, git_sha1, depot):
  310. json_url = GITHASH_TO_SVN_URL[depot] % git_sha1
  311. response = urllib.urlopen(json_url)
  312. if response.getcode() == 200:
  313. try:
  314. data = json.loads(response.read()[4:])
  315. except ValueError:
  316. print('ValueError for JSON URL: %s' % json_url)
  317. raise ValueError
  318. else:
  319. raise ValueError
  320. if 'message' in data:
  321. message = data['message'].split('\n')
  322. message = [line for line in message if line.strip()]
  323. search_pattern = re.compile(SEARCH_PATTERN[depot])
  324. result = search_pattern.search(message[len(message)-1])
  325. if result:
  326. return result.group(1)
  327. else:
  328. if depot == 'chromium':
  329. result = re.search(CHROMIUM_SEARCH_PATTERN_OLD,
  330. message[len(message)-1])
  331. if result:
  332. return result.group(1)
  333. print('Failed to get svn revision number for %s' % git_sha1)
  334. raise ValueError
  335. def _GetSVNRevisionFromGitHashFromGitCheckout(self, git_sha1, depot):
  336. def _RunGit(command, path):
  337. command = ['git'] + command
  338. shell = sys.platform.startswith('win')
  339. proc = subprocess.Popen(command, shell=shell, stdout=subprocess.PIPE,
  340. stderr=subprocess.PIPE, cwd=path)
  341. (output, _) = proc.communicate()
  342. return (output, proc.returncode)
  343. path = self.local_src_path
  344. if depot == 'blink':
  345. path = os.path.join(self.local_src_path, 'third_party', 'WebKit')
  346. revision = None
  347. try:
  348. command = ['svn', 'find-rev', git_sha1]
  349. (git_output, return_code) = _RunGit(command, path)
  350. if not return_code:
  351. revision = git_output.strip('\n')
  352. except ValueError:
  353. pass
  354. if not revision:
  355. command = ['log', '-n1', '--format=%s', git_sha1]
  356. (git_output, return_code) = _RunGit(command, path)
  357. if not return_code:
  358. revision = re.match('SVN changes up to revision ([0-9]+)', git_output)
  359. revision = revision.group(1) if revision else None
  360. if revision:
  361. return revision
  362. raise ValueError
  363. def GetSVNRevisionFromGitHash(self, git_sha1, depot='chromium'):
  364. if not self.local_src_path:
  365. return self._GetSVNRevisionFromGitHashWithoutGitCheckout(git_sha1, depot)
  366. else:
  367. return self._GetSVNRevisionFromGitHashFromGitCheckout(git_sha1, depot)
  368. def GetRevList(self, archive):
  369. """Gets the list of revision numbers between self.good_revision and
  370. self.bad_revision."""
  371. cache = {}
  372. # The cache is stored in the same directory as bisect-builds.py
  373. cache_filename = os.path.join(
  374. os.path.abspath(os.path.dirname(__file__)),
  375. '.bisect-builds-cache.json')
  376. cache_dict_key = self.GetListingURL()
  377. def _LoadBucketFromCache():
  378. if self.use_local_cache:
  379. try:
  380. with open(cache_filename) as cache_file:
  381. for (key, value) in json.load(cache_file).items():
  382. cache[key] = value
  383. revisions = cache.get(cache_dict_key, [])
  384. githash_svn_dict = cache.get('githash_svn_dict', {})
  385. if revisions:
  386. print('Loaded revisions %d-%d from %s' %
  387. (revisions[0], revisions[-1], cache_filename))
  388. return (revisions, githash_svn_dict)
  389. except (EnvironmentError, ValueError):
  390. pass
  391. return ([], {})
  392. def _SaveBucketToCache():
  393. """Save the list of revisions and the git-svn mappings to a file.
  394. The list of revisions is assumed to be sorted."""
  395. if self.use_local_cache:
  396. cache[cache_dict_key] = revlist_all
  397. cache['githash_svn_dict'] = self.githash_svn_dict
  398. try:
  399. with open(cache_filename, 'w') as cache_file:
  400. json.dump(cache, cache_file)
  401. print('Saved revisions %d-%d to %s' %
  402. (revlist_all[0], revlist_all[-1], cache_filename))
  403. except EnvironmentError:
  404. pass
  405. # Download the revlist and filter for just the range between good and bad.
  406. minrev = min(self.good_revision, self.bad_revision)
  407. maxrev = max(self.good_revision, self.bad_revision)
  408. (revlist_all, self.githash_svn_dict) = _LoadBucketFromCache()
  409. last_known_rev = revlist_all[-1] if revlist_all else 0
  410. if last_known_rev < maxrev:
  411. revlist_all.extend(map(int, self.ParseDirectoryIndex(last_known_rev)))
  412. revlist_all = list(set(revlist_all))
  413. revlist_all.sort()
  414. _SaveBucketToCache()
  415. revlist = [x for x in revlist_all if x >= int(minrev) and x <= int(maxrev)]
  416. if len(revlist) < 2: # Don't have enough builds to bisect.
  417. last_known_rev = revlist_all[-1] if revlist_all else 0
  418. first_known_rev = revlist_all[0] if revlist_all else 0
  419. # Check for specifying a number before the available range.
  420. if maxrev < first_known_rev:
  421. msg = (
  422. 'First available bisect revision for %s is %d. Be sure to specify '
  423. 'revision numbers, not branch numbers.' %
  424. (archive, first_known_rev))
  425. raise (RuntimeError(msg))
  426. # Check for specifying a number beyond the available range.
  427. if maxrev > last_known_rev:
  428. # Check for the special case of linux where bisect builds stopped at
  429. # revision 382086, around March 2016.
  430. if archive == 'linux':
  431. msg = ('Last available bisect revision for %s is %d. Try linux64 '
  432. 'instead.' % (archive, last_known_rev))
  433. else:
  434. msg = ('Last available bisect revision for %s is %d. Try a different '
  435. 'good/bad range.' % (archive, last_known_rev))
  436. raise (RuntimeError(msg))
  437. # Otherwise give a generic message.
  438. msg = 'We don\'t have enough builds to bisect. revlist: %s' % revlist
  439. raise RuntimeError(msg)
  440. # Set good and bad revisions to be legit revisions.
  441. if revlist:
  442. if self.good_revision < self.bad_revision:
  443. self.good_revision = revlist[0]
  444. self.bad_revision = revlist[-1]
  445. else:
  446. self.bad_revision = revlist[0]
  447. self.good_revision = revlist[-1]
  448. # Fix chromium rev so that the deps blink revision matches REVISIONS file.
  449. if self.base_url == WEBKIT_BASE_URL:
  450. revlist_all.sort()
  451. self.good_revision = FixChromiumRevForBlink(revlist,
  452. revlist_all,
  453. self,
  454. self.good_revision)
  455. self.bad_revision = FixChromiumRevForBlink(revlist,
  456. revlist_all,
  457. self,
  458. self.bad_revision)
  459. return revlist
  460. def IsMac():
  461. return sys.platform.startswith('darwin')
  462. def UnzipFilenameToDir(filename, directory):
  463. """Unzip |filename| to |directory|."""
  464. cwd = os.getcwd()
  465. if not os.path.isabs(filename):
  466. filename = os.path.join(cwd, filename)
  467. # Make base.
  468. if not os.path.isdir(directory):
  469. os.mkdir(directory)
  470. os.chdir(directory)
  471. # The Python ZipFile does not support symbolic links, which makes it
  472. # unsuitable for Mac builds. so use ditto instead.
  473. if IsMac():
  474. unzip_cmd = ['ditto', '-x', '-k', filename, '.']
  475. proc = subprocess.Popen(unzip_cmd, bufsize=0, stdout=subprocess.PIPE,
  476. stderr=subprocess.PIPE)
  477. proc.communicate()
  478. os.chdir(cwd)
  479. return
  480. zf = zipfile.ZipFile(filename)
  481. # Extract files.
  482. for info in zf.infolist():
  483. name = info.filename
  484. if name.endswith('/'): # dir
  485. if not os.path.isdir(name):
  486. os.makedirs(name)
  487. else: # file
  488. directory = os.path.dirname(name)
  489. if not os.path.isdir(directory):
  490. os.makedirs(directory)
  491. out = open(name, 'wb')
  492. out.write(zf.read(name))
  493. out.close()
  494. # Set permissions. Permission info in external_attr is shifted 16 bits.
  495. os.chmod(name, info.external_attr >> 16)
  496. os.chdir(cwd)
  497. def FetchRevision(context, rev, filename, quit_event=None, progress_event=None):
  498. """Downloads and unzips revision |rev|.
  499. @param context A PathContext instance.
  500. @param rev The Chromium revision number/tag to download.
  501. @param filename The destination for the downloaded file.
  502. @param quit_event A threading.Event which will be set by the master thread to
  503. indicate that the download should be aborted.
  504. @param progress_event A threading.Event which will be set by the master thread
  505. to indicate that the progress of the download should be
  506. displayed.
  507. """
  508. def ReportHook(blocknum, blocksize, totalsize):
  509. if quit_event and quit_event.isSet():
  510. raise RuntimeError('Aborting download of revision %s' % str(rev))
  511. if progress_event and progress_event.isSet():
  512. size = blocknum * blocksize
  513. if totalsize == -1: # Total size not known.
  514. progress = 'Received %d bytes' % size
  515. else:
  516. size = min(totalsize, size)
  517. progress = 'Received %d of %d bytes, %.2f%%' % (
  518. size, totalsize, 100.0 * size / totalsize)
  519. # Send a \r to let all progress messages use just one line of output.
  520. sys.stdout.write('\r' + progress)
  521. sys.stdout.flush()
  522. download_url = context.GetDownloadURL(rev)
  523. try:
  524. urllib.urlretrieve(download_url, filename, ReportHook)
  525. if progress_event and progress_event.isSet():
  526. print()
  527. except RuntimeError:
  528. pass
  529. def CopyMissingFileFromCurrentSource(src_glob, dst):
  530. """Work around missing files in archives.
  531. This happens when archives of Chrome don't contain all of the files
  532. needed to build it. In many cases we can work around this using
  533. files from the current checkout. The source is in the form of a glob
  534. so that it can try to look for possible sources of the file in
  535. multiple locations, but we just arbitrarily try the first match.
  536. Silently fail if this doesn't work because we don't yet have clear
  537. markers for builds that require certain files or a way to test
  538. whether or not launching Chrome succeeded.
  539. """
  540. if not os.path.exists(dst):
  541. matches = glob.glob(src_glob)
  542. if matches:
  543. shutil.copy2(matches[0], dst)
  544. def RunRevision(context, revision, zip_file, profile, num_runs, command, args):
  545. """Given a zipped revision, unzip it and run the test."""
  546. print('Trying revision %s...' % str(revision))
  547. # Create a temp directory and unzip the revision into it.
  548. cwd = os.getcwd()
  549. tempdir = tempfile.mkdtemp(prefix='bisect_tmp')
  550. UnzipFilenameToDir(zip_file, tempdir)
  551. # Hack: Some Chrome OS archives are missing some files; try to copy them
  552. # from the local directory.
  553. if context.platform == 'chromeos' and revision < 591483:
  554. CopyMissingFileFromCurrentSource('third_party/icu/common/icudtl.dat',
  555. '%s/chrome-linux/icudtl.dat' % tempdir)
  556. CopyMissingFileFromCurrentSource('*out*/*/libminigbm.so',
  557. '%s/chrome-linux/libminigbm.so' % tempdir)
  558. os.chdir(tempdir)
  559. # Run the build as many times as specified.
  560. testargs = ['--user-data-dir=%s' % profile] + args
  561. runcommand = []
  562. for token in shlex.split(command):
  563. if token == '%a':
  564. runcommand.extend(testargs)
  565. else:
  566. runcommand.append(
  567. token.replace('%p', os.path.abspath(context.GetLaunchPath(revision))).
  568. replace('%s', ' '.join(testargs)))
  569. result = None
  570. try:
  571. for _ in range(num_runs):
  572. subproc = subprocess.Popen(
  573. runcommand,
  574. bufsize=-1,
  575. stdout=subprocess.PIPE,
  576. stderr=subprocess.PIPE)
  577. (stdout, stderr) = subproc.communicate()
  578. result = (subproc.returncode, stdout, stderr)
  579. if subproc.returncode:
  580. break
  581. return result
  582. finally:
  583. os.chdir(cwd)
  584. try:
  585. shutil.rmtree(tempdir, True)
  586. except Exception:
  587. pass
  588. # The arguments status, stdout and stderr are unused.
  589. # They are present here because this function is passed to Bisect which then
  590. # calls it with 5 arguments.
  591. # pylint: disable=W0613
  592. def AskIsGoodBuild(rev, exit_status, stdout, stderr):
  593. """Asks the user whether build |rev| is good or bad."""
  594. if exit_status:
  595. print('Chrome exit_status: %d. Use s to see output' % exit_status)
  596. # Loop until we get a response that we can parse.
  597. while True:
  598. prompt = ('Revision %s is '
  599. '[(g)ood/(b)ad/(r)etry/(u)nknown/(s)tdout/(q)uit]: ' % str(rev))
  600. if sys.version_info[0] == 3:
  601. response = input(prompt)
  602. else:
  603. response = raw_input(prompt)
  604. if response in ('g', 'b', 'r', 'u'):
  605. return response
  606. if response == 'q':
  607. raise SystemExit()
  608. if response == 's':
  609. print(stdout)
  610. print(stderr)
  611. def IsGoodASANBuild(rev, exit_status, stdout, stderr):
  612. """Determine if an ASAN build |rev| is good or bad
  613. Will examine stderr looking for the error message emitted by ASAN. If not
  614. found then will fallback to asking the user."""
  615. if stderr:
  616. bad_count = 0
  617. for line in stderr.splitlines():
  618. print(line)
  619. if line.find('ERROR: AddressSanitizer:') != -1:
  620. bad_count += 1
  621. if bad_count > 0:
  622. print('Revision %d determined to be bad.' % rev)
  623. return 'b'
  624. return AskIsGoodBuild(rev, exit_status, stdout, stderr)
  625. def DidCommandSucceed(rev, exit_status, stdout, stderr):
  626. if exit_status:
  627. print('Bad revision: %s' % rev)
  628. return 'b'
  629. else:
  630. print('Good revision: %s' % rev)
  631. return 'g'
  632. class DownloadJob(object):
  633. """DownloadJob represents a task to download a given Chromium revision."""
  634. def __init__(self, context, name, rev, zip_file):
  635. super(DownloadJob, self).__init__()
  636. # Store off the input parameters.
  637. self.context = context
  638. self.name = name
  639. self.rev = rev
  640. self.zip_file = zip_file
  641. self.quit_event = threading.Event()
  642. self.progress_event = threading.Event()
  643. self.thread = None
  644. def Start(self):
  645. """Starts the download."""
  646. fetchargs = (self.context,
  647. self.rev,
  648. self.zip_file,
  649. self.quit_event,
  650. self.progress_event)
  651. self.thread = threading.Thread(target=FetchRevision,
  652. name=self.name,
  653. args=fetchargs)
  654. self.thread.start()
  655. def Stop(self):
  656. """Stops the download which must have been started previously."""
  657. assert self.thread, 'DownloadJob must be started before Stop is called.'
  658. self.quit_event.set()
  659. self.thread.join()
  660. os.unlink(self.zip_file)
  661. def WaitFor(self):
  662. """Prints a message and waits for the download to complete. The download
  663. must have been started previously."""
  664. assert self.thread, 'DownloadJob must be started before WaitFor is called.'
  665. print('Downloading revision %s...' % str(self.rev))
  666. self.progress_event.set() # Display progress of download.
  667. try:
  668. while self.thread.is_alive():
  669. # The parameter to join is needed to keep the main thread responsive to
  670. # signals. Without it, the program will not respond to interruptions.
  671. self.thread.join(1)
  672. except (KeyboardInterrupt, SystemExit):
  673. self.Stop()
  674. raise
  675. def VerifyEndpoint(fetch, context, rev, profile, num_runs, command, try_args,
  676. evaluate, expected_answer):
  677. fetch.WaitFor()
  678. try:
  679. answer = 'r'
  680. # This is intended to allow evaluate() to return 'r' to retry RunRevision.
  681. while answer == 'r':
  682. (exit_status, stdout, stderr) = RunRevision(
  683. context, rev, fetch.zip_file, profile, num_runs, command, try_args)
  684. answer = evaluate(rev, exit_status, stdout, stderr)
  685. except Exception as e:
  686. print(e, file=sys.stderr)
  687. raise SystemExit
  688. if (answer != expected_answer):
  689. print('Unexpected result at a range boundary! Your range is not correct.')
  690. raise SystemExit
  691. def Bisect(context,
  692. num_runs=1,
  693. command='%p %a',
  694. try_args=(),
  695. profile=None,
  696. evaluate=AskIsGoodBuild,
  697. verify_range=False,
  698. archive=None):
  699. """Given known good and known bad revisions, run a binary search on all
  700. archived revisions to determine the last known good revision.
  701. @param context PathContext object initialized with user provided parameters.
  702. @param num_runs Number of times to run each build for asking good/bad.
  703. @param try_args A tuple of arguments to pass to the test application.
  704. @param profile The name of the user profile to run with.
  705. @param evaluate A function which returns 'g' if the argument build is good,
  706. 'b' if it's bad or 'u' if unknown.
  707. @param verify_range If true, tests the first and last revisions in the range
  708. before proceeding with the bisect.
  709. Threading is used to fetch Chromium revisions in the background, speeding up
  710. the user's experience. For example, suppose the bounds of the search are
  711. good_rev=0, bad_rev=100. The first revision to be checked is 50. Depending on
  712. whether revision 50 is good or bad, the next revision to check will be either
  713. 25 or 75. So, while revision 50 is being checked, the script will download
  714. revisions 25 and 75 in the background. Once the good/bad verdict on rev 50 is
  715. known:
  716. - If rev 50 is good, the download of rev 25 is cancelled, and the next test
  717. is run on rev 75.
  718. - If rev 50 is bad, the download of rev 75 is cancelled, and the next test
  719. is run on rev 25.
  720. """
  721. if not profile:
  722. profile = 'profile'
  723. good_rev = context.good_revision
  724. bad_rev = context.bad_revision
  725. cwd = os.getcwd()
  726. print('Downloading list of known revisions...', end=' ')
  727. if not context.use_local_cache:
  728. print('(use --use-local-cache to cache and re-use the list of revisions)')
  729. else:
  730. print()
  731. _GetDownloadPath = lambda rev: os.path.join(cwd,
  732. '%s-%s' % (str(rev), context.archive_name))
  733. # Get a list of revisions to bisect across.
  734. revlist = context.GetRevList(archive)
  735. # Figure out our bookends and first pivot point; fetch the pivot revision.
  736. minrev = 0
  737. maxrev = len(revlist) - 1
  738. pivot = int(maxrev / 2)
  739. rev = revlist[pivot]
  740. fetch = DownloadJob(context, 'initial_fetch', rev, _GetDownloadPath(rev))
  741. fetch.Start()
  742. if verify_range:
  743. minrev_fetch = DownloadJob(
  744. context, 'minrev_fetch', revlist[minrev],
  745. _GetDownloadPath(revlist[minrev]))
  746. maxrev_fetch = DownloadJob(
  747. context, 'maxrev_fetch', revlist[maxrev],
  748. _GetDownloadPath(revlist[maxrev]))
  749. minrev_fetch.Start()
  750. maxrev_fetch.Start()
  751. try:
  752. VerifyEndpoint(minrev_fetch, context, revlist[minrev], profile, num_runs,
  753. command, try_args, evaluate, 'b' if bad_rev < good_rev else 'g')
  754. VerifyEndpoint(maxrev_fetch, context, revlist[maxrev], profile, num_runs,
  755. command, try_args, evaluate, 'g' if bad_rev < good_rev else 'b')
  756. except (KeyboardInterrupt, SystemExit):
  757. print('Cleaning up...')
  758. fetch.Stop()
  759. sys.exit(0)
  760. finally:
  761. minrev_fetch.Stop()
  762. maxrev_fetch.Stop()
  763. fetch.WaitFor()
  764. # Binary search time!
  765. prefetch_revisions = True
  766. while fetch and fetch.zip_file and maxrev - minrev > 1:
  767. if bad_rev < good_rev:
  768. min_str, max_str = 'bad', 'good'
  769. else:
  770. min_str, max_str = 'good', 'bad'
  771. print(
  772. 'Bisecting range [%s (%s), %s (%s)], '
  773. 'roughly %d steps left.' % (revlist[minrev], min_str, revlist[maxrev],
  774. max_str, int(maxrev - minrev).bit_length()))
  775. # Pre-fetch next two possible pivots
  776. # - down_pivot is the next revision to check if the current revision turns
  777. # out to be bad.
  778. # - up_pivot is the next revision to check if the current revision turns
  779. # out to be good.
  780. down_pivot = int((pivot - minrev) / 2) + minrev
  781. if prefetch_revisions:
  782. down_fetch = None
  783. if down_pivot != pivot and down_pivot != minrev:
  784. down_rev = revlist[down_pivot]
  785. down_fetch = DownloadJob(context, 'down_fetch', down_rev,
  786. _GetDownloadPath(down_rev))
  787. down_fetch.Start()
  788. up_pivot = int((maxrev - pivot) / 2) + pivot
  789. if prefetch_revisions:
  790. up_fetch = None
  791. if up_pivot != pivot and up_pivot != maxrev:
  792. up_rev = revlist[up_pivot]
  793. up_fetch = DownloadJob(context, 'up_fetch', up_rev,
  794. _GetDownloadPath(up_rev))
  795. up_fetch.Start()
  796. # Run test on the pivot revision.
  797. exit_status = None
  798. stdout = None
  799. stderr = None
  800. try:
  801. (exit_status, stdout, stderr) = RunRevision(
  802. context, rev, fetch.zip_file, profile, num_runs, command, try_args)
  803. except Exception as e:
  804. print(e, file=sys.stderr)
  805. # Call the evaluate function to see if the current revision is good or bad.
  806. # On that basis, kill one of the background downloads and complete the
  807. # other, as described in the comments above.
  808. try:
  809. answer = evaluate(rev, exit_status, stdout, stderr)
  810. prefetch_revisions = True
  811. if ((answer == 'g' and good_rev < bad_rev)
  812. or (answer == 'b' and bad_rev < good_rev)):
  813. fetch.Stop()
  814. minrev = pivot
  815. if down_fetch:
  816. down_fetch.Stop() # Kill the download of the older revision.
  817. fetch = None
  818. if up_fetch:
  819. up_fetch.WaitFor()
  820. pivot = up_pivot
  821. fetch = up_fetch
  822. elif ((answer == 'b' and good_rev < bad_rev)
  823. or (answer == 'g' and bad_rev < good_rev)):
  824. fetch.Stop()
  825. maxrev = pivot
  826. if up_fetch:
  827. up_fetch.Stop() # Kill the download of the newer revision.
  828. fetch = None
  829. if down_fetch:
  830. down_fetch.WaitFor()
  831. pivot = down_pivot
  832. fetch = down_fetch
  833. elif answer == 'r':
  834. # Don't redundantly prefetch.
  835. prefetch_revisions = False
  836. elif answer == 'u':
  837. # Nuke the revision from the revlist and choose a new pivot.
  838. fetch.Stop()
  839. revlist.pop(pivot)
  840. maxrev -= 1 # Assumes maxrev >= pivot.
  841. if maxrev - minrev > 1:
  842. # Alternate between using down_pivot or up_pivot for the new pivot
  843. # point, without affecting the range. Do this instead of setting the
  844. # pivot to the midpoint of the new range because adjacent revisions
  845. # are likely affected by the same issue that caused the (u)nknown
  846. # response.
  847. if up_fetch and down_fetch:
  848. fetch = [up_fetch, down_fetch][len(revlist) % 2]
  849. elif up_fetch:
  850. fetch = up_fetch
  851. else:
  852. fetch = down_fetch
  853. fetch.WaitFor()
  854. if fetch == up_fetch:
  855. pivot = up_pivot - 1 # Subtracts 1 because revlist was resized.
  856. else:
  857. pivot = down_pivot
  858. if down_fetch and fetch != down_fetch:
  859. down_fetch.Stop()
  860. if up_fetch and fetch != up_fetch:
  861. up_fetch.Stop()
  862. else:
  863. assert False, 'Unexpected return value from evaluate(): ' + answer
  864. except (KeyboardInterrupt, SystemExit):
  865. print('Cleaning up...')
  866. for f in [_GetDownloadPath(rev),
  867. _GetDownloadPath(revlist[down_pivot]),
  868. _GetDownloadPath(revlist[up_pivot])]:
  869. try:
  870. os.unlink(f)
  871. except OSError:
  872. pass
  873. sys.exit(0)
  874. rev = revlist[pivot]
  875. return (revlist[minrev], revlist[maxrev], context)
  876. def GetBlinkDEPSRevisionForChromiumRevision(self, rev):
  877. """Returns the blink revision that was in REVISIONS file at
  878. chromium revision |rev|."""
  879. def _GetBlinkRev(url, blink_re):
  880. m = blink_re.search(url.read())
  881. url.close()
  882. if m:
  883. return m.group(1)
  884. url = urllib.urlopen(DEPS_FILE % GetGitHashFromSVNRevision(rev))
  885. if url.getcode() == 200:
  886. blink_re = re.compile(r'webkit_revision\D*\d+;\D*\d+;(\w+)')
  887. blink_git_sha = _GetBlinkRev(url, blink_re)
  888. return self.GetSVNRevisionFromGitHash(blink_git_sha, 'blink')
  889. raise Exception('Could not get Blink revision for Chromium rev %d' % rev)
  890. def GetBlinkRevisionForChromiumRevision(context, rev):
  891. """Returns the blink revision that was in REVISIONS file at
  892. chromium revision |rev|."""
  893. def _IsRevisionNumber(revision):
  894. if isinstance(revision, int):
  895. return True
  896. else:
  897. return revision.isdigit()
  898. if str(rev) in context.githash_svn_dict:
  899. rev = context.githash_svn_dict[str(rev)]
  900. file_url = '%s/%s%s/REVISIONS' % (context.base_url,
  901. context._listing_platform_dir, rev)
  902. url = urllib.urlopen(file_url)
  903. if url.getcode() == 200:
  904. try:
  905. data = json.loads(url.read())
  906. except ValueError:
  907. print('ValueError for JSON URL: %s' % file_url)
  908. raise ValueError
  909. else:
  910. raise ValueError
  911. url.close()
  912. if 'webkit_revision' in data:
  913. blink_rev = data['webkit_revision']
  914. if not _IsRevisionNumber(blink_rev):
  915. blink_rev = int(context.GetSVNRevisionFromGitHash(blink_rev, 'blink'))
  916. return blink_rev
  917. else:
  918. raise Exception('Could not get blink revision for cr rev %d' % rev)
  919. def FixChromiumRevForBlink(revisions_final, revisions, self, rev):
  920. """Returns the chromium revision that has the correct blink revision
  921. for blink bisect, DEPS and REVISIONS file might not match since
  922. blink snapshots point to tip of tree blink.
  923. Note: The revisions_final variable might get modified to include
  924. additional revisions."""
  925. blink_deps_rev = GetBlinkDEPSRevisionForChromiumRevision(self, rev)
  926. while (GetBlinkRevisionForChromiumRevision(self, rev) > blink_deps_rev):
  927. idx = revisions.index(rev)
  928. if idx > 0:
  929. rev = revisions[idx-1]
  930. if rev not in revisions_final:
  931. revisions_final.insert(0, rev)
  932. revisions_final.sort()
  933. return rev
  934. def GetChromiumRevision(context, url):
  935. """Returns the chromium revision read from given URL."""
  936. try:
  937. # Location of the latest build revision number
  938. latest_revision = urllib.urlopen(url).read()
  939. if latest_revision.isdigit():
  940. return int(latest_revision)
  941. return context.GetSVNRevisionFromGitHash(latest_revision)
  942. except Exception:
  943. print('Could not determine latest revision. This could be bad...')
  944. return 999999999
  945. def GetRevision(revision_text):
  946. """Translates from a text description of a revision to an integral revision
  947. number. Currently supported formats are a number (i.e.; '782793') or a
  948. milestone specifier (i.e.; 'M85') or a full version string
  949. (i.e. '85.0.4183.121')."""
  950. # Check if we already have a revision number, such as when -g or -b is
  951. # omitted.
  952. if type(revision_text) == type(0):
  953. return revision_text
  954. arg_revision_text = revision_text
  955. # Translate from stable milestone name to the latest version number released
  956. # for that milestone, i.e.; 'M85' to '85.0.4183.121'.
  957. if revision_text[:1].upper() == 'M':
  958. milestone = revision_text[1:]
  959. response = urllib.urlopen(VERSION_HISTORY_URL)
  960. version_history = json.loads(response.read())
  961. version_matcher = re.compile(
  962. '.*versions/(\d*)\.(\d*)\.(\d*)\.(\d*)/releases.*')
  963. for version in version_history['releases']:
  964. match = version_matcher.match(version['name'])
  965. # There will be multiple versions of each milestone, but we just grab the
  966. # first one that we see which will be the most recent version. If you need
  967. # more granularity then specify a full version number or revision number.
  968. if match and match.groups()[0] == milestone:
  969. revision_text = '.'.join(match.groups())
  970. break
  971. if revision_text[:1].upper() == 'M':
  972. raise Exception('No stable release matching %s found.' %
  973. arg_revision_text)
  974. # Translate from version number to commit position, also known as revision
  975. # number. First read from Chromium Dash, then fall back to OmahaProxy, as CD
  976. # data is more correct but only if it's available (crbug.com/1317667).
  977. if len(revision_text.split('.')) == 4:
  978. revisions_url = CRDASH_REVISIONS_URL % revision_text
  979. fallback_revisions_url = OMAHA_REVISIONS_URL % revision_text
  980. response = urllib.urlopen(revisions_url)
  981. revision_details = json.loads(response.read())
  982. revision_text = revision_details.get('chromium_main_branch_position')
  983. if not revision_text:
  984. # OmahaProxy fallback.
  985. response = urllib.urlopen(fallback_revisions_url)
  986. revision_details = json.loads(response.read())
  987. revision_text = revision_details['chromium_base_position']
  988. if not revision_text:
  989. raise Exception("No 'chromium_base_position' matching %s found." %
  990. arg_revision_text)
  991. # Translate from text commit position to integer commit position.
  992. return int(revision_text)
  993. def GetGitHashFromSVNRevision(svn_revision):
  994. crrev_url = CRREV_URL + str(svn_revision)
  995. url = urllib.urlopen(crrev_url)
  996. if url.getcode() == 200:
  997. data = json.loads(url.read())
  998. if 'git_sha' in data:
  999. return data['git_sha']
  1000. def PrintChangeLog(min_chromium_rev, max_chromium_rev):
  1001. """Prints the changelog URL."""
  1002. print(' ' + CHANGELOG_URL % (GetGitHashFromSVNRevision(min_chromium_rev),
  1003. GetGitHashFromSVNRevision(max_chromium_rev)))
  1004. def error_internal_option(option, opt, value, parser):
  1005. raise optparse.OptionValueError(
  1006. 'The -o and -r options are only\navailable in the internal version of '
  1007. 'this script. Google\nemployees should visit http://go/bisect-builds '
  1008. 'for\nconfiguration instructions.')
  1009. def main():
  1010. usage = ('%prog [options] [-- chromium-options]\n'
  1011. 'Perform binary search on the snapshot builds to find a minimal\n'
  1012. 'range of revisions where a behavior change happened. The\n'
  1013. 'behaviors are described as "good" and "bad".\n'
  1014. 'It is NOT assumed that the behavior of the later revision is\n'
  1015. 'the bad one.\n'
  1016. '\n'
  1017. 'Revision numbers should use\n'
  1018. ' SVN revisions (e.g. 123456) for chromium builds, from trunk.\n'
  1019. ' Use base_trunk_revision from http://omahaproxy.appspot.com/\n'
  1020. ' for earlier revs.\n'
  1021. ' Chrome\'s about: build number and omahaproxy branch_revision\n'
  1022. ' are incorrect, they are from branches.\n'
  1023. '\n'
  1024. 'Use "-- <args-to-pass-to-chromium>" to pass arbitrary extra \n'
  1025. 'arguments to the test binaries. For example, to bypass first-run\n'
  1026. 'prompts, add "-- --no-first-run", and on Mac, also append\n'
  1027. '"--use-mock-keychain --disable-features=DialMediaRouteProvider.')
  1028. parser = optparse.OptionParser(usage=usage)
  1029. # Strangely, the default help output doesn't include the choice list.
  1030. choices = ['mac', 'mac64', 'mac-arm', 'win', 'win64', 'linux', 'linux64',
  1031. 'linux-arm', 'chromeos']
  1032. parser.add_option('-a', '--archive',
  1033. choices=choices,
  1034. help='The buildbot archive to bisect [%s].' %
  1035. '|'.join(choices))
  1036. parser.add_option('-b',
  1037. '--bad',
  1038. type='str',
  1039. help='A bad revision to start bisection. '
  1040. 'May be earlier or later than the good revision. '
  1041. 'Default is HEAD. Can be a revision number, milestone '
  1042. 'name (eg. M85, matches the most recent stable release of '
  1043. 'that milestone) or version number (eg. 85.0.4183.121)')
  1044. parser.add_option('-g',
  1045. '--good',
  1046. type='str',
  1047. help='A good revision to start bisection. ' +
  1048. 'May be earlier or later than the bad revision. ' +
  1049. 'Default is 0. Can be a revision number, milestone '
  1050. 'name (eg. M85, matches the most recent stable release of '
  1051. 'that milestone) or version number (eg. 85.0.4183.121)')
  1052. parser.add_option('-p', '--profile', '--user-data-dir',
  1053. type='str',
  1054. default='profile',
  1055. help='Profile to use; this will not reset every run. '
  1056. 'Defaults to a clean profile.')
  1057. parser.add_option('-t', '--times',
  1058. type='int',
  1059. default=1,
  1060. help='Number of times to run each build before asking '
  1061. 'if it\'s good or bad. Temporary profiles are reused.')
  1062. parser.add_option('-c',
  1063. '--command',
  1064. type='str',
  1065. default='%p %a',
  1066. help='Command to execute. %p and %a refer to Chrome '
  1067. 'executable and specified extra arguments respectively. '
  1068. 'Use %s to specify all extra arguments as one string. '
  1069. 'Defaults to "%p %a". Note that any extra paths specified '
  1070. 'should be absolute. If you just need to append an '
  1071. 'argument to the Chrome command line use "-- '
  1072. '<args-to-pass-to-chromium>" instead.')
  1073. parser.add_option('-l', '--blink',
  1074. action='store_true',
  1075. help='Use Blink bisect instead of Chromium. ')
  1076. parser.add_option('', '--not-interactive',
  1077. action='store_true',
  1078. default=False,
  1079. help='Use command exit code to tell good/bad revision.')
  1080. parser.add_option('--asan',
  1081. dest='asan',
  1082. action='store_true',
  1083. default=False,
  1084. help='Allow the script to bisect ASAN builds')
  1085. parser.add_option('--use-local-cache',
  1086. dest='use_local_cache',
  1087. action='store_true',
  1088. default=False,
  1089. help='Use a local file in the current directory to cache '
  1090. 'a list of known revisions to speed up the '
  1091. 'initialization of this script.')
  1092. parser.add_option('--verify-range',
  1093. dest='verify_range',
  1094. action='store_true',
  1095. default=False,
  1096. help='Test the first and last revisions in the range ' +
  1097. 'before proceeding with the bisect.')
  1098. parser.add_option("-r", action="callback", callback=error_internal_option)
  1099. parser.add_option("-o", action="callback", callback=error_internal_option)
  1100. (opts, args) = parser.parse_args()
  1101. if opts.archive is None:
  1102. print('Error: missing required parameter: --archive')
  1103. print()
  1104. parser.print_help()
  1105. return 1
  1106. if opts.asan:
  1107. supported_platforms = ['linux', 'mac', 'win']
  1108. if opts.archive not in supported_platforms:
  1109. print('Error: ASAN bisecting only supported on these platforms: [%s].' %
  1110. ('|'.join(supported_platforms)))
  1111. return 1
  1112. if opts.asan:
  1113. base_url = ASAN_BASE_URL
  1114. elif opts.blink:
  1115. base_url = WEBKIT_BASE_URL
  1116. else:
  1117. base_url = CHROMIUM_BASE_URL
  1118. # Create the context. Initialize 0 for the revisions as they are set below.
  1119. context = PathContext(base_url, opts.archive, opts.good, opts.bad, opts.asan,
  1120. opts.use_local_cache)
  1121. # Pick a starting point, try to get HEAD for this.
  1122. if not opts.bad:
  1123. context.bad_revision = '999.0.0.0'
  1124. context.bad_revision = GetChromiumRevision(
  1125. context, context.GetLastChangeURL())
  1126. # Find out when we were good.
  1127. if not opts.good:
  1128. context.good_revision = 0
  1129. context.good_revision = GetRevision(context.good_revision)
  1130. context.bad_revision = GetRevision(context.bad_revision)
  1131. if opts.times < 1:
  1132. print('Number of times to run (%d) must be greater than or equal to 1.' %
  1133. opts.times)
  1134. parser.print_help()
  1135. return 1
  1136. if opts.not_interactive:
  1137. evaluator = DidCommandSucceed
  1138. elif opts.asan:
  1139. evaluator = IsGoodASANBuild
  1140. else:
  1141. evaluator = AskIsGoodBuild
  1142. # Save these revision numbers to compare when showing the changelog URL
  1143. # after the bisect.
  1144. good_rev = context.good_revision
  1145. bad_rev = context.bad_revision
  1146. print('Scanning from %d to %d (%d revisions).' %
  1147. (good_rev, bad_rev, abs(good_rev - bad_rev)))
  1148. (min_chromium_rev, max_chromium_rev,
  1149. context) = Bisect(context, opts.times, opts.command, args, opts.profile,
  1150. evaluator, opts.verify_range, opts.archive)
  1151. # Get corresponding blink revisions.
  1152. try:
  1153. min_blink_rev = GetBlinkRevisionForChromiumRevision(context,
  1154. min_chromium_rev)
  1155. max_blink_rev = GetBlinkRevisionForChromiumRevision(context,
  1156. max_chromium_rev)
  1157. except Exception:
  1158. # Silently ignore the failure.
  1159. min_blink_rev, max_blink_rev = 0, 0
  1160. if opts.blink:
  1161. # We're done. Let the user know the results in an official manner.
  1162. if good_rev > bad_rev:
  1163. print(DONE_MESSAGE_GOOD_MAX % (str(min_blink_rev), str(max_blink_rev)))
  1164. else:
  1165. print(DONE_MESSAGE_GOOD_MIN % (str(min_blink_rev), str(max_blink_rev)))
  1166. print('BLINK CHANGELOG URL:')
  1167. print(' ' + BLINK_CHANGELOG_URL % (max_blink_rev, min_blink_rev))
  1168. else:
  1169. # We're done. Let the user know the results in an official manner.
  1170. if good_rev > bad_rev:
  1171. print(DONE_MESSAGE_GOOD_MAX % (str(min_chromium_rev),
  1172. str(max_chromium_rev)))
  1173. else:
  1174. print(DONE_MESSAGE_GOOD_MIN % (str(min_chromium_rev),
  1175. str(max_chromium_rev)))
  1176. if min_blink_rev != max_blink_rev:
  1177. print ('NOTE: There is a Blink roll in the range, '
  1178. 'you might also want to do a Blink bisect.')
  1179. print('CHANGELOG URL:')
  1180. PrintChangeLog(min_chromium_rev, max_chromium_rev)
  1181. if __name__ == '__main__':
  1182. sys.exit(main())