blob: e6d7849da0f39ac733e35c5b08a3c45b412fc8a6 [file] [log] [blame]
Dan Shi4df39252013-03-19 13:19:45 -07001# pylint: disable-msg=C0111
2
Chris Masone859fdec2012-01-30 08:38:09 -08003# 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
7__author__ = 'cmasone@chromium.org (Chris Masone)'
8
9import common
Simran Basi773a86e2015-05-13 19:15:42 -070010import ConfigParser
Chris Masonea8066a92012-05-01 16:52:31 -070011import datetime
Chris Masone859fdec2012-01-30 08:38:09 -080012import logging
Simran Basi71206ef2014-08-13 13:51:18 -070013import os
14import shutil
Aviv Keshetd83ef442013-01-16 16:19:35 -080015
Jakob Juelich82b7d1c2014-09-15 16:10:57 -070016from autotest_lib.frontend.afe import models
Matthew Sartorid96fb9b2015-05-19 18:04:58 -070017from autotest_lib.client.common_lib import control_data
Aviv Keshetd83ef442013-01-16 16:19:35 -080018from autotest_lib.client.common_lib import error
Simran Basi71206ef2014-08-13 13:51:18 -070019from autotest_lib.client.common_lib import global_config
Alex Miller7d658cf2013-09-04 16:00:35 -070020from autotest_lib.client.common_lib import priorities
Dan Shidfea3682014-08-10 23:38:40 -070021from autotest_lib.client.common_lib import time_utils
Chris Masone859fdec2012-01-30 08:38:09 -080022from autotest_lib.client.common_lib.cros import dev_server
Gabe Black1e1c41b2015-02-04 23:55:15 -080023from autotest_lib.client.common_lib.cros.graphite import autotest_stats
Jakob Juelich9fffe4f2014-08-14 18:07:05 -070024from autotest_lib.frontend.afe import rpc_utils
Simran Basib6ec8ae2014-04-23 12:05:08 -070025from autotest_lib.server import utils
Dan Shi36cfd832014-10-10 13:38:51 -070026from autotest_lib.server.cros import provision
Chris Masone44e4d6c2012-08-15 14:25:53 -070027from autotest_lib.server.cros.dynamic_suite import constants
Chris Masoneb4935552012-08-14 12:05:54 -070028from autotest_lib.server.cros.dynamic_suite import control_file_getter
Chris Masone44e4d6c2012-08-15 14:25:53 -070029from autotest_lib.server.cros.dynamic_suite import tools
Dan Shi36cfd832014-10-10 13:38:51 -070030from autotest_lib.server.cros.dynamic_suite.suite import Suite
Simran Basi71206ef2014-08-13 13:51:18 -070031from autotest_lib.server.hosts import moblab_host
Dan Shidfea3682014-08-10 23:38:40 -070032from autotest_lib.site_utils import host_history
Dan Shi193905e2014-07-25 23:33:09 -070033from autotest_lib.site_utils import job_history
Dan Shid7bb4f12015-01-06 10:53:50 -080034from autotest_lib.site_utils import server_manager_utils
Dan Shi6964fa52014-12-18 11:04:27 -080035from autotest_lib.site_utils import stable_version_utils
Simran Basi71206ef2014-08-13 13:51:18 -070036
37
38_CONFIG = global_config.global_config
39MOBLAB_BOTO_LOCATION = '/home/moblab/.boto'
Chris Masone859fdec2012-01-30 08:38:09 -080040
Chris Masonef8b53062012-05-08 22:14:18 -070041# Relevant CrosDynamicSuiteExceptions are defined in client/common_lib/error.py.
Chris Masone859fdec2012-01-30 08:38:09 -080042
43
Chris Masone62579122012-03-08 15:18:43 -080044def canonicalize_suite_name(suite_name):
45 return 'test_suites/control.%s' % suite_name
46
47
Chris Masoneaa10f8e2012-05-15 13:34:21 -070048def formatted_now():
Dan Shidfea3682014-08-10 23:38:40 -070049 return datetime.datetime.now().strftime(time_utils.TIME_FMT)
Chris Masoneaa10f8e2012-05-15 13:34:21 -070050
51
Simran Basib6ec8ae2014-04-23 12:05:08 -070052def _get_control_file_contents_by_name(build, ds, suite_name):
Chris Masone8dd27e02012-06-25 15:59:43 -070053 """Return control file contents for |suite_name|.
54
55 Query the dev server at |ds| for the control file |suite_name|, included
56 in |build| for |board|.
57
58 @param build: unique name by which to refer to the image from now on.
Chris Masone8dd27e02012-06-25 15:59:43 -070059 @param ds: a dev_server.DevServer instance to fetch control file with.
60 @param suite_name: canonicalized suite name, e.g. test_suites/control.bvt.
61 @raises ControlFileNotFound if a unique suite control file doesn't exist.
62 @raises NoControlFileList if we can't list the control files at all.
63 @raises ControlFileEmpty if the control file exists on the server, but
64 can't be read.
65
66 @return the contents of the desired control file.
67 """
68 getter = control_file_getter.DevServerGetter.create(build, ds)
Gabe Black1e1c41b2015-02-04 23:55:15 -080069 timer = autotest_stats.Timer('control_files.parse.%s.%s' %
70 (ds.get_server_name(ds.url()
71 ).replace('.', '_'),
72 suite_name.rsplit('.')[-1]))
Chris Masone8dd27e02012-06-25 15:59:43 -070073 # Get the control file for the suite.
74 try:
Prashanth Balasubramanianabe3bb72014-11-20 12:00:37 -080075 with timer:
76 control_file_in = getter.get_control_file_contents_by_name(
77 suite_name)
Chris Masone8dd27e02012-06-25 15:59:43 -070078 except error.CrosDynamicSuiteException as e:
Simran Basib6ec8ae2014-04-23 12:05:08 -070079 raise type(e)("%s while testing %s." % (e, build))
Chris Masone8dd27e02012-06-25 15:59:43 -070080 if not control_file_in:
81 raise error.ControlFileEmpty(
82 "Fetching %s returned no data." % suite_name)
Alex Millera713e252013-03-01 10:45:44 -080083 # Force control files to only contain ascii characters.
84 try:
85 control_file_in.encode('ascii')
86 except UnicodeDecodeError as e:
87 raise error.ControlFileMalformed(str(e))
88
Chris Masone8dd27e02012-06-25 15:59:43 -070089 return control_file_in
90
91
Simran Basib6ec8ae2014-04-23 12:05:08 -070092def _stage_build_artifacts(build):
93 """
94 Ensure components of |build| necessary for installing images are staged.
95
96 @param build image we want to stage.
97
Prashanth B6285f6a2014-05-08 18:01:27 -070098 @raises StageControlFileFailure: if the dev server throws 500 while staging
99 suite control files.
Simran Basib6ec8ae2014-04-23 12:05:08 -0700100
101 @return: dev_server.ImageServer instance to use with this build.
102 @return: timings dictionary containing staging start/end times.
103 """
104 timings = {}
Prashanth B6285f6a2014-05-08 18:01:27 -0700105 # Ensure components of |build| necessary for installing images are staged
106 # on the dev server. However set synchronous to False to allow other
107 # components to be downloaded in the background.
Simran Basib6ec8ae2014-04-23 12:05:08 -0700108 ds = dev_server.ImageServer.resolve(build)
109 timings[constants.DOWNLOAD_STARTED_TIME] = formatted_now()
Gabe Black1e1c41b2015-02-04 23:55:15 -0800110 timer = autotest_stats.Timer('control_files.stage.%s' % (
111 ds.get_server_name(ds.url()).replace('.', '_')))
Simran Basib6ec8ae2014-04-23 12:05:08 -0700112 try:
Prashanth Balasubramanianabe3bb72014-11-20 12:00:37 -0800113 with timer:
114 ds.stage_artifacts(build, ['test_suites'])
Simran Basib6ec8ae2014-04-23 12:05:08 -0700115 except dev_server.DevServerException as e:
Prashanth B6285f6a2014-05-08 18:01:27 -0700116 raise error.StageControlFileFailure(
Simran Basib6ec8ae2014-04-23 12:05:08 -0700117 "Failed to stage %s: %s" % (build, e))
118 timings[constants.PAYLOAD_FINISHED_TIME] = formatted_now()
119 return (ds, timings)
120
121
122def create_suite_job(name='', board='', build='', pool='', control_file='',
123 check_hosts=True, num=None, file_bugs=False, timeout=24,
124 timeout_mins=None, priority=priorities.Priority.DEFAULT,
Fang Deng058860c2014-05-15 15:41:50 -0700125 suite_args=None, wait_for_results=True, job_retry=False,
Fang Deng443f1952015-01-02 14:51:49 -0800126 max_retries=None, max_runtime_mins=None, suite_min_duts=0,
Dan Shi36cfd832014-10-10 13:38:51 -0700127 offload_failures_only=False, builds={},
128 test_source_build=None, **kwargs):
Chris Masone859fdec2012-01-30 08:38:09 -0800129 """
130 Create a job to run a test suite on the given device with the given image.
131
132 When the timeout specified in the control file is reached, the
133 job is guaranteed to have completed and results will be available.
134
Simran Basib6ec8ae2014-04-23 12:05:08 -0700135 @param name: The test name if control_file is supplied, otherwise the name
136 of the test suite to run, e.g. 'bvt'.
Chris Masone859fdec2012-01-30 08:38:09 -0800137 @param board: the kind of device to run the tests on.
138 @param build: unique name by which to refer to the image from now on.
Dan Shi36cfd832014-10-10 13:38:51 -0700139 @param builds: the builds to install e.g.
140 {'cros-version:': 'x86-alex-release/R18-1655.0.0',
141 'fw-version:': 'x86-alex-firmware/R36-5771.50.0',
142 'fwro-version:': 'x86-alex-firmware/R36-5771.49.0'}
143 If builds is given a value, it overrides argument build.
144 @param test_source_build: Build that contains the server-side test code.
Scott Zawalski65650172012-02-16 11:48:26 -0500145 @param pool: Specify the pool of machines to use for scheduling
146 purposes.
Chris Masone62579122012-03-08 15:18:43 -0800147 @param check_hosts: require appropriate live hosts to exist in the lab.
Aviv Keshetd83ef442013-01-16 16:19:35 -0800148 @param num: Specify the number of machines to schedule across (integer).
149 Leave unspecified or use None to use default sharding factor.
Alex Millerc577f3e2012-09-27 14:06:07 -0700150 @param file_bugs: File a bug on each test failure in this suite.
Alex Miller139690b2013-09-07 15:35:49 -0700151 @param timeout: The max lifetime of this suite, in hours.
Simran Basi7e605742013-11-12 13:43:36 -0800152 @param timeout_mins: The max lifetime of this suite, in minutes. Takes
153 priority over timeout.
Alex Miller139690b2013-09-07 15:35:49 -0700154 @param priority: Integer denoting priority. Higher is more important.
Aviv Keshet7cd12312013-07-25 10:25:55 -0700155 @param suite_args: Optional arguments which will be parsed by the suite
156 control file. Used by control.test_that_wrapper to
157 determine which tests to run.
Dan Shi95122412013-11-12 16:20:33 -0800158 @param wait_for_results: Set to False to run the suite job without waiting
159 for test jobs to finish. Default is True.
Fang Deng058860c2014-05-15 15:41:50 -0700160 @param job_retry: Set to True to enable job-level retry. Default is False.
Fang Deng443f1952015-01-02 14:51:49 -0800161 @param max_retries: Integer, maximum job retries allowed at suite level.
162 None for no max.
Simran Basi102e3522014-09-11 11:46:10 -0700163 @param max_runtime_mins: Maximum amount of time a job can be running in
164 minutes.
Fang Dengcbc01212014-11-25 16:09:46 -0800165 @param suite_min_duts: Integer. Scheduler will prioritize getting the
166 minimum number of machines for the suite when it is
167 competing with another suite that has a higher
168 priority but already got minimum machines it needs.
Simran Basi1e10e922015-04-16 15:09:56 -0700169 @param offload_failures_only: Only enable gs_offloading for failed jobs.
Simran Basib6ec8ae2014-04-23 12:05:08 -0700170 @param kwargs: extra keyword args. NOT USED.
Chris Masone859fdec2012-01-30 08:38:09 -0800171
Chris Masone8dd27e02012-06-25 15:59:43 -0700172 @raises ControlFileNotFound: if a unique suite control file doesn't exist.
173 @raises NoControlFileList: if we can't list the control files at all.
Prashanth B6285f6a2014-05-08 18:01:27 -0700174 @raises StageControlFileFailure: If the dev server throws 500 while
175 staging test_suites.
Chris Masone8dd27e02012-06-25 15:59:43 -0700176 @raises ControlFileEmpty: if the control file exists on the server, but
177 can't be read.
Chris Masone859fdec2012-01-30 08:38:09 -0800178
179 @return: the job ID of the suite; -1 on error.
180 """
Aviv Keshetd83ef442013-01-16 16:19:35 -0800181 if type(num) is not int and num is not None:
Chris Sosa18c70b32013-02-15 14:12:43 -0800182 raise error.SuiteArgumentException('Ill specified num argument %r. '
183 'Must be an integer or None.' % num)
Aviv Keshetd83ef442013-01-16 16:19:35 -0800184 if num == 0:
185 logging.warning("Can't run on 0 hosts; using default.")
186 num = None
Dan Shi36cfd832014-10-10 13:38:51 -0700187
188 # TODO(dshi): crbug.com/496782 Remove argument build and its reference after
189 # R45 falls out of stable channel.
190 if build and not builds:
191 builds = {provision.CROS_VERSION_PREFIX: build}
192 # TODO(dshi): crbug.com/497236 Remove this check after firmware ro provision
193 # is supported in Autotest.
194 if provision.FW_RO_VERSION_PREFIX in builds:
195 raise error.SuiteArgumentException(
196 'Updating RO firmware is not supported yet.')
197 # Default test source build to CrOS build if it's not specified.
198 test_source_build = Suite.get_test_source_build(
199 builds, test_source_build=test_source_build)
200
201 (ds, keyvals) = _stage_build_artifacts(test_source_build)
Fang Dengcbc01212014-11-25 16:09:46 -0800202 keyvals[constants.SUITE_MIN_DUTS_KEY] = suite_min_duts
Chris Masone859fdec2012-01-30 08:38:09 -0800203
Simran Basib6ec8ae2014-04-23 12:05:08 -0700204 if not control_file:
Dan Shi36cfd832014-10-10 13:38:51 -0700205 # No control file was supplied so look it up from the build artifacts.
206 suite_name = canonicalize_suite_name(name)
207 control_file = _get_control_file_contents_by_name(test_source_build,
208 ds, suite_name)
209 name = '%s-%s' % (test_source_build, suite_name)
Chris Masone46d0eb12012-07-27 18:56:39 -0700210
Simran Basi7e605742013-11-12 13:43:36 -0800211 timeout_mins = timeout_mins or timeout * 60
Simran Basi102e3522014-09-11 11:46:10 -0700212 max_runtime_mins = max_runtime_mins or timeout * 60
Simran Basi7e605742013-11-12 13:43:36 -0800213
Simran Basib6ec8ae2014-04-23 12:05:08 -0700214 if not board:
Dan Shid215dbe2015-06-18 16:14:59 -0700215 board = utils.ParseBuildName(builds[provision.CROS_VERSION_PREFIX])[0]
Chris Masone46d0eb12012-07-27 18:56:39 -0700216
Dan Shi36cfd832014-10-10 13:38:51 -0700217 # TODO(dshi): crbug.com/496782 Remove argument build and its reference after
218 # R45 falls out of stable channel.
Simran Basib6ec8ae2014-04-23 12:05:08 -0700219 # Prepend build and board to the control file.
Scott Zawalski65650172012-02-16 11:48:26 -0500220 inject_dict = {'board': board,
Dan Shi36cfd832014-10-10 13:38:51 -0700221 'build': test_source_build,
222 'builds': builds,
Chris Masone62579122012-03-08 15:18:43 -0800223 'check_hosts': check_hosts,
Chris Masone46d0eb12012-07-27 18:56:39 -0700224 'pool': pool,
Aviv Keshetd83ef442013-01-16 16:19:35 -0800225 'num': num,
Dan Shib8a99112013-06-18 13:46:10 -0700226 'file_bugs': file_bugs,
Alex Miller139690b2013-09-07 15:35:49 -0700227 'timeout': timeout,
Simran Basi7e605742013-11-12 13:43:36 -0800228 'timeout_mins': timeout_mins,
Alex Miller7d658cf2013-09-04 16:00:35 -0700229 'devserver_url': ds.url(),
Aviv Keshet7cd12312013-07-25 10:25:55 -0700230 'priority': priority,
Dan Shi95122412013-11-12 16:20:33 -0800231 'suite_args' : suite_args,
Fang Deng058860c2014-05-15 15:41:50 -0700232 'wait_for_results': wait_for_results,
Simran Basi102e3522014-09-11 11:46:10 -0700233 'job_retry': job_retry,
Fang Deng443f1952015-01-02 14:51:49 -0800234 'max_retries': max_retries,
Fang Dengcbc01212014-11-25 16:09:46 -0800235 'max_runtime_mins': max_runtime_mins,
Dan Shi36cfd832014-10-10 13:38:51 -0700236 'offload_failures_only': offload_failures_only,
237 'test_source_build': test_source_build
Aviv Keshet7cd12312013-07-25 10:25:55 -0700238 }
239
Simran Basib6ec8ae2014-04-23 12:05:08 -0700240 control_file = tools.inject_vars(inject_dict, control_file)
Chris Masone859fdec2012-01-30 08:38:09 -0800241
Jakob Juelich9fffe4f2014-08-14 18:07:05 -0700242 return rpc_utils.create_job_common(name,
Jakob Juelich59cfe542014-09-02 16:37:46 -0700243 priority=priority,
244 timeout_mins=timeout_mins,
245 max_runtime_mins=max_runtime_mins,
246 control_type='Server',
247 control_file=control_file,
248 hostless=True,
Fang Dengcbc01212014-11-25 16:09:46 -0800249 keyvals=keyvals)
Simran Basi71206ef2014-08-13 13:51:18 -0700250
251
252# TODO: hide the following rpcs under is_moblab
253def moblab_only(func):
254 """Ensure moblab specific functions only run on Moblab devices."""
255 def verify(*args, **kwargs):
256 if not utils.is_moblab():
257 raise error.RPCException('RPC: %s can only run on Moblab Systems!',
258 func.__name__)
259 return func(*args, **kwargs)
260 return verify
261
262
263@moblab_only
264def get_config_values():
265 """Returns all config values parsed from global and shadow configs.
266
267 Config values are grouped by sections, and each section is composed of
268 a list of name value pairs.
269 """
270 sections =_CONFIG.get_sections()
271 config_values = {}
272 for section in sections:
273 config_values[section] = _CONFIG.config.items(section)
Jakob Juelich9fffe4f2014-08-14 18:07:05 -0700274 return rpc_utils.prepare_for_serialization(config_values)
Simran Basi71206ef2014-08-13 13:51:18 -0700275
276
277@moblab_only
278def update_config_handler(config_values):
279 """
280 Update config values and override shadow config.
281
282 @param config_values: See get_moblab_settings().
283 """
Simran Basi773a86e2015-05-13 19:15:42 -0700284 original_config = global_config.global_config_class()
285 original_config.set_config_files(shadow_file='')
286 new_shadow = ConfigParser.RawConfigParser()
Simran Basi71206ef2014-08-13 13:51:18 -0700287 for section, config_value_list in config_values.iteritems():
288 for key, value in config_value_list:
Simran Basi773a86e2015-05-13 19:15:42 -0700289 if original_config.get_config_value(section, key,
290 default='',
291 allow_blank=True) != value:
292 if not new_shadow.has_section(section):
293 new_shadow.add_section(section)
294 new_shadow.set(section, key, value)
Simran Basi71206ef2014-08-13 13:51:18 -0700295 if not _CONFIG.shadow_file or not os.path.exists(_CONFIG.shadow_file):
296 raise error.RPCException('Shadow config file does not exist.')
297
298 with open(_CONFIG.shadow_file, 'w') as config_file:
Simran Basi773a86e2015-05-13 19:15:42 -0700299 new_shadow.write(config_file)
Simran Basi71206ef2014-08-13 13:51:18 -0700300 # TODO (sbasi) crbug.com/403916 - Remove the reboot command and
301 # instead restart the services that rely on the config values.
302 os.system('sudo reboot')
303
304
305@moblab_only
306def reset_config_settings():
307 with open(_CONFIG.shadow_file, 'w') as config_file:
Dan Shi36cfd832014-10-10 13:38:51 -0700308 pass
Simran Basi71206ef2014-08-13 13:51:18 -0700309 os.system('sudo reboot')
310
311
312@moblab_only
313def set_boto_key(boto_key):
314 """Update the boto_key file.
315
316 @param boto_key: File name of boto_key uploaded through handle_file_upload.
317 """
318 if not os.path.exists(boto_key):
319 raise error.RPCException('Boto key: %s does not exist!' % boto_key)
320 shutil.copyfile(boto_key, moblab_host.MOBLAB_BOTO_LOCATION)
Dan Shi193905e2014-07-25 23:33:09 -0700321
322
323def get_job_history(**filter_data):
324 """Get history of the job, including the special tasks executed for the job
325
326 @param filter_data: filter for the call, should at least include
327 {'job_id': [job id]}
328 @returns: JSON string of the job's history, including the information such
329 as the hosts run the job and the special tasks executed before
330 and after the job.
331 """
332 job_id = filter_data['job_id']
333 job_info = job_history.get_job_info(job_id)
Dan Shidfea3682014-08-10 23:38:40 -0700334 return rpc_utils.prepare_for_serialization(job_info.get_history())
335
336
337def get_host_history(start_time, end_time, hosts=None, board=None, pool=None):
338 """Get history of a list of host.
339
340 The return is a JSON string of host history for each host, for example,
341 {'172.22.33.51': [{'status': 'Resetting'
342 'start_time': '2014-08-07 10:02:16',
343 'end_time': '2014-08-07 10:03:16',
344 'log_url': 'http://autotest/reset-546546/debug',
345 'dbg_str': 'Task: Special Task 19441991 (host ...)'},
346 {'status': 'Running'
347 'start_time': '2014-08-07 10:03:18',
348 'end_time': '2014-08-07 10:13:00',
349 'log_url': 'http://autotest/reset-546546/debug',
350 'dbg_str': 'HQE: 15305005, for job: 14995562'}
351 ]
352 }
353 @param start_time: start time to search for history, can be string value or
354 epoch time.
355 @param end_time: end time to search for history, can be string value or
356 epoch time.
357 @param hosts: A list of hosts to search for history. Default is None.
358 @param board: board type of hosts. Default is None.
359 @param pool: pool type of hosts. Default is None.
360 @returns: JSON string of the host history.
361 """
362 return rpc_utils.prepare_for_serialization(
363 host_history.get_history_details(
364 start_time=start_time, end_time=end_time,
365 hosts=hosts, board=board, pool=pool,
366 process_pool_size=4))
Jakob Juelich59cfe542014-09-02 16:37:46 -0700367
368
Jakob Juelich1b525742014-09-30 13:08:07 -0700369def shard_heartbeat(shard_hostname, jobs=(), hqes=(),
370 known_job_ids=(), known_host_ids=()):
371 """Receive updates for job statuses from shards and assign hosts and jobs.
Jakob Juelich59cfe542014-09-02 16:37:46 -0700372
373 @param shard_hostname: Hostname of the calling shard
Jakob Juelicha94efe62014-09-18 16:02:49 -0700374 @param jobs: Jobs in serialized form that should be updated with newer
375 status from a shard.
376 @param hqes: Hostqueueentries in serialized form that should be updated with
377 newer status from a shard. Note that for every hostqueueentry
378 the corresponding job must be in jobs.
Jakob Juelich1b525742014-09-30 13:08:07 -0700379 @param known_job_ids: List of ids of jobs the shard already has.
380 @param known_host_ids: List of ids of hosts the shard already has.
Jakob Juelicha94efe62014-09-18 16:02:49 -0700381
Fang Dengf3705992014-12-16 17:32:18 -0800382 @returns: Serialized representations of hosts, jobs, suite job keyvals
383 and their dependencies to be inserted into a shard's database.
Jakob Juelich59cfe542014-09-02 16:37:46 -0700384 """
Jakob Juelich1b525742014-09-30 13:08:07 -0700385 # The following alternatives to sending host and job ids in every heartbeat
386 # have been considered:
387 # 1. Sending the highest known job and host ids. This would work for jobs:
388 # Newer jobs always have larger ids. Also, if a job is not assigned to a
389 # particular shard during a heartbeat, it never will be assigned to this
390 # shard later.
391 # This is not true for hosts though: A host that is leased won't be sent
392 # to the shard now, but might be sent in a future heartbeat. This means
393 # sometimes hosts should be transfered that have a lower id than the
394 # maximum host id the shard knows.
395 # 2. Send the number of jobs/hosts the shard knows to the master in each
396 # heartbeat. Compare these to the number of records that already have
397 # the shard_id set to this shard. In the normal case, they should match.
398 # In case they don't, resend all entities of that type.
399 # This would work well for hosts, because there aren't that many.
400 # Resending all jobs is quite a big overhead though.
401 # Also, this approach might run into edge cases when entities are
402 # ever deleted.
403 # 3. Mixtures of the above: Use 1 for jobs and 2 for hosts.
404 # Using two different approaches isn't consistent and might cause
405 # confusion. Also the issues with the case of deletions might still
406 # occur.
407 #
408 # The overhead of sending all job and host ids in every heartbeat is low:
409 # At peaks one board has about 1200 created but unfinished jobs.
410 # See the numbers here: http://goo.gl/gQCGWH
411 # Assuming that job id's have 6 digits and that json serialization takes a
412 # comma and a space as overhead, the traffic per id sent is about 8 bytes.
413 # If 5000 ids need to be sent, this means 40 kilobytes of traffic.
414 # A NOT IN query with 5000 ids took about 30ms in tests made.
415 # These numbers seem low enough to outweigh the disadvantages of the
416 # solutions described above.
Gabe Black1e1c41b2015-02-04 23:55:15 -0800417 timer = autotest_stats.Timer('shard_heartbeat')
Jakob Juelich59cfe542014-09-02 16:37:46 -0700418 with timer:
419 shard_obj = rpc_utils.retrieve_shard(shard_hostname=shard_hostname)
Jakob Juelicha94efe62014-09-18 16:02:49 -0700420 rpc_utils.persist_records_sent_from_shard(shard_obj, jobs, hqes)
Fang Dengf3705992014-12-16 17:32:18 -0800421 hosts, jobs, suite_keyvals = rpc_utils.find_records_for_shard(
Jakob Juelich1b525742014-09-30 13:08:07 -0700422 shard_obj,
423 known_job_ids=known_job_ids, known_host_ids=known_host_ids)
Jakob Juelich59cfe542014-09-02 16:37:46 -0700424 return {
425 'hosts': [host.serialize() for host in hosts],
426 'jobs': [job.serialize() for job in jobs],
Fang Dengf3705992014-12-16 17:32:18 -0800427 'suite_keyvals': [kv.serialize() for kv in suite_keyvals],
Jakob Juelich59cfe542014-09-02 16:37:46 -0700428 }
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700429
430
431def get_shards(**filter_data):
432 """Return a list of all shards.
433
434 @returns A sequence of nested dictionaries of shard information.
435 """
436 shards = models.Shard.query_objects(filter_data)
437 serialized_shards = rpc_utils.prepare_rows_as_nested_dicts(shards, ())
438 for serialized, shard in zip(serialized_shards, shards):
439 serialized['labels'] = [label.name for label in shard.labels.all()]
440
441 return serialized_shards
442
443
444def add_shard(hostname, label):
445 """Add a shard and start running jobs on it.
446
447 @param hostname: The hostname of the shard to be added; needs to be unique.
448 @param label: A platform label. Jobs of this label will be assigned to the
449 shard.
450
Jakob Juelich8b110ee2014-09-15 16:13:42 -0700451 @raises error.RPCException: If label provided doesn't start with `board:`
452 @raises model_logic.ValidationError: If a shard with the given hostname
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700453 already exists.
Jakob Juelich8b110ee2014-09-15 16:13:42 -0700454 @raises models.Label.DoesNotExist: If the label specified doesn't exist.
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700455 """
Jakob Juelich8b110ee2014-09-15 16:13:42 -0700456 if not label.startswith('board:'):
457 raise error.RPCException('Sharding only supported for `board:.*` '
458 'labels.')
459
460 # Fetch label first, so shard isn't created when label doesn't exist.
461 label = models.Label.smart_get(label)
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700462 shard = models.Shard.add_object(hostname=hostname)
Jakob Juelich8b110ee2014-09-15 16:13:42 -0700463 shard.labels.add(label)
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700464 return shard.id
465
466
467def delete_shard(hostname):
468 """Delete a shard and reclaim all resources from it.
469
470 This claims back all assigned hosts from the shard. To ensure all DUTs are
471 in a sane state, a Repair task is scheduled for them. This reboots the DUTs
472 and therefore clears all running processes that might be left.
473
474 The shard_id of jobs of that shard will be set to None.
475
476 The status of jobs that haven't been reported to be finished yet, will be
477 lost. The master scheduler will pick up the jobs and execute them.
478
479 @param hostname: Hostname of the shard to delete.
480 """
481 shard = rpc_utils.retrieve_shard(shard_hostname=hostname)
482
483 # TODO(beeps): Power off shard
484
485 # For ChromeOS hosts, repair reboots the DUT.
486 # Repair will excalate through multiple repair steps and will verify the
487 # success after each of them. Anyway, it will always run at least the first
488 # one, which includes a reboot.
489 # After a reboot we can be sure no processes from prior tests that were run
490 # by a shard are still running on the DUT.
491 # Important: Don't just set the status to Repair Failed, as that would run
492 # Verify first, before doing any repair measures. Verify would probably
493 # succeed, so this wouldn't change anything on the DUT.
494 for host in models.Host.objects.filter(shard=shard):
495 models.SpecialTask.objects.create(
496 task=models.SpecialTask.Task.REPAIR,
497 host=host,
498 requested_by=models.User.current_user())
499 models.Host.objects.filter(shard=shard).update(shard=None)
500
501 models.Job.objects.filter(shard=shard).update(shard=None)
502
503 shard.labels.clear()
504
505 shard.delete()
Dan Shi6964fa52014-12-18 11:04:27 -0800506
507
Dan Shid7bb4f12015-01-06 10:53:50 -0800508def get_servers(role=None, status=None):
509 """Get a list of servers with matching role and status.
510
511 @param role: Name of the server role, e.g., drone, scheduler. Default to
512 None to match any role.
513 @param status: Status of the server, e.g., primary, backup, repair_required.
514 Default to None to match any server status.
515
516 @raises error.RPCException: If server database is not used.
517 @return: A list of server names for servers with matching role and status.
518 """
519 if not server_manager_utils.use_server_db():
520 raise error.RPCException('Server database is not enabled. Please try '
521 'retrieve servers from global config.')
522 servers = server_manager_utils.get_servers(hostname=None, role=role,
523 status=status)
524 return [s.get_details() for s in servers]
525
526
MK Ryufbb002c2015-06-08 14:13:16 -0700527@rpc_utils.route_rpc_to_master
Dan Shi6964fa52014-12-18 11:04:27 -0800528def get_stable_version(board=stable_version_utils.DEFAULT):
529 """Get stable version for the given board.
530
531 @param board: Name of the board.
532 @return: Stable version of the given board. Return global configure value
533 of CROS.stable_cros_version if stable_versinos table does not have
534 entry of board DEFAULT.
535 """
Dan Shi25e1fd42014-12-19 14:36:42 -0800536 return stable_version_utils.get(board)
537
538
MK Ryufbb002c2015-06-08 14:13:16 -0700539@rpc_utils.route_rpc_to_master
Dan Shi25e1fd42014-12-19 14:36:42 -0800540def get_all_stable_versions():
541 """Get stable versions for all boards.
542
543 @return: A dictionary of board:version.
544 """
545 return stable_version_utils.get_all()
546
547
MK Ryufbb002c2015-06-08 14:13:16 -0700548@rpc_utils.route_rpc_to_master
Dan Shi25e1fd42014-12-19 14:36:42 -0800549def set_stable_version(version, board=stable_version_utils.DEFAULT):
550 """Modify stable version for the given board.
551
552 @param version: The new value of stable version for given board.
553 @param board: Name of the board, default to value `DEFAULT`.
554 """
555 stable_version_utils.set(version=version, board=board)
556
557
MK Ryufbb002c2015-06-08 14:13:16 -0700558@rpc_utils.route_rpc_to_master
Dan Shi25e1fd42014-12-19 14:36:42 -0800559def delete_stable_version(board):
560 """Modify stable version for the given board.
561
562 Delete a stable version entry in afe_stable_versions table for a given
563 board, so default stable version will be used.
564
565 @param board: Name of the board.
566 """
567 stable_version_utils.delete(board=board)
Matthew Sartorid96fb9b2015-05-19 18:04:58 -0700568
569
570def get_tests_by_build(build):
571 """Get the tests that are available for the specified build.
572
573 @param build: unique name by which to refer to the image.
574
575 @return: A sorted list of all tests that are in the build specified.
576 """
577 # Stage the test artifacts.
578 try:
579 ds = dev_server.ImageServer.resolve(build)
580 build = ds.translate(build)
581 except dev_server.DevServerException as e:
582 raise ValueError('Could not resolve build %s: %s' % (build, e))
583
584 try:
585 ds.stage_artifacts(build, ['test_suites'])
586 except dev_server.DevServerException as e:
587 raise error.StageControlFileFailure(
588 'Failed to stage %s: %s' % (build, e))
589
590 # Collect the control files specified in this build
591 cfile_getter = control_file_getter.DevServerGetter.create(build, ds)
592 control_file_list = cfile_getter.get_control_file_list()
593
594 test_objects = []
595 _id = 0
596 for control_file_path in control_file_list:
597 # Read and parse the control file
598 control_file = cfile_getter.get_control_file_contents(
599 control_file_path)
600 control_obj = control_data.parse_control_string(control_file)
601
602 # Extract the values needed for the AFE from the control_obj.
603 # The keys list represents attributes in the control_obj that
604 # are required by the AFE
605 keys = ['author', 'doc', 'name', 'time', 'test_type', 'experimental',
606 'test_category', 'test_class', 'dependencies', 'run_verify',
607 'sync_count', 'job_retries', 'retries', 'path']
608
609 test_object = {}
610 for key in keys:
611 test_object[key] = getattr(control_obj, key) if hasattr(
612 control_obj, key) else ''
613
614 # Unfortunately, the AFE expects different key-names for certain
615 # values, these must be corrected to avoid the risk of tests
616 # being omitted by the AFE.
617 # The 'id' is an additional value used in the AFE.
Matthew Sartori10438092015-06-24 14:30:18 -0700618 # The control_data parsing does not reference 'run_reset', but it
619 # is also used in the AFE and defaults to True.
Matthew Sartorid96fb9b2015-05-19 18:04:58 -0700620 test_object['id'] = _id
Matthew Sartori10438092015-06-24 14:30:18 -0700621 test_object['run_reset'] = True
Matthew Sartorid96fb9b2015-05-19 18:04:58 -0700622 test_object['description'] = test_object.get('doc', '')
623 test_object['test_time'] = test_object.get('time', 0)
624 test_object['test_retry'] = test_object.get('retries', 0)
625
626 # Fix the test name to be consistent with the current presentation
627 # of test names in the AFE.
628 testpath, subname = os.path.split(control_file_path)
629 testname = os.path.basename(testpath)
630 subname = subname.split('.')[1:]
631 if subname:
632 testname = '%s:%s' % (testname, ':'.join(subname))
633
634 test_object['name'] = testname
635
Matthew Sartori10438092015-06-24 14:30:18 -0700636 # Correct the test path as parse_control_string sets an empty string.
637 test_object['path'] = control_file_path
638
Matthew Sartorid96fb9b2015-05-19 18:04:58 -0700639 _id += 1
640 test_objects.append(test_object)
641
Matthew Sartori10438092015-06-24 14:30:18 -0700642 test_objects = sorted(test_objects, key=lambda x: x.get('name'))
Matthew Sartorid96fb9b2015-05-19 18:04:58 -0700643 return rpc_utils.prepare_for_serialization(test_objects)