blob: dd991a86fd94bc853b1ff854b54e1400f86f0f50 [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
Aviv Keshetd83ef442013-01-16 16:19:35 -080017from autotest_lib.client.common_lib import error
Simran Basi71206ef2014-08-13 13:51:18 -070018from autotest_lib.client.common_lib import global_config
Alex Miller7d658cf2013-09-04 16:00:35 -070019from autotest_lib.client.common_lib import priorities
Dan Shidfea3682014-08-10 23:38:40 -070020from autotest_lib.client.common_lib import time_utils
Chris Masone859fdec2012-01-30 08:38:09 -080021from autotest_lib.client.common_lib.cros import dev_server
Gabe Black1e1c41b2015-02-04 23:55:15 -080022from autotest_lib.client.common_lib.cros.graphite import autotest_stats
Jakob Juelich9fffe4f2014-08-14 18:07:05 -070023from autotest_lib.frontend.afe import rpc_utils
Simran Basib6ec8ae2014-04-23 12:05:08 -070024from autotest_lib.server import utils
Chris Masone44e4d6c2012-08-15 14:25:53 -070025from autotest_lib.server.cros.dynamic_suite import constants
Chris Masoneb4935552012-08-14 12:05:54 -070026from autotest_lib.server.cros.dynamic_suite import control_file_getter
Chris Masone44e4d6c2012-08-15 14:25:53 -070027from autotest_lib.server.cros.dynamic_suite import tools
Simran Basi71206ef2014-08-13 13:51:18 -070028from autotest_lib.server.hosts import moblab_host
Dan Shidfea3682014-08-10 23:38:40 -070029from autotest_lib.site_utils import host_history
Dan Shi193905e2014-07-25 23:33:09 -070030from autotest_lib.site_utils import job_history
Dan Shid7bb4f12015-01-06 10:53:50 -080031from autotest_lib.site_utils import server_manager_utils
Dan Shi6964fa52014-12-18 11:04:27 -080032from autotest_lib.site_utils import stable_version_utils
Simran Basi71206ef2014-08-13 13:51:18 -070033
34
35_CONFIG = global_config.global_config
36MOBLAB_BOTO_LOCATION = '/home/moblab/.boto'
Chris Masone859fdec2012-01-30 08:38:09 -080037
Chris Masonef8b53062012-05-08 22:14:18 -070038# Relevant CrosDynamicSuiteExceptions are defined in client/common_lib/error.py.
Chris Masone859fdec2012-01-30 08:38:09 -080039
40
Chris Masone62579122012-03-08 15:18:43 -080041def canonicalize_suite_name(suite_name):
42 return 'test_suites/control.%s' % suite_name
43
44
Chris Masoneaa10f8e2012-05-15 13:34:21 -070045def formatted_now():
Dan Shidfea3682014-08-10 23:38:40 -070046 return datetime.datetime.now().strftime(time_utils.TIME_FMT)
Chris Masoneaa10f8e2012-05-15 13:34:21 -070047
48
Simran Basib6ec8ae2014-04-23 12:05:08 -070049def _get_control_file_contents_by_name(build, ds, suite_name):
Chris Masone8dd27e02012-06-25 15:59:43 -070050 """Return control file contents for |suite_name|.
51
52 Query the dev server at |ds| for the control file |suite_name|, included
53 in |build| for |board|.
54
55 @param build: unique name by which to refer to the image from now on.
Chris Masone8dd27e02012-06-25 15:59:43 -070056 @param ds: a dev_server.DevServer instance to fetch control file with.
57 @param suite_name: canonicalized suite name, e.g. test_suites/control.bvt.
58 @raises ControlFileNotFound if a unique suite control file doesn't exist.
59 @raises NoControlFileList if we can't list the control files at all.
60 @raises ControlFileEmpty if the control file exists on the server, but
61 can't be read.
62
63 @return the contents of the desired control file.
64 """
65 getter = control_file_getter.DevServerGetter.create(build, ds)
Gabe Black1e1c41b2015-02-04 23:55:15 -080066 timer = autotest_stats.Timer('control_files.parse.%s.%s' %
67 (ds.get_server_name(ds.url()
68 ).replace('.', '_'),
69 suite_name.rsplit('.')[-1]))
Chris Masone8dd27e02012-06-25 15:59:43 -070070 # Get the control file for the suite.
71 try:
Prashanth Balasubramanianabe3bb72014-11-20 12:00:37 -080072 with timer:
73 control_file_in = getter.get_control_file_contents_by_name(
74 suite_name)
Chris Masone8dd27e02012-06-25 15:59:43 -070075 except error.CrosDynamicSuiteException as e:
Simran Basib6ec8ae2014-04-23 12:05:08 -070076 raise type(e)("%s while testing %s." % (e, build))
Chris Masone8dd27e02012-06-25 15:59:43 -070077 if not control_file_in:
78 raise error.ControlFileEmpty(
79 "Fetching %s returned no data." % suite_name)
Alex Millera713e252013-03-01 10:45:44 -080080 # Force control files to only contain ascii characters.
81 try:
82 control_file_in.encode('ascii')
83 except UnicodeDecodeError as e:
84 raise error.ControlFileMalformed(str(e))
85
Chris Masone8dd27e02012-06-25 15:59:43 -070086 return control_file_in
87
88
Simran Basib6ec8ae2014-04-23 12:05:08 -070089def _stage_build_artifacts(build):
90 """
91 Ensure components of |build| necessary for installing images are staged.
92
93 @param build image we want to stage.
94
Prashanth B6285f6a2014-05-08 18:01:27 -070095 @raises StageControlFileFailure: if the dev server throws 500 while staging
96 suite control files.
Simran Basib6ec8ae2014-04-23 12:05:08 -070097
98 @return: dev_server.ImageServer instance to use with this build.
99 @return: timings dictionary containing staging start/end times.
100 """
101 timings = {}
Prashanth B6285f6a2014-05-08 18:01:27 -0700102 # Ensure components of |build| necessary for installing images are staged
103 # on the dev server. However set synchronous to False to allow other
104 # components to be downloaded in the background.
Simran Basib6ec8ae2014-04-23 12:05:08 -0700105 ds = dev_server.ImageServer.resolve(build)
106 timings[constants.DOWNLOAD_STARTED_TIME] = formatted_now()
Gabe Black1e1c41b2015-02-04 23:55:15 -0800107 timer = autotest_stats.Timer('control_files.stage.%s' % (
108 ds.get_server_name(ds.url()).replace('.', '_')))
Simran Basib6ec8ae2014-04-23 12:05:08 -0700109 try:
Prashanth Balasubramanianabe3bb72014-11-20 12:00:37 -0800110 with timer:
111 ds.stage_artifacts(build, ['test_suites'])
Simran Basib6ec8ae2014-04-23 12:05:08 -0700112 except dev_server.DevServerException as e:
Prashanth B6285f6a2014-05-08 18:01:27 -0700113 raise error.StageControlFileFailure(
Simran Basib6ec8ae2014-04-23 12:05:08 -0700114 "Failed to stage %s: %s" % (build, e))
115 timings[constants.PAYLOAD_FINISHED_TIME] = formatted_now()
116 return (ds, timings)
117
118
119def create_suite_job(name='', board='', build='', pool='', control_file='',
120 check_hosts=True, num=None, file_bugs=False, timeout=24,
121 timeout_mins=None, priority=priorities.Priority.DEFAULT,
Fang Deng058860c2014-05-15 15:41:50 -0700122 suite_args=None, wait_for_results=True, job_retry=False,
Fang Deng443f1952015-01-02 14:51:49 -0800123 max_retries=None, max_runtime_mins=None, suite_min_duts=0,
Simran Basi1e10e922015-04-16 15:09:56 -0700124 offload_failures_only=False, **kwargs):
Chris Masone859fdec2012-01-30 08:38:09 -0800125 """
126 Create a job to run a test suite on the given device with the given image.
127
128 When the timeout specified in the control file is reached, the
129 job is guaranteed to have completed and results will be available.
130
Simran Basib6ec8ae2014-04-23 12:05:08 -0700131 @param name: The test name if control_file is supplied, otherwise the name
132 of the test suite to run, e.g. 'bvt'.
Chris Masone859fdec2012-01-30 08:38:09 -0800133 @param board: the kind of device to run the tests on.
134 @param build: unique name by which to refer to the image from now on.
Scott Zawalski65650172012-02-16 11:48:26 -0500135 @param pool: Specify the pool of machines to use for scheduling
136 purposes.
Chris Masone62579122012-03-08 15:18:43 -0800137 @param check_hosts: require appropriate live hosts to exist in the lab.
Aviv Keshetd83ef442013-01-16 16:19:35 -0800138 @param num: Specify the number of machines to schedule across (integer).
139 Leave unspecified or use None to use default sharding factor.
Alex Millerc577f3e2012-09-27 14:06:07 -0700140 @param file_bugs: File a bug on each test failure in this suite.
Alex Miller139690b2013-09-07 15:35:49 -0700141 @param timeout: The max lifetime of this suite, in hours.
Simran Basi7e605742013-11-12 13:43:36 -0800142 @param timeout_mins: The max lifetime of this suite, in minutes. Takes
143 priority over timeout.
Alex Miller139690b2013-09-07 15:35:49 -0700144 @param priority: Integer denoting priority. Higher is more important.
Aviv Keshet7cd12312013-07-25 10:25:55 -0700145 @param suite_args: Optional arguments which will be parsed by the suite
146 control file. Used by control.test_that_wrapper to
147 determine which tests to run.
Dan Shi95122412013-11-12 16:20:33 -0800148 @param wait_for_results: Set to False to run the suite job without waiting
149 for test jobs to finish. Default is True.
Fang Deng058860c2014-05-15 15:41:50 -0700150 @param job_retry: Set to True to enable job-level retry. Default is False.
Fang Deng443f1952015-01-02 14:51:49 -0800151 @param max_retries: Integer, maximum job retries allowed at suite level.
152 None for no max.
Simran Basi102e3522014-09-11 11:46:10 -0700153 @param max_runtime_mins: Maximum amount of time a job can be running in
154 minutes.
Fang Dengcbc01212014-11-25 16:09:46 -0800155 @param suite_min_duts: Integer. Scheduler will prioritize getting the
156 minimum number of machines for the suite when it is
157 competing with another suite that has a higher
158 priority but already got minimum machines it needs.
Simran Basi1e10e922015-04-16 15:09:56 -0700159 @param offload_failures_only: Only enable gs_offloading for failed jobs.
Simran Basib6ec8ae2014-04-23 12:05:08 -0700160 @param kwargs: extra keyword args. NOT USED.
Chris Masone859fdec2012-01-30 08:38:09 -0800161
Chris Masone8dd27e02012-06-25 15:59:43 -0700162 @raises ControlFileNotFound: if a unique suite control file doesn't exist.
163 @raises NoControlFileList: if we can't list the control files at all.
Prashanth B6285f6a2014-05-08 18:01:27 -0700164 @raises StageControlFileFailure: If the dev server throws 500 while
165 staging test_suites.
Chris Masone8dd27e02012-06-25 15:59:43 -0700166 @raises ControlFileEmpty: if the control file exists on the server, but
167 can't be read.
Chris Masone859fdec2012-01-30 08:38:09 -0800168
169 @return: the job ID of the suite; -1 on error.
170 """
Aviv Keshetd83ef442013-01-16 16:19:35 -0800171 if type(num) is not int and num is not None:
Chris Sosa18c70b32013-02-15 14:12:43 -0800172 raise error.SuiteArgumentException('Ill specified num argument %r. '
173 'Must be an integer or None.' % num)
Aviv Keshetd83ef442013-01-16 16:19:35 -0800174 if num == 0:
175 logging.warning("Can't run on 0 hosts; using default.")
176 num = None
Fang Dengcbc01212014-11-25 16:09:46 -0800177 (ds, keyvals) = _stage_build_artifacts(build)
178 keyvals[constants.SUITE_MIN_DUTS_KEY] = suite_min_duts
Chris Masone859fdec2012-01-30 08:38:09 -0800179
Simran Basib6ec8ae2014-04-23 12:05:08 -0700180 if not control_file:
181 # No control file was supplied so look it up from the build artifacts.
182 suite_name = canonicalize_suite_name(name)
183 control_file = _get_control_file_contents_by_name(build, ds, suite_name)
184 name = '%s-%s' % (build, suite_name)
Chris Masone46d0eb12012-07-27 18:56:39 -0700185
Simran Basi7e605742013-11-12 13:43:36 -0800186 timeout_mins = timeout_mins or timeout * 60
Simran Basi102e3522014-09-11 11:46:10 -0700187 max_runtime_mins = max_runtime_mins or timeout * 60
Simran Basi7e605742013-11-12 13:43:36 -0800188
Simran Basib6ec8ae2014-04-23 12:05:08 -0700189 if not board:
190 board = utils.ParseBuildName(build)[0]
Chris Masone46d0eb12012-07-27 18:56:39 -0700191
Simran Basib6ec8ae2014-04-23 12:05:08 -0700192 # Prepend build and board to the control file.
Scott Zawalski65650172012-02-16 11:48:26 -0500193 inject_dict = {'board': board,
194 'build': build,
Chris Masone62579122012-03-08 15:18:43 -0800195 'check_hosts': check_hosts,
Chris Masone46d0eb12012-07-27 18:56:39 -0700196 'pool': pool,
Aviv Keshetd83ef442013-01-16 16:19:35 -0800197 'num': num,
Dan Shib8a99112013-06-18 13:46:10 -0700198 'file_bugs': file_bugs,
Alex Miller139690b2013-09-07 15:35:49 -0700199 'timeout': timeout,
Simran Basi7e605742013-11-12 13:43:36 -0800200 'timeout_mins': timeout_mins,
Alex Miller7d658cf2013-09-04 16:00:35 -0700201 'devserver_url': ds.url(),
Aviv Keshet7cd12312013-07-25 10:25:55 -0700202 'priority': priority,
Dan Shi95122412013-11-12 16:20:33 -0800203 'suite_args' : suite_args,
Fang Deng058860c2014-05-15 15:41:50 -0700204 'wait_for_results': wait_for_results,
Simran Basi102e3522014-09-11 11:46:10 -0700205 'job_retry': job_retry,
Fang Deng443f1952015-01-02 14:51:49 -0800206 'max_retries': max_retries,
Fang Dengcbc01212014-11-25 16:09:46 -0800207 'max_runtime_mins': max_runtime_mins,
Simran Basi1e10e922015-04-16 15:09:56 -0700208 'offload_failures_only': offload_failures_only
Aviv Keshet7cd12312013-07-25 10:25:55 -0700209 }
210
Simran Basib6ec8ae2014-04-23 12:05:08 -0700211 control_file = tools.inject_vars(inject_dict, control_file)
Chris Masone859fdec2012-01-30 08:38:09 -0800212
Jakob Juelich9fffe4f2014-08-14 18:07:05 -0700213 return rpc_utils.create_job_common(name,
Jakob Juelich59cfe542014-09-02 16:37:46 -0700214 priority=priority,
215 timeout_mins=timeout_mins,
216 max_runtime_mins=max_runtime_mins,
217 control_type='Server',
218 control_file=control_file,
219 hostless=True,
Fang Dengcbc01212014-11-25 16:09:46 -0800220 keyvals=keyvals)
Simran Basi71206ef2014-08-13 13:51:18 -0700221
222
223# TODO: hide the following rpcs under is_moblab
224def moblab_only(func):
225 """Ensure moblab specific functions only run on Moblab devices."""
226 def verify(*args, **kwargs):
227 if not utils.is_moblab():
228 raise error.RPCException('RPC: %s can only run on Moblab Systems!',
229 func.__name__)
230 return func(*args, **kwargs)
231 return verify
232
233
234@moblab_only
235def get_config_values():
236 """Returns all config values parsed from global and shadow configs.
237
238 Config values are grouped by sections, and each section is composed of
239 a list of name value pairs.
240 """
241 sections =_CONFIG.get_sections()
242 config_values = {}
243 for section in sections:
244 config_values[section] = _CONFIG.config.items(section)
Jakob Juelich9fffe4f2014-08-14 18:07:05 -0700245 return rpc_utils.prepare_for_serialization(config_values)
Simran Basi71206ef2014-08-13 13:51:18 -0700246
247
248@moblab_only
249def update_config_handler(config_values):
250 """
251 Update config values and override shadow config.
252
253 @param config_values: See get_moblab_settings().
254 """
Simran Basi773a86e2015-05-13 19:15:42 -0700255 original_config = global_config.global_config_class()
256 original_config.set_config_files(shadow_file='')
257 new_shadow = ConfigParser.RawConfigParser()
Simran Basi71206ef2014-08-13 13:51:18 -0700258 for section, config_value_list in config_values.iteritems():
259 for key, value in config_value_list:
Simran Basi773a86e2015-05-13 19:15:42 -0700260 if original_config.get_config_value(section, key,
261 default='',
262 allow_blank=True) != value:
263 if not new_shadow.has_section(section):
264 new_shadow.add_section(section)
265 new_shadow.set(section, key, value)
Simran Basi71206ef2014-08-13 13:51:18 -0700266 if not _CONFIG.shadow_file or not os.path.exists(_CONFIG.shadow_file):
267 raise error.RPCException('Shadow config file does not exist.')
268
269 with open(_CONFIG.shadow_file, 'w') as config_file:
Simran Basi773a86e2015-05-13 19:15:42 -0700270 new_shadow.write(config_file)
Simran Basi71206ef2014-08-13 13:51:18 -0700271 # TODO (sbasi) crbug.com/403916 - Remove the reboot command and
272 # instead restart the services that rely on the config values.
273 os.system('sudo reboot')
274
275
276@moblab_only
277def reset_config_settings():
278 with open(_CONFIG.shadow_file, 'w') as config_file:
279 pass
280 os.system('sudo reboot')
281
282
283@moblab_only
284def set_boto_key(boto_key):
285 """Update the boto_key file.
286
287 @param boto_key: File name of boto_key uploaded through handle_file_upload.
288 """
289 if not os.path.exists(boto_key):
290 raise error.RPCException('Boto key: %s does not exist!' % boto_key)
291 shutil.copyfile(boto_key, moblab_host.MOBLAB_BOTO_LOCATION)
Dan Shi193905e2014-07-25 23:33:09 -0700292
293
294def get_job_history(**filter_data):
295 """Get history of the job, including the special tasks executed for the job
296
297 @param filter_data: filter for the call, should at least include
298 {'job_id': [job id]}
299 @returns: JSON string of the job's history, including the information such
300 as the hosts run the job and the special tasks executed before
301 and after the job.
302 """
303 job_id = filter_data['job_id']
304 job_info = job_history.get_job_info(job_id)
Dan Shidfea3682014-08-10 23:38:40 -0700305 return rpc_utils.prepare_for_serialization(job_info.get_history())
306
307
308def get_host_history(start_time, end_time, hosts=None, board=None, pool=None):
309 """Get history of a list of host.
310
311 The return is a JSON string of host history for each host, for example,
312 {'172.22.33.51': [{'status': 'Resetting'
313 'start_time': '2014-08-07 10:02:16',
314 'end_time': '2014-08-07 10:03:16',
315 'log_url': 'http://autotest/reset-546546/debug',
316 'dbg_str': 'Task: Special Task 19441991 (host ...)'},
317 {'status': 'Running'
318 'start_time': '2014-08-07 10:03:18',
319 'end_time': '2014-08-07 10:13:00',
320 'log_url': 'http://autotest/reset-546546/debug',
321 'dbg_str': 'HQE: 15305005, for job: 14995562'}
322 ]
323 }
324 @param start_time: start time to search for history, can be string value or
325 epoch time.
326 @param end_time: end time to search for history, can be string value or
327 epoch time.
328 @param hosts: A list of hosts to search for history. Default is None.
329 @param board: board type of hosts. Default is None.
330 @param pool: pool type of hosts. Default is None.
331 @returns: JSON string of the host history.
332 """
333 return rpc_utils.prepare_for_serialization(
334 host_history.get_history_details(
335 start_time=start_time, end_time=end_time,
336 hosts=hosts, board=board, pool=pool,
337 process_pool_size=4))
Jakob Juelich59cfe542014-09-02 16:37:46 -0700338
339
Jakob Juelich1b525742014-09-30 13:08:07 -0700340def shard_heartbeat(shard_hostname, jobs=(), hqes=(),
341 known_job_ids=(), known_host_ids=()):
342 """Receive updates for job statuses from shards and assign hosts and jobs.
Jakob Juelich59cfe542014-09-02 16:37:46 -0700343
344 @param shard_hostname: Hostname of the calling shard
Jakob Juelicha94efe62014-09-18 16:02:49 -0700345 @param jobs: Jobs in serialized form that should be updated with newer
346 status from a shard.
347 @param hqes: Hostqueueentries in serialized form that should be updated with
348 newer status from a shard. Note that for every hostqueueentry
349 the corresponding job must be in jobs.
Jakob Juelich1b525742014-09-30 13:08:07 -0700350 @param known_job_ids: List of ids of jobs the shard already has.
351 @param known_host_ids: List of ids of hosts the shard already has.
Jakob Juelicha94efe62014-09-18 16:02:49 -0700352
Fang Dengf3705992014-12-16 17:32:18 -0800353 @returns: Serialized representations of hosts, jobs, suite job keyvals
354 and their dependencies to be inserted into a shard's database.
Jakob Juelich59cfe542014-09-02 16:37:46 -0700355 """
Jakob Juelich1b525742014-09-30 13:08:07 -0700356 # The following alternatives to sending host and job ids in every heartbeat
357 # have been considered:
358 # 1. Sending the highest known job and host ids. This would work for jobs:
359 # Newer jobs always have larger ids. Also, if a job is not assigned to a
360 # particular shard during a heartbeat, it never will be assigned to this
361 # shard later.
362 # This is not true for hosts though: A host that is leased won't be sent
363 # to the shard now, but might be sent in a future heartbeat. This means
364 # sometimes hosts should be transfered that have a lower id than the
365 # maximum host id the shard knows.
366 # 2. Send the number of jobs/hosts the shard knows to the master in each
367 # heartbeat. Compare these to the number of records that already have
368 # the shard_id set to this shard. In the normal case, they should match.
369 # In case they don't, resend all entities of that type.
370 # This would work well for hosts, because there aren't that many.
371 # Resending all jobs is quite a big overhead though.
372 # Also, this approach might run into edge cases when entities are
373 # ever deleted.
374 # 3. Mixtures of the above: Use 1 for jobs and 2 for hosts.
375 # Using two different approaches isn't consistent and might cause
376 # confusion. Also the issues with the case of deletions might still
377 # occur.
378 #
379 # The overhead of sending all job and host ids in every heartbeat is low:
380 # At peaks one board has about 1200 created but unfinished jobs.
381 # See the numbers here: http://goo.gl/gQCGWH
382 # Assuming that job id's have 6 digits and that json serialization takes a
383 # comma and a space as overhead, the traffic per id sent is about 8 bytes.
384 # If 5000 ids need to be sent, this means 40 kilobytes of traffic.
385 # A NOT IN query with 5000 ids took about 30ms in tests made.
386 # These numbers seem low enough to outweigh the disadvantages of the
387 # solutions described above.
Gabe Black1e1c41b2015-02-04 23:55:15 -0800388 timer = autotest_stats.Timer('shard_heartbeat')
Jakob Juelich59cfe542014-09-02 16:37:46 -0700389 with timer:
390 shard_obj = rpc_utils.retrieve_shard(shard_hostname=shard_hostname)
Jakob Juelicha94efe62014-09-18 16:02:49 -0700391 rpc_utils.persist_records_sent_from_shard(shard_obj, jobs, hqes)
Fang Dengf3705992014-12-16 17:32:18 -0800392 hosts, jobs, suite_keyvals = rpc_utils.find_records_for_shard(
Jakob Juelich1b525742014-09-30 13:08:07 -0700393 shard_obj,
394 known_job_ids=known_job_ids, known_host_ids=known_host_ids)
Jakob Juelich59cfe542014-09-02 16:37:46 -0700395 return {
396 'hosts': [host.serialize() for host in hosts],
397 'jobs': [job.serialize() for job in jobs],
Fang Dengf3705992014-12-16 17:32:18 -0800398 'suite_keyvals': [kv.serialize() for kv in suite_keyvals],
Jakob Juelich59cfe542014-09-02 16:37:46 -0700399 }
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700400
401
402def get_shards(**filter_data):
403 """Return a list of all shards.
404
405 @returns A sequence of nested dictionaries of shard information.
406 """
407 shards = models.Shard.query_objects(filter_data)
408 serialized_shards = rpc_utils.prepare_rows_as_nested_dicts(shards, ())
409 for serialized, shard in zip(serialized_shards, shards):
410 serialized['labels'] = [label.name for label in shard.labels.all()]
411
412 return serialized_shards
413
414
415def add_shard(hostname, label):
416 """Add a shard and start running jobs on it.
417
418 @param hostname: The hostname of the shard to be added; needs to be unique.
419 @param label: A platform label. Jobs of this label will be assigned to the
420 shard.
421
Jakob Juelich8b110ee2014-09-15 16:13:42 -0700422 @raises error.RPCException: If label provided doesn't start with `board:`
423 @raises model_logic.ValidationError: If a shard with the given hostname
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700424 already exists.
Jakob Juelich8b110ee2014-09-15 16:13:42 -0700425 @raises models.Label.DoesNotExist: If the label specified doesn't exist.
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700426 """
Jakob Juelich8b110ee2014-09-15 16:13:42 -0700427 if not label.startswith('board:'):
428 raise error.RPCException('Sharding only supported for `board:.*` '
429 'labels.')
430
431 # Fetch label first, so shard isn't created when label doesn't exist.
432 label = models.Label.smart_get(label)
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700433 shard = models.Shard.add_object(hostname=hostname)
Jakob Juelich8b110ee2014-09-15 16:13:42 -0700434 shard.labels.add(label)
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700435 return shard.id
436
437
438def delete_shard(hostname):
439 """Delete a shard and reclaim all resources from it.
440
441 This claims back all assigned hosts from the shard. To ensure all DUTs are
442 in a sane state, a Repair task is scheduled for them. This reboots the DUTs
443 and therefore clears all running processes that might be left.
444
445 The shard_id of jobs of that shard will be set to None.
446
447 The status of jobs that haven't been reported to be finished yet, will be
448 lost. The master scheduler will pick up the jobs and execute them.
449
450 @param hostname: Hostname of the shard to delete.
451 """
452 shard = rpc_utils.retrieve_shard(shard_hostname=hostname)
453
454 # TODO(beeps): Power off shard
455
456 # For ChromeOS hosts, repair reboots the DUT.
457 # Repair will excalate through multiple repair steps and will verify the
458 # success after each of them. Anyway, it will always run at least the first
459 # one, which includes a reboot.
460 # After a reboot we can be sure no processes from prior tests that were run
461 # by a shard are still running on the DUT.
462 # Important: Don't just set the status to Repair Failed, as that would run
463 # Verify first, before doing any repair measures. Verify would probably
464 # succeed, so this wouldn't change anything on the DUT.
465 for host in models.Host.objects.filter(shard=shard):
466 models.SpecialTask.objects.create(
467 task=models.SpecialTask.Task.REPAIR,
468 host=host,
469 requested_by=models.User.current_user())
470 models.Host.objects.filter(shard=shard).update(shard=None)
471
472 models.Job.objects.filter(shard=shard).update(shard=None)
473
474 shard.labels.clear()
475
476 shard.delete()
Dan Shi6964fa52014-12-18 11:04:27 -0800477
478
Dan Shid7bb4f12015-01-06 10:53:50 -0800479def get_servers(role=None, status=None):
480 """Get a list of servers with matching role and status.
481
482 @param role: Name of the server role, e.g., drone, scheduler. Default to
483 None to match any role.
484 @param status: Status of the server, e.g., primary, backup, repair_required.
485 Default to None to match any server status.
486
487 @raises error.RPCException: If server database is not used.
488 @return: A list of server names for servers with matching role and status.
489 """
490 if not server_manager_utils.use_server_db():
491 raise error.RPCException('Server database is not enabled. Please try '
492 'retrieve servers from global config.')
493 servers = server_manager_utils.get_servers(hostname=None, role=role,
494 status=status)
495 return [s.get_details() for s in servers]
496
497
Dan Shi6964fa52014-12-18 11:04:27 -0800498def get_stable_version(board=stable_version_utils.DEFAULT):
499 """Get stable version for the given board.
500
501 @param board: Name of the board.
502 @return: Stable version of the given board. Return global configure value
503 of CROS.stable_cros_version if stable_versinos table does not have
504 entry of board DEFAULT.
505 """
MK Ryu6766de72015-05-13 16:08:24 -0700506 # This RPC call should be accepted only by master.
507 if utils.is_shard():
508 return rpc_utils.route_rpc_to_master('get_stable_version', board=board)
Dan Shi25e1fd42014-12-19 14:36:42 -0800509 return stable_version_utils.get(board)
510
511
512def get_all_stable_versions():
513 """Get stable versions for all boards.
514
515 @return: A dictionary of board:version.
516 """
MK Ryu6766de72015-05-13 16:08:24 -0700517 # This RPC call should be accepted only by master.
518 if utils.is_shard():
519 return rpc_utils.route_rpc_to_master('get_all_stable_versions')
Dan Shi25e1fd42014-12-19 14:36:42 -0800520 return stable_version_utils.get_all()
521
522
523def set_stable_version(version, board=stable_version_utils.DEFAULT):
524 """Modify stable version for the given board.
525
526 @param version: The new value of stable version for given board.
527 @param board: Name of the board, default to value `DEFAULT`.
528 """
MK Ryu6766de72015-05-13 16:08:24 -0700529 # This RPC call should be accepted only by master.
530 if utils.is_shard():
531 return rpc_utils.route_rpc_to_master('set_stable_version',
532 version=version, board=board)
Dan Shi25e1fd42014-12-19 14:36:42 -0800533 stable_version_utils.set(version=version, board=board)
534
535
536def delete_stable_version(board):
537 """Modify stable version for the given board.
538
539 Delete a stable version entry in afe_stable_versions table for a given
540 board, so default stable version will be used.
541
542 @param board: Name of the board.
543 """
MK Ryu6766de72015-05-13 16:08:24 -0700544 # This RPC call should be accepted only by master.
545 if utils.is_shard():
546 return rpc_utils.route_rpc_to_master('delete_stable_version',
547 board=board)
Dan Shi25e1fd42014-12-19 14:36:42 -0800548 stable_version_utils.delete(board=board)