PageRenderTime 51ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/build/automationutils.py

https://bitbucket.org/lahabana/mozilla-central
Python | 535 lines | 484 code | 23 blank | 28 comment | 34 complexity | 612bb8d62a3db2bb9b8c32979b5bf4ac MD5 | raw file
Possible License(s): GPL-2.0, Apache-2.0, LGPL-3.0, AGPL-1.0, LGPL-2.1, BSD-3-Clause, JSON, 0BSD, MIT, MPL-2.0-no-copyleft-exception
  1. #
  2. # This Source Code Form is subject to the terms of the Mozilla Public
  3. # License, v. 2.0. If a copy of the MPL was not distributed with this
  4. # file, You can obtain one at http://mozilla.org/MPL/2.0/.
  5. from __future__ import with_statement
  6. import glob, logging, os, platform, shutil, subprocess, sys, tempfile, urllib2, zipfile
  7. import re
  8. from urlparse import urlparse
  9. from operator import itemgetter
  10. __all__ = [
  11. "ZipFileReader",
  12. "addCommonOptions",
  13. "checkForCrashes",
  14. "dumpLeakLog",
  15. "isURL",
  16. "processLeakLog",
  17. "getDebuggerInfo",
  18. "DEBUGGER_INFO",
  19. "replaceBackSlashes",
  20. "wrapCommand",
  21. "ShutdownLeakLogger"
  22. ]
  23. # Map of debugging programs to information about them, like default arguments
  24. # and whether or not they are interactive.
  25. DEBUGGER_INFO = {
  26. # gdb requires that you supply the '--args' flag in order to pass arguments
  27. # after the executable name to the executable.
  28. "gdb": {
  29. "interactive": True,
  30. "args": "-q --args"
  31. },
  32. # valgrind doesn't explain much about leaks unless you set the
  33. # '--leak-check=full' flag.
  34. "valgrind": {
  35. "interactive": False,
  36. "args": "--leak-check=full"
  37. }
  38. }
  39. class ZipFileReader(object):
  40. """
  41. Class to read zip files in Python 2.5 and later. Limited to only what we
  42. actually use.
  43. """
  44. def __init__(self, filename):
  45. self._zipfile = zipfile.ZipFile(filename, "r")
  46. def __del__(self):
  47. self._zipfile.close()
  48. def _getnormalizedpath(self, path):
  49. """
  50. Gets a normalized path from 'path' (or the current working directory if
  51. 'path' is None). Also asserts that the path exists.
  52. """
  53. if path is None:
  54. path = os.curdir
  55. path = os.path.normpath(os.path.expanduser(path))
  56. assert os.path.isdir(path)
  57. return path
  58. def _extractname(self, name, path):
  59. """
  60. Extracts a file with the given name from the zip file to the given path.
  61. Also creates any directories needed along the way.
  62. """
  63. filename = os.path.normpath(os.path.join(path, name))
  64. if name.endswith("/"):
  65. os.makedirs(filename)
  66. else:
  67. path = os.path.split(filename)[0]
  68. if not os.path.isdir(path):
  69. os.makedirs(path)
  70. with open(filename, "wb") as dest:
  71. dest.write(self._zipfile.read(name))
  72. def namelist(self):
  73. return self._zipfile.namelist()
  74. def read(self, name):
  75. return self._zipfile.read(name)
  76. def extract(self, name, path = None):
  77. if hasattr(self._zipfile, "extract"):
  78. return self._zipfile.extract(name, path)
  79. # This will throw if name is not part of the zip file.
  80. self._zipfile.getinfo(name)
  81. self._extractname(name, self._getnormalizedpath(path))
  82. def extractall(self, path = None):
  83. if hasattr(self._zipfile, "extractall"):
  84. return self._zipfile.extractall(path)
  85. path = self._getnormalizedpath(path)
  86. for name in self._zipfile.namelist():
  87. self._extractname(name, path)
  88. log = logging.getLogger()
  89. def isURL(thing):
  90. """Return True if |thing| looks like a URL."""
  91. # We want to download URLs like http://... but not Windows paths like c:\...
  92. return len(urlparse(thing).scheme) >= 2
  93. def addCommonOptions(parser, defaults={}):
  94. parser.add_option("--xre-path",
  95. action = "store", type = "string", dest = "xrePath",
  96. # individual scripts will set a sane default
  97. default = None,
  98. help = "absolute path to directory containing XRE (probably xulrunner)")
  99. if 'SYMBOLS_PATH' not in defaults:
  100. defaults['SYMBOLS_PATH'] = None
  101. parser.add_option("--symbols-path",
  102. action = "store", type = "string", dest = "symbolsPath",
  103. default = defaults['SYMBOLS_PATH'],
  104. help = "absolute path to directory containing breakpad symbols, or the URL of a zip file containing symbols")
  105. parser.add_option("--debugger",
  106. action = "store", dest = "debugger",
  107. help = "use the given debugger to launch the application")
  108. parser.add_option("--debugger-args",
  109. action = "store", dest = "debuggerArgs",
  110. help = "pass the given args to the debugger _before_ "
  111. "the application on the command line")
  112. parser.add_option("--debugger-interactive",
  113. action = "store_true", dest = "debuggerInteractive",
  114. help = "prevents the test harness from redirecting "
  115. "stdout and stderr for interactive debuggers")
  116. def checkForCrashes(dumpDir, symbolsPath, testName=None):
  117. stackwalkPath = os.environ.get('MINIDUMP_STACKWALK', None)
  118. # try to get the caller's filename if no test name is given
  119. if testName is None:
  120. try:
  121. testName = os.path.basename(sys._getframe(1).f_code.co_filename)
  122. except:
  123. testName = "unknown"
  124. # Check preconditions
  125. dumps = glob.glob(os.path.join(dumpDir, '*.dmp'))
  126. if len(dumps) == 0:
  127. return False
  128. foundCrash = False
  129. removeSymbolsPath = False
  130. # If our symbols are at a remote URL, download them now
  131. if isURL(symbolsPath):
  132. print "Downloading symbols from: " + symbolsPath
  133. removeSymbolsPath = True
  134. # Get the symbols and write them to a temporary zipfile
  135. data = urllib2.urlopen(symbolsPath)
  136. symbolsFile = tempfile.TemporaryFile()
  137. symbolsFile.write(data.read())
  138. # extract symbols to a temporary directory (which we'll delete after
  139. # processing all crashes)
  140. symbolsPath = tempfile.mkdtemp()
  141. zfile = ZipFileReader(symbolsFile)
  142. zfile.extractall(symbolsPath)
  143. try:
  144. for d in dumps:
  145. log.info("PROCESS-CRASH | %s | application crashed (minidump found)", testName)
  146. print "Crash dump filename: " + d
  147. if symbolsPath and stackwalkPath and os.path.exists(stackwalkPath):
  148. # run minidump stackwalk
  149. p = subprocess.Popen([stackwalkPath, d, symbolsPath],
  150. stdout=subprocess.PIPE,
  151. stderr=subprocess.PIPE)
  152. (out, err) = p.communicate()
  153. if len(out) > 3:
  154. # minidump_stackwalk is chatty, so ignore stderr when it succeeds.
  155. print out
  156. else:
  157. print "stderr from minidump_stackwalk:"
  158. print err
  159. if p.returncode != 0:
  160. print "minidump_stackwalk exited with return code %d" % p.returncode
  161. else:
  162. if not symbolsPath:
  163. print "No symbols path given, can't process dump."
  164. if not stackwalkPath:
  165. print "MINIDUMP_STACKWALK not set, can't process dump."
  166. elif stackwalkPath and not os.path.exists(stackwalkPath):
  167. print "MINIDUMP_STACKWALK binary not found: %s" % stackwalkPath
  168. dumpSavePath = os.environ.get('MINIDUMP_SAVE_PATH', None)
  169. if dumpSavePath:
  170. shutil.move(d, dumpSavePath)
  171. print "Saved dump as %s" % os.path.join(dumpSavePath,
  172. os.path.basename(d))
  173. else:
  174. os.remove(d)
  175. extra = os.path.splitext(d)[0] + ".extra"
  176. if os.path.exists(extra):
  177. os.remove(extra)
  178. foundCrash = True
  179. finally:
  180. if removeSymbolsPath:
  181. shutil.rmtree(symbolsPath)
  182. return foundCrash
  183. def getFullPath(directory, path):
  184. "Get an absolute path relative to 'directory'."
  185. return os.path.normpath(os.path.join(directory, os.path.expanduser(path)))
  186. def searchPath(directory, path):
  187. "Go one step beyond getFullPath and try the various folders in PATH"
  188. # Try looking in the current working directory first.
  189. newpath = getFullPath(directory, path)
  190. if os.path.isfile(newpath):
  191. return newpath
  192. # At this point we have to fail if a directory was given (to prevent cases
  193. # like './gdb' from matching '/usr/bin/./gdb').
  194. if not os.path.dirname(path):
  195. for dir in os.environ['PATH'].split(os.pathsep):
  196. newpath = os.path.join(dir, path)
  197. if os.path.isfile(newpath):
  198. return newpath
  199. return None
  200. def getDebuggerInfo(directory, debugger, debuggerArgs, debuggerInteractive = False):
  201. debuggerInfo = None
  202. if debugger:
  203. debuggerPath = searchPath(directory, debugger)
  204. if not debuggerPath:
  205. print "Error: Path %s doesn't exist." % debugger
  206. sys.exit(1)
  207. debuggerName = os.path.basename(debuggerPath).lower()
  208. def getDebuggerInfo(type, default):
  209. if debuggerName in DEBUGGER_INFO and type in DEBUGGER_INFO[debuggerName]:
  210. return DEBUGGER_INFO[debuggerName][type]
  211. return default
  212. debuggerInfo = {
  213. "path": debuggerPath,
  214. "interactive" : getDebuggerInfo("interactive", False),
  215. "args": getDebuggerInfo("args", "").split()
  216. }
  217. if debuggerArgs:
  218. debuggerInfo["args"] = debuggerArgs.split()
  219. if debuggerInteractive:
  220. debuggerInfo["interactive"] = debuggerInteractive
  221. return debuggerInfo
  222. def dumpLeakLog(leakLogFile, filter = False):
  223. """Process the leak log, without parsing it.
  224. Use this function if you want the raw log only.
  225. Use it preferably with the |XPCOM_MEM_LEAK_LOG| environment variable.
  226. """
  227. # Don't warn (nor "info") if the log file is not there.
  228. if not os.path.exists(leakLogFile):
  229. return
  230. leaks = open(leakLogFile, "r")
  231. leakReport = leaks.read()
  232. leaks.close()
  233. # Only |XPCOM_MEM_LEAK_LOG| reports can be actually filtered out.
  234. # Only check whether an actual leak was reported.
  235. if filter and not "0 TOTAL " in leakReport:
  236. return
  237. # Simply copy the log.
  238. log.info(leakReport.rstrip("\n"))
  239. def processSingleLeakFile(leakLogFileName, PID, processType, leakThreshold):
  240. """Process a single leak log, corresponding to the specified
  241. process PID and type.
  242. """
  243. # Per-Inst Leaked Total Rem ...
  244. # 0 TOTAL 17 192 419115886 2 ...
  245. # 833 nsTimerImpl 60 120 24726 2 ...
  246. lineRe = re.compile(r"^\s*\d+\s+(?P<name>\S+)\s+"
  247. r"(?P<size>-?\d+)\s+(?P<bytesLeaked>-?\d+)\s+"
  248. r"-?\d+\s+(?P<numLeaked>-?\d+)")
  249. processString = ""
  250. if PID and processType:
  251. processString = "| %s process %s " % (processType, PID)
  252. leaks = open(leakLogFileName, "r")
  253. for line in leaks:
  254. matches = lineRe.match(line)
  255. if (matches and
  256. int(matches.group("numLeaked")) == 0 and
  257. matches.group("name") != "TOTAL"):
  258. continue
  259. log.info(line.rstrip())
  260. leaks.close()
  261. leaks = open(leakLogFileName, "r")
  262. seenTotal = False
  263. crashedOnPurpose = False
  264. prefix = "TEST-PASS"
  265. numObjects = 0
  266. for line in leaks:
  267. if line.find("purposefully crash") > -1:
  268. crashedOnPurpose = True
  269. matches = lineRe.match(line)
  270. if not matches:
  271. continue
  272. name = matches.group("name")
  273. size = int(matches.group("size"))
  274. bytesLeaked = int(matches.group("bytesLeaked"))
  275. numLeaked = int(matches.group("numLeaked"))
  276. if size < 0 or bytesLeaked < 0 or numLeaked < 0:
  277. log.info("TEST-UNEXPECTED-FAIL %s| automationutils.processLeakLog() | negative leaks caught!" %
  278. processString)
  279. if name == "TOTAL":
  280. seenTotal = True
  281. elif name == "TOTAL":
  282. seenTotal = True
  283. # Check for leaks.
  284. if bytesLeaked < 0 or bytesLeaked > leakThreshold:
  285. prefix = "TEST-UNEXPECTED-FAIL"
  286. leakLog = "TEST-UNEXPECTED-FAIL %s| automationutils.processLeakLog() | leaked" \
  287. " %d bytes during test execution" % (processString, bytesLeaked)
  288. elif bytesLeaked > 0:
  289. leakLog = "TEST-PASS %s| automationutils.processLeakLog() | WARNING leaked" \
  290. " %d bytes during test execution" % (processString, bytesLeaked)
  291. else:
  292. leakLog = "TEST-PASS %s| automationutils.processLeakLog() | no leaks detected!" \
  293. % processString
  294. # Remind the threshold if it is not 0, which is the default/goal.
  295. if leakThreshold != 0:
  296. leakLog += " (threshold set at %d bytes)" % leakThreshold
  297. # Log the information.
  298. log.info(leakLog)
  299. else:
  300. if numLeaked != 0:
  301. if numLeaked > 1:
  302. instance = "instances"
  303. rest = " each (%s bytes total)" % matches.group("bytesLeaked")
  304. else:
  305. instance = "instance"
  306. rest = ""
  307. numObjects += 1
  308. if numObjects > 5:
  309. # don't spam brief tinderbox logs with tons of leak output
  310. prefix = "TEST-INFO"
  311. log.info("%(prefix)s %(process)s| automationutils.processLeakLog() | leaked %(numLeaked)d %(instance)s of %(name)s "
  312. "with size %(size)s bytes%(rest)s" %
  313. { "prefix": prefix,
  314. "process": processString,
  315. "numLeaked": numLeaked,
  316. "instance": instance,
  317. "name": name,
  318. "size": matches.group("size"),
  319. "rest": rest })
  320. if not seenTotal:
  321. if crashedOnPurpose:
  322. log.info("INFO | automationutils.processLeakLog() | process %s was " \
  323. "deliberately crashed and thus has no leak log" % PID)
  324. else:
  325. log.info("TEST-UNEXPECTED-FAIL %s| automationutils.processLeakLog() | missing output line for total leaks!" %
  326. processString)
  327. leaks.close()
  328. def processLeakLog(leakLogFile, leakThreshold = 0):
  329. """Process the leak log, including separate leak logs created
  330. by child processes.
  331. Use this function if you want an additional PASS/FAIL summary.
  332. It must be used with the |XPCOM_MEM_BLOAT_LOG| environment variable.
  333. """
  334. if not os.path.exists(leakLogFile):
  335. log.info("WARNING | automationutils.processLeakLog() | refcount logging is off, so leaks can't be detected!")
  336. return
  337. (leakLogFileDir, leakFileBase) = os.path.split(leakLogFile)
  338. pidRegExp = re.compile(r".*?_([a-z]*)_pid(\d*)$")
  339. if leakFileBase[-4:] == ".log":
  340. leakFileBase = leakFileBase[:-4]
  341. pidRegExp = re.compile(r".*?_([a-z]*)_pid(\d*).log$")
  342. for fileName in os.listdir(leakLogFileDir):
  343. if fileName.find(leakFileBase) != -1:
  344. thisFile = os.path.join(leakLogFileDir, fileName)
  345. processPID = 0
  346. processType = None
  347. m = pidRegExp.search(fileName)
  348. if m:
  349. processType = m.group(1)
  350. processPID = m.group(2)
  351. processSingleLeakFile(thisFile, processPID, processType, leakThreshold)
  352. def replaceBackSlashes(input):
  353. return input.replace('\\', '/')
  354. def wrapCommand(cmd):
  355. """
  356. If running on OS X 10.5 or older, wrap |cmd| so that it will
  357. be executed as an i386 binary, in case it's a 32-bit/64-bit universal
  358. binary.
  359. """
  360. if platform.system() == "Darwin" and \
  361. hasattr(platform, 'mac_ver') and \
  362. platform.mac_ver()[0][:4] < '10.6':
  363. return ["arch", "-arch", "i386"] + cmd
  364. # otherwise just execute the command normally
  365. return cmd
  366. class ShutdownLeakLogger(object):
  367. """
  368. Parses the mochitest run log when running a debug build, assigns all leaked
  369. DOM windows (that are still around after test suite shutdown, despite running
  370. the GC) to the tests that created them and prints leak statistics.
  371. """
  372. MAX_LEAK_COUNT = 7
  373. def __init__(self, logger):
  374. self.logger = logger
  375. self.tests = []
  376. self.leakedWindows = {}
  377. self.leakedDocShells = set()
  378. self.currentTest = None
  379. self.seenShutdown = False
  380. def log(self, line):
  381. if line[2:11] == "DOMWINDOW":
  382. self._logWindow(line)
  383. elif line[2:10] == "DOCSHELL":
  384. self._logDocShell(line)
  385. elif line.startswith("TEST-START"):
  386. fileName = line.split(" ")[-1].strip().replace("chrome://mochitests/content/browser/", "")
  387. self.currentTest = {"fileName": fileName, "windows": set(), "docShells": set()}
  388. elif line.startswith("INFO TEST-END"):
  389. # don't track a test if no windows or docShells leaked
  390. if self.currentTest and (self.currentTest["windows"] or self.currentTest["docShells"]):
  391. self.tests.append(self.currentTest)
  392. self.currentTest = None
  393. elif line.startswith("INFO TEST-START | Shutdown"):
  394. self.seenShutdown = True
  395. def parse(self):
  396. leakingTests = self._parseLeakingTests()
  397. if leakingTests:
  398. totalWindows = sum(len(test["leakedWindows"]) for test in leakingTests)
  399. totalDocShells = sum(len(test["leakedDocShells"]) for test in leakingTests)
  400. msgType = "INFO" if totalWindows + totalDocShells <= self.MAX_LEAK_COUNT else "UNEXPECTED-FAIL"
  401. self.logger.info("TEST-%s | ShutdownLeaks | leaked %d DOMWindow(s) and %d DocShell(s) until shutdown", msgType, totalWindows, totalDocShells)
  402. for test in leakingTests:
  403. self.logger.info("\n[%s]", test["fileName"])
  404. for url, count in self._zipLeakedWindows(test["leakedWindows"]):
  405. self.logger.info(" %d window(s) [url = %s]", count, url)
  406. if test["leakedDocShells"]:
  407. self.logger.info(" %d docShell(s)", len(test["leakedDocShells"]))
  408. def _logWindow(self, line):
  409. created = line[:2] == "++"
  410. id = self._parseValue(line, "serial")
  411. # log line has invalid format
  412. if not id:
  413. return
  414. if self.currentTest:
  415. windows = self.currentTest["windows"]
  416. if created:
  417. windows.add(id)
  418. else:
  419. windows.discard(id)
  420. elif self.seenShutdown and not created:
  421. self.leakedWindows[id] = self._parseValue(line, "url")
  422. def _logDocShell(self, line):
  423. created = line[:2] == "++"
  424. id = self._parseValue(line, "id")
  425. # log line has invalid format
  426. if not id:
  427. return
  428. if self.currentTest:
  429. docShells = self.currentTest["docShells"]
  430. if created:
  431. docShells.add(id)
  432. else:
  433. docShells.discard(id)
  434. elif self.seenShutdown and not created:
  435. self.leakedDocShells.add(id)
  436. def _parseValue(self, line, name):
  437. match = re.search("\[%s = (.+?)\]" % name, line)
  438. if match:
  439. return match.group(1)
  440. return None
  441. def _parseLeakingTests(self):
  442. leakingTests = []
  443. for test in self.tests:
  444. test["leakedWindows"] = [self.leakedWindows[id] for id in test["windows"] if id in self.leakedWindows]
  445. test["leakedDocShells"] = [id for id in test["docShells"] if id in self.leakedDocShells]
  446. test["leakCount"] = len(test["leakedWindows"]) + len(test["leakedDocShells"])
  447. if test["leakCount"]:
  448. leakingTests.append(test)
  449. return sorted(leakingTests, key=itemgetter("leakCount"), reverse=True)
  450. def _zipLeakedWindows(self, leakedWindows):
  451. counts = []
  452. counted = set()
  453. for url in leakedWindows:
  454. if not url in counted:
  455. counts.append((url, leakedWindows.count(url)))
  456. counted.add(url)
  457. return sorted(counts, key=itemgetter(1), reverse=True)