blob: 863ee558c5114749d4b8f3fded52a5e4b9d37af1 [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
Chris Masonea8066a92012-05-01 16:52:31 -070010import datetime
Chris Masone859fdec2012-01-30 08:38:09 -080011import logging
Simran Basi71206ef2014-08-13 13:51:18 -070012import os
13import shutil
Aviv Keshetd83ef442013-01-16 16:19:35 -080014
Jakob Juelich82b7d1c2014-09-15 16:10:57 -070015from autotest_lib.frontend.afe import models
Aviv Keshetd83ef442013-01-16 16:19:35 -080016from autotest_lib.client.common_lib import error
Simran Basi71206ef2014-08-13 13:51:18 -070017from autotest_lib.client.common_lib import global_config
Alex Miller7d658cf2013-09-04 16:00:35 -070018from autotest_lib.client.common_lib import priorities
Dan Shidfea3682014-08-10 23:38:40 -070019from autotest_lib.client.common_lib import time_utils
Chris Masone859fdec2012-01-30 08:38:09 -080020from autotest_lib.client.common_lib.cros import dev_server
Gabe Black1e1c41b2015-02-04 23:55:15 -080021from autotest_lib.client.common_lib.cros.graphite import autotest_stats
Jakob Juelich9fffe4f2014-08-14 18:07:05 -070022from autotest_lib.frontend.afe import rpc_utils
Simran Basib6ec8ae2014-04-23 12:05:08 -070023from autotest_lib.server import utils
Chris Masone44e4d6c2012-08-15 14:25:53 -070024from autotest_lib.server.cros.dynamic_suite import constants
Chris Masoneb4935552012-08-14 12:05:54 -070025from autotest_lib.server.cros.dynamic_suite import control_file_getter
Chris Masone44e4d6c2012-08-15 14:25:53 -070026from autotest_lib.server.cros.dynamic_suite import tools
Simran Basi71206ef2014-08-13 13:51:18 -070027from autotest_lib.server.hosts import moblab_host
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
35MOBLAB_BOTO_LOCATION = '/home/moblab/.boto'
Chris Masone859fdec2012-01-30 08:38:09 -080036
Chris Masonef8b53062012-05-08 22:14:18 -070037# Relevant CrosDynamicSuiteExceptions are defined in client/common_lib/error.py.
Chris Masone859fdec2012-01-30 08:38:09 -080038
39
Chris Masone62579122012-03-08 15:18:43 -080040def canonicalize_suite_name(suite_name):
41 return 'test_suites/control.%s' % suite_name
42
43
Chris Masoneaa10f8e2012-05-15 13:34:21 -070044def formatted_now():
Dan Shidfea3682014-08-10 23:38:40 -070045 return datetime.datetime.now().strftime(time_utils.TIME_FMT)
Chris Masoneaa10f8e2012-05-15 13:34:21 -070046
47
Simran Basib6ec8ae2014-04-23 12:05:08 -070048def _get_control_file_contents_by_name(build, ds, suite_name):
Chris Masone8dd27e02012-06-25 15:59:43 -070049 """Return control file contents for |suite_name|.
50
51 Query the dev server at |ds| for the control file |suite_name|, included
52 in |build| for |board|.
53
54 @param build: unique name by which to refer to the image from now on.
Chris Masone8dd27e02012-06-25 15:59:43 -070055 @param ds: a dev_server.DevServer instance to fetch control file with.
56 @param suite_name: canonicalized suite name, e.g. test_suites/control.bvt.
57 @raises ControlFileNotFound if a unique suite control file doesn't exist.
58 @raises NoControlFileList if we can't list the control files at all.
59 @raises ControlFileEmpty if the control file exists on the server, but
60 can't be read.
61
62 @return the contents of the desired control file.
63 """
64 getter = control_file_getter.DevServerGetter.create(build, ds)
Gabe Black1e1c41b2015-02-04 23:55:15 -080065 timer = autotest_stats.Timer('control_files.parse.%s.%s' %
66 (ds.get_server_name(ds.url()
67 ).replace('.', '_'),
68 suite_name.rsplit('.')[-1]))
Chris Masone8dd27e02012-06-25 15:59:43 -070069 # Get the control file for the suite.
70 try:
Prashanth Balasubramanianabe3bb72014-11-20 12:00:37 -080071 with timer:
72 control_file_in = getter.get_control_file_contents_by_name(
73 suite_name)
Chris Masone8dd27e02012-06-25 15:59:43 -070074 except error.CrosDynamicSuiteException as e:
Simran Basib6ec8ae2014-04-23 12:05:08 -070075 raise type(e)("%s while testing %s." % (e, build))
Chris Masone8dd27e02012-06-25 15:59:43 -070076 if not control_file_in:
77 raise error.ControlFileEmpty(
78 "Fetching %s returned no data." % suite_name)
Alex Millera713e252013-03-01 10:45:44 -080079 # Force control files to only contain ascii characters.
80 try:
81 control_file_in.encode('ascii')
82 except UnicodeDecodeError as e:
83 raise error.ControlFileMalformed(str(e))
84
Chris Masone8dd27e02012-06-25 15:59:43 -070085 return control_file_in
86
87
Simran Basib6ec8ae2014-04-23 12:05:08 -070088def _stage_build_artifacts(build):
89 """
90 Ensure components of |build| necessary for installing images are staged.
91
92 @param build image we want to stage.
93
Prashanth B6285f6a2014-05-08 18:01:27 -070094 @raises StageControlFileFailure: if the dev server throws 500 while staging
95 suite control files.
Simran Basib6ec8ae2014-04-23 12:05:08 -070096
97 @return: dev_server.ImageServer instance to use with this build.
98 @return: timings dictionary containing staging start/end times.
99 """
100 timings = {}
Prashanth B6285f6a2014-05-08 18:01:27 -0700101 # Ensure components of |build| necessary for installing images are staged
102 # on the dev server. However set synchronous to False to allow other
103 # components to be downloaded in the background.
Simran Basib6ec8ae2014-04-23 12:05:08 -0700104 ds = dev_server.ImageServer.resolve(build)
105 timings[constants.DOWNLOAD_STARTED_TIME] = formatted_now()
Gabe Black1e1c41b2015-02-04 23:55:15 -0800106 timer = autotest_stats.Timer('control_files.stage.%s' % (
107 ds.get_server_name(ds.url()).replace('.', '_')))
Simran Basib6ec8ae2014-04-23 12:05:08 -0700108 try:
Prashanth Balasubramanianabe3bb72014-11-20 12:00:37 -0800109 with timer:
110 ds.stage_artifacts(build, ['test_suites'])
Simran Basib6ec8ae2014-04-23 12:05:08 -0700111 except dev_server.DevServerException as e:
Prashanth B6285f6a2014-05-08 18:01:27 -0700112 raise error.StageControlFileFailure(
Simran Basib6ec8ae2014-04-23 12:05:08 -0700113 "Failed to stage %s: %s" % (build, e))
114 timings[constants.PAYLOAD_FINISHED_TIME] = formatted_now()
115 return (ds, timings)
116
117
118def create_suite_job(name='', board='', build='', pool='', control_file='',
119 check_hosts=True, num=None, file_bugs=False, timeout=24,
120 timeout_mins=None, priority=priorities.Priority.DEFAULT,
Fang Deng058860c2014-05-15 15:41:50 -0700121 suite_args=None, wait_for_results=True, job_retry=False,
Fang Deng443f1952015-01-02 14:51:49 -0800122 max_retries=None, max_runtime_mins=None, suite_min_duts=0,
Simran Basi1e10e922015-04-16 15:09:56 -0700123 offload_failures_only=False, **kwargs):
Chris Masone859fdec2012-01-30 08:38:09 -0800124 """
125 Create a job to run a test suite on the given device with the given image.
126
127 When the timeout specified in the control file is reached, the
128 job is guaranteed to have completed and results will be available.
129
Simran Basib6ec8ae2014-04-23 12:05:08 -0700130 @param name: The test name if control_file is supplied, otherwise the name
131 of the test suite to run, e.g. 'bvt'.
Chris Masone859fdec2012-01-30 08:38:09 -0800132 @param board: the kind of device to run the tests on.
133 @param build: unique name by which to refer to the image from now on.
Scott Zawalski65650172012-02-16 11:48:26 -0500134 @param pool: Specify the pool of machines to use for scheduling
135 purposes.
Chris Masone62579122012-03-08 15:18:43 -0800136 @param check_hosts: require appropriate live hosts to exist in the lab.
Aviv Keshetd83ef442013-01-16 16:19:35 -0800137 @param num: Specify the number of machines to schedule across (integer).
138 Leave unspecified or use None to use default sharding factor.
Alex Millerc577f3e2012-09-27 14:06:07 -0700139 @param file_bugs: File a bug on each test failure in this suite.
Alex Miller139690b2013-09-07 15:35:49 -0700140 @param timeout: The max lifetime of this suite, in hours.
Simran Basi7e605742013-11-12 13:43:36 -0800141 @param timeout_mins: The max lifetime of this suite, in minutes. Takes
142 priority over timeout.
Alex Miller139690b2013-09-07 15:35:49 -0700143 @param priority: Integer denoting priority. Higher is more important.
Aviv Keshet7cd12312013-07-25 10:25:55 -0700144 @param suite_args: Optional arguments which will be parsed by the suite
145 control file. Used by control.test_that_wrapper to
146 determine which tests to run.
Dan Shi95122412013-11-12 16:20:33 -0800147 @param wait_for_results: Set to False to run the suite job without waiting
148 for test jobs to finish. Default is True.
Fang Deng058860c2014-05-15 15:41:50 -0700149 @param job_retry: Set to True to enable job-level retry. Default is False.
Fang Deng443f1952015-01-02 14:51:49 -0800150 @param max_retries: Integer, maximum job retries allowed at suite level.
151 None for no max.
Simran Basi102e3522014-09-11 11:46:10 -0700152 @param max_runtime_mins: Maximum amount of time a job can be running in
153 minutes.
Fang Dengcbc01212014-11-25 16:09:46 -0800154 @param suite_min_duts: Integer. Scheduler will prioritize getting the
155 minimum number of machines for the suite when it is
156 competing with another suite that has a higher
157 priority but already got minimum machines it needs.
Simran Basi1e10e922015-04-16 15:09:56 -0700158 @param offload_failures_only: Only enable gs_offloading for failed jobs.
Simran Basib6ec8ae2014-04-23 12:05:08 -0700159 @param kwargs: extra keyword args. NOT USED.
Chris Masone859fdec2012-01-30 08:38:09 -0800160
Chris Masone8dd27e02012-06-25 15:59:43 -0700161 @raises ControlFileNotFound: if a unique suite control file doesn't exist.
162 @raises NoControlFileList: if we can't list the control files at all.
Prashanth B6285f6a2014-05-08 18:01:27 -0700163 @raises StageControlFileFailure: If the dev server throws 500 while
164 staging test_suites.
Chris Masone8dd27e02012-06-25 15:59:43 -0700165 @raises ControlFileEmpty: if the control file exists on the server, but
166 can't be read.
Chris Masone859fdec2012-01-30 08:38:09 -0800167
168 @return: the job ID of the suite; -1 on error.
169 """
Aviv Keshetd83ef442013-01-16 16:19:35 -0800170 if type(num) is not int and num is not None:
Chris Sosa18c70b32013-02-15 14:12:43 -0800171 raise error.SuiteArgumentException('Ill specified num argument %r. '
172 'Must be an integer or None.' % num)
Aviv Keshetd83ef442013-01-16 16:19:35 -0800173 if num == 0:
174 logging.warning("Can't run on 0 hosts; using default.")
175 num = None
Fang Dengcbc01212014-11-25 16:09:46 -0800176 (ds, keyvals) = _stage_build_artifacts(build)
177 keyvals[constants.SUITE_MIN_DUTS_KEY] = suite_min_duts
Chris Masone859fdec2012-01-30 08:38:09 -0800178
Simran Basib6ec8ae2014-04-23 12:05:08 -0700179 if not control_file:
180 # No control file was supplied so look it up from the build artifacts.
181 suite_name = canonicalize_suite_name(name)
182 control_file = _get_control_file_contents_by_name(build, ds, suite_name)
183 name = '%s-%s' % (build, suite_name)
Chris Masone46d0eb12012-07-27 18:56:39 -0700184
Simran Basi7e605742013-11-12 13:43:36 -0800185 timeout_mins = timeout_mins or timeout * 60
Simran Basi102e3522014-09-11 11:46:10 -0700186 max_runtime_mins = max_runtime_mins or timeout * 60
Simran Basi7e605742013-11-12 13:43:36 -0800187
Simran Basib6ec8ae2014-04-23 12:05:08 -0700188 if not board:
189 board = utils.ParseBuildName(build)[0]
Chris Masone46d0eb12012-07-27 18:56:39 -0700190
Simran Basib6ec8ae2014-04-23 12:05:08 -0700191 # Prepend build and board to the control file.
Scott Zawalski65650172012-02-16 11:48:26 -0500192 inject_dict = {'board': board,
193 'build': build,
Chris Masone62579122012-03-08 15:18:43 -0800194 'check_hosts': check_hosts,
Chris Masone46d0eb12012-07-27 18:56:39 -0700195 'pool': pool,
Aviv Keshetd83ef442013-01-16 16:19:35 -0800196 'num': num,
Dan Shib8a99112013-06-18 13:46:10 -0700197 'file_bugs': file_bugs,
Alex Miller139690b2013-09-07 15:35:49 -0700198 'timeout': timeout,
Simran Basi7e605742013-11-12 13:43:36 -0800199 'timeout_mins': timeout_mins,
Alex Miller7d658cf2013-09-04 16:00:35 -0700200 'devserver_url': ds.url(),
Aviv Keshet7cd12312013-07-25 10:25:55 -0700201 'priority': priority,
Dan Shi95122412013-11-12 16:20:33 -0800202 'suite_args' : suite_args,
Fang Deng058860c2014-05-15 15:41:50 -0700203 'wait_for_results': wait_for_results,
Simran Basi102e3522014-09-11 11:46:10 -0700204 'job_retry': job_retry,
Fang Deng443f1952015-01-02 14:51:49 -0800205 'max_retries': max_retries,
Fang Dengcbc01212014-11-25 16:09:46 -0800206 'max_runtime_mins': max_runtime_mins,
Simran Basi1e10e922015-04-16 15:09:56 -0700207 'offload_failures_only': offload_failures_only
Aviv Keshet7cd12312013-07-25 10:25:55 -0700208 }
209
Simran Basib6ec8ae2014-04-23 12:05:08 -0700210 control_file = tools.inject_vars(inject_dict, control_file)
Chris Masone859fdec2012-01-30 08:38:09 -0800211
Jakob Juelich9fffe4f2014-08-14 18:07:05 -0700212 return rpc_utils.create_job_common(name,
Jakob Juelich59cfe542014-09-02 16:37:46 -0700213 priority=priority,
214 timeout_mins=timeout_mins,
215 max_runtime_mins=max_runtime_mins,
216 control_type='Server',
217 control_file=control_file,
218 hostless=True,
Fang Dengcbc01212014-11-25 16:09:46 -0800219 keyvals=keyvals)
Simran Basi71206ef2014-08-13 13:51:18 -0700220
221
222# TODO: hide the following rpcs under is_moblab
223def moblab_only(func):
224 """Ensure moblab specific functions only run on Moblab devices."""
225 def verify(*args, **kwargs):
226 if not utils.is_moblab():
227 raise error.RPCException('RPC: %s can only run on Moblab Systems!',
228 func.__name__)
229 return func(*args, **kwargs)
230 return verify
231
232
233@moblab_only
234def get_config_values():
235 """Returns all config values parsed from global and shadow configs.
236
237 Config values are grouped by sections, and each section is composed of
238 a list of name value pairs.
239 """
240 sections =_CONFIG.get_sections()
241 config_values = {}
242 for section in sections:
243 config_values[section] = _CONFIG.config.items(section)
Jakob Juelich9fffe4f2014-08-14 18:07:05 -0700244 return rpc_utils.prepare_for_serialization(config_values)
Simran Basi71206ef2014-08-13 13:51:18 -0700245
246
247@moblab_only
248def update_config_handler(config_values):
249 """
250 Update config values and override shadow config.
251
252 @param config_values: See get_moblab_settings().
253 """
254 for section, config_value_list in config_values.iteritems():
255 for key, value in config_value_list:
256 _CONFIG.override_config_value(section, key, value)
257 if not _CONFIG.shadow_file or not os.path.exists(_CONFIG.shadow_file):
258 raise error.RPCException('Shadow config file does not exist.')
259
260 with open(_CONFIG.shadow_file, 'w') as config_file:
261 _CONFIG.config.write(config_file)
262 # TODO (sbasi) crbug.com/403916 - Remove the reboot command and
263 # instead restart the services that rely on the config values.
264 os.system('sudo reboot')
265
266
267@moblab_only
268def reset_config_settings():
269 with open(_CONFIG.shadow_file, 'w') as config_file:
270 pass
271 os.system('sudo reboot')
272
273
274@moblab_only
275def set_boto_key(boto_key):
276 """Update the boto_key file.
277
278 @param boto_key: File name of boto_key uploaded through handle_file_upload.
279 """
280 if not os.path.exists(boto_key):
281 raise error.RPCException('Boto key: %s does not exist!' % boto_key)
282 shutil.copyfile(boto_key, moblab_host.MOBLAB_BOTO_LOCATION)
Dan Shi193905e2014-07-25 23:33:09 -0700283
284
285def get_job_history(**filter_data):
286 """Get history of the job, including the special tasks executed for the job
287
288 @param filter_data: filter for the call, should at least include
289 {'job_id': [job id]}
290 @returns: JSON string of the job's history, including the information such
291 as the hosts run the job and the special tasks executed before
292 and after the job.
293 """
294 job_id = filter_data['job_id']
295 job_info = job_history.get_job_info(job_id)
Dan Shidfea3682014-08-10 23:38:40 -0700296 return rpc_utils.prepare_for_serialization(job_info.get_history())
297
298
299def get_host_history(start_time, end_time, hosts=None, board=None, pool=None):
300 """Get history of a list of host.
301
302 The return is a JSON string of host history for each host, for example,
303 {'172.22.33.51': [{'status': 'Resetting'
304 'start_time': '2014-08-07 10:02:16',
305 'end_time': '2014-08-07 10:03:16',
306 'log_url': 'http://autotest/reset-546546/debug',
307 'dbg_str': 'Task: Special Task 19441991 (host ...)'},
308 {'status': 'Running'
309 'start_time': '2014-08-07 10:03:18',
310 'end_time': '2014-08-07 10:13:00',
311 'log_url': 'http://autotest/reset-546546/debug',
312 'dbg_str': 'HQE: 15305005, for job: 14995562'}
313 ]
314 }
315 @param start_time: start time to search for history, can be string value or
316 epoch time.
317 @param end_time: end time to search for history, can be string value or
318 epoch time.
319 @param hosts: A list of hosts to search for history. Default is None.
320 @param board: board type of hosts. Default is None.
321 @param pool: pool type of hosts. Default is None.
322 @returns: JSON string of the host history.
323 """
324 return rpc_utils.prepare_for_serialization(
325 host_history.get_history_details(
326 start_time=start_time, end_time=end_time,
327 hosts=hosts, board=board, pool=pool,
328 process_pool_size=4))
Jakob Juelich59cfe542014-09-02 16:37:46 -0700329
330
Jakob Juelich1b525742014-09-30 13:08:07 -0700331def shard_heartbeat(shard_hostname, jobs=(), hqes=(),
332 known_job_ids=(), known_host_ids=()):
333 """Receive updates for job statuses from shards and assign hosts and jobs.
Jakob Juelich59cfe542014-09-02 16:37:46 -0700334
335 @param shard_hostname: Hostname of the calling shard
Jakob Juelicha94efe62014-09-18 16:02:49 -0700336 @param jobs: Jobs in serialized form that should be updated with newer
337 status from a shard.
338 @param hqes: Hostqueueentries in serialized form that should be updated with
339 newer status from a shard. Note that for every hostqueueentry
340 the corresponding job must be in jobs.
Jakob Juelich1b525742014-09-30 13:08:07 -0700341 @param known_job_ids: List of ids of jobs the shard already has.
342 @param known_host_ids: List of ids of hosts the shard already has.
Jakob Juelicha94efe62014-09-18 16:02:49 -0700343
Fang Dengf3705992014-12-16 17:32:18 -0800344 @returns: Serialized representations of hosts, jobs, suite job keyvals
345 and their dependencies to be inserted into a shard's database.
Jakob Juelich59cfe542014-09-02 16:37:46 -0700346 """
Jakob Juelich1b525742014-09-30 13:08:07 -0700347 # The following alternatives to sending host and job ids in every heartbeat
348 # have been considered:
349 # 1. Sending the highest known job and host ids. This would work for jobs:
350 # Newer jobs always have larger ids. Also, if a job is not assigned to a
351 # particular shard during a heartbeat, it never will be assigned to this
352 # shard later.
353 # This is not true for hosts though: A host that is leased won't be sent
354 # to the shard now, but might be sent in a future heartbeat. This means
355 # sometimes hosts should be transfered that have a lower id than the
356 # maximum host id the shard knows.
357 # 2. Send the number of jobs/hosts the shard knows to the master in each
358 # heartbeat. Compare these to the number of records that already have
359 # the shard_id set to this shard. In the normal case, they should match.
360 # In case they don't, resend all entities of that type.
361 # This would work well for hosts, because there aren't that many.
362 # Resending all jobs is quite a big overhead though.
363 # Also, this approach might run into edge cases when entities are
364 # ever deleted.
365 # 3. Mixtures of the above: Use 1 for jobs and 2 for hosts.
366 # Using two different approaches isn't consistent and might cause
367 # confusion. Also the issues with the case of deletions might still
368 # occur.
369 #
370 # The overhead of sending all job and host ids in every heartbeat is low:
371 # At peaks one board has about 1200 created but unfinished jobs.
372 # See the numbers here: http://goo.gl/gQCGWH
373 # Assuming that job id's have 6 digits and that json serialization takes a
374 # comma and a space as overhead, the traffic per id sent is about 8 bytes.
375 # If 5000 ids need to be sent, this means 40 kilobytes of traffic.
376 # A NOT IN query with 5000 ids took about 30ms in tests made.
377 # These numbers seem low enough to outweigh the disadvantages of the
378 # solutions described above.
Gabe Black1e1c41b2015-02-04 23:55:15 -0800379 timer = autotest_stats.Timer('shard_heartbeat')
Jakob Juelich59cfe542014-09-02 16:37:46 -0700380 with timer:
381 shard_obj = rpc_utils.retrieve_shard(shard_hostname=shard_hostname)
Jakob Juelicha94efe62014-09-18 16:02:49 -0700382 rpc_utils.persist_records_sent_from_shard(shard_obj, jobs, hqes)
Fang Dengf3705992014-12-16 17:32:18 -0800383 hosts, jobs, suite_keyvals = rpc_utils.find_records_for_shard(
Jakob Juelich1b525742014-09-30 13:08:07 -0700384 shard_obj,
385 known_job_ids=known_job_ids, known_host_ids=known_host_ids)
Jakob Juelich59cfe542014-09-02 16:37:46 -0700386 return {
387 'hosts': [host.serialize() for host in hosts],
388 'jobs': [job.serialize() for job in jobs],
Fang Dengf3705992014-12-16 17:32:18 -0800389 'suite_keyvals': [kv.serialize() for kv in suite_keyvals],
Jakob Juelich59cfe542014-09-02 16:37:46 -0700390 }
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700391
392
393def get_shards(**filter_data):
394 """Return a list of all shards.
395
396 @returns A sequence of nested dictionaries of shard information.
397 """
398 shards = models.Shard.query_objects(filter_data)
399 serialized_shards = rpc_utils.prepare_rows_as_nested_dicts(shards, ())
400 for serialized, shard in zip(serialized_shards, shards):
401 serialized['labels'] = [label.name for label in shard.labels.all()]
402
403 return serialized_shards
404
405
406def add_shard(hostname, label):
407 """Add a shard and start running jobs on it.
408
409 @param hostname: The hostname of the shard to be added; needs to be unique.
410 @param label: A platform label. Jobs of this label will be assigned to the
411 shard.
412
Jakob Juelich8b110ee2014-09-15 16:13:42 -0700413 @raises error.RPCException: If label provided doesn't start with `board:`
414 @raises model_logic.ValidationError: If a shard with the given hostname
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700415 already exists.
Jakob Juelich8b110ee2014-09-15 16:13:42 -0700416 @raises models.Label.DoesNotExist: If the label specified doesn't exist.
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700417 """
Jakob Juelich8b110ee2014-09-15 16:13:42 -0700418 if not label.startswith('board:'):
419 raise error.RPCException('Sharding only supported for `board:.*` '
420 'labels.')
421
422 # Fetch label first, so shard isn't created when label doesn't exist.
423 label = models.Label.smart_get(label)
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700424 shard = models.Shard.add_object(hostname=hostname)
Jakob Juelich8b110ee2014-09-15 16:13:42 -0700425 shard.labels.add(label)
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700426 return shard.id
427
428
429def delete_shard(hostname):
430 """Delete a shard and reclaim all resources from it.
431
432 This claims back all assigned hosts from the shard. To ensure all DUTs are
433 in a sane state, a Repair task is scheduled for them. This reboots the DUTs
434 and therefore clears all running processes that might be left.
435
436 The shard_id of jobs of that shard will be set to None.
437
438 The status of jobs that haven't been reported to be finished yet, will be
439 lost. The master scheduler will pick up the jobs and execute them.
440
441 @param hostname: Hostname of the shard to delete.
442 """
443 shard = rpc_utils.retrieve_shard(shard_hostname=hostname)
444
445 # TODO(beeps): Power off shard
446
447 # For ChromeOS hosts, repair reboots the DUT.
448 # Repair will excalate through multiple repair steps and will verify the
449 # success after each of them. Anyway, it will always run at least the first
450 # one, which includes a reboot.
451 # After a reboot we can be sure no processes from prior tests that were run
452 # by a shard are still running on the DUT.
453 # Important: Don't just set the status to Repair Failed, as that would run
454 # Verify first, before doing any repair measures. Verify would probably
455 # succeed, so this wouldn't change anything on the DUT.
456 for host in models.Host.objects.filter(shard=shard):
457 models.SpecialTask.objects.create(
458 task=models.SpecialTask.Task.REPAIR,
459 host=host,
460 requested_by=models.User.current_user())
461 models.Host.objects.filter(shard=shard).update(shard=None)
462
463 models.Job.objects.filter(shard=shard).update(shard=None)
464
465 shard.labels.clear()
466
467 shard.delete()
Dan Shi6964fa52014-12-18 11:04:27 -0800468
469
Dan Shid7bb4f12015-01-06 10:53:50 -0800470def get_servers(role=None, status=None):
471 """Get a list of servers with matching role and status.
472
473 @param role: Name of the server role, e.g., drone, scheduler. Default to
474 None to match any role.
475 @param status: Status of the server, e.g., primary, backup, repair_required.
476 Default to None to match any server status.
477
478 @raises error.RPCException: If server database is not used.
479 @return: A list of server names for servers with matching role and status.
480 """
481 if not server_manager_utils.use_server_db():
482 raise error.RPCException('Server database is not enabled. Please try '
483 'retrieve servers from global config.')
484 servers = server_manager_utils.get_servers(hostname=None, role=role,
485 status=status)
486 return [s.get_details() for s in servers]
487
488
Dan Shi6964fa52014-12-18 11:04:27 -0800489def get_stable_version(board=stable_version_utils.DEFAULT):
490 """Get stable version for the given board.
491
492 @param board: Name of the board.
493 @return: Stable version of the given board. Return global configure value
494 of CROS.stable_cros_version if stable_versinos table does not have
495 entry of board DEFAULT.
496 """
MK Ryu6766de72015-05-13 16:08:24 -0700497 # This RPC call should be accepted only by master.
498 if utils.is_shard():
499 return rpc_utils.route_rpc_to_master('get_stable_version', board=board)
Dan Shi25e1fd42014-12-19 14:36:42 -0800500 return stable_version_utils.get(board)
501
502
503def get_all_stable_versions():
504 """Get stable versions for all boards.
505
506 @return: A dictionary of board:version.
507 """
MK Ryu6766de72015-05-13 16:08:24 -0700508 # This RPC call should be accepted only by master.
509 if utils.is_shard():
510 return rpc_utils.route_rpc_to_master('get_all_stable_versions')
Dan Shi25e1fd42014-12-19 14:36:42 -0800511 return stable_version_utils.get_all()
512
513
514def set_stable_version(version, board=stable_version_utils.DEFAULT):
515 """Modify stable version for the given board.
516
517 @param version: The new value of stable version for given board.
518 @param board: Name of the board, default to value `DEFAULT`.
519 """
MK Ryu6766de72015-05-13 16:08:24 -0700520 # This RPC call should be accepted only by master.
521 if utils.is_shard():
522 return rpc_utils.route_rpc_to_master('set_stable_version',
523 version=version, board=board)
Dan Shi25e1fd42014-12-19 14:36:42 -0800524 stable_version_utils.set(version=version, board=board)
525
526
527def delete_stable_version(board):
528 """Modify stable version for the given board.
529
530 Delete a stable version entry in afe_stable_versions table for a given
531 board, so default stable version will be used.
532
533 @param board: Name of the board.
534 """
MK Ryu6766de72015-05-13 16:08:24 -0700535 # This RPC call should be accepted only by master.
536 if utils.is_shard():
537 return rpc_utils.route_rpc_to_master('delete_stable_version',
538 board=board)
Dan Shi25e1fd42014-12-19 14:36:42 -0800539 stable_version_utils.delete(board=board)