queues.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. # Copyright (c) 2009 Google Inc. All rights reserved.
  2. # Copyright (c) 2009 Apple Inc. All rights reserved.
  3. #
  4. # Redistribution and use in source and binary forms, with or without
  5. # modification, are permitted provided that the following conditions are
  6. # met:
  7. #
  8. # * Redistributions of source code must retain the above copyright
  9. # notice, this list of conditions and the following disclaimer.
  10. # * Redistributions in binary form must reproduce the above
  11. # copyright notice, this list of conditions and the following disclaimer
  12. # in the documentation and/or other materials provided with the
  13. # distribution.
  14. # * Neither the name of Google Inc. nor the names of its
  15. # contributors may be used to endorse or promote products derived from
  16. # this software without specific prior written permission.
  17. #
  18. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  20. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  21. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  22. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  23. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  24. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  25. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  26. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  28. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. import codecs
  30. import logging
  31. import os
  32. import sys
  33. import time
  34. import traceback
  35. from datetime import datetime
  36. from optparse import make_option
  37. from StringIO import StringIO
  38. from webkitpy.common.config.committervalidator import CommitterValidator
  39. from webkitpy.common.config.ports import DeprecatedPort
  40. from webkitpy.common.net.bugzilla import Attachment
  41. from webkitpy.common.net.statusserver import StatusServer
  42. from webkitpy.common.system.executive import ScriptError
  43. from webkitpy.tool.bot.botinfo import BotInfo
  44. from webkitpy.tool.bot.commitqueuetask import CommitQueueTask, CommitQueueTaskDelegate
  45. from webkitpy.tool.bot.expectedfailures import ExpectedFailures
  46. from webkitpy.tool.bot.feeders import CommitQueueFeeder, EWSFeeder
  47. from webkitpy.tool.bot.flakytestreporter import FlakyTestReporter
  48. from webkitpy.tool.bot.layouttestresultsreader import LayoutTestResultsReader
  49. from webkitpy.tool.bot.patchanalysistask import UnableToApplyPatch
  50. from webkitpy.tool.bot.queueengine import QueueEngine, QueueEngineDelegate
  51. from webkitpy.tool.bot.stylequeuetask import StyleQueueTask, StyleQueueTaskDelegate
  52. from webkitpy.tool.commands.stepsequence import StepSequenceErrorHandler
  53. from webkitpy.tool.multicommandtool import Command, TryAgain
  54. _log = logging.getLogger(__name__)
  55. class AbstractQueue(Command, QueueEngineDelegate):
  56. watchers = [
  57. ]
  58. _pass_status = "Pass"
  59. _fail_status = "Fail"
  60. _retry_status = "Retry"
  61. _error_status = "Error"
  62. def __init__(self, options=None): # Default values should never be collections (like []) as default values are shared between invocations
  63. options_list = (options or []) + [
  64. make_option("--no-confirm", action="store_false", dest="confirm", default=True, help="Do not ask the user for confirmation before running the queue. Dangerous!"),
  65. make_option("--exit-after-iteration", action="store", type="int", dest="iterations", default=None, help="Stop running the queue after iterating this number of times."),
  66. ]
  67. self.help_text = "Run the %s" % self.name
  68. Command.__init__(self, options=options_list)
  69. self._iteration_count = 0
  70. def _cc_watchers(self, bug_id):
  71. try:
  72. self._tool.bugs.add_cc_to_bug(bug_id, self.watchers)
  73. except Exception, e:
  74. traceback.print_exc()
  75. _log.error("Failed to CC watchers.")
  76. def run_webkit_patch(self, args):
  77. webkit_patch_args = [self._tool.path()]
  78. # FIXME: This is a hack, we should have a more general way to pass global options.
  79. # FIXME: We must always pass global options and their value in one argument
  80. # because our global option code looks for the first argument which does
  81. # not begin with "-" and assumes that is the command name.
  82. webkit_patch_args += ["--status-host=%s" % self._tool.status_server.host]
  83. if self._tool.status_server.bot_id:
  84. webkit_patch_args += ["--bot-id=%s" % self._tool.status_server.bot_id]
  85. if self._options.port:
  86. webkit_patch_args += ["--port=%s" % self._options.port]
  87. webkit_patch_args.extend(args)
  88. try:
  89. args_for_printing = list(webkit_patch_args)
  90. args_for_printing[0] = 'webkit-patch' # Printing our path for each log is redundant.
  91. _log.info("Running: %s" % self._tool.executive.command_for_printing(args_for_printing))
  92. command_output = self._tool.executive.run_command(webkit_patch_args, cwd=self._tool.scm().checkout_root)
  93. except ScriptError, e:
  94. # Make sure the whole output gets printed if the command failed.
  95. _log.error(e.message_with_output(output_limit=None))
  96. raise
  97. return command_output
  98. def _log_directory(self):
  99. return os.path.join("..", "%s-logs" % self.name)
  100. # QueueEngineDelegate methods
  101. def queue_log_path(self):
  102. return os.path.join(self._log_directory(), "%s.log" % self.name)
  103. def work_item_log_path(self, work_item):
  104. raise NotImplementedError, "subclasses must implement"
  105. def begin_work_queue(self):
  106. _log.info("CAUTION: %s will discard all local changes in \"%s\"" % (self.name, self._tool.scm().checkout_root))
  107. if self._options.confirm:
  108. response = self._tool.user.prompt("Are you sure? Type \"yes\" to continue: ")
  109. if (response != "yes"):
  110. _log.error("User declined.")
  111. sys.exit(1)
  112. _log.info("Running WebKit %s." % self.name)
  113. self._tool.status_server.update_status(self.name, "Starting Queue")
  114. def stop_work_queue(self, reason):
  115. self._tool.status_server.update_status(self.name, "Stopping Queue, reason: %s" % reason)
  116. def should_continue_work_queue(self):
  117. self._iteration_count += 1
  118. return not self._options.iterations or self._iteration_count <= self._options.iterations
  119. def next_work_item(self):
  120. raise NotImplementedError, "subclasses must implement"
  121. def process_work_item(self, work_item):
  122. raise NotImplementedError, "subclasses must implement"
  123. def handle_unexpected_error(self, work_item, message):
  124. raise NotImplementedError, "subclasses must implement"
  125. # Command methods
  126. def execute(self, options, args, tool, engine=QueueEngine):
  127. self._options = options # FIXME: This code is wrong. Command.options is a list, this assumes an Options element!
  128. self._tool = tool # FIXME: This code is wrong too! Command.bind_to_tool handles this!
  129. return engine(self.name, self, self._tool.wakeup_event, self._options.seconds_to_sleep).run()
  130. @classmethod
  131. def _log_from_script_error_for_upload(cls, script_error, output_limit=None):
  132. # We have seen request timeouts with app engine due to large
  133. # log uploads. Trying only the last 512k.
  134. if not output_limit:
  135. output_limit = 512 * 1024 # 512k
  136. output = script_error.message_with_output(output_limit=output_limit)
  137. # We pre-encode the string to a byte array before passing it
  138. # to status_server, because ClientForm (part of mechanize)
  139. # wants a file-like object with pre-encoded data.
  140. return StringIO(output.encode("utf-8"))
  141. @classmethod
  142. def _update_status_for_script_error(cls, tool, state, script_error, is_error=False):
  143. message = str(script_error)
  144. if is_error:
  145. message = "Error: %s" % message
  146. failure_log = cls._log_from_script_error_for_upload(script_error)
  147. return tool.status_server.update_status(cls.name, message, state["patch"], failure_log)
  148. class FeederQueue(AbstractQueue):
  149. name = "feeder-queue"
  150. _sleep_duration = 30 # seconds
  151. # AbstractQueue methods
  152. def begin_work_queue(self):
  153. AbstractQueue.begin_work_queue(self)
  154. self.feeders = [
  155. CommitQueueFeeder(self._tool),
  156. EWSFeeder(self._tool),
  157. ]
  158. def next_work_item(self):
  159. # This really show inherit from some more basic class that doesn't
  160. # understand work items, but the base class in the heirarchy currently
  161. # understands work items.
  162. return "synthetic-work-item"
  163. def process_work_item(self, work_item):
  164. for feeder in self.feeders:
  165. feeder.feed()
  166. time.sleep(self._sleep_duration)
  167. return True
  168. def work_item_log_path(self, work_item):
  169. return None
  170. def handle_unexpected_error(self, work_item, message):
  171. _log.error(message)
  172. class AbstractPatchQueue(AbstractQueue):
  173. def _update_status(self, message, patch=None, results_file=None):
  174. return self._tool.status_server.update_status(self.name, message, patch, results_file)
  175. def _next_patch(self):
  176. # FIXME: Bugzilla accessibility should be checked here; if it's unaccessible,
  177. # it should return None.
  178. patch = None
  179. while not patch:
  180. patch_id = self._tool.status_server.next_work_item(self.name)
  181. if not patch_id:
  182. return None
  183. patch = self._tool.bugs.fetch_attachment(patch_id)
  184. if not patch:
  185. # FIXME: Using a fake patch because release_work_item has the wrong API.
  186. # We also don't really need to release the lock (although that's fine),
  187. # mostly we just need to remove this bogus patch from our queue.
  188. # If for some reason bugzilla is just down, then it will be re-fed later.
  189. fake_patch = Attachment({'id': patch_id}, None)
  190. self._release_work_item(fake_patch)
  191. return patch
  192. def _release_work_item(self, patch):
  193. self._tool.status_server.release_work_item(self.name, patch)
  194. def _did_pass(self, patch):
  195. self._update_status(self._pass_status, patch)
  196. self._release_work_item(patch)
  197. def _did_fail(self, patch):
  198. self._update_status(self._fail_status, patch)
  199. self._release_work_item(patch)
  200. def _did_retry(self, patch):
  201. self._update_status(self._retry_status, patch)
  202. self._release_work_item(patch)
  203. def _did_error(self, patch, reason):
  204. message = "%s: %s" % (self._error_status, reason)
  205. self._update_status(message, patch)
  206. self._release_work_item(patch)
  207. def work_item_log_path(self, patch):
  208. return os.path.join(self._log_directory(), "%s.log" % patch.bug_id())
  209. # Used to share code between the EWS and commit-queue.
  210. class PatchProcessingQueue(AbstractPatchQueue):
  211. # Subclasses must override.
  212. port_name = None
  213. def __init__(self, options=None):
  214. self._port = None # We can't instantiate port here because tool isn't avaialble.
  215. AbstractPatchQueue.__init__(self, options)
  216. # FIXME: This is a hack to map between the old port names and the new port names.
  217. def _new_port_name_from_old(self, port_name, platform):
  218. # ApplePort.determine_full_port_name asserts if the name doesn't include version.
  219. if port_name == 'mac':
  220. return 'mac-' + platform.os_version
  221. if port_name == 'win':
  222. return 'win-future'
  223. return port_name
  224. def begin_work_queue(self):
  225. AbstractPatchQueue.begin_work_queue(self)
  226. if not self.port_name:
  227. return
  228. # FIXME: This is only used for self._deprecated_port.flag()
  229. self._deprecated_port = DeprecatedPort.port(self.port_name)
  230. # FIXME: This violates abstraction
  231. self._tool._deprecated_port = self._deprecated_port
  232. self._port = self._tool.port_factory.get(self._new_port_name_from_old(self.port_name, self._tool.platform))
  233. def _upload_results_archive_for_patch(self, patch, results_archive_zip):
  234. if not self._port:
  235. self._port = self._tool.port_factory.get(self._new_port_name_from_old(self.port_name, self._tool.platform))
  236. bot_id = self._tool.status_server.bot_id or "bot"
  237. description = "Archive of layout-test-results from %s for %s" % (bot_id, self._port.name())
  238. # results_archive is a ZipFile object, grab the File object (.fp) to pass to Mechanize for uploading.
  239. results_archive_file = results_archive_zip.fp
  240. # Rewind the file object to start (since Mechanize won't do that automatically)
  241. # See https://bugs.webkit.org/show_bug.cgi?id=54593
  242. results_archive_file.seek(0)
  243. # FIXME: This is a small lie to always say run-webkit-tests since Chromium uses new-run-webkit-tests.
  244. # We could make this code look up the test script name off the port.
  245. comment_text = "The attached test failures were seen while running run-webkit-tests on the %s.\n" % (self.name)
  246. # FIXME: We could easily list the test failures from the archive here,
  247. # currently callers do that separately.
  248. comment_text += BotInfo(self._tool, self._port.name()).summary_text()
  249. self._tool.bugs.add_attachment_to_bug(patch.bug_id(), results_archive_file, description, filename="layout-test-results.zip", comment_text=comment_text)
  250. class CommitQueue(PatchProcessingQueue, StepSequenceErrorHandler, CommitQueueTaskDelegate):
  251. name = "commit-queue"
  252. port_name = "mac-mountainlion"
  253. # AbstractPatchQueue methods
  254. def begin_work_queue(self):
  255. PatchProcessingQueue.begin_work_queue(self)
  256. self.committer_validator = CommitterValidator(self._tool)
  257. self._expected_failures = ExpectedFailures()
  258. self._layout_test_results_reader = LayoutTestResultsReader(self._tool, self._port.results_directory(), self._log_directory())
  259. def next_work_item(self):
  260. return self._next_patch()
  261. def process_work_item(self, patch):
  262. self._cc_watchers(patch.bug_id())
  263. task = CommitQueueTask(self, patch)
  264. try:
  265. if task.run():
  266. self._did_pass(patch)
  267. return True
  268. self._did_retry(patch)
  269. except ScriptError, e:
  270. validator = CommitterValidator(self._tool)
  271. validator.reject_patch_from_commit_queue(patch.id(), self._error_message_for_bug(task, patch, e))
  272. results_archive = task.results_archive_from_patch_test_run(patch)
  273. if results_archive:
  274. self._upload_results_archive_for_patch(patch, results_archive)
  275. self._did_fail(patch)
  276. def _failing_tests_message(self, task, patch):
  277. results = task.results_from_patch_test_run(patch)
  278. unexpected_failures = self._expected_failures.unexpected_failures_observed(results)
  279. if not unexpected_failures:
  280. return None
  281. return "New failing tests:\n%s" % "\n".join(unexpected_failures)
  282. def _error_message_for_bug(self, task, patch, script_error):
  283. message = self._failing_tests_message(task, patch)
  284. if not message:
  285. message = script_error.message_with_output()
  286. results_link = self._tool.status_server.results_url_for_status(task.failure_status_id)
  287. return "%s\nFull output: %s" % (message, results_link)
  288. def handle_unexpected_error(self, patch, message):
  289. self.committer_validator.reject_patch_from_commit_queue(patch.id(), message)
  290. # CommitQueueTaskDelegate methods
  291. def run_command(self, command):
  292. self.run_webkit_patch(command + [self._deprecated_port.flag()])
  293. def command_passed(self, message, patch):
  294. self._update_status(message, patch=patch)
  295. def command_failed(self, message, script_error, patch):
  296. failure_log = self._log_from_script_error_for_upload(script_error)
  297. return self._update_status(message, patch=patch, results_file=failure_log)
  298. def expected_failures(self):
  299. return self._expected_failures
  300. def test_results(self):
  301. return self._layout_test_results_reader.results()
  302. def archive_last_test_results(self, patch):
  303. return self._layout_test_results_reader.archive(patch)
  304. def build_style(self):
  305. return "release"
  306. def refetch_patch(self, patch):
  307. return self._tool.bugs.fetch_attachment(patch.id())
  308. def report_flaky_tests(self, patch, flaky_test_results, results_archive=None):
  309. reporter = FlakyTestReporter(self._tool, self.name)
  310. reporter.report_flaky_tests(patch, flaky_test_results, results_archive)
  311. def did_pass_testing_ews(self, patch):
  312. # Only Mac and Mac WK2 run tests
  313. # FIXME: We shouldn't have to hard-code it here.
  314. patch_status = self._tool.status_server.patch_status
  315. return patch_status("mac-ews", patch.id()) == self._pass_status or patch_status("mac-wk2-ews", patch.id()) == self._pass_status
  316. # StepSequenceErrorHandler methods
  317. @classmethod
  318. def handle_script_error(cls, tool, state, script_error):
  319. # Hitting this error handler should be pretty rare. It does occur,
  320. # however, when a patch no longer applies to top-of-tree in the final
  321. # land step.
  322. _log.error(script_error.message_with_output())
  323. @classmethod
  324. def handle_checkout_needs_update(cls, tool, state, options, error):
  325. message = "Tests passed, but commit failed (checkout out of date). Updating, then landing without building or re-running tests."
  326. tool.status_server.update_status(cls.name, message, state["patch"])
  327. # The only time when we find out that out checkout needs update is
  328. # when we were ready to actually pull the trigger and land the patch.
  329. # Rather than spinning in the master process, we retry without
  330. # building or testing, which is much faster.
  331. options.build = False
  332. options.test = False
  333. options.update = True
  334. raise TryAgain()
  335. class AbstractReviewQueue(PatchProcessingQueue, StepSequenceErrorHandler):
  336. """This is the base-class for the EWS queues and the style-queue."""
  337. def __init__(self, options=None):
  338. PatchProcessingQueue.__init__(self, options)
  339. def review_patch(self, patch):
  340. raise NotImplementedError("subclasses must implement")
  341. # AbstractPatchQueue methods
  342. def begin_work_queue(self):
  343. PatchProcessingQueue.begin_work_queue(self)
  344. def next_work_item(self):
  345. return self._next_patch()
  346. def process_work_item(self, patch):
  347. try:
  348. if not self.review_patch(patch):
  349. return False
  350. self._did_pass(patch)
  351. return True
  352. except ScriptError, e:
  353. if e.exit_code != QueueEngine.handled_error_code:
  354. self._did_fail(patch)
  355. else:
  356. # The subprocess handled the error, but won't have released the patch, so we do.
  357. # FIXME: We need to simplify the rules by which _release_work_item is called.
  358. self._release_work_item(patch)
  359. raise e
  360. def handle_unexpected_error(self, patch, message):
  361. _log.error(message)
  362. # StepSequenceErrorHandler methods
  363. @classmethod
  364. def handle_script_error(cls, tool, state, script_error):
  365. _log.error(script_error.output)
  366. class StyleQueue(AbstractReviewQueue, StyleQueueTaskDelegate):
  367. name = "style-queue"
  368. def __init__(self):
  369. AbstractReviewQueue.__init__(self)
  370. def review_patch(self, patch):
  371. task = StyleQueueTask(self, patch)
  372. if not task.validate():
  373. self._did_error(patch, "%s did not process patch." % self.name)
  374. return False
  375. try:
  376. return task.run()
  377. except UnableToApplyPatch, e:
  378. self._did_error(patch, "%s unable to apply patch." % self.name)
  379. return False
  380. except ScriptError, e:
  381. message = "Attachment %s did not pass %s:\n\n%s\n\nIf any of these errors are false positives, please file a bug against check-webkit-style." % (patch.id(), self.name, e.output)
  382. self._tool.bugs.post_comment_to_bug(patch.bug_id(), message, cc=self.watchers)
  383. self._did_fail(patch)
  384. return False
  385. return True
  386. # StyleQueueTaskDelegate methods
  387. def run_command(self, command):
  388. self.run_webkit_patch(command)
  389. def command_passed(self, message, patch):
  390. self._update_status(message, patch=patch)
  391. def command_failed(self, message, script_error, patch):
  392. failure_log = self._log_from_script_error_for_upload(script_error)
  393. return self._update_status(message, patch=patch, results_file=failure_log)
  394. def expected_failures(self):
  395. return None
  396. def refetch_patch(self, patch):
  397. return self._tool.bugs.fetch_attachment(patch.id())