blob: 9aed8ec46f615d67d9fcb881cefd832f6beebc6a [file] [log] [blame]
Chris Masone24b80f12012-02-14 14:18:01 -08001#!/usr/bin/python
2#
3# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
4# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
6
Fang Deng5a43be62014-05-07 17:17:04 -07007
Chris Masone24b80f12012-02-14 14:18:01 -08008"""Tool for running suites of tests and waiting for completion.
9
Fang Deng5a43be62014-05-07 17:17:04 -070010The desired test suite will be scheduled with autotest. By default,
Chris Masone24b80f12012-02-14 14:18:01 -080011this tool will block until the job is complete, printing a summary
12at the end. Error conditions result in exceptions.
13
14This is intended for use only with Chrome OS test suits that leverage the
15dynamic suite infrastructure in server/cros/dynamic_suite.py.
Fang Deng5a43be62014-05-07 17:17:04 -070016
17This script exits with one of the following codes:
180 - OK: Suite finished successfully
191 - ERROR: Test(s) failed, or hits its own timeout
Fang Dengaeab6172014-05-07 17:17:04 -0700202 - WARNING: Test(s) raised a warning or passed on retry, none failed/timed out.
Fang Deng5a43be62014-05-07 17:17:04 -0700213 - INFRA_FAILURE: Infrastructure related issues, e.g.
22 * Lab is down
23 * Too many duts (defined as a constant) in repair failed status
24 * Suite job issues, like bug in dynamic suite,
25 user aborted the suite, lose a drone/all devservers/rpc server,
26 0 tests ran, etc.
Fang Deng95af42f2014-09-12 14:16:11 -070027 * provision failed
28 TODO(fdeng): crbug.com/413918, reexamine treating all provision
29 failures as INFRA failures.
Fang Deng5a43be62014-05-07 17:17:04 -0700304 - SUITE_TIMEOUT: Suite timed out, some tests ran,
31 none failed by the time the suite job was aborted. This will cover,
32 but not limited to, the following cases:
33 * A devserver failure that manifests as a timeout
34 * No DUTs available midway through a suite
35 * Provision/Reset/Cleanup took longer time than expected for new image
36 * A regression in scheduler tick time.
Fang Deng6197da32014-09-25 10:18:48 -0700375- BOARD_NOT_AVAILABLE: If there is no host for the requested board/pool.
386- INVALID_OPTIONS: If options are not valid.
Chris Masone24b80f12012-02-14 14:18:01 -080039"""
40
Allen Li93f4db52016-09-14 14:44:59 -070041import argparse
42import ast
Allen Licc205492017-07-10 17:26:04 -070043import collections
Allen Li340414e2016-08-16 14:19:08 -070044from collections import namedtuple
Chris Masonecfa7efc2012-09-06 16:00:07 -070045from datetime import datetime
Allen Li93f4db52016-09-14 14:44:59 -070046from datetime import timedelta
Allen Licc205492017-07-10 17:26:04 -070047import functools
Allen Li93f4db52016-09-14 14:44:59 -070048import getpass
49import json
50import logging
51import os
52import re
53import sys
54import time
Allen Li04afc8f2017-11-27 15:36:34 -080055import warnings
Chris Masonecfa7efc2012-09-06 16:00:07 -070056
Chris Masone24b80f12012-02-14 14:18:01 -080057import common
Allen Lie082ced2016-09-14 15:19:20 -070058from chromite.lib import buildbot_annotations as annotations
59
Shuqian Zhao2fecacd2015-08-05 22:56:30 -070060from autotest_lib.client.common_lib import control_data
Fang Deng5a43be62014-05-07 17:17:04 -070061from autotest_lib.client.common_lib import error
J. Richard Barnette3cbd76b2013-11-27 12:11:25 -080062from autotest_lib.client.common_lib import global_config, enum
63from autotest_lib.client.common_lib import priorities
Dan Shidfea3682014-08-10 23:38:40 -070064from autotest_lib.client.common_lib import time_utils
Prashanth B6285f6a2014-05-08 18:01:27 -070065from autotest_lib.client.common_lib.cros import retry
Prathmesh Prabhucd246f52018-01-03 13:45:48 -080066from autotest_lib.frontend.afe import rpc_client_lib
Prashanth B923ca262014-03-14 12:36:29 -070067from autotest_lib.frontend.afe.json_rpc import proxy
xixuanae791b12017-06-29 15:40:19 -070068from autotest_lib.server import site_utils
J. Richard Barnette3cbd76b2013-11-27 12:11:25 -080069from autotest_lib.server import utils
Dan Shi36cfd832014-10-10 13:38:51 -070070from autotest_lib.server.cros import provision
Chris Masone44e4d6c2012-08-15 14:25:53 -070071from autotest_lib.server.cros.dynamic_suite import constants
Chris Masoneb4935552012-08-14 12:05:54 -070072from autotest_lib.server.cros.dynamic_suite import frontend_wrappers
Prashanth B923ca262014-03-14 12:36:29 -070073from autotest_lib.server.cros.dynamic_suite import reporting_utils
J. Richard Barnettee7b98bb2013-08-21 16:34:16 -070074from autotest_lib.server.cros.dynamic_suite import tools
Prashanth B923ca262014-03-14 12:36:29 -070075from autotest_lib.site_utils import diagnosis_utils
MK Ryu977a9752014-10-21 11:58:09 -070076from autotest_lib.site_utils import job_overhead
77
Chris Masone1120cdf2012-02-27 17:35:07 -080078CONFIG = global_config.global_config
79
Allen Lidc2c69a2016-09-14 19:05:47 -070080_DEFAULT_AUTOTEST_INSTANCE = CONFIG.get_config_value(
81 'SERVER', 'hostname', type=str)
82_URL_PATTERN = CONFIG.get_config_value('CROS', 'log_url_pattern', type=str)
Simran Basi7203d4e2015-02-03 15:50:18 -080083
Simran Basi22aa9fe2012-12-07 16:37:09 -080084# Return code that will be sent back to autotest_rpc_server.py
Fang Deng5a43be62014-05-07 17:17:04 -070085RETURN_CODES = enum.Enum(
Fang Dengfb4a9492014-09-18 17:52:06 -070086 'OK', 'ERROR', 'WARNING', 'INFRA_FAILURE', 'SUITE_TIMEOUT',
Simran Basiba90ec82017-02-17 02:02:50 +000087 'BOARD_NOT_AVAILABLE', 'INVALID_OPTIONS')
Fang Deng5a43be62014-05-07 17:17:04 -070088
xixuanae791b12017-06-29 15:40:19 -070089# Minimum RPC timeout setting for calls expected to take long time, e.g.,
90# create_suite_job. If default socket time (socket.getdefaulttimeout()) is
91# None or greater than this value, the default will be used.
92# The value here is set to be the same as the timeout for the RetryingAFE object
93# so long running RPCs can wait long enough before being aborted.
94_MIN_RPC_TIMEOUT = 600
95
96# Number of days back to search for existing job.
97_SEARCH_JOB_MAX_DAYS = 14
98
Allen Li977760b2017-11-06 18:11:37 -080099_PROVISION_SUITE = 'provision'
100
Fang Deng5a43be62014-05-07 17:17:04 -0700101
Allen Licc205492017-07-10 17:26:04 -0700102@functools.total_ordering
103class _ReturnResult(object):
104 """Represents overall result of run_suite operation.
Fang Deng5a43be62014-05-07 17:17:04 -0700105
Allen Licc205492017-07-10 17:26:04 -0700106 _ReturnResult instances sort based on priority (the order in
107 _RETURN_RESULTS).
Fang Deng5a43be62014-05-07 17:17:04 -0700108
Allen Licc205492017-07-10 17:26:04 -0700109 Furthermore, _ReturnResult instances can be combined by bitwise or
110 ("union"), which returns the instance with the higher priority
111 between the two (the instance with higher priority is a "superset"
112 of the other).
Fang Deng5a43be62014-05-07 17:17:04 -0700113
Allen Licc205492017-07-10 17:26:04 -0700114 Do not create new instances of this; use _RETURN_RESULTS instead.
Fang Deng5a43be62014-05-07 17:17:04 -0700115 """
Allen Licc205492017-07-10 17:26:04 -0700116
117 def __init__(self, return_code, message):
118 self.return_code = return_code
119 self.message = message
120
121 def __repr__(self):
122 return '<{cls} {key}, {this.return_code}, {this.message}>'.format(
123 cls=type(self).__name__,
124 key=self._getkey(),
125 this=self)
126
127 def __gt__(self, other):
128 if isinstance(other, type(self)):
129 return self._getkey() > other._getkey()
130 else:
131 return NotImplemented
132
133 def __eq__(self, other):
134 if isinstance(other, type(self)):
135 return (self.return_code == other.return_code
136 and self.message == other.message)
137 else:
138 return NotImplemented
139
140 def __hash__(self):
141 return hash(self.return_code) ^ hash(self.message)
142
143 def __or__(self, other):
144 if isinstance(other, type(self)):
145 if self > other:
146 return self
147 else:
148 return other
149 else:
150 return NotImplemented
151
152 def _getkey(self):
153 """Return sort key."""
154 return _RETURN_RESULTS_LIST.index(self)
155
156 def suite_result(self, output_dict=None):
157 """Make a SuiteResult using this _ReturnResult.
158
159 @param output_dict: output_dict to merge into SuiteResult.
160 """
161 if output_dict is None:
162 output_dict = dict()
163 else:
164 output_dict = output_dict.copy()
165 if self.message:
166 output_dict['return_message'] = self.message
167 return SuiteResult(self.return_code, output_dict)
168
169
170_RETURN_RESULTS = collections.OrderedDict([
171 ('ok', _ReturnResult(RETURN_CODES.OK, '')),
172
173 ('test_warning', _ReturnResult(
174 RETURN_CODES.WARNING, 'Test job raised warning.')),
175 ('suite_warning', _ReturnResult(
176 RETURN_CODES.WARNING, 'Suite job raised warning.')),
177 ('test_retry', _ReturnResult(
178 RETURN_CODES.WARNING, 'Tests were retried.')),
179
180 ('aborted_test', _ReturnResult(
181 RETURN_CODES.SUITE_TIMEOUT,
182 'Tests were aborted before running; suite must have timed out.')),
183 ('suite_timeout', _ReturnResult(
184 RETURN_CODES.SUITE_TIMEOUT, 'Suite job timed out.')),
185
186 ('test_views_missing', _ReturnResult(
187 RETURN_CODES.INFRA_FAILURE, 'No test views found.')),
188 ('suite_failed', _ReturnResult(
189 RETURN_CODES.INFRA_FAILURE, 'Suite job failed.')),
190 ('provision_failed', _ReturnResult(
191 RETURN_CODES.INFRA_FAILURE, 'Provisioning failed.')),
192
193 ('test_failure', _ReturnResult(
194 RETURN_CODES.ERROR, 'Tests failed.')),
195])
196_RETURN_RESULTS_LIST = list(_RETURN_RESULTS.values())
Simran Basi22aa9fe2012-12-07 16:37:09 -0800197
Chris Masonedfa0beba2012-03-19 11:41:47 -0700198
Allen Li93f4db52016-09-14 14:44:59 -0700199def bool_str(x):
200 """Boolean string type for option arguments.
201
202 @param x: string representation of boolean value.
203
204 """
205 if x == 'True':
206 return True
207 elif x == 'False':
208 return False
209 else:
210 raise argparse.ArgumentTypeError(
211 '%s is not one of True or False' % (x,))
212
213
Allen Li603728a2016-12-08 13:58:11 -0800214def _get_priority_value(x):
215 """Convert a priority representation to its int value.
216
217 Priorities can be described either by an int value (possibly as a string)
218 or a name string. This function coerces both forms to an int value.
219
220 This function is intended for casting command line arguments during
221 parsing.
222
223 @param x: priority value as an int, int string, or name string
224
225 @returns: int value of priority
226 """
227 try:
228 return int(x)
229 except ValueError:
230 try:
231 return priorities.Priority.get_value(x)
232 except AttributeError:
233 raise argparse.ArgumentTypeError(
234 'Unknown priority level %s. Try one of %s.'
235 % (x, ', '.join(priorities.Priority.names)))
236
237
Allen Li93f4db52016-09-14 14:44:59 -0700238def make_parser():
239 """Make ArgumentParser instance for run_suite.py."""
240 parser = argparse.ArgumentParser(
241 usage="%(prog)s [options]")
242 parser.add_argument("-b", "--board", dest="board")
Prathmesh Prabhu9b8e7ad2017-10-30 14:26:13 -0700243 parser.add_argument(
244 "--model",
245 help="The device model to run tests against. For non-unified "
246 "builds, model and board are synonymous, but board is more "
247 "accurate in some cases. Only pass this option if your build "
248 "is a unified build.",
249 )
Allen Li93f4db52016-09-14 14:44:59 -0700250 parser.add_argument("-i", "--build", dest="build")
251 parser.add_argument(
252 "-w", "--web", dest="web", default=None,
253 help="Address of a webserver to receive suite requests.")
254 parser.add_argument(
Rohit Makasanadf0a3a32017-06-30 13:55:18 -0700255 '--cheets_build', dest='cheets_build', default=None,
256 help='ChromeOS Android build to be installed on dut.')
257 parser.add_argument(
Allen Li93f4db52016-09-14 14:44:59 -0700258 '--firmware_rw_build', dest='firmware_rw_build', default=None,
259 help='Firmware build to be installed in dut RW firmware.')
260 parser.add_argument(
261 '--firmware_ro_build', dest='firmware_ro_build', default=None,
262 help='Firmware build to be installed in dut RO firmware.')
263 parser.add_argument(
264 '--test_source_build', dest='test_source_build', default=None,
265 help=('Build that contains the test code, '
266 'e.g., it can be the value of `--build`, '
267 '`--firmware_rw_build` or `--firmware_ro_build` '
268 'arguments. Default is None, that is, use the test '
269 'code from `--build` (CrOS image)'))
Chris Masone359c0fd2012-03-13 15:18:59 -0700270 # This should just be a boolean flag, but the autotest "proxy" code
271 # can't handle flags that don't take arguments.
Allen Li93f4db52016-09-14 14:44:59 -0700272 parser.add_argument(
273 "-n", "--no_wait", dest="no_wait", default=False, type=bool_str,
274 help='Must pass "True" or "False" if used.')
Alex Miller0032e932013-10-23 12:52:58 -0700275 # If you really want no pool, --pool="" will do it. USE WITH CARE.
Allen Li93f4db52016-09-14 14:44:59 -0700276 parser.add_argument("-p", "--pool", dest="pool", default="suites")
277 parser.add_argument("-s", "--suite_name", dest="name")
278 parser.add_argument("-a", "--afe_timeout_mins", type=int,
279 dest="afe_timeout_mins", default=30)
280 parser.add_argument("-t", "--timeout_mins", type=int,
281 dest="timeout_mins", default=1440)
282 parser.add_argument("-x", "--max_runtime_mins", type=int,
283 dest="max_runtime_mins", default=1440)
284 parser.add_argument("-d", "--delay_sec", type=int,
285 dest="delay_sec", default=10)
286 parser.add_argument("-m", "--mock_job_id", dest="mock_job_id",
287 help="Attach to existing job id for already running "
288 "suite, and creates report.")
Aviv Keshetdb321de2015-04-10 19:09:58 -0700289 # NOTE(akeshet): This looks similar to --no_wait, but behaves differently.
290 # --no_wait is passed in to the suite rpc itself and affects the suite,
291 # while this does not.
Allen Li93f4db52016-09-14 14:44:59 -0700292 parser.add_argument("-c", "--create_and_return", dest="create_and_return",
293 action="store_true",
294 help="Create the suite and print the job id, then "
295 "finish immediately.")
296 parser.add_argument("-u", "--num", dest="num", type=int, default=None,
Allen Li04afc8f2017-11-27 15:36:34 -0800297 help="Deprecated, does nothing.")
Alex Millerf43d0eb2012-10-01 13:43:13 -0700298 # Same boolean flag issue applies here.
Allen Li93f4db52016-09-14 14:44:59 -0700299 parser.add_argument(
300 "-f", "--file_bugs", dest="file_bugs", default=False, type=bool_str,
301 help=('File bugs on test failures. Must pass "True" or '
302 '"False" if used.'))
303 parser.add_argument("-l", "--bypass_labstatus", dest="bypass_labstatus",
304 action="store_true", help='Bypass lab status check.')
Alex Miller88762a82013-09-04 15:41:28 -0700305 # We allow either a number or a string for the priority. This way, if you
306 # know what you're doing, one can specify a custom priority level between
307 # other levels.
Allen Li93f4db52016-09-14 14:44:59 -0700308 parser.add_argument("-r", "--priority", dest="priority",
Allen Li603728a2016-12-08 13:58:11 -0800309 type=_get_priority_value,
Allen Li93f4db52016-09-14 14:44:59 -0700310 default=priorities.Priority.DEFAULT,
311 action="store",
312 help="Priority of suite. Either numerical value, or "
313 "one of (" + ", ".join(priorities.Priority.names)
314 + ").")
315 parser.add_argument(
316 '--retry', dest='retry', default=False, type=bool_str, action='store',
317 help='Enable test retry. Must pass "True" or "False" if used.')
318 parser.add_argument('--max_retries', dest='max_retries', default=None,
319 type=int, action='store', help='Maximum retries'
320 'allowed at suite level. No limit if not specified.')
321 parser.add_argument('--minimum_duts', dest='minimum_duts', type=int,
322 default=0, action='store',
323 help='Check that the pool has at least such many '
324 'healthy machines, otherwise suite will not run. '
325 'Default to 0.')
326 parser.add_argument('--suite_min_duts', dest='suite_min_duts', type=int,
327 default=0, action='store',
328 help='Preferred minimum number of machines. Scheduler '
329 'will prioritize on getting such many machines for '
330 'the suite when it is competing with another suite '
331 'that has a higher priority but already got minimum '
332 'machines it needs. Default to 0.')
333 parser.add_argument("--suite_args", dest="suite_args",
Allen Liecdba6c2017-07-11 12:10:26 -0700334 type=ast.literal_eval,
Allen Li93f4db52016-09-14 14:44:59 -0700335 default=None, action="store",
Allen Liecdba6c2017-07-11 12:10:26 -0700336 help="A dict of args passed to the suite control file.")
Allen Li93f4db52016-09-14 14:44:59 -0700337 parser.add_argument('--offload_failures_only',
Allen Li40599a32016-12-08 13:23:35 -0800338 dest='offload_failures_only', type=bool_str,
339 action='store', default=False,
Allen Li93f4db52016-09-14 14:44:59 -0700340 help='Only enable gs_offloading for failed tests. '
341 'Successful tests will be deleted. Must pass "True"'
342 ' or "False" if used.')
343 parser.add_argument('--use_suite_attr', dest='use_suite_attr',
344 action='store_true', default=False,
345 help='Advanced. Run the suite based on ATTRIBUTES of '
346 'control files, rather than SUITE.')
347 parser.add_argument('--json_dump', dest='json_dump', action='store_true',
348 default=False,
349 help='Dump the output of run_suite to stdout.')
350 parser.add_argument(
351 '--run_prod_code', dest='run_prod_code',
352 action='store_true', default=False,
353 help='Run the test code that lives in prod aka the test '
354 'code currently on the lab servers.')
355 parser.add_argument(
356 '--delay_minutes', type=int, default=0,
357 help=('Delay the creation of test jobs for a given '
358 'number of minutes. This argument can be used to '
359 'force provision jobs being delayed, which helps '
360 'to distribute loads across devservers.'))
361 parser.add_argument(
362 '--skip_duts_check', dest='skip_duts_check', action='store_true',
363 default=False, help='If True, skip minimum available DUTs check')
Shuqian Zhao843ae5c72017-02-22 11:25:01 -0800364 parser.add_argument(
Shuqian Zhao637d22c2017-03-06 15:52:32 -0800365 '--job_keyvals', dest='job_keyvals', type=ast.literal_eval,
Shuqian Zhao843ae5c72017-02-22 11:25:01 -0800366 action='store', default=None,
367 help='A dict of job keyvals to be inject to suite control file')
Shuqian Zhaoed0da862017-03-06 14:47:13 -0800368 parser.add_argument(
369 '--test_args', dest='test_args', type=ast.literal_eval,
370 action='store', default=None,
371 help=('A dict of args passed all the way to each individual test that '
372 'will be actually ran.'))
xixuand3cb33d2017-07-07 14:47:53 -0700373 parser.add_argument(
xixuan99eba0b2017-07-12 15:10:01 -0700374 '--require_logfile', action='store_true',
xixuand3cb33d2017-07-07 14:47:53 -0700375 help=('Stream logs of run_suite.py to a local file named '
376 'run_suite-<build name>.log.'))
Aviv Keshet97bebd42017-05-24 21:02:32 -0700377
378 # Used for monitoring purposes, to measure no-op swarming proxy latency.
379 parser.add_argument('--do_nothing', action='store_true',
380 help=argparse.SUPPRESS)
381
xixuanae791b12017-06-29 15:40:19 -0700382 # Used when lab/job status checking is needed. Currently its only user is
383 # suite scheduler v2.
384 parser.add_argument(
385 '--pre_check', action='store_true',
386 help=('Check lab and job status before kicking off a suite. Used by '
387 'suite scheduler v2.'))
388
Allen Li02b46c52017-09-11 11:48:12 -0700389 # TODO(crbug.com/763207): This is to support calling old moblab RPC
390 # with ToT code. This does not need to be supported after M62.
391 parser.add_argument('--oldrpc', action='store_true',
392 help='Use old AFE RPC.')
393
Allen Li93f4db52016-09-14 14:44:59 -0700394 return parser
Chris Masone24b80f12012-02-14 14:18:01 -0800395
396
Allen Li85ae5df2017-07-10 14:58:16 -0700397def verify_and_clean_options(options):
Allen Li93f4db52016-09-14 14:44:59 -0700398 """Verify the validity of options.
Fang Dengdd20e452014-04-07 15:39:47 -0700399
Fang Dengdd20e452014-04-07 15:39:47 -0700400 @param options: The parsed options to verify.
Fang Dengdd20e452014-04-07 15:39:47 -0700401
402 @returns: True if verification passes, False otherwise.
403
404 """
Fang Deng6865aab2015-02-20 14:49:47 -0800405 if options.mock_job_id and (
406 not options.build or not options.name or not options.board):
407 print ('When using -m, need to specify build, board and suite '
408 'name which you have used for creating the original job')
409 return False
410 else:
Fang Dengdd20e452014-04-07 15:39:47 -0700411 if not options.build:
412 print 'Need to specify which build to use'
413 return False
414 if not options.board:
415 print 'Need to specify board'
416 return False
417 if not options.name:
418 print 'Need to specify suite name'
419 return False
Allen Li04afc8f2017-11-27 15:36:34 -0800420 if options.num is not None:
421 warnings.warn('-u/--num option is deprecated; it does nothing.')
422 del options.num
Allen Li93f4db52016-09-14 14:44:59 -0700423 if not options.retry and options.max_retries is not None:
Fang Deng443f1952015-01-02 14:51:49 -0800424 print 'max_retries can only be used with --retry=True'
425 return False
Shuqian Zhaoab1bedc2015-06-02 11:12:28 -0700426 if options.use_suite_attr and options.suite_args is not None:
427 print ('The new suite control file cannot parse the suite_args: %s.'
428 'Please not specify any suite_args here.' % options.suite_args)
429 return False
Allen Li93f4db52016-09-14 14:44:59 -0700430 if options.no_wait and options.retry:
Fang Deng058860c2014-05-15 15:41:50 -0700431 print 'Test retry is not available when using --no_wait=True'
Dan Shi36cfd832014-10-10 13:38:51 -0700432 # Default to use the test code in CrOS build.
433 if not options.test_source_build and options.build:
434 options.test_source_build = options.build
Fang Dengdd20e452014-04-07 15:39:47 -0700435 return True
436
437
Shuqian Zhaoab1bedc2015-06-02 11:12:28 -0700438def change_options_for_suite_attr(options):
439 """Change options to be prepared to run the suite_attr_wrapper.
440
441 If specify 'use_suite_attr' from the cmd line, it indicates to run the
442 new style suite control file, suite_attr_wrapper. Then, change the
Allen Li6a612392016-08-18 12:09:32 -0700443 options.name to 'suite_attr_wrapper', change the options.suite_args to
Shuqian Zhaoab1bedc2015-06-02 11:12:28 -0700444 include the arguments needed by suite_attr_wrapper.
445
446 @param options: The verified options.
447
448 @returns: The changed options.
449
450 """
451 # Convert the suite_name to attribute boolean expression.
452 if type(options.name) is str:
453 attr_filter_val = 'suite:%s' % options.name
454 else:
455 attr_filter_val = ' or '.join(['suite:%s' % x for x in options.name])
456
457 # change the suite_args to be a dict of arguments for suite_attr_wrapper
458 # if suite_args is not None, store the values in 'other_args' of the dict
459 args_dict = {}
460 args_dict['attr_filter'] = attr_filter_val
Allen Liecdba6c2017-07-11 12:10:26 -0700461 options.suite_args = args_dict
Shuqian Zhaoab1bedc2015-06-02 11:12:28 -0700462 options.name = 'suite_attr_wrapper'
463
464 return options
465
466
Allen Li34613242016-09-02 11:52:34 -0700467class TestResult(object):
Aviv Keshet1480c4a2013-03-21 16:38:31 -0700468
Allen Li34613242016-09-02 11:52:34 -0700469 """Represents the result of a TestView."""
Aviv Keshet1480c4a2013-03-21 16:38:31 -0700470
Allen Li34613242016-09-02 11:52:34 -0700471 def __init__(self, test_view, retry_count=0):
472 """Initialize instance.
473
474 @param test_view: TestView instance.
475 @param retry_count: Retry count for test. Optional.
476 """
477 self.name = test_view.get_testname()
478 self.status = test_view['status']
479 self.reason = test_view['reason']
480 self.retry_count = retry_count
481
482 _PRETTY_STATUS_MAP = {
483 'GOOD': '[ PASSED ]',
484 'TEST_NA': '[ INFO ]',
485 }
486
487 @property
488 def _pretty_status(self):
489 """Pretty status string."""
490 return self._PRETTY_STATUS_MAP.get(self.status, '[ FAILED ]')
491
492 def log_using(self, log_function, name_column_width):
493 """Log the test result using the given log function.
494
495 @param log_function: Log function to use. Example: logging.info
496 @param name_column_width: Width of name column for formatting.
497 """
498 padded_name = self.name.ljust(name_column_width)
499 log_function('%s%s', padded_name, self._pretty_status)
500 if self.status != 'GOOD':
501 log_function('%s %s: %s', padded_name, self.status, self.reason)
502 if self.retry_count > 0:
503 log_function('%s retry_count: %s', padded_name, self.retry_count)
Chris Masone24b80f12012-02-14 14:18:01 -0800504
Fang Dengdd20e452014-04-07 15:39:47 -0700505
Shuqian Zhaof39bf2a2015-09-29 14:19:28 -0700506def get_original_suite_name(suite_name, suite_args):
507 """Get the original suite name when running suite_attr_wrapper.
508
509 @param suite_name: the name of the suite launched in afe. When it is
510 suite_attr_wrapper, the suite that actually running is
511 specified in the suite_args.
Allen Liecdba6c2017-07-11 12:10:26 -0700512 @param suite_args: dict of suite args from argument parsing.
Shuqian Zhaof39bf2a2015-09-29 14:19:28 -0700513
514 @returns: the original suite name.
515
516 """
517 if suite_name == 'suite_attr_wrapper':
Allen Liecdba6c2017-07-11 12:10:26 -0700518 attrs = suite_args.get('attr_filter', '')
Shuqian Zhaof39bf2a2015-09-29 14:19:28 -0700519 suite_list = ([x[6:] for x in re.split('[() ]', attrs)
520 if x and x.startswith('suite:')])
521 return suite_list[0] if suite_list else suite_name
522 return suite_name
523
524
Craig Harrison25eb0f32012-08-23 16:48:49 -0700525class LogLink(object):
J. Richard Barnetteb9c911d2013-08-23 11:24:21 -0700526 """Information needed to record a link in the logs.
Craig Harrison25eb0f32012-08-23 16:48:49 -0700527
J. Richard Barnetteb9c911d2013-08-23 11:24:21 -0700528 Depending on context and the information provided at
529 construction time, the link may point to either to log files for
530 a job, or to a bug filed for a failure in the job.
Craig Harrison25eb0f32012-08-23 16:48:49 -0700531
J. Richard Barnetteb9c911d2013-08-23 11:24:21 -0700532 @var anchor The link text.
533 @var url The link url.
534 @var bug_id Id of a bug to link to, or None.
535 """
536
Kevin Cheng2bdd3722016-03-24 21:30:52 -0700537 # A list of tests that don't get retried so skip the dashboard.
538 _SKIP_RETRY_DASHBOARD = ['provision']
539
Ningning Xiabd911bd2016-04-19 14:06:03 -0700540 _BUG_LINK_PREFIX = 'Auto-Bug'
541 _LOG_LINK_PREFIX = 'Test-Logs'
542
J. Richard Barnetteb9c911d2013-08-23 11:24:21 -0700543
Fang Dengaeab6172014-05-07 17:17:04 -0700544 def __init__(self, anchor, server, job_string, bug_info=None, reason=None,
Dan Shi9b620c22017-10-10 10:58:37 -0700545 retry_count=0, testname=None, sponge_url=None):
J. Richard Barnetteb9c911d2013-08-23 11:24:21 -0700546 """Initialize the LogLink by generating the log URL.
547
548 @param anchor The link text.
Alex Millerc7a59522013-10-30 15:18:57 -0700549 @param server The hostname of the server this suite ran on.
J. Richard Barnetteb9c911d2013-08-23 11:24:21 -0700550 @param job_string The job whose logs we'd like to link to.
551 @param bug_info Info about the bug, if one was filed.
Fang Deng53c6ff52014-02-24 17:51:24 -0800552 @param reason A string representing the reason of failure if any.
Fang Dengaeab6172014-05-07 17:17:04 -0700553 @param retry_count How many times the test has been retried.
Simran Basi7203d4e2015-02-03 15:50:18 -0800554 @param testname Optional Arg that supplies the testname.
Dan Shi9b620c22017-10-10 10:58:37 -0700555 @param sponge_url url to Sponge result.
Craig Harrison25eb0f32012-08-23 16:48:49 -0700556 """
557 self.anchor = anchor
Prathmesh Prabhucd246f52018-01-03 13:45:48 -0800558 self.url = _URL_PATTERN % (rpc_client_lib.add_protocol(server),
559 job_string)
Fang Deng53c6ff52014-02-24 17:51:24 -0800560 self.reason = reason
Fang Dengaeab6172014-05-07 17:17:04 -0700561 self.retry_count = retry_count
Simran Basi7203d4e2015-02-03 15:50:18 -0800562 self.testname = testname
Dan Shi9b620c22017-10-10 10:58:37 -0700563 self.sponge_url = sponge_url
J. Richard Barnetteb9c911d2013-08-23 11:24:21 -0700564 if bug_info:
565 self.bug_id, self.bug_count = bug_info
566 else:
567 self.bug_id = None
568 self.bug_count = None
Craig Harrison25eb0f32012-08-23 16:48:49 -0700569
570
Allen Lie082ced2016-09-14 15:19:20 -0700571 @property
572 def bug_url(self):
573 """URL of associated bug."""
574 if self.bug_id:
575 return reporting_utils.link_crbug(self.bug_id)
576 else:
577 return None
578
579
580 @property
581 def _bug_count_text(self):
582 """Return bug count as human friendly text."""
583 if self.bug_count is None:
584 bug_info = 'unknown number of reports'
585 elif self.bug_count == 1:
586 bug_info = 'new report'
587 else:
588 bug_info = '%s reports' % self.bug_count
589 return bug_info
590
591
Ningning Xiabd911bd2016-04-19 14:06:03 -0700592 def GenerateBuildbotLinks(self):
J. Richard Barnetteb9c911d2013-08-23 11:24:21 -0700593 """Generate a link formatted to meet buildbot expectations.
594
Ningning Xiabd911bd2016-04-19 14:06:03 -0700595 If there is a bug associated with this link, report a link to the bug
Allen Li4e7365e2017-07-10 15:40:24 -0700596 and a link to the job logs; otherwise report a link to the job logs.
Craig Harrison25eb0f32012-08-23 16:48:49 -0700597
Allen Li4e7365e2017-07-10 15:40:24 -0700598 @return A generator of links formatted for the buildbot log annotator.
Craig Harrison25eb0f32012-08-23 16:48:49 -0700599 """
Allen Li4e7365e2017-07-10 15:40:24 -0700600 if self.bug_url:
601 yield self._get_link_to_bug()
602 yield self._get_link_to_job_logs()
Ningning Xiabd911bd2016-04-19 14:06:03 -0700603
Allen Li4e7365e2017-07-10 15:40:24 -0700604
605 def _get_link_to_bug(self):
606 """Return buildbot link to bug.
607
608 @return A link formatted for the buildbot log annotator.
609 """
610 info_strings = self._get_info_strings()
611 info_strings.append(self._bug_count_text)
612 anchor_text = self._format_anchor_text(self._BUG_LINK_PREFIX,
613 info_strings)
614 return annotations.StepLink(anchor_text, self.bug_url)
615
616
617 def _get_link_to_job_logs(self):
618 """Return buildbot link to job logs.
619
620 @return A link formatted for the buildbot log annotator.
621 """
622 anchor_text = self._format_anchor_text(self._LOG_LINK_PREFIX,
623 self._get_info_strings())
624 return annotations.StepLink(anchor_text, self.url)
625
626
627 def _get_info_strings(self):
628 """Return a list of info strings for _format_anchor_text()."""
629 info_strings = []
Fang Dengaeab6172014-05-07 17:17:04 -0700630 if self.retry_count > 0:
631 info_strings.append('retry_count: %d' % self.retry_count)
Fang Deng53c6ff52014-02-24 17:51:24 -0800632 if self.reason:
Allen Lie082ced2016-09-14 15:19:20 -0700633 info_strings.append(self.reason)
Allen Li4e7365e2017-07-10 15:40:24 -0700634 return info_strings
Ningning Xiabd911bd2016-04-19 14:06:03 -0700635
636
Allen Lie082ced2016-09-14 15:19:20 -0700637 def _format_anchor_text(self, prefix, info_strings):
638 """Format anchor text given a prefix and info strings.
Ningning Xiabd911bd2016-04-19 14:06:03 -0700639
640 @param prefix The prefix of the anchor text.
Allen Lib1cb3842017-07-10 15:34:29 -0700641 @param info_strings Iterable of strings.
Ningning Xiabd911bd2016-04-19 14:06:03 -0700642 @return A anchor_text with the right prefix and info strings.
643 """
Allen Lib1cb3842017-07-10 15:34:29 -0700644 return '[{prefix}]: {anchor}: {info}'.format(
Allen Lie082ced2016-09-14 15:19:20 -0700645 prefix=prefix,
Allen Lib1cb3842017-07-10 15:34:29 -0700646 anchor=self.anchor.strip(),
647 info=', '.join(info_strings))
Craig Harrison25eb0f32012-08-23 16:48:49 -0700648
Allen Lie082ced2016-09-14 15:19:20 -0700649 @property
650 def text_link(self):
651 """Link to the job's logs, for consumption by a human.
Craig Harrison25eb0f32012-08-23 16:48:49 -0700652
Craig Harrisond8451572012-08-31 10:29:33 -0700653 @return A link formatted for human readability.
Craig Harrison25eb0f32012-08-23 16:48:49 -0700654 """
Aviv Keshet269848b2016-10-03 00:13:19 -0700655 return '%s %s' % (self.anchor, self.url)
Craig Harrison25eb0f32012-08-23 16:48:49 -0700656
Shuhei Takahashi18f56492017-11-14 16:23:46 +0900657 def GenerateRetryLink(self):
658 """Generate a link to the retry dashboard.
Simran Basi7203d4e2015-02-03 15:50:18 -0800659
660 @return A link formatted for the buildbot log annotator.
661 """
Allen Lie082ced2016-09-14 15:19:20 -0700662 if not self.testname or self.testname in self._SKIP_RETRY_DASHBOARD:
Simran Basi7203d4e2015-02-03 15:50:18 -0800663 return None
Allen Lie082ced2016-09-14 15:19:20 -0700664 return annotations.StepLink(
665 text='[Flake-Dashboard]: %s' % self.testname,
666 url=reporting_utils.link_retry_url(self.testname))
Simran Basi7203d4e2015-02-03 15:50:18 -0800667
Shuhei Takahashi18f56492017-11-14 16:23:46 +0900668 def GenerateHistoryLink(self):
669 """Generate a link to the test history dashboard.
David Rileya0cd1c22017-07-10 11:15:57 -0700670
671 @return A link formatted for the buildbot log annotator.
672 """
673 if not self.testname or self.testname in self._SKIP_RETRY_DASHBOARD:
674 return None
675 return annotations.StepLink(
676 text='[Test-History]: %s' % self.testname,
677 url=reporting_utils.link_test_history(self.testname))
678
Simran Basi7203d4e2015-02-03 15:50:18 -0800679
Chris Masoneb61b4052012-04-30 14:35:28 -0700680class Timings(object):
681 """Timings for important events during a suite.
682
683 All timestamps are datetime.datetime objects.
684
Fang Dengdd20e452014-04-07 15:39:47 -0700685 @var suite_job_id: the afe job id of the suite job for which
686 we are recording the timing for.
687 @var download_start_time: the time the devserver starts staging
688 the build artifacts. Recorded in create_suite_job.
689 @var payload_end_time: the time when the artifacts only necessary to start
690 installsing images onto DUT's are staged.
691 Recorded in create_suite_job.
692 @var artifact_end_time: the remaining artifacts are downloaded after we kick
693 off the reimaging job, at which point we record
694 artifact_end_time. Recorded in dynamic_suite.py.
Chris Masoneb61b4052012-04-30 14:35:28 -0700695 @var suite_start_time: the time the suite started.
Chris Masoneb61b4052012-04-30 14:35:28 -0700696 @var tests_start_time: the time the first test started running.
Fang Dengdd20e452014-04-07 15:39:47 -0700697 @var tests_end_time: the time the last test finished running.
Chris Masoneb61b4052012-04-30 14:35:28 -0700698 """
beeps6f02d192013-03-22 13:15:49 -0700699
Fang Dengdd20e452014-04-07 15:39:47 -0700700 def __init__(self, suite_job_id):
701 self.suite_job_id = suite_job_id
702 # Timings related to staging artifacts on devserver.
703 self.download_start_time = None
704 self.payload_end_time = None
705 self.artifact_end_time = None
beeps6f02d192013-03-22 13:15:49 -0700706
Fang Dengdd20e452014-04-07 15:39:47 -0700707 # The test_start_time, but taken off the view that corresponds to the
708 # suite instead of an individual test.
709 self.suite_start_time = None
beeps6f02d192013-03-22 13:15:49 -0700710
Fang Dengdd20e452014-04-07 15:39:47 -0700711 # Earliest and Latest tests in the set of TestViews passed to us.
712 self.tests_start_time = None
713 self.tests_end_time = None
714
Chris Masoneb61b4052012-04-30 14:35:28 -0700715
Chris Masoned9f13c52012-08-29 10:37:08 -0700716 def RecordTiming(self, view):
717 """Given a test report view, extract and record pertinent time info.
Chris Masoneb61b4052012-04-30 14:35:28 -0700718
719 get_detailed_test_views() returns a list of entries that provide
720 info about the various parts of a suite run. This method can take
721 any one of these entries and look up timestamp info we might want
722 and record it.
723
Chris Masonecfa7efc2012-09-06 16:00:07 -0700724 If timestamps are unavailable, datetime.datetime.min/max will be used.
725
Fang Dengaeab6172014-05-07 17:17:04 -0700726 @param view: A TestView object.
Chris Masoneb61b4052012-04-30 14:35:28 -0700727 """
Chris Masonecfa7efc2012-09-06 16:00:07 -0700728 start_candidate = datetime.min
729 end_candidate = datetime.max
730 if view['test_started_time']:
Dan Shidfea3682014-08-10 23:38:40 -0700731 start_candidate = time_utils.time_string_to_datetime(
732 view['test_started_time'])
Chris Masonecfa7efc2012-09-06 16:00:07 -0700733 if view['test_finished_time']:
Dan Shidfea3682014-08-10 23:38:40 -0700734 end_candidate = time_utils.time_string_to_datetime(
735 view['test_finished_time'])
Chris Masonecfa7efc2012-09-06 16:00:07 -0700736
Shuqian Zhaoc085abb2016-02-24 11:27:26 -0800737 if view.get_testname() == TestView.SUITE_JOB:
Chris Masoneb61b4052012-04-30 14:35:28 -0700738 self.suite_start_time = start_candidate
Chris Masoneb61b4052012-04-30 14:35:28 -0700739 else:
740 self._UpdateFirstTestStartTime(start_candidate)
741 self._UpdateLastTestEndTime(end_candidate)
Fang Dengdd20e452014-04-07 15:39:47 -0700742 if view['afe_job_id'] == self.suite_job_id and 'job_keyvals' in view:
Chris Masoned9f13c52012-08-29 10:37:08 -0700743 keyvals = view['job_keyvals']
Dan Shidfea3682014-08-10 23:38:40 -0700744 self.download_start_time = time_utils.time_string_to_datetime(
745 keyvals.get(constants.DOWNLOAD_STARTED_TIME),
746 handle_type_error=True)
beeps6f02d192013-03-22 13:15:49 -0700747
Dan Shidfea3682014-08-10 23:38:40 -0700748 self.payload_end_time = time_utils.time_string_to_datetime(
749 keyvals.get(constants.PAYLOAD_FINISHED_TIME),
750 handle_type_error=True)
beeps6f02d192013-03-22 13:15:49 -0700751
Dan Shidfea3682014-08-10 23:38:40 -0700752 self.artifact_end_time = time_utils.time_string_to_datetime(
753 keyvals.get(constants.ARTIFACT_FINISHED_TIME),
754 handle_type_error=True)
Chris Masone44e4d6c2012-08-15 14:25:53 -0700755
Chris Masoneb61b4052012-04-30 14:35:28 -0700756
757 def _UpdateFirstTestStartTime(self, candidate):
758 """Update self.tests_start_time, iff candidate is an earlier time.
759
760 @param candidate: a datetime.datetime object.
761 """
762 if not self.tests_start_time or candidate < self.tests_start_time:
763 self.tests_start_time = candidate
764
765
766 def _UpdateLastTestEndTime(self, candidate):
767 """Update self.tests_end_time, iff candidate is a later time.
768
769 @param candidate: a datetime.datetime object.
770 """
771 if not self.tests_end_time or candidate > self.tests_end_time:
772 self.tests_end_time = candidate
773
774
775 def __str__(self):
776 return ('\n'
777 'Suite timings:\n'
Chris Masonea8066a92012-05-01 16:52:31 -0700778 'Downloads started at %s\n'
779 'Payload downloads ended at %s\n'
Chris Masoneb61b4052012-04-30 14:35:28 -0700780 'Suite started at %s\n'
Chris Masonea8066a92012-05-01 16:52:31 -0700781 'Artifact downloads ended (at latest) at %s\n'
Chris Masoneb61b4052012-04-30 14:35:28 -0700782 'Testing started at %s\n'
Chris Masonea8066a92012-05-01 16:52:31 -0700783 'Testing ended at %s\n' % (self.download_start_time,
784 self.payload_end_time,
785 self.suite_start_time,
Chris Masonea8066a92012-05-01 16:52:31 -0700786 self.artifact_end_time,
Chris Masoneb61b4052012-04-30 14:35:28 -0700787 self.tests_start_time,
788 self.tests_end_time))
789
790
Alex Millerc7a59522013-10-30 15:18:57 -0700791def instance_for_pool(pool_name):
792 """
793 Return the hostname of the server that should be used to service a suite
794 for the specified pool.
795
796 @param pool_name: The pool (without 'pool:' to schedule the suite against.
797 @return: The correct host that should be used to service this suite run.
798 """
799 return CONFIG.get_config_value(
800 'POOL_INSTANCE_SHARDING', pool_name,
801 default=_DEFAULT_AUTOTEST_INSTANCE)
802
803
Fang Dengaeab6172014-05-07 17:17:04 -0700804class TestView(object):
805 """Represents a test view and provides a set of helper functions."""
806
807
Shuqian Zhaoc085abb2016-02-24 11:27:26 -0800808 SUITE_JOB = 'Suite job'
Fang Dengaeab6172014-05-07 17:17:04 -0700809
810
Simran Basi17ca77c2015-10-14 19:05:00 -0700811 def __init__(self, view, afe_job, suite_name, build, user,
812 solo_test_run=False):
Fang Dengaeab6172014-05-07 17:17:04 -0700813 """Init a TestView object representing a tko test view.
814
815 @param view: A dictionary representing a tko test view.
Fang Dengf8503532014-06-12 18:21:55 -0700816 @param afe_job: An instance of frontend.afe.models.Job
817 representing the job that kicked off the test.
Fang Dengaeab6172014-05-07 17:17:04 -0700818 @param suite_name: The name of the suite
819 that the test belongs to.
820 @param build: The build for which the test is run.
Simran Basi01984f52015-10-12 15:36:45 -0700821 @param user: The user for which the test is run.
Simran Basi17ca77c2015-10-14 19:05:00 -0700822 @param solo_test_run: This is a solo test run not part of a suite.
Fang Dengaeab6172014-05-07 17:17:04 -0700823 """
824 self.view = view
Fang Dengf8503532014-06-12 18:21:55 -0700825 self.afe_job = afe_job
Fang Dengaeab6172014-05-07 17:17:04 -0700826 self.suite_name = suite_name
827 self.build = build
Simran Basi17ca77c2015-10-14 19:05:00 -0700828 self.is_suite_view = afe_job.parent_job is None and not solo_test_run
Fang Dengaeab6172014-05-07 17:17:04 -0700829 # This is the test name that will be shown in the output.
830 self.testname = None
Simran Basi01984f52015-10-12 15:36:45 -0700831 self.user = user
Fang Dengaeab6172014-05-07 17:17:04 -0700832
Fang Dengf8503532014-06-12 18:21:55 -0700833 # The case that a job was aborted before it got a chance to run
834 # usually indicates suite has timed out (unless aborted by user).
835 # In this case, the abort reason will be None.
836 # Update the reason with proper information.
837 if (self.is_relevant_suite_view() and
Shuqian Zhaoc085abb2016-02-24 11:27:26 -0800838 not self.get_testname() == self.SUITE_JOB and
Fang Dengf8503532014-06-12 18:21:55 -0700839 self.view['status'] == 'ABORT' and
840 not self.view['reason']):
841 self.view['reason'] = 'Timed out, did not run.'
842
Fang Dengaeab6172014-05-07 17:17:04 -0700843
844 def __getitem__(self, key):
845 """Overload __getitem__ so that we can still use []
846
847 @param key: A key of the tko test view.
848
849 @returns: The value of an attribute in the view.
850
851 """
852 return self.view[key]
853
854
Fang Dengaeab6172014-05-07 17:17:04 -0700855 def __iter__(self):
856 """Overload __iter__ so that it supports 'in' operator."""
857 return iter(self.view)
858
859
860 def get_testname(self):
861 """Get test name that should be shown in the output.
862
863 Formalize the test_name we got from the test view.
864
Allen Lie6236ec2017-07-05 12:52:36 -0700865 Remove 'build/suite' prefix if any.
Fang Dengaeab6172014-05-07 17:17:04 -0700866
867 If one runs a test in control file via the following code,
868 job.runtest('my_Test', tag='tag')
869 for most of the cases, view['test_name'] would look like 'my_Test.tag'.
870 If this is the case, this method will just return the original
871 test name, i.e. 'my_Test.tag'.
872
873 There are four special cases.
874 1) A test view is for the suite job's SERVER_JOB.
Shuqian Zhaoc085abb2016-02-24 11:27:26 -0800875 In this case, this method will return 'Suite job'.
Fang Dengaeab6172014-05-07 17:17:04 -0700876
Simran Basi17ca77c2015-10-14 19:05:00 -0700877 2) A test view is of a child job or a solo test run not part of a
878 suite, and for a SERVER_JOB or CLIENT_JOB.
Fang Dengaeab6172014-05-07 17:17:04 -0700879 In this case, we will take the job name, remove the build/suite
880 prefix from the job name, and append the rest to 'SERVER_JOB'
881 or 'CLIENT_JOB' as a prefix. So the names returned by this
882 method will look like:
Allen Lie6236ec2017-07-05 12:52:36 -0700883 'dummy_Pass_SERVER_JOB'
Fang Dengaeab6172014-05-07 17:17:04 -0700884 'dummy_Fail_SERVER_JOB'
885
Fang Dengf8503532014-06-12 18:21:55 -0700886 3) A test view is of a suite job and its status is ABORT.
Fang Dengaeab6172014-05-07 17:17:04 -0700887 In this case, the view['test_name'] is the child job's name.
Allen Lie6236ec2017-07-05 12:52:36 -0700888 For instance,
Allen Lie6236ec2017-07-05 12:52:36 -0700889 'lumpy-release/R35-5712.0.0/dummy/dummy_Pass'
Fang Dengaeab6172014-05-07 17:17:04 -0700890 'lumpy-release/R35-5712.0.0/dummy/dummy_Fail'
891 The above names will be converted to the following:
Allen Lie6236ec2017-07-05 12:52:36 -0700892 'dummy_Pass'
Fang Dengaeab6172014-05-07 17:17:04 -0700893 'dummy_Fail'
894
Fang Dengf8503532014-06-12 18:21:55 -0700895 4) A test view's status is of a suite job and its status is TEST_NA.
Fang Dengaeab6172014-05-07 17:17:04 -0700896 In this case, the view['test_name'] is the NAME field of the control
Allen Lie6236ec2017-07-05 12:52:36 -0700897 file. For instance,
Allen Lie6236ec2017-07-05 12:52:36 -0700898 'dummy_Pass'
Fang Dengaeab6172014-05-07 17:17:04 -0700899 'dummy_Fail'
900 This method will not modify these names.
901
902 @returns: Test name after normalization.
903
904 """
905 if self.testname is not None:
906 return self.testname
907
908 if (self.is_suite_view and
909 self.view['test_name'].startswith('SERVER_JOB')):
Shuqian Zhaoc085abb2016-02-24 11:27:26 -0800910 # Rename suite job's SERVER_JOB to 'Suite job'.
911 self.testname = self.SUITE_JOB
Fang Dengaeab6172014-05-07 17:17:04 -0700912 return self.testname
913
914 if (self.view['test_name'].startswith('SERVER_JOB') or
915 self.view['test_name'].startswith('CLIENT_JOB')):
916 # Append job name as a prefix for SERVER_JOB and CLIENT_JOB
917 testname= '%s_%s' % (self.view['job_name'], self.view['test_name'])
918 else:
919 testname = self.view['test_name']
Fang Dengaeab6172014-05-07 17:17:04 -0700920 # Remove the build and suite name from testname if any.
Allen Lie6236ec2017-07-05 12:52:36 -0700921 self.testname = tools.get_test_name(
Fang Dengaeab6172014-05-07 17:17:04 -0700922 self.build, self.suite_name, testname)
Fang Dengaeab6172014-05-07 17:17:04 -0700923 return self.testname
924
925
926 def is_relevant_suite_view(self):
927 """Checks whether this is a suite view we should care about.
928
929 @returns: True if it is relevant. False otherwise.
930 """
Shuqian Zhaoc085abb2016-02-24 11:27:26 -0800931 return (self.get_testname() == self.SUITE_JOB or
Fang Dengaeab6172014-05-07 17:17:04 -0700932 (self.is_suite_view and
933 not self.view['test_name'].startswith('CLIENT_JOB') and
934 not self.view['subdir']))
935
936
937 def is_test(self):
938 """Return whether the view is for an actual test.
939
940 @returns True if the view is for an actual test.
941 False if the view is for SERVER_JOB or CLIENT_JOB.
942
943 """
944 return not (self.view['test_name'].startswith('SERVER_JOB') or
945 self.view['test_name'].startswith('CLIENT_JOB'))
946
947
948 def is_retry(self):
949 """Check whether the view is for a retry.
950
951 @returns: True, if the view is for a retry; False otherwise.
952
953 """
954 return self.view['job_keyvals'].get('retry_original_job_id') is not None
955
956
Fang Dengf8503532014-06-12 18:21:55 -0700957 def hit_timeout(self):
958 """Check whether the corresponding job has hit its own timeout.
Fang Dengaeab6172014-05-07 17:17:04 -0700959
Fang Dengf8503532014-06-12 18:21:55 -0700960 Note this method should not be called for those test views
961 that belongs to a suite job and are determined as irrelevant
962 by is_relevant_suite_view. This is because they are associated
963 to the suite job, whose job start/finished time make no sense
964 to an irrelevant test view.
Fang Dengaeab6172014-05-07 17:17:04 -0700965
Fang Dengf8503532014-06-12 18:21:55 -0700966 @returns: True if the corresponding afe job has hit timeout.
967 False otherwise.
968 """
969 if (self.is_relevant_suite_view() and
Shuqian Zhaoc085abb2016-02-24 11:27:26 -0800970 self.get_testname() != self.SUITE_JOB):
971 # Any relevant suite test view except SUITE_JOB
Fang Dengf8503532014-06-12 18:21:55 -0700972 # did not hit its own timeout because it was not ever run.
973 return False
974 start = (datetime.strptime(
Dan Shidfea3682014-08-10 23:38:40 -0700975 self.view['job_started_time'], time_utils.TIME_FMT)
Fang Dengf8503532014-06-12 18:21:55 -0700976 if self.view['job_started_time'] else None)
977 end = (datetime.strptime(
Dan Shidfea3682014-08-10 23:38:40 -0700978 self.view['job_finished_time'], time_utils.TIME_FMT)
Fang Dengf8503532014-06-12 18:21:55 -0700979 if self.view['job_finished_time'] else None)
980 if not start or not end:
981 return False
982 else:
983 return ((end - start).total_seconds()/60.0
984 > self.afe_job.max_runtime_mins)
985
986
987 def is_aborted(self):
988 """Check if the view was aborted.
989
Shuqian Zhaoc085abb2016-02-24 11:27:26 -0800990 For suite job and child job test views, we check job keyval
Fang Dengf8503532014-06-12 18:21:55 -0700991 'aborted_by' and test status.
992
993 For relevant suite job test views, we only check test status
994 because the suite job keyval won't make sense to individual
995 test views.
996
997 @returns: True if the test was as aborted, False otherwise.
Fang Dengaeab6172014-05-07 17:17:04 -0700998
999 """
Fang Dengf8503532014-06-12 18:21:55 -07001000
1001 if (self.is_relevant_suite_view() and
Shuqian Zhaoc085abb2016-02-24 11:27:26 -08001002 self.get_testname() != self.SUITE_JOB):
Fang Dengf8503532014-06-12 18:21:55 -07001003 return self.view['status'] == 'ABORT'
1004 else:
1005 return (bool(self.view['job_keyvals'].get('aborted_by')) and
1006 self.view['status'] in ['ABORT', 'RUNNING'])
Fang Dengaeab6172014-05-07 17:17:04 -07001007
1008
1009 def is_in_fail_status(self):
Fang Deng95af42f2014-09-12 14:16:11 -07001010 """Check if the given test's status corresponds to a failure.
Fang Dengaeab6172014-05-07 17:17:04 -07001011
1012 @returns: True if the test's status is FAIL or ERROR. False otherwise.
1013
1014 """
1015 # All the statuses tests can have when they fail.
1016 return self.view['status'] in ['FAIL', 'ERROR', 'ABORT']
1017
1018
Allen Licc205492017-07-10 17:26:04 -07001019 def is_provision(self):
1020 """Check whether this is a provision test."""
1021 return self.get_testname() == 'provision'
Fang Deng95af42f2014-09-12 14:16:11 -07001022
1023
Fang Dengaeab6172014-05-07 17:17:04 -07001024 def get_buildbot_link_reason(self):
1025 """Generate the buildbot link reason for the test.
1026
1027 @returns: A string representing the reason.
1028
1029 """
1030 return ('%s: %s' % (self.view['status'], self.view['reason'])
1031 if self.view['reason'] else self.view['status'])
1032
1033
1034 def get_job_id_owner_str(self):
1035 """Generate the job_id_owner string for a test.
1036
1037 @returns: A string which looks like 135036-username
1038
1039 """
Simran Basi01984f52015-10-12 15:36:45 -07001040 return '%s-%s' % (self.view['afe_job_id'], self.user)
Fang Dengaeab6172014-05-07 17:17:04 -07001041
1042
1043 def get_bug_info(self, suite_job_keyvals):
1044 """Get the bug info from suite_job_keyvals.
1045
1046 If a bug has been filed for the test, its bug info (bug id and counts)
1047 will be stored in the suite job's keyvals. This method attempts to
1048 retrieve bug info of the test from |suite_job_keyvals|. It will return
1049 None if no bug info is found. No need to check bug info if the view is
Shuqian Zhaoc085abb2016-02-24 11:27:26 -08001050 SUITE_JOB.
Fang Dengaeab6172014-05-07 17:17:04 -07001051
1052 @param suite_job_keyvals: The job keyval dictionary of the suite job.
1053 All the bug info about child jobs are stored in
1054 suite job's keyvals.
1055
1056 @returns: None if there is no bug info, or a pair with the
1057 id of the bug, and the count of the number of
1058 times the bug has been seen.
1059
1060 """
Shuqian Zhaoc085abb2016-02-24 11:27:26 -08001061 if self.get_testname() == self.SUITE_JOB:
Fang Dengaeab6172014-05-07 17:17:04 -07001062 return None
1063 if (self.view['test_name'].startswith('SERVER_JOB') or
1064 self.view['test_name'].startswith('CLIENT_JOB')):
1065 # Append job name as a prefix for SERVER_JOB and CLIENT_JOB
1066 testname= '%s_%s' % (self.view['job_name'], self.view['test_name'])
1067 else:
1068 testname = self.view['test_name']
1069
1070 return tools.get_test_failure_bug_info(
1071 suite_job_keyvals, self.view['afe_job_id'],
1072 testname)
1073
1074
1075 def should_display_buildbot_link(self):
1076 """Check whether a buildbot link should show for this view.
1077
Shuqian Zhaoc085abb2016-02-24 11:27:26 -08001078 For suite job view, show buildbot link if it fails.
Fang Dengf8503532014-06-12 18:21:55 -07001079 For normal test view,
1080 show buildbot link if it is a retry
1081 show buildbot link if it hits its own timeout.
1082 show buildbot link if it fails. This doesn't
1083 include the case where it was aborted but has
1084 not hit its own timeout (most likely it was aborted because
1085 suite has timed out).
Fang Dengaeab6172014-05-07 17:17:04 -07001086
1087 @returns: True if we should show the buildbot link.
1088 False otherwise.
1089 """
1090 is_bad_status = (self.view['status'] != 'GOOD' and
1091 self.view['status'] != 'TEST_NA')
Shuqian Zhaoc085abb2016-02-24 11:27:26 -08001092 if self.get_testname() == self.SUITE_JOB:
Fang Dengf8503532014-06-12 18:21:55 -07001093 return is_bad_status
1094 else:
1095 if self.is_retry():
1096 return True
1097 if is_bad_status:
1098 return not self.is_aborted() or self.hit_timeout()
Fang Dengaeab6172014-05-07 17:17:04 -07001099
1100
Shuqian Zhao2fecacd2015-08-05 22:56:30 -07001101 def get_control_file_attributes(self):
1102 """Get the attributes from the control file of the test.
1103
1104 @returns: A list of test attribute or None.
1105 """
1106 control_file = self.afe_job.control_file
1107 attributes = None
1108 if control_file:
1109 cd = control_data.parse_control_string(control_file)
1110 attributes = list(cd.attributes)
1111 return attributes
1112
1113
David Rileydcd1a642017-03-01 23:15:08 -08001114 def override_afe_job_id(self, afe_job_id):
1115 """Overrides the AFE job id for the test.
1116
1117 @param afe_job_id: The new AFE job id to use.
1118 """
1119 self.view['afe_job_id'] = afe_job_id
1120
1121
Allen Lidc2c69a2016-09-14 19:05:47 -07001122def log_buildbot_links(log_func, links):
1123 """Output buildbot links to log.
1124
1125 @param log_func: Logging function to use.
1126 @param links: Iterable of LogLink instances.
1127 """
1128 for link in links:
1129 for generated_link in link.GenerateBuildbotLinks():
1130 log_func(generated_link)
Shuhei Takahashi18f56492017-11-14 16:23:46 +09001131 retry_link = link.GenerateRetryLink()
1132 if retry_link:
1133 log_func(retry_link)
1134 history_link = link.GenerateHistoryLink()
1135 if history_link:
1136 log_func(history_link)
Allen Lidc2c69a2016-09-14 19:05:47 -07001137
1138
Allen Li0b675b62017-07-05 13:38:04 -07001139class _ReturnCodeComputer(object):
Allen Li422f24b2017-07-12 15:15:43 -07001140 """This is responsible for returning the _ReturnResult for a suite."""
Allen Li0b675b62017-07-05 13:38:04 -07001141
1142 def __call__(self, test_views):
1143 """Compute the exit code based on test results."""
Allen Licc205492017-07-10 17:26:04 -07001144 result = _RETURN_RESULTS['ok']
Allen Li0b675b62017-07-05 13:38:04 -07001145
1146 for v in test_views:
Allen Li0b675b62017-07-05 13:38:04 -07001147 if v.get_testname() == TestView.SUITE_JOB:
Allen Li422f24b2017-07-12 15:15:43 -07001148 result |= self._get_suite_result(v)
Allen Li0b675b62017-07-05 13:38:04 -07001149 else:
Allen Li422f24b2017-07-12 15:15:43 -07001150 result |= self._get_test_result(v)
1151 return result
1152
1153 def _get_suite_result(self, test_view):
1154 """Return the _ReturnResult for the given suite job."""
1155 # The order of checking each case is important.
1156 if test_view.is_aborted() and test_view.hit_timeout():
1157 return _RETURN_RESULTS['suite_timeout']
1158 elif test_view.is_in_fail_status():
1159 return _RETURN_RESULTS['suite_failed']
1160 elif test_view['status'] == 'WARN':
1161 return _RETURN_RESULTS['suite_warning']
1162 else:
1163 return _RETURN_RESULTS['ok']
1164
1165 def _get_test_result(self, test_view):
1166 """Return the _ReturnResult for the given test job."""
1167 # The order of checking each case is important.
1168 if test_view.is_aborted() and test_view.is_relevant_suite_view():
1169 # The test was aborted before started
1170 # This gurantees that the suite has timed out.
1171 return _RETURN_RESULTS['aborted_test']
1172 elif test_view.is_aborted() and not test_view.hit_timeout():
1173 # The test was aborted, but
1174 # not due to a timeout. This is most likely
1175 # because the suite has timed out, but may
1176 # also because it was aborted by the user.
1177 # Since suite timing out is determined by checking
1178 # the suite job view, we simply ignore this view here.
1179 return _RETURN_RESULTS['ok']
1180 elif test_view.is_in_fail_status(): # The test job failed
1181 if test_view.is_provision():
1182 return _RETURN_RESULTS['provision_failed']
1183 else:
1184 return _RETURN_RESULTS['test_failure']
1185 elif test_view['status'] == 'WARN':
1186 return _RETURN_RESULTS['test_warning']
1187 elif test_view.is_retry():
1188 # The test is a passing retry.
1189 return _RETURN_RESULTS['test_retry']
1190 else:
1191 return _RETURN_RESULTS['ok']
1192
1193
1194class _ProvisionReturnCodeComputer(_ReturnCodeComputer):
1195 """This is used for returning the _ReturnResult for provision suites."""
1196
1197 def __init__(self, num_required):
1198 """Initialize instance.
1199
1200 num_required is the number of passing provision jobs needed.
1201 """
1202 super(_ProvisionReturnCodeComputer, self).__init__()
1203 self._num_required = num_required
1204 self._num_successful = 0
1205
1206 def __call__(self, test_views):
1207 result = super(_ProvisionReturnCodeComputer, self).__call__(test_views)
1208 if self._num_successful >= self._num_required:
1209 logging.info('Return result upgraded from %r'
1210 ' due to enough ok provisions',
1211 result)
1212 return _RETURN_RESULTS['ok']
1213 else:
1214 return result
1215
1216 def _get_test_result(self, test_view):
1217 result = (super(_ProvisionReturnCodeComputer, self)
1218 ._get_test_result(test_view))
1219 if result in {_RETURN_RESULTS[s] for s in ('ok', 'test_retry')}:
1220 self._num_successful += 1
Allen Licc205492017-07-10 17:26:04 -07001221 return result
Allen Li0b675b62017-07-05 13:38:04 -07001222
1223
Fang Dengdd20e452014-04-07 15:39:47 -07001224class ResultCollector(object):
Simran Basi17ca77c2015-10-14 19:05:00 -07001225 """Collect test results of a suite or a single test run.
Fang Dengdd20e452014-04-07 15:39:47 -07001226
1227 Once a suite job has finished, use this class to collect test results.
1228 `run` is the core method that is to be called first. Then the caller
1229 could retrieve information like return code, return message, is_aborted,
1230 and timings by accessing the collector's public attributes. And output
1231 the test results and links by calling the 'output_*' methods.
1232
1233 Here is a overview of what `run` method does.
1234
1235 1) Collect the suite job's results from tko_test_view_2.
1236 For the suite job, we only pull test views without a 'subdir'.
1237 A NULL subdir indicates that the test was _not_ executed. This could be
1238 that no child job was scheduled for this test or the child job got
1239 aborted before starts running.
1240 (Note 'SERVER_JOB'/'CLIENT_JOB' are handled specially)
1241
1242 2) Collect the child jobs' results from tko_test_view_2.
1243 For child jobs, we pull all the test views associated with them.
Allen Lidc2c69a2016-09-14 19:05:47 -07001244 (Note 'SERVER_JOB'/'CLIENT_JOB' are handled specially)
Fang Dengdd20e452014-04-07 15:39:47 -07001245
Fang Dengaeab6172014-05-07 17:17:04 -07001246 3) Generate web and buildbot links.
Fang Dengdd20e452014-04-07 15:39:47 -07001247 4) Compute timings of the suite run.
1248 5) Compute the return code based on test results.
1249
1250 @var _instance_server: The hostname of the server that is used
1251 to service the suite.
1252 @var _afe: The afe rpc client.
1253 @var _tko: The tko rpc client.
1254 @var _build: The build for which the suite is run,
1255 e.g. 'lumpy-release/R35-5712.0.0'
MK Ryu977a9752014-10-21 11:58:09 -07001256 @var _board: The target board for which the suite is run,
1257 e.g., 'lumpy', 'link'.
Fang Dengdd20e452014-04-07 15:39:47 -07001258 @var _suite_name: The suite name, e.g. 'bvt', 'dummy'.
1259 @var _suite_job_id: The job id of the suite for which we are going to
1260 collect results.
Shuqian Zhaof39bf2a2015-09-29 14:19:28 -07001261 @var _original_suite_name: The suite name we record timing would be
1262 different from _suite_name when running
1263 suite_attr_wrapper.
Allen Li0b675b62017-07-05 13:38:04 -07001264 @var _return_code_function: Called to return what the overall result of
1265 the suite is.
Fang Dengaeab6172014-05-07 17:17:04 -07001266 @var _suite_views: A list of TestView objects, representing relevant
1267 test views of the suite job.
1268 @var _child_views: A list of TestView objects, representing test views
1269 of the child jobs.
1270 @var _test_views: A list of TestView objects, representing all test views
1271 from _suite_views and _child_views.
Fang Dengdd20e452014-04-07 15:39:47 -07001272 @var _web_links: A list of web links pointing to the results of jobs.
Allen Li28be0642017-07-10 15:16:26 -07001273 @var buildbot_links: A list of buildbot links for non-passing tests.
Simran Basi17ca77c2015-10-14 19:05:00 -07001274 @var _solo_test_run: True if this is a single test run.
Allen Licc205492017-07-10 17:26:04 -07001275 @var return_result: The _ReturnResult of the suite run.
Fang Dengdd20e452014-04-07 15:39:47 -07001276 @var is_aborted: Whether the suite was aborted or not.
1277 True, False or None (aborting status is unknown yet)
1278 @var timings: A Timing object that records the suite's timings.
1279
1280 """
1281
1282
MK Ryu977a9752014-10-21 11:58:09 -07001283 def __init__(self, instance_server, afe, tko, build, board,
Allen Li0b675b62017-07-05 13:38:04 -07001284 suite_name, suite_job_id,
1285 return_code_function,
1286 original_suite_name=None,
Simran Basi17ca77c2015-10-14 19:05:00 -07001287 user=None, solo_test_run=False):
Fang Dengdd20e452014-04-07 15:39:47 -07001288 self._instance_server = instance_server
1289 self._afe = afe
1290 self._tko = tko
1291 self._build = build
MK Ryu977a9752014-10-21 11:58:09 -07001292 self._board = board
Fang Dengdd20e452014-04-07 15:39:47 -07001293 self._suite_name = suite_name
1294 self._suite_job_id = suite_job_id
Shuqian Zhaof39bf2a2015-09-29 14:19:28 -07001295 self._original_suite_name = original_suite_name or suite_name
Allen Li0b675b62017-07-05 13:38:04 -07001296 self._return_code_function = return_code_function
Fang Deng0454e632014-04-07 15:39:47 -07001297 self._suite_views = []
1298 self._child_views = []
Fang Dengdd20e452014-04-07 15:39:47 -07001299 self._test_views = []
Fang Dengaeab6172014-05-07 17:17:04 -07001300 self._retry_counts = {}
David Rileydcd1a642017-03-01 23:15:08 -08001301 self._missing_results = {}
Fang Dengdd20e452014-04-07 15:39:47 -07001302 self._web_links = []
Allen Li28be0642017-07-10 15:16:26 -07001303 self.buildbot_links = []
MK Ryu977a9752014-10-21 11:58:09 -07001304 self._num_child_jobs = 0
Allen Licc205492017-07-10 17:26:04 -07001305 self.return_result = None
Fang Dengdd20e452014-04-07 15:39:47 -07001306 self.is_aborted = None
1307 self.timings = None
Simran Basi01984f52015-10-12 15:36:45 -07001308 self._user = user or getpass.getuser()
Simran Basi17ca77c2015-10-14 19:05:00 -07001309 self._solo_test_run = solo_test_run
Fang Dengdd20e452014-04-07 15:39:47 -07001310
1311
Fang Dengdd20e452014-04-07 15:39:47 -07001312 def _fetch_relevant_test_views_of_suite(self):
1313 """Fetch relevant test views of the suite job.
1314
1315 For the suite job, there will be a test view for SERVER_JOB, and views
Allen Lidc2c69a2016-09-14 19:05:47 -07001316 for results of its child jobs. For example, assume we've created
Fang Dengdd20e452014-04-07 15:39:47 -07001317 a suite job (afe_job_id: 40) that runs dummy_Pass, dummy_Fail,
1318 dummy_Pass.bluetooth. Assume dummy_Pass was aborted before running while
1319 dummy_Path.bluetooth got TEST_NA as no duts have bluetooth.
1320 So the suite job's test views would look like
1321 _____________________________________________________________________
1322 test_idx| job_idx|test_name |subdir |afe_job_id|status
1323 10 | 1000 |SERVER_JOB |---- |40 |GOOD
1324 11 | 1000 |dummy_Pass |NULL |40 |ABORT
1325 12 | 1000 |dummy_Fail.Fail |41-onwer/...|40 |FAIL
1326 13 | 1000 |dummy_Fail.Error |42-owner/...|40 |ERROR
1327 14 | 1000 |dummy_Pass.bluetooth|NULL |40 |TEST_NA
1328
1329 For a suite job, we only care about
1330 a) The test view for the suite job's SERVER_JOB
1331 b) The test views for real tests without a subdir. A NULL subdir
1332 indicates that a test didn't get executed.
1333 So, for the above example, we only keep test views whose test_idxs
1334 are 10, 11, 14.
1335
Fang Dengaeab6172014-05-07 17:17:04 -07001336 @returns: A list of TestView objects, representing relevant
1337 test views of the suite job.
Fang Dengdd20e452014-04-07 15:39:47 -07001338
1339 """
Fang Dengf8503532014-06-12 18:21:55 -07001340 suite_job = self._afe.get_jobs(id=self._suite_job_id)[0]
Fang Deng0454e632014-04-07 15:39:47 -07001341 views = self._tko.run(call='get_detailed_test_views',
1342 afe_job_id=self._suite_job_id)
Fang Dengdd20e452014-04-07 15:39:47 -07001343 relevant_views = []
1344 for v in views:
Simran Basi17ca77c2015-10-14 19:05:00 -07001345 v = TestView(v, suite_job, self._suite_name, self._build, self._user,
1346 solo_test_run=self._solo_test_run)
Fang Dengaeab6172014-05-07 17:17:04 -07001347 if v.is_relevant_suite_view():
David Rileydcd1a642017-03-01 23:15:08 -08001348 # If the test doesn't have results in TKO and is being
1349 # displayed in the suite view instead of the child view,
1350 # then afe_job_id is incorrect and from the suite.
1351 # Override it based on the AFE job id which was missing
1352 # results.
1353 # TODO: This is likely inaccurate if a test has multiple
1354 # tries which all fail TKO parse stage.
1355 if v['test_name'] in self._missing_results:
1356 v.override_afe_job_id(
1357 self._missing_results[v['test_name']][0])
Fang Dengdd20e452014-04-07 15:39:47 -07001358 relevant_views.append(v)
Fang Dengdd20e452014-04-07 15:39:47 -07001359 return relevant_views
1360
1361
Fang Dengaeab6172014-05-07 17:17:04 -07001362 def _compute_retry_count(self, view):
1363 """Return how many times the test has been retried.
1364
1365 @param view: A TestView instance.
1366 @returns: An int value indicating the retry count.
1367
1368 """
1369 old_job = view['job_keyvals'].get('retry_original_job_id')
1370 count = 0
1371 while old_job:
1372 count += 1
1373 views = self._tko.run(
1374 call='get_detailed_test_views', afe_job_id=old_job)
1375 old_job = (views[0]['job_keyvals'].get('retry_original_job_id')
1376 if views else None)
1377 return count
1378
1379
Simran Basi17ca77c2015-10-14 19:05:00 -07001380 def _fetch_test_views_of_child_jobs(self, jobs=None):
Fang Dengdd20e452014-04-07 15:39:47 -07001381 """Fetch test views of child jobs.
1382
David Rileydcd1a642017-03-01 23:15:08 -08001383 @returns: A tuple (child_views, retry_counts, missing_results)
Fang Dengaeab6172014-05-07 17:17:04 -07001384 child_views is list of TestView objects, representing
David Rileydcd1a642017-03-01 23:15:08 -08001385 all valid views.
1386 retry_counts is a dictionary that maps test_idx to retry
1387 counts. It only stores retry counts that are greater than 0.
1388 missing_results is a dictionary that maps test names to
1389 lists of job ids.
Fang Deng0454e632014-04-07 15:39:47 -07001390
Fang Dengdd20e452014-04-07 15:39:47 -07001391 """
Fang Dengdd20e452014-04-07 15:39:47 -07001392 child_views = []
Fang Dengaeab6172014-05-07 17:17:04 -07001393 retry_counts = {}
David Rileydcd1a642017-03-01 23:15:08 -08001394 missing_results = {}
Simran Basi17ca77c2015-10-14 19:05:00 -07001395 child_jobs = jobs or self._afe.get_jobs(parent_job_id=self._suite_job_id)
MK Ryu977a9752014-10-21 11:58:09 -07001396 if child_jobs:
1397 self._num_child_jobs = len(child_jobs)
Fang Dengf8503532014-06-12 18:21:55 -07001398 for job in child_jobs:
Simran Basi01984f52015-10-12 15:36:45 -07001399 views = [TestView(v, job, self._suite_name, self._build, self._user)
Fang Dengaeab6172014-05-07 17:17:04 -07001400 for v in self._tko.run(
Fang Dengf8503532014-06-12 18:21:55 -07001401 call='get_detailed_test_views', afe_job_id=job.id,
Fang Dengaeab6172014-05-07 17:17:04 -07001402 invalid=0)]
David Rileydcd1a642017-03-01 23:15:08 -08001403 if len(views) == 0:
1404 missing_results.setdefault(job.name, []).append(job.id)
Fang Dengdd20e452014-04-07 15:39:47 -07001405 contains_test_failure = any(
Fang Dengaeab6172014-05-07 17:17:04 -07001406 v.is_test() and v['status'] != 'GOOD' for v in views)
Fang Dengdd20e452014-04-07 15:39:47 -07001407 for v in views:
Fang Dengaeab6172014-05-07 17:17:04 -07001408 if (v.is_test() or
1409 v['status'] != 'GOOD' and not contains_test_failure):
1410 # For normal test view, just keep it.
1411 # For SERVER_JOB or CLIENT_JOB, only keep it
1412 # if it fails and no other test failure.
Fang Dengdd20e452014-04-07 15:39:47 -07001413 child_views.append(v)
Fang Dengaeab6172014-05-07 17:17:04 -07001414 retry_count = self._compute_retry_count(v)
1415 if retry_count > 0:
1416 retry_counts[v['test_idx']] = retry_count
David Rileydcd1a642017-03-01 23:15:08 -08001417 return child_views, retry_counts, missing_results
Fang Dengdd20e452014-04-07 15:39:47 -07001418
1419
1420 def _generate_web_and_buildbot_links(self):
1421 """Generate web links and buildbot links."""
1422 # TODO(fdeng): If a job was aborted before it reaches Running
1423 # state, we read the test view from the suite job
1424 # and thus this method generates a link pointing to the
1425 # suite job's page for the aborted job. Need a fix.
1426 self._web_links = []
Allen Li28be0642017-07-10 15:16:26 -07001427 self.buildbot_links = []
Fang Dengdd20e452014-04-07 15:39:47 -07001428 # Bug info are stored in the suite job's keyvals.
Simran Basi17ca77c2015-10-14 19:05:00 -07001429 if self._solo_test_run:
1430 suite_job_keyvals = {}
1431 else:
1432 suite_job_keyvals = self._suite_views[0]['job_keyvals']
Fang Dengdd20e452014-04-07 15:39:47 -07001433 for v in self._test_views:
Fang Dengaeab6172014-05-07 17:17:04 -07001434 retry_count = self._retry_counts.get(v['test_idx'], 0)
1435 bug_info = v.get_bug_info(suite_job_keyvals)
1436 job_id_owner = v.get_job_id_owner_str()
Fang Dengdd20e452014-04-07 15:39:47 -07001437 link = LogLink(
Allen Li34613242016-09-02 11:52:34 -07001438 anchor=v.get_testname(),
Fang Dengdd20e452014-04-07 15:39:47 -07001439 server=self._instance_server,
1440 job_string=job_id_owner,
Simran Basi7203d4e2015-02-03 15:50:18 -08001441 bug_info=bug_info, retry_count=retry_count,
Dan Shi9b620c22017-10-10 10:58:37 -07001442 testname=v.get_testname(),
1443 sponge_url=suite_job_keyvals.get('sponge_url'))
Fang Dengdd20e452014-04-07 15:39:47 -07001444 self._web_links.append(link)
1445
Fang Dengaeab6172014-05-07 17:17:04 -07001446 if v.should_display_buildbot_link():
1447 link.reason = v.get_buildbot_link_reason()
Allen Li28be0642017-07-10 15:16:26 -07001448 self.buildbot_links.append(link)
Fang Dengdd20e452014-04-07 15:39:47 -07001449
1450
1451 def _record_timings(self):
1452 """Record suite timings."""
1453 self.timings = Timings(self._suite_job_id)
1454 for v in self._test_views:
1455 self.timings.RecordTiming(v)
1456
1457
1458 def _compute_return_code(self):
1459 """Compute the exit code based on test results."""
Allen Licc205492017-07-10 17:26:04 -07001460 self.return_result = self._return_code_function(self._test_views)
Fang Dengdd20e452014-04-07 15:39:47 -07001461
1462
Allen Li34613242016-09-02 11:52:34 -07001463 def _make_test_results(self):
1464 """Make TestResults for collected tests.
1465
1466 @returns: List of TestResult instances.
1467 """
1468 test_results = []
1469 for test_view in self._test_views:
1470 test_result = TestResult(
1471 test_view=test_view,
1472 retry_count=self._retry_counts.get(test_view['test_idx'], 0))
1473 test_results.append(test_result)
1474 return test_results
1475
1476
Fang Dengdd20e452014-04-07 15:39:47 -07001477 def output_results(self):
1478 """Output test results, timings and web links."""
1479 # Output test results
Allen Li34613242016-09-02 11:52:34 -07001480 test_results = self._make_test_results()
Brian Norrisc7575d32017-09-25 17:08:19 -07001481 if len(test_results) == 0:
1482 max_name_length = 0
1483 else:
1484 max_name_length = max(len(t.name) for t in test_results)
Allen Li34613242016-09-02 11:52:34 -07001485 for test_result in test_results:
1486 test_result.log_using(logging.info, max_name_length + 3)
Fang Dengdd20e452014-04-07 15:39:47 -07001487 # Output suite timings
1488 logging.info(self.timings)
1489 # Output links to test logs
1490 logging.info('\nLinks to test logs:')
1491 for link in self._web_links:
Allen Lie082ced2016-09-14 15:19:20 -07001492 logging.info(link.text_link)
Fang Deng5a43be62014-05-07 17:17:04 -07001493 logging.info('\n')
Fang Dengdd20e452014-04-07 15:39:47 -07001494
1495
Shuqian Zhao2fecacd2015-08-05 22:56:30 -07001496 def get_results_dict(self):
1497 """Write test results, timings and web links into a dict.
1498
1499 @returns: A dict of results in the format like:
1500 {
1501 'tests': {
1502 'test_1': {'status': 'PASSED', 'attributes': [1,2], ...}
1503 'test_2': {'status': 'FAILED', 'attributes': [1],...}
1504 }
1505 'suite_timings': {
1506 'download_start': '1998-07-17 00:00:00',
1507 'payload_download_end': '1998-07-17 00:00:05',
1508 ...
1509 }
1510 }
1511 """
1512 output_dict = {}
1513 tests_dict = output_dict.setdefault('tests', {})
1514 for v in self._test_views:
Shuqian Zhaofae149c2017-01-30 16:46:53 -08001515 test_name = v.get_testname()
1516 test_info = tests_dict.setdefault(test_name, {})
1517 test_info.update({
1518 'status': v['status'],
1519 'attributes': v.get_control_file_attributes() or list(),
1520 'reason': v['reason'],
1521 'retry_count': self._retry_counts.get(v['test_idx'], 0),
1522 })
1523 # For aborted test, the control file will not be parsed and thus
1524 # fail to get the attributes info. Therefore, the subsystems the
1525 # abort test testing will be missing. For this case, we will assume
1526 # the aborted test will test all subsystems, set subsystem:default.
1527 if (test_info['status'] == 'ABORT' and
1528 not any('subsystem:' in a for a in test_info['attributes'])):
1529 test_info['attributes'].append('subsystem:default')
Shuqian Zhao2fecacd2015-08-05 22:56:30 -07001530
1531 # Write the links to test logs into the |tests_dict| of |output_dict|.
1532 # For test whose status is not 'GOOD', the link is also buildbot_link.
1533 for link in self._web_links:
Shuqian Zhaofae149c2017-01-30 16:46:53 -08001534 test_name = link.anchor.strip()
1535 test_info = tests_dict.get(test_name)
1536 if test_info:
1537 test_info['link_to_logs'] = link.url
Dan Shi9b620c22017-10-10 10:58:37 -07001538 test_info['sponge_url'] = link.sponge_url
Shuhei Takahashi18f56492017-11-14 16:23:46 +09001539 # Write the retry dashboard link into the dict.
Allen Li28be0642017-07-10 15:16:26 -07001540 if link in self.buildbot_links and link.testname:
Shuhei Takahashi18f56492017-11-14 16:23:46 +09001541 test_info['retry_dashboard_link'] \
Shuqian Zhaofae149c2017-01-30 16:46:53 -08001542 = reporting_utils.link_retry_url(link.testname)
Shuhei Takahashi18f56492017-11-14 16:23:46 +09001543 # Always write the wmatrix link for compatibility.
1544 test_info['wmatrix_link'] \
1545 = reporting_utils.link_wmatrix_retry_url(link.testname)
Shuqian Zhaofae149c2017-01-30 16:46:53 -08001546 # Write the bug url into the dict.
1547 if link.bug_id:
1548 test_info['bug_url'] = link.bug_url
Shuqian Zhao2fecacd2015-08-05 22:56:30 -07001549
1550 # Write the suite timings into |output_dict|
Allen Li2c5d44b2016-08-15 17:58:58 -07001551 timings = self.timings
1552 if timings is not None:
1553 time_dict = output_dict.setdefault('suite_timings', {})
1554 time_dict.update({
1555 'download_start' : str(timings.download_start_time),
1556 'payload_download_end' : str(timings.payload_end_time),
1557 'suite_start' : str(timings.suite_start_time),
1558 'artifact_download_end' : str(timings.artifact_end_time),
1559 'tests_start' : str(timings.tests_start_time),
1560 'tests_end' : str(timings.tests_end_time),
1561 })
Shuqian Zhao2fecacd2015-08-05 22:56:30 -07001562
1563 output_dict['suite_job_id'] = self._suite_job_id
1564
1565 return output_dict
1566
1567
Fang Dengdd20e452014-04-07 15:39:47 -07001568 def run(self):
1569 """Collect test results.
1570
1571 This method goes through the following steps:
1572 Fetch relevent test views of the suite job.
1573 Fetch test views of child jobs
1574 Check whether the suite was aborted.
Fang Dengaeab6172014-05-07 17:17:04 -07001575 Generate links.
Fang Dengdd20e452014-04-07 15:39:47 -07001576 Calculate suite timings.
1577 Compute return code based on the test result.
1578
1579 """
Simran Basi17ca77c2015-10-14 19:05:00 -07001580 if self._solo_test_run:
Allen Li29f5e242017-07-10 15:00:57 -07001581 self._test_views, self._retry_counts, self._missing_results = (
Simran Basi17ca77c2015-10-14 19:05:00 -07001582 self._fetch_test_views_of_child_jobs(
1583 jobs=self._afe.get_jobs(id=self._suite_job_id)))
1584 else:
David Rileydcd1a642017-03-01 23:15:08 -08001585 self._child_views, self._retry_counts, self._missing_results = (
Simran Basi17ca77c2015-10-14 19:05:00 -07001586 self._fetch_test_views_of_child_jobs())
David Rileydcd1a642017-03-01 23:15:08 -08001587 self._suite_views = self._fetch_relevant_test_views_of_suite()
Simran Basi17ca77c2015-10-14 19:05:00 -07001588 self._test_views = self._suite_views + self._child_views
Fang Dengdd20e452014-04-07 15:39:47 -07001589 # For hostless job in Starting status, there is no test view associated.
1590 # This can happen when a suite job in Starting status is aborted. When
1591 # the scheduler hits some limit, e.g., max_hostless_jobs_per_drone,
1592 # max_jobs_started_per_cycle, a suite job can stays in Starting status.
1593 if not self._test_views:
Allen Licc205492017-07-10 17:26:04 -07001594 self.return_result = _RETURN_RESULTS['test_views_missing']
Fang Dengdd20e452014-04-07 15:39:47 -07001595 return
1596 self.is_aborted = any([view['job_keyvals'].get('aborted_by')
1597 for view in self._suite_views])
Fang Dengdd20e452014-04-07 15:39:47 -07001598 self._generate_web_and_buildbot_links()
1599 self._record_timings()
1600 self._compute_return_code()
1601
1602
MK Ryu977a9752014-10-21 11:58:09 -07001603 def gather_timing_stats(self):
1604 """Collect timing related statistics."""
MK Ryu977a9752014-10-21 11:58:09 -07001605 # Record suite runtime in metadata db.
Prathmesh Prabhua3713a02015-03-11 13:50:55 -07001606 # Some failure modes can leave times unassigned, report sentinel value
1607 # in that case.
1608 runtime_in_secs = -1
1609 if (self.timings.tests_end_time is not None and
1610 self.timings.suite_start_time is not None):
Dan Shi0723bf52015-06-24 10:52:38 -07001611 runtime_in_secs = (self.timings.tests_end_time -
1612 self.timings.suite_start_time).total_seconds()
Prathmesh Prabhua3713a02015-03-11 13:50:55 -07001613
MK Ryu977a9752014-10-21 11:58:09 -07001614 job_overhead.record_suite_runtime(self._suite_job_id, self._suite_name,
1615 self._board, self._build, self._num_child_jobs, runtime_in_secs)
1616
1617
Allen Li0b675b62017-07-05 13:38:04 -07001618
Allen Li0716efa2016-12-08 13:51:31 -08001619def _make_builds_from_options(options):
1620 """Create a dict of builds for creating a suite job.
Prashanth B6285f6a2014-05-08 18:01:27 -07001621
Allen Li0716efa2016-12-08 13:51:31 -08001622 The returned dict maps version label prefixes to build names. Together,
1623 each key-value pair describes a complete label.
Prashanth B6285f6a2014-05-08 18:01:27 -07001624
Allen Li0716efa2016-12-08 13:51:31 -08001625 @param options: SimpleNamespace from argument parsing.
1626
1627 @return: dict mapping version label prefixes to build names
Prashanth B6285f6a2014-05-08 18:01:27 -07001628 """
Dan Shi36cfd832014-10-10 13:38:51 -07001629 builds = {}
Rohit Makasanadf0a3a32017-06-30 13:55:18 -07001630 build_prefix = None
Dan Shi36cfd832014-10-10 13:38:51 -07001631 if options.build:
Rohit Makasanadf0a3a32017-06-30 13:55:18 -07001632 build_prefix = provision.get_version_label_prefix(options.build)
1633 builds[build_prefix] = options.build
1634 if options.cheets_build:
1635 builds[provision.CROS_ANDROID_VERSION_PREFIX] = options.cheets_build
1636 if build_prefix == provision.CROS_VERSION_PREFIX:
1637 builds[build_prefix] += provision.CHEETS_SUFFIX
Dan Shi0723bf52015-06-24 10:52:38 -07001638 if options.firmware_rw_build:
1639 builds[provision.FW_RW_VERSION_PREFIX] = options.firmware_rw_build
Dan Shi36cfd832014-10-10 13:38:51 -07001640 if options.firmware_ro_build:
1641 builds[provision.FW_RO_VERSION_PREFIX] = options.firmware_ro_build
Allen Li0716efa2016-12-08 13:51:31 -08001642 return builds
1643
1644
Prathmesh Prabhu9b8e7ad2017-10-30 14:26:13 -07001645def _make_child_deps_from_options(options):
1646 """Creates a list of extra dependencies for child jobs.
1647
1648 @param options: Parsed arguments to run_suite.
1649
1650 @returns: A list of label strings if any dependencies should be added. None
1651 otherwise.
1652 """
1653 if not options.model:
1654 return ()
1655 return ['model:%s' % options.model]
1656
1657
Allen Li0716efa2016-12-08 13:51:31 -08001658@retry.retry(error.StageControlFileFailure, timeout_min=10)
1659def create_suite(afe, options):
1660 """Create a suite with retries.
1661
1662 @param afe: The afe object to insert the new suite job into.
1663 @param options: The options to use in creating the suite.
1664
1665 @return: The afe_job_id of the new suite job.
1666 """
Prashanth B6285f6a2014-05-08 18:01:27 -07001667 logging.info('%s Submitted create_suite_job rpc',
1668 diagnosis_utils.JobTimer.format_time(datetime.now()))
Allen Li02b46c52017-09-11 11:48:12 -07001669
1670 # TODO(crbug.com/763207): This is to support calling old moblab RPC
1671 # with ToT code. This does not need to be supported after M62.
1672 if options.oldrpc:
1673 suite_args = options.suite_args
1674 if 'tests' in suite_args:
1675 # This is for test_that_wrapper
1676 suite_args = ' '.join([':lab:'] + suite_args['tests'])
1677 else:
1678 # This is for suite_attr_wrapper
1679 suite_args = repr(suite_args)
1680 options.suite_args = suite_args
1681
Allen Li53121702016-12-08 12:50:22 -08001682 return afe.run(
1683 'create_suite_job',
1684 name=options.name,
1685 board=options.board,
Allen Li0716efa2016-12-08 13:51:31 -08001686 builds=_make_builds_from_options(options),
Allen Li53121702016-12-08 12:50:22 -08001687 test_source_build=options.test_source_build,
Allen Li0fd08892016-12-08 13:47:38 -08001688 check_hosts=not options.no_wait,
Allen Li53121702016-12-08 12:50:22 -08001689 pool=options.pool,
Allen Lid3758d42016-12-08 13:46:17 -08001690 file_bugs=options.file_bugs,
Allen Li603728a2016-12-08 13:58:11 -08001691 priority=options.priority,
Allen Li53121702016-12-08 12:50:22 -08001692 suite_args=options.suite_args,
Allen Li0fd08892016-12-08 13:47:38 -08001693 wait_for_results=not options.no_wait,
Allen Li53121702016-12-08 12:50:22 -08001694 timeout_mins=options.timeout_mins + options.delay_minutes,
1695 max_runtime_mins=options.max_runtime_mins + options.delay_minutes,
1696 job_retry=options.retry,
1697 max_retries=options.max_retries,
1698 suite_min_duts=options.suite_min_duts,
Allen Li40599a32016-12-08 13:23:35 -08001699 offload_failures_only=options.offload_failures_only,
Allen Li53121702016-12-08 12:50:22 -08001700 run_prod_code=options.run_prod_code,
1701 delay_minutes=options.delay_minutes,
Shuqian Zhao843ae5c72017-02-22 11:25:01 -08001702 job_keyvals=options.job_keyvals,
Shuqian Zhaoed0da862017-03-06 14:47:13 -08001703 test_args=options.test_args,
Prathmesh Prabhu9b8e7ad2017-10-30 14:26:13 -07001704 child_dependencies=_make_child_deps_from_options(options),
Allen Li53121702016-12-08 12:50:22 -08001705 )
Prashanth B6285f6a2014-05-08 18:01:27 -07001706
1707
Allen Li85ae5df2017-07-10 14:58:16 -07001708class SuiteResult(namedtuple('SuiteResult', ['return_code', 'output_dict'])):
1709 """Result of running a suite to return."""
1710
Allen Licc205492017-07-10 17:26:04 -07001711 def __new__(cls, return_code, output_dict=None):
1712 if output_dict is None:
1713 output_dict = dict()
1714 else:
1715 output_dict = output_dict.copy()
1716 output_dict['return_code'] = return_code
Allen Li85ae5df2017-07-10 14:58:16 -07001717 return super(SuiteResult, cls).__new__(cls, return_code, output_dict)
Allen Li340414e2016-08-16 14:19:08 -07001718
1719
Allen Li5e9c35f2017-07-05 14:24:18 -07001720def _run_suite(options):
Aviv Keshet1480c4a2013-03-21 16:38:31 -07001721 """
Shuqian Zhao2fecacd2015-08-05 22:56:30 -07001722 run_suite script without exception handling.
Shuqian Zhaod2351072015-08-06 01:48:23 +00001723
Shuqian Zhao2fecacd2015-08-05 22:56:30 -07001724 @param options: The parsed options.
1725
1726 @returns: A tuple contains the return_code of run_suite and the dictionary
1727 of the output.
1728
1729 """
Shuqian Zhaoab1bedc2015-06-02 11:12:28 -07001730 # If indicate to use the new style suite control file, convert the args
1731 if options.use_suite_attr:
1732 options = change_options_for_suite_attr(options)
1733
xixuan99eba0b2017-07-12 15:10:01 -07001734 log_name = _get_log_name(options)
1735 utils.setup_logging(logfile=log_name)
Alex Miller88762a82013-09-04 15:41:28 -07001736
John Carey1425d292016-09-30 15:25:09 -07001737 if not options.bypass_labstatus and not options.web:
Fang Deng6197da32014-09-25 10:18:48 -07001738 utils.check_lab_status(options.build)
xixuanae791b12017-06-29 15:40:19 -07001739
1740 afe = _create_afe(options)
1741 instance_server = afe.server
Chris Masone359c0fd2012-03-13 15:18:59 -07001742
Dan Shi20952c12014-05-14 17:07:38 -07001743 rpc_helper = diagnosis_utils.RPCHelper(afe)
Fang Deng6865aab2015-02-20 14:49:47 -08001744 is_real_time = True
Chris Masone986459e2012-04-11 11:36:48 -07001745 if options.mock_job_id:
1746 job_id = int(options.mock_job_id)
Fang Deng6865aab2015-02-20 14:49:47 -08001747 existing_job = afe.get_jobs(id=job_id, finished=True)
1748 if existing_job:
1749 is_real_time = False
1750 else:
1751 existing_job = afe.get_jobs(id=job_id)
1752 if existing_job:
1753 job_created_on = time_utils.date_string_to_epoch_time(
1754 existing_job[0].created_on)
1755 else:
1756 raise utils.TestLabException('Failed to retrieve job: %d' % job_id)
Chris Masone986459e2012-04-11 11:36:48 -07001757 else:
Fang Deng5a43be62014-05-07 17:17:04 -07001758 try:
Fang Deng6865aab2015-02-20 14:49:47 -08001759 rpc_helper.check_dut_availability(options.board, options.pool,
Ningning Xiaf2c206c2016-04-13 14:15:51 -07001760 options.minimum_duts,
1761 options.skip_duts_check)
Prashanth B6285f6a2014-05-08 18:01:27 -07001762 job_id = create_suite(afe, options)
Fang Deng6865aab2015-02-20 14:49:47 -08001763 job_created_on = time.time()
Fang Deng5a43be62014-05-07 17:17:04 -07001764 except (error.CrosDynamicSuiteException,
1765 error.RPCException, proxy.JSONRPCException) as e:
Allen Lic3aa7692016-08-08 11:45:00 -07001766 logging.exception('Error Message: %s', e)
Allen Li096e1852017-07-14 09:46:07 -07001767 return SuiteResult(RETURN_CODES.INFRA_FAILURE,
1768 {'return_message': str(e)})
Xixuan Wu610606b2017-11-13 14:03:33 -08001769 except AttributeError as e:
1770 logging.exception('Error Message: %s', e)
Allen Licc205492017-07-10 17:26:04 -07001771 return SuiteResult(RETURN_CODES.INVALID_OPTIONS)
Fang Deng5a43be62014-05-07 17:17:04 -07001772
Prashanth B923ca262014-03-14 12:36:29 -07001773 job_timer = diagnosis_utils.JobTimer(
Fang Deng6865aab2015-02-20 14:49:47 -08001774 job_created_on, float(options.timeout_mins))
Aviv Keshet9afee5e2014-10-09 16:33:09 -07001775 job_url = reporting_utils.link_job(job_id,
1776 instance_server=instance_server)
Prashanth B923ca262014-03-14 12:36:29 -07001777 logging.info('%s Created suite job: %s',
1778 job_timer.format_time(job_timer.job_created_time),
Aviv Keshet9afee5e2014-10-09 16:33:09 -07001779 job_url)
Allen Lie082ced2016-09-14 15:19:20 -07001780 logging.info(annotations.StepLink(
1781 text='Link to suite',
1782 url=job_url))
Aviv Keshetdb321de2015-04-10 19:09:58 -07001783
1784 if options.create_and_return:
Shuqian Zhao2fecacd2015-08-05 22:56:30 -07001785 msg = '--create_and_return was specified, terminating now.'
1786 logging.info(msg)
Prathmesh Prabhud9d23802017-08-22 00:46:01 +00001787 return SuiteResult(RETURN_CODES.OK, {'return_message': msg})
Aviv Keshetdb321de2015-04-10 19:09:58 -07001788
Allen Li93f4db52016-09-14 14:44:59 -07001789 if options.no_wait:
Allen Li340414e2016-08-16 14:19:08 -07001790 return _handle_job_nowait(job_id, options, instance_server)
Allen Li93f4db52016-09-14 14:44:59 -07001791 else:
1792 return _handle_job_wait(afe, job_id, options, job_timer, is_real_time)
Allen Li340414e2016-08-16 14:19:08 -07001793
1794
xixuan99eba0b2017-07-12 15:10:01 -07001795def _get_log_name(options):
1796 """Return local log file's name.
1797
1798 @param options: Parsed options.
1799
1800 @return log_name, a string file name.
1801 """
1802 if options.require_logfile:
1803 # options.build is verified to exist in verify_options.
1804 # convert build name from containing / to containing only _.
1805 log_name = 'run_suite-%s.log' % options.build.replace('/', '_')
1806 log_dir = os.path.join(common.autotest_dir, 'logs')
1807 if os.path.exists(log_dir):
1808 log_name = os.path.join(log_dir, log_name)
1809
1810 return log_name
1811 else:
1812 return None
1813
1814
xixuanae791b12017-06-29 15:40:19 -07001815def _create_afe(options):
1816 """Return an afe instance based on options.
1817
1818 @param options Parsed options.
1819
1820 @return afe, an AFE instance.
1821 """
1822 instance_server = (options.web if options.web else
1823 instance_for_pool(options.pool))
1824 afe = frontend_wrappers.RetryingAFE(server=instance_server,
1825 timeout_min=options.afe_timeout_mins,
1826 delay_sec=options.delay_sec)
1827 logging.info('Autotest instance created: %s', instance_server)
1828 return afe
1829
1830
Allen Li340414e2016-08-16 14:19:08 -07001831def _handle_job_wait(afe, job_id, options, job_timer, is_real_time):
1832 """Handle suite job synchronously.
1833
1834 @param afe AFE instance.
1835 @param job_id Suite job id.
1836 @param options Parsed options.
1837 @param job_timer JobTimer for suite job.
1838 @param is_real_time Whether or not to handle job timeout.
1839
1840 @return SuiteResult of suite job.
1841 """
Allen Li340414e2016-08-16 14:19:08 -07001842 rpc_helper = diagnosis_utils.RPCHelper(afe)
1843 instance_server = afe.server
1844 while not afe.get_jobs(id=job_id, finished=True):
Allen Li425d91f2017-07-10 15:14:20 -07001845 _poke_buildbot_with_output(afe, job_id, job_timer)
Allen Li340414e2016-08-16 14:19:08 -07001846 if job_timer.debug_output_timer.poll():
1847 logging.info('The suite job has another %s till timeout.',
Allen Li425d91f2017-07-10 15:14:20 -07001848 job_timer.timeout_hours - job_timer.elapsed_time())
Allen Li340414e2016-08-16 14:19:08 -07001849 time.sleep(10)
xixuana96bd212017-01-13 12:51:22 +08001850 logging.info('%s Suite job is finished.',
1851 diagnosis_utils.JobTimer.format_time(datetime.now()))
Allen Li340414e2016-08-16 14:19:08 -07001852 # For most cases, ResultCollector should be able to determine whether
1853 # a suite has timed out by checking information in the test view.
1854 # However, occationally tko parser may fail on parsing the
1855 # job_finished time from the job's keyval file. So we add another
1856 # layer of timeout check in run_suite. We do the check right after
1857 # the suite finishes to make it as accurate as possible.
1858 # There is a minor race condition here where we might have aborted
1859 # for some reason other than a timeout, and the job_timer thinks
1860 # it's a timeout because of the jitter in waiting for results.
1861 # The consequence would be that run_suite exits with code
1862 # SUITE_TIMEOUT while it should have returned INFRA_FAILURE
1863 # instead, which should happen very rarely.
1864 # Note the timeout will have no sense when using -m option.
1865 is_suite_timeout = job_timer.is_suite_timeout()
1866
1867 # Extract the original suite name to record timing.
1868 original_suite_name = get_original_suite_name(options.name,
Allen Li425d91f2017-07-10 15:14:20 -07001869 options.suite_args)
Allen Li340414e2016-08-16 14:19:08 -07001870 # Start collecting test results.
Aseda Aboagyed72df752017-05-22 14:30:11 -07001871 logging.info('%s Start collecting test results and dump them to json.',
xixuana96bd212017-01-13 12:51:22 +08001872 diagnosis_utils.JobTimer.format_time(datetime.now()))
Alex Millerc7a59522013-10-30 15:18:57 -07001873 TKO = frontend_wrappers.RetryingTKO(server=instance_server,
Simran Basi25effe32013-11-26 13:02:11 -08001874 timeout_min=options.afe_timeout_mins,
Chris Masone8ac66712012-02-15 14:21:02 -08001875 delay_sec=options.delay_sec)
Allen Li637683b2017-11-06 17:36:27 -08001876 # TODO(crbug.com/672348): It needs to be possible for provision
1877 # suite to pass if only a few tests fail. Otherwise, a single
1878 # failing test will be reported as failure even if the suite reports
1879 # success.
Allen Li977760b2017-11-06 18:11:37 -08001880 if options.name == _PROVISION_SUITE:
Allen Li637683b2017-11-06 17:36:27 -08001881 # TODO(crbug.com/672348): Creating the suite job requires that
1882 # suite_args contains num_required.
Allen Li422f24b2017-07-12 15:15:43 -07001883 return_code_function = _ProvisionReturnCodeComputer(
1884 num_required=options.suite_args['num_required'])
1885 else:
1886 return_code_function = _ReturnCodeComputer()
Allen Li340414e2016-08-16 14:19:08 -07001887 collector = ResultCollector(instance_server=instance_server,
1888 afe=afe, tko=TKO, build=options.build,
1889 board=options.board,
1890 suite_name=options.name,
1891 suite_job_id=job_id,
Allen Li422f24b2017-07-12 15:15:43 -07001892 return_code_function=return_code_function,
Allen Li340414e2016-08-16 14:19:08 -07001893 original_suite_name=original_suite_name)
1894 collector.run()
1895 # Dump test outputs into json.
1896 output_dict = collector.get_results_dict()
1897 output_dict['autotest_instance'] = instance_server
1898 if not options.json_dump:
1899 collector.output_results()
Allen Licc205492017-07-10 17:26:04 -07001900 result = collector.return_result
Allen Li340414e2016-08-16 14:19:08 -07001901 if is_real_time:
1902 # Do not record stats if the suite was aborted (either by a user
1903 # or through the golo rpc).
1904 # Also do not record stats if is_aborted is None, indicating
1905 # aborting status is unknown yet.
1906 if collector.is_aborted == False:
xixuana96bd212017-01-13 12:51:22 +08001907 logging.info('%s Gathering timing stats for the suite job.',
1908 diagnosis_utils.JobTimer.format_time(datetime.now()))
Allen Li340414e2016-08-16 14:19:08 -07001909 collector.gather_timing_stats()
J. Richard Barnette712eb402013-08-13 18:03:00 -07001910
Allen Li340414e2016-08-16 14:19:08 -07001911 if collector.is_aborted == True and is_suite_timeout:
1912 # There are two possible cases when a suite times out.
1913 # 1. the suite job was aborted due to timing out
1914 # 2. the suite job succeeded, but some child jobs
1915 # were already aborted before the suite job exited.
1916 # The case 2 was handled by ResultCollector,
1917 # here we handle case 1.
Allen Licc205492017-07-10 17:26:04 -07001918 result |= _RETURN_RESULTS['suite_timeout']
xixuana96bd212017-01-13 12:51:22 +08001919 logging.info('\n %s Attempting to display pool info: %s',
1920 diagnosis_utils.JobTimer.format_time(datetime.now()),
1921 options.pool)
Allen Li340414e2016-08-16 14:19:08 -07001922 try:
1923 # Add some jitter to make up for any latency in
1924 # aborting the suite or checking for results.
Allen Li0b675b62017-07-05 13:38:04 -07001925 cutoff = job_timer.timeout_hours + timedelta(hours=0.3)
Allen Li340414e2016-08-16 14:19:08 -07001926 rpc_helper.diagnose_pool(
1927 options.board, options.pool, cutoff)
Allen Lid4aa2fb2016-12-08 14:03:54 -08001928 except proxy.JSONRPCException:
Allen Li340414e2016-08-16 14:19:08 -07001929 logging.warning('Unable to display pool info.')
Aviv Keshet6b1122d2016-06-20 13:29:52 -07001930
Allen Li340414e2016-08-16 14:19:08 -07001931 # And output return message.
Allen Licc205492017-07-10 17:26:04 -07001932 if result.message:
1933 logging.info('Reason: %s', result.message)
Fang Deng5a43be62014-05-07 17:17:04 -07001934
xixuana96bd212017-01-13 12:51:22 +08001935 logging.info('\n %s Output below this line is for buildbot consumption:',
1936 diagnosis_utils.JobTimer.format_time(datetime.now()))
Allen Li28be0642017-07-10 15:16:26 -07001937 log_buildbot_links(logging.info, collector.buildbot_links)
Allen Licc205492017-07-10 17:26:04 -07001938 return result.suite_result(output_dict)
Prashanth B923ca262014-03-14 12:36:29 -07001939
Allen Li340414e2016-08-16 14:19:08 -07001940
1941def _handle_job_nowait(job_id, options, instance_server):
1942 """Handle suite job asynchronously.
1943
1944 @param job_id Suite job id.
1945 @param options Parsed options.
1946 @param instance_server Autotest instance hostname.
1947
1948 @return SuiteResult of suite job.
1949 """
1950 logging.info('Created suite job: %r', job_id)
1951 link = LogLink(options.name, instance_server,
Allen Li0b675b62017-07-05 13:38:04 -07001952 '%s-%s' % (job_id, getpass.getuser()))
Allen Li340414e2016-08-16 14:19:08 -07001953 for generate_link in link.GenerateBuildbotLinks():
1954 logging.info(generate_link)
1955 logging.info('--no_wait specified; Exiting.')
1956 return SuiteResult(RETURN_CODES.OK,
Allen Li0b675b62017-07-05 13:38:04 -07001957 {'return_message': '--no_wait specified; Exiting.'})
Chris Masone24b80f12012-02-14 14:18:01 -08001958
Fang Dengdd20e452014-04-07 15:39:47 -07001959
xixuanae791b12017-06-29 15:40:19 -07001960def _should_run(options):
1961 """Check whether the suite should be run based on lab/job status checking.
1962
1963 @param options Parsed options.
1964 """
1965 try:
1966 site_utils.check_lab_status(options.test_source_build)
1967 except site_utils.TestLabException as ex:
1968 logging.exception('Lab is closed or build is blocked. Skipping '
1969 'suite %s, board %s, build %s: %s',
1970 options.name, options.board,
1971 options.test_source_build, str(ex))
1972 return False
1973
1974 start_time = str(datetime.now() -
1975 timedelta(days=_SEARCH_JOB_MAX_DAYS))
1976 afe = _create_afe(options)
Xixuan Wuf8ca7822017-09-07 17:28:09 -07001977 afe_job_id = afe.get_jobs(
xixuanae791b12017-06-29 15:40:19 -07001978 name__istartswith=options.test_source_build,
1979 name__iendswith='control.'+options.name,
1980 created_on__gte=start_time,
1981 min_rpc_timeout=_MIN_RPC_TIMEOUT)
Xixuan Wuf8ca7822017-09-07 17:28:09 -07001982 if afe_job_id:
1983 logging.info('Found duplicate suite %s scheduled in past.',
1984 afe_job_id)
1985 return False
xixuanae791b12017-06-29 15:40:19 -07001986
Xixuan Wu3ae6e8b2017-10-12 09:57:07 -07001987 return True
1988
Shuqian Zhao2fecacd2015-08-05 22:56:30 -07001989
Allen Li425d91f2017-07-10 15:14:20 -07001990def _poke_buildbot_with_output(afe, job_id, job_timer):
1991 """Poke buildbot so it doesn't timeout from silence.
1992
1993 @param afe AFE instance.
1994 @param job_id Suite job id.
1995 @param job_timer JobTimer for suite job.
1996 """
1997 rpc_helper = diagnosis_utils.RPCHelper(afe)
1998 # Note that this call logs output, preventing buildbot's
1999 # 9000 second silent timeout from kicking in. Let there be no
2000 # doubt, this is a hack. The timeout is from upstream buildbot and
2001 # this is the easiest work around.
2002 if job_timer.first_past_halftime():
2003 rpc_helper.diagnose_job(job_id, afe.server)
2004
2005
2006
Allen Li85ae5df2017-07-10 14:58:16 -07002007def _run_task(options):
Allen Li5e9c35f2017-07-05 14:24:18 -07002008 """Perform this script's function minus setup.
Aviv Keshet97bebd42017-05-24 21:02:32 -07002009
Allen Li5e9c35f2017-07-05 14:24:18 -07002010 Boilerplate like argument parsing, logging, output formatting happen
2011 elsewhere.
Allen Li85ae5df2017-07-10 14:58:16 -07002012
2013 Returns a SuiteResult instance.
2014
2015 TODO(ayatane): The try/except should be moved into _run_suite().
2016 Good luck trying to figure out which function calls are supposed to
2017 raise which of the exceptions.
Allen Li5e9c35f2017-07-05 14:24:18 -07002018 """
Fang Dengfb4a9492014-09-18 17:52:06 -07002019 try:
Allen Li85ae5df2017-07-10 14:58:16 -07002020 return _run_suite(options)
Shuqian Zhaoade6e7d2015-12-07 18:01:11 -08002021 except diagnosis_utils.BoardNotAvailableError as e:
Allen Li85ae5df2017-07-10 14:58:16 -07002022 result = SuiteResult(
2023 RETURN_CODES.BOARD_NOT_AVAILABLE,
2024 {'return_message': 'Skipping testing: %s' % e.message})
2025 logging.info(result.output_dict['return_message'])
2026 return result
Shuqian Zhaoade6e7d2015-12-07 18:01:11 -08002027 except utils.TestLabException as e:
Allen Li85ae5df2017-07-10 14:58:16 -07002028 result = SuiteResult(
2029 RETURN_CODES.INFRA_FAILURE,
2030 {'return_message': 'TestLabException: %s' % e})
2031 logging.exception(result.output_dict['return_message'])
2032 return result
2033
2034
2035class _ExceptionHandler(object):
2036 """Global exception handler replacement."""
2037
2038 def __init__(self, dump_json):
2039 """Initialize instance.
2040
2041 @param dump_json: Whether to print a JSON dump of the result dict to
2042 stdout.
2043 """
2044 self._should_dump_json = dump_json
2045
2046 def __call__(self, exc_type, value, traceback):
2047 if self._should_dump_json:
2048 _dump_json({'return_message': ('Unhandled run_suite exception: %s'
2049 % value)})
2050 sys.exit(RETURN_CODES.INFRA_FAILURE)
Allen Li5e9c35f2017-07-05 14:24:18 -07002051
2052
2053def main():
2054 """Entry point."""
2055 utils.verify_not_root_user()
2056
2057 parser = make_parser()
2058 options = parser.parse_args()
2059 if options.do_nothing:
Allen Li85ae5df2017-07-10 14:58:16 -07002060 return 0
2061
2062 sys.exceptionhandler = _ExceptionHandler(dump_json=options.json_dump)
Allen Li5e9c35f2017-07-05 14:24:18 -07002063 if options.json_dump:
2064 logging.disable(logging.CRITICAL)
2065
Allen Li85ae5df2017-07-10 14:58:16 -07002066 options_okay = verify_and_clean_options(options)
Xixuan Wuf8ca7822017-09-07 17:28:09 -07002067 # Set StreamHandler first to capture error messages if suite is not run.
2068 utils.setup_logging()
Allen Li85ae5df2017-07-10 14:58:16 -07002069 if not options_okay:
2070 parser.print_help()
Allen Licc205492017-07-10 17:26:04 -07002071 result = SuiteResult(RETURN_CODES.INVALID_OPTIONS)
Allen Li85ae5df2017-07-10 14:58:16 -07002072 elif options.pre_check and not _should_run(options):
Xixuan Wuf8ca7822017-09-07 17:28:09 -07002073 logging.info('Suite %s-%s is terminated: Lab is closed, OR build is '
2074 'blocked, OR this suite has already been kicked off '
Allen Li85ae5df2017-07-10 14:58:16 -07002075 'once in past %d days.',
2076 options.test_source_build, options.name,
2077 _SEARCH_JOB_MAX_DAYS)
2078 result = SuiteResult(
2079 RETURN_CODES.ERROR,
2080 {'return_message': ("Lab is closed OR other reason"
2081 " (see code, it's complicated)")})
2082 else:
2083 result = _run_task(options)
Shuqian Zhao2fecacd2015-08-05 22:56:30 -07002084
Shuqian Zhao2fecacd2015-08-05 22:56:30 -07002085 if options.json_dump:
Allen Li85ae5df2017-07-10 14:58:16 -07002086 _dump_json(result.output_dict)
Fang Deng6197da32014-09-25 10:18:48 -07002087
2088 logging.info('Will return from run_suite with status: %s',
Allen Li85ae5df2017-07-10 14:58:16 -07002089 RETURN_CODES.get_string(result.return_code))
2090 return result.return_code
2091
2092
2093def _dump_json(obj):
2094 """Write obj JSON to stdout."""
2095 output_json = json.dumps(obj, sort_keys=True)
Prathmesh Prabhud9d23802017-08-22 00:46:01 +00002096 sys.stdout.write('#JSON_START#%s#JSON_END#' % output_json.strip())
Fang Dengfb4a9492014-09-18 17:52:06 -07002097
2098
Chris Masone24b80f12012-02-14 14:18:01 -08002099if __name__ == "__main__":
2100 sys.exit(main())