blob: 0eb605422116e7af9278f81fdc7c96476dea13d4 [file] [log] [blame]
Chris Masone859fdec2012-01-30 08:38:09 -08001# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5__author__ = 'cmasone@chromium.org (Chris Masone)'
6
7import common
Chris Masonea8066a92012-05-01 16:52:31 -07008import datetime
Chris Masone859fdec2012-01-30 08:38:09 -08009import logging
Simran Basi71206ef2014-08-13 13:51:18 -070010import os
Aviv Keshetd83ef442013-01-16 16:19:35 -080011
Jakob Juelich82b7d1c2014-09-15 16:10:57 -070012from autotest_lib.frontend.afe import models
Matthew Sartorid96fb9b2015-05-19 18:04:58 -070013from autotest_lib.client.common_lib import control_data
Aviv Keshetd83ef442013-01-16 16:19:35 -080014from autotest_lib.client.common_lib import error
Simran Basi71206ef2014-08-13 13:51:18 -070015from autotest_lib.client.common_lib import global_config
Alex Miller7d658cf2013-09-04 16:00:35 -070016from autotest_lib.client.common_lib import priorities
Dan Shidfea3682014-08-10 23:38:40 -070017from autotest_lib.client.common_lib import time_utils
Chris Masone859fdec2012-01-30 08:38:09 -080018from autotest_lib.client.common_lib.cros import dev_server
Gabe Black1e1c41b2015-02-04 23:55:15 -080019from autotest_lib.client.common_lib.cros.graphite import autotest_stats
Jakob Juelich9fffe4f2014-08-14 18:07:05 -070020from autotest_lib.frontend.afe import rpc_utils
Simran Basib6ec8ae2014-04-23 12:05:08 -070021from autotest_lib.server import utils
Dan Shi36cfd832014-10-10 13:38:51 -070022from autotest_lib.server.cros import provision
Chris Masone44e4d6c2012-08-15 14:25:53 -070023from autotest_lib.server.cros.dynamic_suite import constants
Chris Masoneb4935552012-08-14 12:05:54 -070024from autotest_lib.server.cros.dynamic_suite import control_file_getter
Chris Masone44e4d6c2012-08-15 14:25:53 -070025from autotest_lib.server.cros.dynamic_suite import tools
xixuan0f7755d2016-04-18 14:49:12 -070026from autotest_lib.server.cros.dynamic_suite import suite as SuiteBase
Dan Shi36cfd832014-10-10 13:38:51 -070027from autotest_lib.server.cros.dynamic_suite.suite import Suite
Dan Shidfea3682014-08-10 23:38:40 -070028from autotest_lib.site_utils import host_history
Dan Shi193905e2014-07-25 23:33:09 -070029from autotest_lib.site_utils import job_history
Dan Shid7bb4f12015-01-06 10:53:50 -080030from autotest_lib.site_utils import server_manager_utils
Dan Shi6964fa52014-12-18 11:04:27 -080031from autotest_lib.site_utils import stable_version_utils
Simran Basi71206ef2014-08-13 13:51:18 -070032
33
34_CONFIG = global_config.global_config
Chris Masone859fdec2012-01-30 08:38:09 -080035
Chris Masonef8b53062012-05-08 22:14:18 -070036# Relevant CrosDynamicSuiteExceptions are defined in client/common_lib/error.py.
Chris Masone859fdec2012-01-30 08:38:09 -080037
38
Chris Masone62579122012-03-08 15:18:43 -080039def canonicalize_suite_name(suite_name):
xixuanba232a32016-08-25 17:01:59 -070040 """Canonicalize the suite's name.
41
42 @param suite_name: the name of the suite.
43 """
Dan Shi70647ca2015-07-16 22:52:35 -070044 # Do not change this naming convention without updating
45 # site_utils.parse_job_name.
Chris Masone62579122012-03-08 15:18:43 -080046 return 'test_suites/control.%s' % suite_name
47
48
Chris Masoneaa10f8e2012-05-15 13:34:21 -070049def formatted_now():
xixuanba232a32016-08-25 17:01:59 -070050 """Format the current datetime."""
Dan Shidfea3682014-08-10 23:38:40 -070051 return datetime.datetime.now().strftime(time_utils.TIME_FMT)
Chris Masoneaa10f8e2012-05-15 13:34:21 -070052
53
Simran Basib6ec8ae2014-04-23 12:05:08 -070054def _get_control_file_contents_by_name(build, ds, suite_name):
Chris Masone8dd27e02012-06-25 15:59:43 -070055 """Return control file contents for |suite_name|.
56
57 Query the dev server at |ds| for the control file |suite_name|, included
58 in |build| for |board|.
59
60 @param build: unique name by which to refer to the image from now on.
Chris Masone8dd27e02012-06-25 15:59:43 -070061 @param ds: a dev_server.DevServer instance to fetch control file with.
62 @param suite_name: canonicalized suite name, e.g. test_suites/control.bvt.
63 @raises ControlFileNotFound if a unique suite control file doesn't exist.
64 @raises NoControlFileList if we can't list the control files at all.
65 @raises ControlFileEmpty if the control file exists on the server, but
66 can't be read.
67
68 @return the contents of the desired control file.
69 """
70 getter = control_file_getter.DevServerGetter.create(build, ds)
Gabe Black1e1c41b2015-02-04 23:55:15 -080071 timer = autotest_stats.Timer('control_files.parse.%s.%s' %
72 (ds.get_server_name(ds.url()
73 ).replace('.', '_'),
74 suite_name.rsplit('.')[-1]))
Chris Masone8dd27e02012-06-25 15:59:43 -070075 # Get the control file for the suite.
76 try:
Prashanth Balasubramanianabe3bb72014-11-20 12:00:37 -080077 with timer:
78 control_file_in = getter.get_control_file_contents_by_name(
79 suite_name)
Chris Masone8dd27e02012-06-25 15:59:43 -070080 except error.CrosDynamicSuiteException as e:
Simran Basib6ec8ae2014-04-23 12:05:08 -070081 raise type(e)("%s while testing %s." % (e, build))
Chris Masone8dd27e02012-06-25 15:59:43 -070082 if not control_file_in:
83 raise error.ControlFileEmpty(
84 "Fetching %s returned no data." % suite_name)
Alex Millera713e252013-03-01 10:45:44 -080085 # Force control files to only contain ascii characters.
86 try:
87 control_file_in.encode('ascii')
88 except UnicodeDecodeError as e:
89 raise error.ControlFileMalformed(str(e))
90
Chris Masone8dd27e02012-06-25 15:59:43 -070091 return control_file_in
92
93
Dan Shi5e8fa182016-04-15 11:04:36 -070094def _stage_build_artifacts(build, hostname=None):
Simran Basib6ec8ae2014-04-23 12:05:08 -070095 """
96 Ensure components of |build| necessary for installing images are staged.
97
98 @param build image we want to stage.
Dan Shi5e8fa182016-04-15 11:04:36 -070099 @param hostname hostname of a dut may run test on. This is to help to locate
100 a devserver closer to duts if needed. Default is None.
Simran Basib6ec8ae2014-04-23 12:05:08 -0700101
Prashanth B6285f6a2014-05-08 18:01:27 -0700102 @raises StageControlFileFailure: if the dev server throws 500 while staging
103 suite control files.
Simran Basib6ec8ae2014-04-23 12:05:08 -0700104
105 @return: dev_server.ImageServer instance to use with this build.
106 @return: timings dictionary containing staging start/end times.
107 """
108 timings = {}
Prashanth B6285f6a2014-05-08 18:01:27 -0700109 # Ensure components of |build| necessary for installing images are staged
110 # on the dev server. However set synchronous to False to allow other
111 # components to be downloaded in the background.
Dan Shi5e8fa182016-04-15 11:04:36 -0700112 ds = dev_server.resolve(build, hostname=hostname)
Simran Basib6ec8ae2014-04-23 12:05:08 -0700113 timings[constants.DOWNLOAD_STARTED_TIME] = formatted_now()
Gabe Black1e1c41b2015-02-04 23:55:15 -0800114 timer = autotest_stats.Timer('control_files.stage.%s' % (
115 ds.get_server_name(ds.url()).replace('.', '_')))
Simran Basib6ec8ae2014-04-23 12:05:08 -0700116 try:
Prashanth Balasubramanianabe3bb72014-11-20 12:00:37 -0800117 with timer:
Dan Shi6450e142016-03-11 11:52:20 -0800118 ds.stage_artifacts(image=build, artifacts=['test_suites'])
Simran Basib6ec8ae2014-04-23 12:05:08 -0700119 except dev_server.DevServerException as e:
Prashanth B6285f6a2014-05-08 18:01:27 -0700120 raise error.StageControlFileFailure(
Simran Basib6ec8ae2014-04-23 12:05:08 -0700121 "Failed to stage %s: %s" % (build, e))
122 timings[constants.PAYLOAD_FINISHED_TIME] = formatted_now()
123 return (ds, timings)
124
125
MK Ryue301eb72015-06-25 12:51:02 -0700126@rpc_utils.route_rpc_to_master
Dan Shi5984d782016-04-05 18:43:51 -0700127def create_suite_job(name='', board='', pool='', control_file='',
Simran Basib6ec8ae2014-04-23 12:05:08 -0700128 check_hosts=True, num=None, file_bugs=False, timeout=24,
129 timeout_mins=None, priority=priorities.Priority.DEFAULT,
Fang Deng058860c2014-05-15 15:41:50 -0700130 suite_args=None, wait_for_results=True, job_retry=False,
Fang Deng443f1952015-01-02 14:51:49 -0800131 max_retries=None, max_runtime_mins=None, suite_min_duts=0,
Dan Shi36cfd832014-10-10 13:38:51 -0700132 offload_failures_only=False, builds={},
Dan Shi059261a2016-02-22 12:06:37 -0800133 test_source_build=None, run_prod_code=False,
Michael Tang6dc174e2016-05-31 23:13:42 -0700134 delay_minutes=0, is_cloning=False, **kwargs):
Chris Masone859fdec2012-01-30 08:38:09 -0800135 """
136 Create a job to run a test suite on the given device with the given image.
137
138 When the timeout specified in the control file is reached, the
139 job is guaranteed to have completed and results will be available.
140
Simran Basib6ec8ae2014-04-23 12:05:08 -0700141 @param name: The test name if control_file is supplied, otherwise the name
142 of the test suite to run, e.g. 'bvt'.
Chris Masone859fdec2012-01-30 08:38:09 -0800143 @param board: the kind of device to run the tests on.
Dan Shi36cfd832014-10-10 13:38:51 -0700144 @param builds: the builds to install e.g.
145 {'cros-version:': 'x86-alex-release/R18-1655.0.0',
Dan Shi5984d782016-04-05 18:43:51 -0700146 'fwrw-version:': 'x86-alex-firmware/R36-5771.50.0',
Dan Shi36cfd832014-10-10 13:38:51 -0700147 'fwro-version:': 'x86-alex-firmware/R36-5771.49.0'}
148 If builds is given a value, it overrides argument build.
149 @param test_source_build: Build that contains the server-side test code.
Scott Zawalski65650172012-02-16 11:48:26 -0500150 @param pool: Specify the pool of machines to use for scheduling
151 purposes.
xixuanba232a32016-08-25 17:01:59 -0700152 @param control_file: the control file of the job.
Chris Masone62579122012-03-08 15:18:43 -0800153 @param check_hosts: require appropriate live hosts to exist in the lab.
Aviv Keshetd83ef442013-01-16 16:19:35 -0800154 @param num: Specify the number of machines to schedule across (integer).
155 Leave unspecified or use None to use default sharding factor.
Alex Millerc577f3e2012-09-27 14:06:07 -0700156 @param file_bugs: File a bug on each test failure in this suite.
Alex Miller139690b2013-09-07 15:35:49 -0700157 @param timeout: The max lifetime of this suite, in hours.
Simran Basi7e605742013-11-12 13:43:36 -0800158 @param timeout_mins: The max lifetime of this suite, in minutes. Takes
159 priority over timeout.
Alex Miller139690b2013-09-07 15:35:49 -0700160 @param priority: Integer denoting priority. Higher is more important.
Aviv Keshet7cd12312013-07-25 10:25:55 -0700161 @param suite_args: Optional arguments which will be parsed by the suite
162 control file. Used by control.test_that_wrapper to
163 determine which tests to run.
Dan Shi95122412013-11-12 16:20:33 -0800164 @param wait_for_results: Set to False to run the suite job without waiting
165 for test jobs to finish. Default is True.
Fang Deng058860c2014-05-15 15:41:50 -0700166 @param job_retry: Set to True to enable job-level retry. Default is False.
Fang Deng443f1952015-01-02 14:51:49 -0800167 @param max_retries: Integer, maximum job retries allowed at suite level.
168 None for no max.
Simran Basi102e3522014-09-11 11:46:10 -0700169 @param max_runtime_mins: Maximum amount of time a job can be running in
170 minutes.
Fang Dengcbc01212014-11-25 16:09:46 -0800171 @param suite_min_duts: Integer. Scheduler will prioritize getting the
172 minimum number of machines for the suite when it is
173 competing with another suite that has a higher
174 priority but already got minimum machines it needs.
Simran Basi1e10e922015-04-16 15:09:56 -0700175 @param offload_failures_only: Only enable gs_offloading for failed jobs.
Simran Basi5ace6f22016-01-06 17:30:44 -0800176 @param run_prod_code: If True, the suite will run the test code that
177 lives in prod aka the test code currently on the
178 lab servers. If False, the control files and test
179 code for this suite run will be retrieved from the
180 build artifacts.
Dan Shi059261a2016-02-22 12:06:37 -0800181 @param delay_minutes: Delay the creation of test jobs for a given number of
182 minutes.
Michael Tang6dc174e2016-05-31 23:13:42 -0700183 @param is_cloning: True if creating a cloning job.
Simran Basib6ec8ae2014-04-23 12:05:08 -0700184 @param kwargs: extra keyword args. NOT USED.
Chris Masone859fdec2012-01-30 08:38:09 -0800185
Chris Masone8dd27e02012-06-25 15:59:43 -0700186 @raises ControlFileNotFound: if a unique suite control file doesn't exist.
187 @raises NoControlFileList: if we can't list the control files at all.
Prashanth B6285f6a2014-05-08 18:01:27 -0700188 @raises StageControlFileFailure: If the dev server throws 500 while
189 staging test_suites.
Chris Masone8dd27e02012-06-25 15:59:43 -0700190 @raises ControlFileEmpty: if the control file exists on the server, but
191 can't be read.
Chris Masone859fdec2012-01-30 08:38:09 -0800192
193 @return: the job ID of the suite; -1 on error.
194 """
Aviv Keshetd83ef442013-01-16 16:19:35 -0800195 if type(num) is not int and num is not None:
Chris Sosa18c70b32013-02-15 14:12:43 -0800196 raise error.SuiteArgumentException('Ill specified num argument %r. '
197 'Must be an integer or None.' % num)
Aviv Keshetd83ef442013-01-16 16:19:35 -0800198 if num == 0:
199 logging.warning("Can't run on 0 hosts; using default.")
200 num = None
Dan Shi36cfd832014-10-10 13:38:51 -0700201
Dan Shi2121a332016-02-25 14:22:22 -0800202 # Default test source build to CrOS build if it's not specified and
203 # run_prod_code is set to False.
204 if not run_prod_code:
205 test_source_build = Suite.get_test_source_build(
206 builds, test_source_build=test_source_build)
Dan Shi36cfd832014-10-10 13:38:51 -0700207
Dan Shi5e8fa182016-04-15 11:04:36 -0700208 # If 'prefer_local_devserver' is True in global setting, and both board
209 # and pool are specified, pick a dut in the given board and pool, and
210 # use that to help to pick a devserver in the same subnet of the duts
211 # to be used to run tests.
212 if dev_server.PREFER_LOCAL_DEVSERVER and pool and board:
213 sample_dut = rpc_utils.get_sample_dut(board, pool)
214 else:
215 sample_dut = None
216
Simran Basi5ace6f22016-01-06 17:30:44 -0800217 suite_name = canonicalize_suite_name(name)
218 if run_prod_code:
Dan Shi5e8fa182016-04-15 11:04:36 -0700219 ds = dev_server.resolve(test_source_build, hostname=sample_dut)
Simran Basi5ace6f22016-01-06 17:30:44 -0800220 keyvals = {}
221 getter = control_file_getter.FileSystemGetter(
222 [_CONFIG.get_config_value('SCHEDULER',
223 'drone_installation_directory')])
224 control_file = getter.get_control_file_contents_by_name(suite_name)
225 else:
Dan Shi5e8fa182016-04-15 11:04:36 -0700226 (ds, keyvals) = _stage_build_artifacts(
227 test_source_build, hostname=sample_dut)
Fang Dengcbc01212014-11-25 16:09:46 -0800228 keyvals[constants.SUITE_MIN_DUTS_KEY] = suite_min_duts
Chris Masone859fdec2012-01-30 08:38:09 -0800229
Simran Basib6ec8ae2014-04-23 12:05:08 -0700230 if not control_file:
Dan Shi36cfd832014-10-10 13:38:51 -0700231 # No control file was supplied so look it up from the build artifacts.
232 suite_name = canonicalize_suite_name(name)
233 control_file = _get_control_file_contents_by_name(test_source_build,
234 ds, suite_name)
Simran Basi86fe9c92016-02-09 17:58:20 -0800235 # Do not change this naming convention without updating
236 # site_utils.parse_job_name.
Dan Shi2121a332016-02-25 14:22:22 -0800237 if not run_prod_code:
238 name = '%s-%s' % (test_source_build, suite_name)
239 else:
240 # If run_prod_code is True, test_source_build is not set, use the
241 # first build in the builds list for the sutie job name.
242 name = '%s-%s' % (builds.values()[0], suite_name)
Chris Masone46d0eb12012-07-27 18:56:39 -0700243
Simran Basi7e605742013-11-12 13:43:36 -0800244 timeout_mins = timeout_mins or timeout * 60
Simran Basi102e3522014-09-11 11:46:10 -0700245 max_runtime_mins = max_runtime_mins or timeout * 60
Simran Basi7e605742013-11-12 13:43:36 -0800246
Simran Basib6ec8ae2014-04-23 12:05:08 -0700247 if not board:
Dan Shid215dbe2015-06-18 16:14:59 -0700248 board = utils.ParseBuildName(builds[provision.CROS_VERSION_PREFIX])[0]
Chris Masone46d0eb12012-07-27 18:56:39 -0700249
Dan Shi5984d782016-04-05 18:43:51 -0700250 # Prepend builds and board to the control file.
Scott Zawalski65650172012-02-16 11:48:26 -0500251 inject_dict = {'board': board,
Dan Shi6dc22d12016-04-06 22:10:04 -0700252 # `build` is needed for suites like AU to stage image inside
253 # suite control file.
254 'build': test_source_build,
Dan Shi36cfd832014-10-10 13:38:51 -0700255 'builds': builds,
Chris Masone62579122012-03-08 15:18:43 -0800256 'check_hosts': check_hosts,
Chris Masone46d0eb12012-07-27 18:56:39 -0700257 'pool': pool,
Aviv Keshetd83ef442013-01-16 16:19:35 -0800258 'num': num,
Dan Shib8a99112013-06-18 13:46:10 -0700259 'file_bugs': file_bugs,
Alex Miller139690b2013-09-07 15:35:49 -0700260 'timeout': timeout,
Simran Basi7e605742013-11-12 13:43:36 -0800261 'timeout_mins': timeout_mins,
Alex Miller7d658cf2013-09-04 16:00:35 -0700262 'devserver_url': ds.url(),
Aviv Keshet7cd12312013-07-25 10:25:55 -0700263 'priority': priority,
Dan Shi95122412013-11-12 16:20:33 -0800264 'suite_args' : suite_args,
Fang Deng058860c2014-05-15 15:41:50 -0700265 'wait_for_results': wait_for_results,
Simran Basi102e3522014-09-11 11:46:10 -0700266 'job_retry': job_retry,
Fang Deng443f1952015-01-02 14:51:49 -0800267 'max_retries': max_retries,
Fang Dengcbc01212014-11-25 16:09:46 -0800268 'max_runtime_mins': max_runtime_mins,
Dan Shi36cfd832014-10-10 13:38:51 -0700269 'offload_failures_only': offload_failures_only,
Simran Basi5ace6f22016-01-06 17:30:44 -0800270 'test_source_build': test_source_build,
Dan Shi059261a2016-02-22 12:06:37 -0800271 'run_prod_code': run_prod_code,
272 'delay_minutes': delay_minutes,
Aviv Keshet7cd12312013-07-25 10:25:55 -0700273 }
274
Michael Tang6dc174e2016-05-31 23:13:42 -0700275 if is_cloning:
276 control_file = tools.remove_injection(control_file)
Simran Basib6ec8ae2014-04-23 12:05:08 -0700277 control_file = tools.inject_vars(inject_dict, control_file)
Chris Masone859fdec2012-01-30 08:38:09 -0800278
Jakob Juelich9fffe4f2014-08-14 18:07:05 -0700279 return rpc_utils.create_job_common(name,
Jakob Juelich59cfe542014-09-02 16:37:46 -0700280 priority=priority,
281 timeout_mins=timeout_mins,
282 max_runtime_mins=max_runtime_mins,
283 control_type='Server',
284 control_file=control_file,
285 hostless=True,
Fang Dengcbc01212014-11-25 16:09:46 -0800286 keyvals=keyvals)
Simran Basi71206ef2014-08-13 13:51:18 -0700287
288
Dan Shi193905e2014-07-25 23:33:09 -0700289def get_job_history(**filter_data):
290 """Get history of the job, including the special tasks executed for the job
291
292 @param filter_data: filter for the call, should at least include
293 {'job_id': [job id]}
294 @returns: JSON string of the job's history, including the information such
295 as the hosts run the job and the special tasks executed before
296 and after the job.
297 """
298 job_id = filter_data['job_id']
299 job_info = job_history.get_job_info(job_id)
Dan Shidfea3682014-08-10 23:38:40 -0700300 return rpc_utils.prepare_for_serialization(job_info.get_history())
301
302
303def get_host_history(start_time, end_time, hosts=None, board=None, pool=None):
304 """Get history of a list of host.
305
306 The return is a JSON string of host history for each host, for example,
307 {'172.22.33.51': [{'status': 'Resetting'
308 'start_time': '2014-08-07 10:02:16',
309 'end_time': '2014-08-07 10:03:16',
310 'log_url': 'http://autotest/reset-546546/debug',
311 'dbg_str': 'Task: Special Task 19441991 (host ...)'},
312 {'status': 'Running'
313 'start_time': '2014-08-07 10:03:18',
314 'end_time': '2014-08-07 10:13:00',
315 'log_url': 'http://autotest/reset-546546/debug',
316 'dbg_str': 'HQE: 15305005, for job: 14995562'}
317 ]
318 }
319 @param start_time: start time to search for history, can be string value or
320 epoch time.
321 @param end_time: end time to search for history, can be string value or
322 epoch time.
323 @param hosts: A list of hosts to search for history. Default is None.
324 @param board: board type of hosts. Default is None.
325 @param pool: pool type of hosts. Default is None.
326 @returns: JSON string of the host history.
327 """
328 return rpc_utils.prepare_for_serialization(
329 host_history.get_history_details(
330 start_time=start_time, end_time=end_time,
331 hosts=hosts, board=board, pool=pool,
332 process_pool_size=4))
Jakob Juelich59cfe542014-09-02 16:37:46 -0700333
334
MK Ryu07a109f2015-07-21 17:44:32 -0700335def shard_heartbeat(shard_hostname, jobs=(), hqes=(), known_job_ids=(),
336 known_host_ids=(), known_host_statuses=()):
Jakob Juelich1b525742014-09-30 13:08:07 -0700337 """Receive updates for job statuses from shards and assign hosts and jobs.
Jakob Juelich59cfe542014-09-02 16:37:46 -0700338
339 @param shard_hostname: Hostname of the calling shard
Jakob Juelicha94efe62014-09-18 16:02:49 -0700340 @param jobs: Jobs in serialized form that should be updated with newer
341 status from a shard.
342 @param hqes: Hostqueueentries in serialized form that should be updated with
343 newer status from a shard. Note that for every hostqueueentry
344 the corresponding job must be in jobs.
Jakob Juelich1b525742014-09-30 13:08:07 -0700345 @param known_job_ids: List of ids of jobs the shard already has.
346 @param known_host_ids: List of ids of hosts the shard already has.
MK Ryu07a109f2015-07-21 17:44:32 -0700347 @param known_host_statuses: List of statuses of hosts the shard already has.
Jakob Juelicha94efe62014-09-18 16:02:49 -0700348
Fang Dengf3705992014-12-16 17:32:18 -0800349 @returns: Serialized representations of hosts, jobs, suite job keyvals
350 and their dependencies to be inserted into a shard's database.
Jakob Juelich59cfe542014-09-02 16:37:46 -0700351 """
Jakob Juelich1b525742014-09-30 13:08:07 -0700352 # The following alternatives to sending host and job ids in every heartbeat
353 # have been considered:
354 # 1. Sending the highest known job and host ids. This would work for jobs:
355 # Newer jobs always have larger ids. Also, if a job is not assigned to a
356 # particular shard during a heartbeat, it never will be assigned to this
357 # shard later.
358 # This is not true for hosts though: A host that is leased won't be sent
359 # to the shard now, but might be sent in a future heartbeat. This means
360 # sometimes hosts should be transfered that have a lower id than the
361 # maximum host id the shard knows.
362 # 2. Send the number of jobs/hosts the shard knows to the master in each
363 # heartbeat. Compare these to the number of records that already have
364 # the shard_id set to this shard. In the normal case, they should match.
365 # In case they don't, resend all entities of that type.
366 # This would work well for hosts, because there aren't that many.
367 # Resending all jobs is quite a big overhead though.
368 # Also, this approach might run into edge cases when entities are
369 # ever deleted.
370 # 3. Mixtures of the above: Use 1 for jobs and 2 for hosts.
371 # Using two different approaches isn't consistent and might cause
372 # confusion. Also the issues with the case of deletions might still
373 # occur.
374 #
375 # The overhead of sending all job and host ids in every heartbeat is low:
376 # At peaks one board has about 1200 created but unfinished jobs.
377 # See the numbers here: http://goo.gl/gQCGWH
378 # Assuming that job id's have 6 digits and that json serialization takes a
379 # comma and a space as overhead, the traffic per id sent is about 8 bytes.
380 # If 5000 ids need to be sent, this means 40 kilobytes of traffic.
381 # A NOT IN query with 5000 ids took about 30ms in tests made.
382 # These numbers seem low enough to outweigh the disadvantages of the
383 # solutions described above.
Gabe Black1e1c41b2015-02-04 23:55:15 -0800384 timer = autotest_stats.Timer('shard_heartbeat')
Jakob Juelich59cfe542014-09-02 16:37:46 -0700385 with timer:
386 shard_obj = rpc_utils.retrieve_shard(shard_hostname=shard_hostname)
Jakob Juelicha94efe62014-09-18 16:02:49 -0700387 rpc_utils.persist_records_sent_from_shard(shard_obj, jobs, hqes)
MK Ryu07a109f2015-07-21 17:44:32 -0700388 assert len(known_host_ids) == len(known_host_statuses)
389 for i in range(len(known_host_ids)):
390 host_model = models.Host.objects.get(pk=known_host_ids[i])
391 if host_model.status != known_host_statuses[i]:
392 host_model.status = known_host_statuses[i]
393 host_model.save()
394
Fang Dengf3705992014-12-16 17:32:18 -0800395 hosts, jobs, suite_keyvals = rpc_utils.find_records_for_shard(
MK Ryu07a109f2015-07-21 17:44:32 -0700396 shard_obj, known_job_ids=known_job_ids,
397 known_host_ids=known_host_ids)
Jakob Juelich59cfe542014-09-02 16:37:46 -0700398 return {
399 'hosts': [host.serialize() for host in hosts],
400 'jobs': [job.serialize() for job in jobs],
Fang Dengf3705992014-12-16 17:32:18 -0800401 'suite_keyvals': [kv.serialize() for kv in suite_keyvals],
Jakob Juelich59cfe542014-09-02 16:37:46 -0700402 }
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700403
404
405def get_shards(**filter_data):
406 """Return a list of all shards.
407
408 @returns A sequence of nested dictionaries of shard information.
409 """
410 shards = models.Shard.query_objects(filter_data)
411 serialized_shards = rpc_utils.prepare_rows_as_nested_dicts(shards, ())
412 for serialized, shard in zip(serialized_shards, shards):
413 serialized['labels'] = [label.name for label in shard.labels.all()]
414
415 return serialized_shards
416
417
Shuqian Zhao68139fb2016-08-03 16:29:56 -0700418def _assign_board_to_shard_precheck(labels):
419 """Verify whether board labels are valid to be added to a given shard.
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700420
Shuqian Zhao68139fb2016-08-03 16:29:56 -0700421 First check whether board label is in correct format. Second, check whether
422 the board label exist. Third, check whether the board has already been
423 assigned to shard.
424
425 @param labels: Board labels separated by comma.
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700426
Jakob Juelich8b110ee2014-09-15 16:13:42 -0700427 @raises error.RPCException: If label provided doesn't start with `board:`
Shuqian Zhao68139fb2016-08-03 16:29:56 -0700428 or board has been added to shard already.
Jakob Juelich8b110ee2014-09-15 16:13:42 -0700429 @raises models.Label.DoesNotExist: If the label specified doesn't exist.
Shuqian Zhao68139fb2016-08-03 16:29:56 -0700430
431 @returns: A list of label models that ready to be added to shard.
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700432 """
MK Ryu5dfcc892015-07-16 15:34:04 -0700433 labels = labels.split(',')
434 label_models = []
435 for label in labels:
Shuqian Zhao68139fb2016-08-03 16:29:56 -0700436 # Check whether the board label is in correct format.
MK Ryu5dfcc892015-07-16 15:34:04 -0700437 if not label.startswith('board:'):
Shuqian Zhao68139fb2016-08-03 16:29:56 -0700438 raise error.RPCException('Sharding only supports `board:.*` label.')
439 # Check whether the board label exist. If not, exception will be thrown
440 # by smart_get function.
441 label = models.Label.smart_get(label)
442 label_id = models.Label.list_objects({'name':label})[0].get('id')
443 # Check whether the board has been sharded already
444 try:
445 shard = models.Shard.objects.get(labels=label)
446 raise error.RPCException(
447 '%s is already on shard %s' % (label, shard.hostname))
448 except models.Shard.DoesNotExist as e:
449 # board is not on any shard, so it's valid.
450 label_models.append(label)
451 return label_models
Jakob Juelich8b110ee2014-09-15 16:13:42 -0700452
Shuqian Zhao68139fb2016-08-03 16:29:56 -0700453
454def add_shard(hostname, labels):
455 """Add a shard and start running jobs on it.
456
457 @param hostname: The hostname of the shard to be added; needs to be unique.
458 @param labels: Board labels separated by comma. Jobs of one of the labels
459 will be assigned to the shard.
460
461 @raises error.RPCException: If label provided doesn't start with `board:` or
462 board has been added to shard already.
463 @raises model_logic.ValidationError: If a shard with the given hostname
464 already exist.
465 @raises models.Label.DoesNotExist: If the label specified doesn't exist.
466
467 @returns: The id of the added shard.
468 """
469 labels = _assign_board_to_shard_precheck(labels)
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700470 shard = models.Shard.add_object(hostname=hostname)
Shuqian Zhao68139fb2016-08-03 16:29:56 -0700471 for label in labels:
472 shard.labels.add(label)
473 return shard.id
474
475
476def add_board_to_shard(hostname, labels):
477 """Add boards to a given shard
478
479 @param hostname: The hostname of the shard to be changed.
480 @param labels: Board labels separated by comma.
481
482 @raises error.RPCException: If label provided doesn't start with `board:` or
483 board has been added to shard already.
484 @raises models.Label.DoesNotExist: If the label specified doesn't exist.
485
486 @returns: The id of the changed shard.
487 """
488 labels = _assign_board_to_shard_precheck(labels)
489 shard = models.Shard.objects.get(hostname=hostname)
490 for label in labels:
MK Ryu5dfcc892015-07-16 15:34:04 -0700491 shard.labels.add(label)
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700492 return shard.id
493
494
495def delete_shard(hostname):
496 """Delete a shard and reclaim all resources from it.
497
498 This claims back all assigned hosts from the shard. To ensure all DUTs are
xixuan03cb93f2016-03-22 16:21:41 -0700499 in a sane state, a Reboot task with highest priority is scheduled for them.
500 This reboots the DUTs and then all left tasks continue to run in drone of
501 the master.
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700502
xixuan03cb93f2016-03-22 16:21:41 -0700503 The procedure for deleting a shard:
504 * Lock all unlocked hosts on that shard.
505 * Remove shard information .
506 * Assign a reboot task with highest priority to these hosts.
507 * Unlock these hosts, then, the reboot tasks run in front of all other
508 tasks.
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700509
510 The status of jobs that haven't been reported to be finished yet, will be
511 lost. The master scheduler will pick up the jobs and execute them.
512
513 @param hostname: Hostname of the shard to delete.
514 """
515 shard = rpc_utils.retrieve_shard(shard_hostname=hostname)
xixuan03cb93f2016-03-22 16:21:41 -0700516 hostnames_to_lock = [h.hostname for h in
517 models.Host.objects.filter(shard=shard, locked=False)]
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700518
519 # TODO(beeps): Power off shard
xixuan03cb93f2016-03-22 16:21:41 -0700520 # For ChromeOS hosts, a reboot test with the highest priority is added to
521 # the DUT. After a reboot it should be ganranteed that no processes from
522 # prior tests that were run by a shard are still running on.
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700523
xixuan03cb93f2016-03-22 16:21:41 -0700524 # Lock all unlocked hosts.
525 dicts = {'locked': True, 'lock_time': datetime.datetime.now()}
526 models.Host.objects.filter(hostname__in=hostnames_to_lock).update(**dicts)
527
528 # Remove shard information.
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700529 models.Host.objects.filter(shard=shard).update(shard=None)
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700530 models.Job.objects.filter(shard=shard).update(shard=None)
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700531 shard.labels.clear()
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700532 shard.delete()
Dan Shi6964fa52014-12-18 11:04:27 -0800533
xixuan03cb93f2016-03-22 16:21:41 -0700534 # Assign a reboot task with highest priority: Super.
535 t = models.Test.objects.get(name='platform_BootPerfServer:shard')
536 c = utils.read_file(os.path.join(common.autotest_dir, t.path))
537 if hostnames_to_lock:
538 rpc_utils.create_job_common(
539 'reboot_dut_for_shard_deletion',
540 priority=priorities.Priority.SUPER,
541 control_type='Server',
542 control_file=c, hosts=hostnames_to_lock)
543
544 # Unlock these shard-related hosts.
545 dicts = {'locked': False, 'lock_time': None}
546 models.Host.objects.filter(hostname__in=hostnames_to_lock).update(**dicts)
547
Dan Shi6964fa52014-12-18 11:04:27 -0800548
MK Ryua34e3b12015-08-21 16:20:47 -0700549def get_servers(hostname=None, role=None, status=None):
Dan Shid7bb4f12015-01-06 10:53:50 -0800550 """Get a list of servers with matching role and status.
551
MK Ryua34e3b12015-08-21 16:20:47 -0700552 @param hostname: FQDN of the server.
Dan Shid7bb4f12015-01-06 10:53:50 -0800553 @param role: Name of the server role, e.g., drone, scheduler. Default to
554 None to match any role.
555 @param status: Status of the server, e.g., primary, backup, repair_required.
556 Default to None to match any server status.
557
558 @raises error.RPCException: If server database is not used.
559 @return: A list of server names for servers with matching role and status.
560 """
561 if not server_manager_utils.use_server_db():
562 raise error.RPCException('Server database is not enabled. Please try '
563 'retrieve servers from global config.')
MK Ryua34e3b12015-08-21 16:20:47 -0700564 servers = server_manager_utils.get_servers(hostname=hostname, role=role,
Dan Shid7bb4f12015-01-06 10:53:50 -0800565 status=status)
566 return [s.get_details() for s in servers]
567
568
MK Ryufbb002c2015-06-08 14:13:16 -0700569@rpc_utils.route_rpc_to_master
Simran Basibeb2bb22016-02-03 15:25:48 -0800570def get_stable_version(board=stable_version_utils.DEFAULT, android=False):
Dan Shi6964fa52014-12-18 11:04:27 -0800571 """Get stable version for the given board.
572
573 @param board: Name of the board.
Simran Basibeb2bb22016-02-03 15:25:48 -0800574 @param android: If True, the given board is an Android-based device. If
575 False, assume its a Chrome OS-based device.
576
Dan Shi6964fa52014-12-18 11:04:27 -0800577 @return: Stable version of the given board. Return global configure value
578 of CROS.stable_cros_version if stable_versinos table does not have
579 entry of board DEFAULT.
580 """
Simran Basibeb2bb22016-02-03 15:25:48 -0800581 return stable_version_utils.get(board=board, android=android)
Dan Shi25e1fd42014-12-19 14:36:42 -0800582
583
MK Ryufbb002c2015-06-08 14:13:16 -0700584@rpc_utils.route_rpc_to_master
Dan Shi25e1fd42014-12-19 14:36:42 -0800585def get_all_stable_versions():
586 """Get stable versions for all boards.
587
588 @return: A dictionary of board:version.
589 """
590 return stable_version_utils.get_all()
591
592
MK Ryufbb002c2015-06-08 14:13:16 -0700593@rpc_utils.route_rpc_to_master
Dan Shi25e1fd42014-12-19 14:36:42 -0800594def set_stable_version(version, board=stable_version_utils.DEFAULT):
595 """Modify stable version for the given board.
596
597 @param version: The new value of stable version for given board.
598 @param board: Name of the board, default to value `DEFAULT`.
599 """
600 stable_version_utils.set(version=version, board=board)
601
602
MK Ryufbb002c2015-06-08 14:13:16 -0700603@rpc_utils.route_rpc_to_master
Dan Shi25e1fd42014-12-19 14:36:42 -0800604def delete_stable_version(board):
605 """Modify stable version for the given board.
606
607 Delete a stable version entry in afe_stable_versions table for a given
608 board, so default stable version will be used.
609
610 @param board: Name of the board.
611 """
612 stable_version_utils.delete(board=board)
Matthew Sartorid96fb9b2015-05-19 18:04:58 -0700613
614
Michael Tang84a2ecf2016-06-07 15:10:53 -0700615def _initialize_control_file_getter(build):
616 """Get the remote control file getter.
Matthew Sartorid96fb9b2015-05-19 18:04:58 -0700617
Michael Tang84a2ecf2016-06-07 15:10:53 -0700618 @param build: unique name by which to refer to a remote build image.
Matthew Sartorid96fb9b2015-05-19 18:04:58 -0700619
Michael Tang84a2ecf2016-06-07 15:10:53 -0700620 @return: A control file getter object.
Matthew Sartorid96fb9b2015-05-19 18:04:58 -0700621 """
622 # Stage the test artifacts.
623 try:
624 ds = dev_server.ImageServer.resolve(build)
625 build = ds.translate(build)
626 except dev_server.DevServerException as e:
627 raise ValueError('Could not resolve build %s: %s' % (build, e))
628
629 try:
Dan Shi6450e142016-03-11 11:52:20 -0800630 ds.stage_artifacts(image=build, artifacts=['test_suites'])
Matthew Sartorid96fb9b2015-05-19 18:04:58 -0700631 except dev_server.DevServerException as e:
632 raise error.StageControlFileFailure(
633 'Failed to stage %s: %s' % (build, e))
634
635 # Collect the control files specified in this build
Michael Tang84a2ecf2016-06-07 15:10:53 -0700636 return control_file_getter.DevServerGetter.create(build, ds)
637
638
639def get_tests_by_build(build, ignore_invalid_tests=True):
640 """Get the tests that are available for the specified build.
641
642 @param build: unique name by which to refer to the image.
643 @param ignore_invalid_tests: flag on if unparsable tests are ignored.
644
645 @return: A sorted list of all tests that are in the build specified.
646 """
647 # Collect the control files specified in this build
648 cfile_getter = _initialize_control_file_getter(build)
xixuan0f7755d2016-04-18 14:49:12 -0700649 if SuiteBase.ENABLE_CONTROLS_IN_BATCH:
650 control_file_info_list = cfile_getter.get_suite_info()
651 control_file_list = control_file_info_list.keys()
652 else:
653 control_file_list = cfile_getter.get_control_file_list()
Matthew Sartorid96fb9b2015-05-19 18:04:58 -0700654
655 test_objects = []
656 _id = 0
657 for control_file_path in control_file_list:
658 # Read and parse the control file
xixuan0f7755d2016-04-18 14:49:12 -0700659 if SuiteBase.ENABLE_CONTROLS_IN_BATCH:
660 control_file = control_file_info_list[control_file_path]
661 else:
662 control_file = cfile_getter.get_control_file_contents(
663 control_file_path)
Michael Tang340efe32016-04-16 12:15:17 -0700664 try:
665 control_obj = control_data.parse_control_string(control_file)
666 except:
Michael Tang6dc174e2016-05-31 23:13:42 -0700667 logging.info('Failed to parse control file: %s', control_file_path)
Michael Tang340efe32016-04-16 12:15:17 -0700668 if not ignore_invalid_tests:
669 raise
Matthew Sartorid96fb9b2015-05-19 18:04:58 -0700670
671 # Extract the values needed for the AFE from the control_obj.
672 # The keys list represents attributes in the control_obj that
673 # are required by the AFE
674 keys = ['author', 'doc', 'name', 'time', 'test_type', 'experimental',
675 'test_category', 'test_class', 'dependencies', 'run_verify',
676 'sync_count', 'job_retries', 'retries', 'path']
677
678 test_object = {}
679 for key in keys:
680 test_object[key] = getattr(control_obj, key) if hasattr(
681 control_obj, key) else ''
682
683 # Unfortunately, the AFE expects different key-names for certain
684 # values, these must be corrected to avoid the risk of tests
685 # being omitted by the AFE.
686 # The 'id' is an additional value used in the AFE.
Matthew Sartori10438092015-06-24 14:30:18 -0700687 # The control_data parsing does not reference 'run_reset', but it
688 # is also used in the AFE and defaults to True.
Matthew Sartorid96fb9b2015-05-19 18:04:58 -0700689 test_object['id'] = _id
Matthew Sartori10438092015-06-24 14:30:18 -0700690 test_object['run_reset'] = True
Matthew Sartorid96fb9b2015-05-19 18:04:58 -0700691 test_object['description'] = test_object.get('doc', '')
692 test_object['test_time'] = test_object.get('time', 0)
693 test_object['test_retry'] = test_object.get('retries', 0)
694
695 # Fix the test name to be consistent with the current presentation
696 # of test names in the AFE.
697 testpath, subname = os.path.split(control_file_path)
698 testname = os.path.basename(testpath)
699 subname = subname.split('.')[1:]
700 if subname:
701 testname = '%s:%s' % (testname, ':'.join(subname))
702
703 test_object['name'] = testname
704
Matthew Sartori10438092015-06-24 14:30:18 -0700705 # Correct the test path as parse_control_string sets an empty string.
706 test_object['path'] = control_file_path
707
Matthew Sartorid96fb9b2015-05-19 18:04:58 -0700708 _id += 1
709 test_objects.append(test_object)
710
Matthew Sartori10438092015-06-24 14:30:18 -0700711 test_objects = sorted(test_objects, key=lambda x: x.get('name'))
Matthew Sartorid96fb9b2015-05-19 18:04:58 -0700712 return rpc_utils.prepare_for_serialization(test_objects)
Michael Tang84a2ecf2016-06-07 15:10:53 -0700713
714
715def get_test_control_files_by_build(tests, build, ignore_invalid_tests=False):
716 """Get the test control files that are available for the specified build.
717
718 @param tests A sequence of test objects to run.
719 @param build: unique name by which to refer to the image.
720 @param ignore_invalid_tests: flag on if unparsable tests are ignored.
721
722 @return: A sorted list of all tests that are in the build specified.
723 """
724 raw_control_files = []
725 # shortcut to avoid staging the image.
726 if not tests:
727 return raw_control_files
728
729 cfile_getter = _initialize_control_file_getter(build)
730 if SuiteBase.ENABLE_CONTROLS_IN_BATCH:
731 control_file_info_list = cfile_getter.get_suite_info()
732
733 for test in tests:
734 # Read and parse the control file
735 if SuiteBase.ENABLE_CONTROLS_IN_BATCH:
736 control_file = control_file_info_list[test.path]
737 else:
738 control_file = cfile_getter.get_control_file_contents(
739 test.path)
740 raw_control_files.append(control_file)
741 return raw_control_files