blob: 71d9c2100c4641c03a1ccc1eafe1d75fe3f98f7b [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
Jakob Juelich59cfe542014-09-02 16:37:46 -070021from autotest_lib.client.common_lib.cros.graphite import 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 Shi6964fa52014-12-18 11:04:27 -080030from autotest_lib.site_utils import stable_version_utils
Simran Basi71206ef2014-08-13 13:51:18 -070031
32
33_CONFIG = global_config.global_config
34MOBLAB_BOTO_LOCATION = '/home/moblab/.boto'
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):
40 return 'test_suites/control.%s' % suite_name
41
42
Chris Masoneaa10f8e2012-05-15 13:34:21 -070043def formatted_now():
Dan Shidfea3682014-08-10 23:38:40 -070044 return datetime.datetime.now().strftime(time_utils.TIME_FMT)
Chris Masoneaa10f8e2012-05-15 13:34:21 -070045
46
Simran Basib6ec8ae2014-04-23 12:05:08 -070047def _get_control_file_contents_by_name(build, ds, suite_name):
Chris Masone8dd27e02012-06-25 15:59:43 -070048 """Return control file contents for |suite_name|.
49
50 Query the dev server at |ds| for the control file |suite_name|, included
51 in |build| for |board|.
52
53 @param build: unique name by which to refer to the image from now on.
Chris Masone8dd27e02012-06-25 15:59:43 -070054 @param ds: a dev_server.DevServer instance to fetch control file with.
55 @param suite_name: canonicalized suite name, e.g. test_suites/control.bvt.
56 @raises ControlFileNotFound if a unique suite control file doesn't exist.
57 @raises NoControlFileList if we can't list the control files at all.
58 @raises ControlFileEmpty if the control file exists on the server, but
59 can't be read.
60
61 @return the contents of the desired control file.
62 """
63 getter = control_file_getter.DevServerGetter.create(build, ds)
Prashanth Balasubramanianabe3bb72014-11-20 12:00:37 -080064 timer = stats.Timer('control_files.parse.%s.%s' %
65 (ds.get_server_name(ds.url()).replace('.', '_'),
66 suite_name.rsplit('.')[-1]))
Chris Masone8dd27e02012-06-25 15:59:43 -070067 # Get the control file for the suite.
68 try:
Prashanth Balasubramanianabe3bb72014-11-20 12:00:37 -080069 with timer:
70 control_file_in = getter.get_control_file_contents_by_name(
71 suite_name)
Chris Masone8dd27e02012-06-25 15:59:43 -070072 except error.CrosDynamicSuiteException as e:
Simran Basib6ec8ae2014-04-23 12:05:08 -070073 raise type(e)("%s while testing %s." % (e, build))
Chris Masone8dd27e02012-06-25 15:59:43 -070074 if not control_file_in:
75 raise error.ControlFileEmpty(
76 "Fetching %s returned no data." % suite_name)
Alex Millera713e252013-03-01 10:45:44 -080077 # Force control files to only contain ascii characters.
78 try:
79 control_file_in.encode('ascii')
80 except UnicodeDecodeError as e:
81 raise error.ControlFileMalformed(str(e))
82
Chris Masone8dd27e02012-06-25 15:59:43 -070083 return control_file_in
84
85
Simran Basib6ec8ae2014-04-23 12:05:08 -070086def _stage_build_artifacts(build):
87 """
88 Ensure components of |build| necessary for installing images are staged.
89
90 @param build image we want to stage.
91
Prashanth B6285f6a2014-05-08 18:01:27 -070092 @raises StageControlFileFailure: if the dev server throws 500 while staging
93 suite control files.
Simran Basib6ec8ae2014-04-23 12:05:08 -070094
95 @return: dev_server.ImageServer instance to use with this build.
96 @return: timings dictionary containing staging start/end times.
97 """
98 timings = {}
Prashanth B6285f6a2014-05-08 18:01:27 -070099 # Ensure components of |build| necessary for installing images are staged
100 # on the dev server. However set synchronous to False to allow other
101 # components to be downloaded in the background.
Simran Basib6ec8ae2014-04-23 12:05:08 -0700102 ds = dev_server.ImageServer.resolve(build)
103 timings[constants.DOWNLOAD_STARTED_TIME] = formatted_now()
Prashanth Balasubramanianabe3bb72014-11-20 12:00:37 -0800104 timer = stats.Timer('control_files.stage.%s' % (
105 ds.get_server_name(ds.url()).replace('.', '_')))
Simran Basib6ec8ae2014-04-23 12:05:08 -0700106 try:
Prashanth Balasubramanianabe3bb72014-11-20 12:00:37 -0800107 with timer:
108 ds.stage_artifacts(build, ['test_suites'])
Simran Basib6ec8ae2014-04-23 12:05:08 -0700109 except dev_server.DevServerException as e:
Prashanth B6285f6a2014-05-08 18:01:27 -0700110 raise error.StageControlFileFailure(
Simran Basib6ec8ae2014-04-23 12:05:08 -0700111 "Failed to stage %s: %s" % (build, e))
112 timings[constants.PAYLOAD_FINISHED_TIME] = formatted_now()
113 return (ds, timings)
114
115
116def create_suite_job(name='', board='', build='', pool='', control_file='',
117 check_hosts=True, num=None, file_bugs=False, timeout=24,
118 timeout_mins=None, priority=priorities.Priority.DEFAULT,
Fang Deng058860c2014-05-15 15:41:50 -0700119 suite_args=None, wait_for_results=True, job_retry=False,
Fang Deng443f1952015-01-02 14:51:49 -0800120 max_retries=None, max_runtime_mins=None, suite_min_duts=0,
121 **kwargs):
Chris Masone859fdec2012-01-30 08:38:09 -0800122 """
123 Create a job to run a test suite on the given device with the given image.
124
125 When the timeout specified in the control file is reached, the
126 job is guaranteed to have completed and results will be available.
127
Simran Basib6ec8ae2014-04-23 12:05:08 -0700128 @param name: The test name if control_file is supplied, otherwise the name
129 of the test suite to run, e.g. 'bvt'.
Chris Masone859fdec2012-01-30 08:38:09 -0800130 @param board: the kind of device to run the tests on.
131 @param build: unique name by which to refer to the image from now on.
Scott Zawalski65650172012-02-16 11:48:26 -0500132 @param pool: Specify the pool of machines to use for scheduling
133 purposes.
Chris Masone62579122012-03-08 15:18:43 -0800134 @param check_hosts: require appropriate live hosts to exist in the lab.
Aviv Keshetd83ef442013-01-16 16:19:35 -0800135 @param num: Specify the number of machines to schedule across (integer).
136 Leave unspecified or use None to use default sharding factor.
Alex Millerc577f3e2012-09-27 14:06:07 -0700137 @param file_bugs: File a bug on each test failure in this suite.
Alex Miller139690b2013-09-07 15:35:49 -0700138 @param timeout: The max lifetime of this suite, in hours.
Simran Basi7e605742013-11-12 13:43:36 -0800139 @param timeout_mins: The max lifetime of this suite, in minutes. Takes
140 priority over timeout.
Alex Miller139690b2013-09-07 15:35:49 -0700141 @param priority: Integer denoting priority. Higher is more important.
Aviv Keshet7cd12312013-07-25 10:25:55 -0700142 @param suite_args: Optional arguments which will be parsed by the suite
143 control file. Used by control.test_that_wrapper to
144 determine which tests to run.
Dan Shi95122412013-11-12 16:20:33 -0800145 @param wait_for_results: Set to False to run the suite job without waiting
146 for test jobs to finish. Default is True.
Fang Deng058860c2014-05-15 15:41:50 -0700147 @param job_retry: Set to True to enable job-level retry. Default is False.
Fang Deng443f1952015-01-02 14:51:49 -0800148 @param max_retries: Integer, maximum job retries allowed at suite level.
149 None for no max.
Simran Basi102e3522014-09-11 11:46:10 -0700150 @param max_runtime_mins: Maximum amount of time a job can be running in
151 minutes.
Fang Dengcbc01212014-11-25 16:09:46 -0800152 @param suite_min_duts: Integer. Scheduler will prioritize getting the
153 minimum number of machines for the suite when it is
154 competing with another suite that has a higher
155 priority but already got minimum machines it needs.
Simran Basib6ec8ae2014-04-23 12:05:08 -0700156 @param kwargs: extra keyword args. NOT USED.
Chris Masone859fdec2012-01-30 08:38:09 -0800157
Chris Masone8dd27e02012-06-25 15:59:43 -0700158 @raises ControlFileNotFound: if a unique suite control file doesn't exist.
159 @raises NoControlFileList: if we can't list the control files at all.
Prashanth B6285f6a2014-05-08 18:01:27 -0700160 @raises StageControlFileFailure: If the dev server throws 500 while
161 staging test_suites.
Chris Masone8dd27e02012-06-25 15:59:43 -0700162 @raises ControlFileEmpty: if the control file exists on the server, but
163 can't be read.
Chris Masone859fdec2012-01-30 08:38:09 -0800164
165 @return: the job ID of the suite; -1 on error.
166 """
Aviv Keshetd83ef442013-01-16 16:19:35 -0800167 if type(num) is not int and num is not None:
Chris Sosa18c70b32013-02-15 14:12:43 -0800168 raise error.SuiteArgumentException('Ill specified num argument %r. '
169 'Must be an integer or None.' % num)
Aviv Keshetd83ef442013-01-16 16:19:35 -0800170 if num == 0:
171 logging.warning("Can't run on 0 hosts; using default.")
172 num = None
Fang Dengcbc01212014-11-25 16:09:46 -0800173 (ds, keyvals) = _stage_build_artifacts(build)
174 keyvals[constants.SUITE_MIN_DUTS_KEY] = suite_min_duts
Chris Masone859fdec2012-01-30 08:38:09 -0800175
Simran Basib6ec8ae2014-04-23 12:05:08 -0700176 if not control_file:
177 # No control file was supplied so look it up from the build artifacts.
178 suite_name = canonicalize_suite_name(name)
179 control_file = _get_control_file_contents_by_name(build, ds, suite_name)
180 name = '%s-%s' % (build, suite_name)
Chris Masone46d0eb12012-07-27 18:56:39 -0700181
Simran Basi7e605742013-11-12 13:43:36 -0800182 timeout_mins = timeout_mins or timeout * 60
Simran Basi102e3522014-09-11 11:46:10 -0700183 max_runtime_mins = max_runtime_mins or timeout * 60
Simran Basi7e605742013-11-12 13:43:36 -0800184
Simran Basib6ec8ae2014-04-23 12:05:08 -0700185 if not board:
186 board = utils.ParseBuildName(build)[0]
Chris Masone46d0eb12012-07-27 18:56:39 -0700187
Simran Basib6ec8ae2014-04-23 12:05:08 -0700188 # Prepend build and board to the control file.
Scott Zawalski65650172012-02-16 11:48:26 -0500189 inject_dict = {'board': board,
190 'build': build,
Chris Masone62579122012-03-08 15:18:43 -0800191 'check_hosts': check_hosts,
Chris Masone46d0eb12012-07-27 18:56:39 -0700192 'pool': pool,
Aviv Keshetd83ef442013-01-16 16:19:35 -0800193 'num': num,
Dan Shib8a99112013-06-18 13:46:10 -0700194 'file_bugs': file_bugs,
Alex Miller139690b2013-09-07 15:35:49 -0700195 'timeout': timeout,
Simran Basi7e605742013-11-12 13:43:36 -0800196 'timeout_mins': timeout_mins,
Alex Miller7d658cf2013-09-04 16:00:35 -0700197 'devserver_url': ds.url(),
Aviv Keshet7cd12312013-07-25 10:25:55 -0700198 'priority': priority,
Dan Shi95122412013-11-12 16:20:33 -0800199 'suite_args' : suite_args,
Fang Deng058860c2014-05-15 15:41:50 -0700200 'wait_for_results': wait_for_results,
Simran Basi102e3522014-09-11 11:46:10 -0700201 'job_retry': job_retry,
Fang Deng443f1952015-01-02 14:51:49 -0800202 'max_retries': max_retries,
Fang Dengcbc01212014-11-25 16:09:46 -0800203 'max_runtime_mins': max_runtime_mins,
Aviv Keshet7cd12312013-07-25 10:25:55 -0700204 }
205
Simran Basib6ec8ae2014-04-23 12:05:08 -0700206 control_file = tools.inject_vars(inject_dict, control_file)
Chris Masone859fdec2012-01-30 08:38:09 -0800207
Jakob Juelich9fffe4f2014-08-14 18:07:05 -0700208 return rpc_utils.create_job_common(name,
Jakob Juelich59cfe542014-09-02 16:37:46 -0700209 priority=priority,
210 timeout_mins=timeout_mins,
211 max_runtime_mins=max_runtime_mins,
212 control_type='Server',
213 control_file=control_file,
214 hostless=True,
Fang Dengcbc01212014-11-25 16:09:46 -0800215 keyvals=keyvals)
Simran Basi71206ef2014-08-13 13:51:18 -0700216
217
218# TODO: hide the following rpcs under is_moblab
219def moblab_only(func):
220 """Ensure moblab specific functions only run on Moblab devices."""
221 def verify(*args, **kwargs):
222 if not utils.is_moblab():
223 raise error.RPCException('RPC: %s can only run on Moblab Systems!',
224 func.__name__)
225 return func(*args, **kwargs)
226 return verify
227
228
229@moblab_only
230def get_config_values():
231 """Returns all config values parsed from global and shadow configs.
232
233 Config values are grouped by sections, and each section is composed of
234 a list of name value pairs.
235 """
236 sections =_CONFIG.get_sections()
237 config_values = {}
238 for section in sections:
239 config_values[section] = _CONFIG.config.items(section)
Jakob Juelich9fffe4f2014-08-14 18:07:05 -0700240 return rpc_utils.prepare_for_serialization(config_values)
Simran Basi71206ef2014-08-13 13:51:18 -0700241
242
243@moblab_only
244def update_config_handler(config_values):
245 """
246 Update config values and override shadow config.
247
248 @param config_values: See get_moblab_settings().
249 """
250 for section, config_value_list in config_values.iteritems():
251 for key, value in config_value_list:
252 _CONFIG.override_config_value(section, key, value)
253 if not _CONFIG.shadow_file or not os.path.exists(_CONFIG.shadow_file):
254 raise error.RPCException('Shadow config file does not exist.')
255
256 with open(_CONFIG.shadow_file, 'w') as config_file:
257 _CONFIG.config.write(config_file)
258 # TODO (sbasi) crbug.com/403916 - Remove the reboot command and
259 # instead restart the services that rely on the config values.
260 os.system('sudo reboot')
261
262
263@moblab_only
264def reset_config_settings():
265 with open(_CONFIG.shadow_file, 'w') as config_file:
266 pass
267 os.system('sudo reboot')
268
269
270@moblab_only
271def set_boto_key(boto_key):
272 """Update the boto_key file.
273
274 @param boto_key: File name of boto_key uploaded through handle_file_upload.
275 """
276 if not os.path.exists(boto_key):
277 raise error.RPCException('Boto key: %s does not exist!' % boto_key)
278 shutil.copyfile(boto_key, moblab_host.MOBLAB_BOTO_LOCATION)
Dan Shi193905e2014-07-25 23:33:09 -0700279
280
281def get_job_history(**filter_data):
282 """Get history of the job, including the special tasks executed for the job
283
284 @param filter_data: filter for the call, should at least include
285 {'job_id': [job id]}
286 @returns: JSON string of the job's history, including the information such
287 as the hosts run the job and the special tasks executed before
288 and after the job.
289 """
290 job_id = filter_data['job_id']
291 job_info = job_history.get_job_info(job_id)
Dan Shidfea3682014-08-10 23:38:40 -0700292 return rpc_utils.prepare_for_serialization(job_info.get_history())
293
294
295def get_host_history(start_time, end_time, hosts=None, board=None, pool=None):
296 """Get history of a list of host.
297
298 The return is a JSON string of host history for each host, for example,
299 {'172.22.33.51': [{'status': 'Resetting'
300 'start_time': '2014-08-07 10:02:16',
301 'end_time': '2014-08-07 10:03:16',
302 'log_url': 'http://autotest/reset-546546/debug',
303 'dbg_str': 'Task: Special Task 19441991 (host ...)'},
304 {'status': 'Running'
305 'start_time': '2014-08-07 10:03:18',
306 'end_time': '2014-08-07 10:13:00',
307 'log_url': 'http://autotest/reset-546546/debug',
308 'dbg_str': 'HQE: 15305005, for job: 14995562'}
309 ]
310 }
311 @param start_time: start time to search for history, can be string value or
312 epoch time.
313 @param end_time: end time to search for history, can be string value or
314 epoch time.
315 @param hosts: A list of hosts to search for history. Default is None.
316 @param board: board type of hosts. Default is None.
317 @param pool: pool type of hosts. Default is None.
318 @returns: JSON string of the host history.
319 """
320 return rpc_utils.prepare_for_serialization(
321 host_history.get_history_details(
322 start_time=start_time, end_time=end_time,
323 hosts=hosts, board=board, pool=pool,
324 process_pool_size=4))
Jakob Juelich59cfe542014-09-02 16:37:46 -0700325
326
Jakob Juelich1b525742014-09-30 13:08:07 -0700327def shard_heartbeat(shard_hostname, jobs=(), hqes=(),
328 known_job_ids=(), known_host_ids=()):
329 """Receive updates for job statuses from shards and assign hosts and jobs.
Jakob Juelich59cfe542014-09-02 16:37:46 -0700330
331 @param shard_hostname: Hostname of the calling shard
Jakob Juelicha94efe62014-09-18 16:02:49 -0700332 @param jobs: Jobs in serialized form that should be updated with newer
333 status from a shard.
334 @param hqes: Hostqueueentries in serialized form that should be updated with
335 newer status from a shard. Note that for every hostqueueentry
336 the corresponding job must be in jobs.
Jakob Juelich1b525742014-09-30 13:08:07 -0700337 @param known_job_ids: List of ids of jobs the shard already has.
338 @param known_host_ids: List of ids of hosts the shard already has.
Jakob Juelicha94efe62014-09-18 16:02:49 -0700339
Jakob Juelich59cfe542014-09-02 16:37:46 -0700340 @returns: Serialized representations of hosts, jobs and their dependencies
341 to be inserted into a shard's database.
342 """
Jakob Juelich1b525742014-09-30 13:08:07 -0700343 # The following alternatives to sending host and job ids in every heartbeat
344 # have been considered:
345 # 1. Sending the highest known job and host ids. This would work for jobs:
346 # Newer jobs always have larger ids. Also, if a job is not assigned to a
347 # particular shard during a heartbeat, it never will be assigned to this
348 # shard later.
349 # This is not true for hosts though: A host that is leased won't be sent
350 # to the shard now, but might be sent in a future heartbeat. This means
351 # sometimes hosts should be transfered that have a lower id than the
352 # maximum host id the shard knows.
353 # 2. Send the number of jobs/hosts the shard knows to the master in each
354 # heartbeat. Compare these to the number of records that already have
355 # the shard_id set to this shard. In the normal case, they should match.
356 # In case they don't, resend all entities of that type.
357 # This would work well for hosts, because there aren't that many.
358 # Resending all jobs is quite a big overhead though.
359 # Also, this approach might run into edge cases when entities are
360 # ever deleted.
361 # 3. Mixtures of the above: Use 1 for jobs and 2 for hosts.
362 # Using two different approaches isn't consistent and might cause
363 # confusion. Also the issues with the case of deletions might still
364 # occur.
365 #
366 # The overhead of sending all job and host ids in every heartbeat is low:
367 # At peaks one board has about 1200 created but unfinished jobs.
368 # See the numbers here: http://goo.gl/gQCGWH
369 # Assuming that job id's have 6 digits and that json serialization takes a
370 # comma and a space as overhead, the traffic per id sent is about 8 bytes.
371 # If 5000 ids need to be sent, this means 40 kilobytes of traffic.
372 # A NOT IN query with 5000 ids took about 30ms in tests made.
373 # These numbers seem low enough to outweigh the disadvantages of the
374 # solutions described above.
Jakob Juelich59cfe542014-09-02 16:37:46 -0700375 timer = stats.Timer('shard_heartbeat')
376 with timer:
377 shard_obj = rpc_utils.retrieve_shard(shard_hostname=shard_hostname)
Jakob Juelicha94efe62014-09-18 16:02:49 -0700378 rpc_utils.persist_records_sent_from_shard(shard_obj, jobs, hqes)
Jakob Juelich1b525742014-09-30 13:08:07 -0700379 hosts, jobs = rpc_utils.find_records_for_shard(
380 shard_obj,
381 known_job_ids=known_job_ids, known_host_ids=known_host_ids)
Jakob Juelich59cfe542014-09-02 16:37:46 -0700382 return {
383 'hosts': [host.serialize() for host in hosts],
384 'jobs': [job.serialize() for job in jobs],
385 }
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700386
387
388def get_shards(**filter_data):
389 """Return a list of all shards.
390
391 @returns A sequence of nested dictionaries of shard information.
392 """
393 shards = models.Shard.query_objects(filter_data)
394 serialized_shards = rpc_utils.prepare_rows_as_nested_dicts(shards, ())
395 for serialized, shard in zip(serialized_shards, shards):
396 serialized['labels'] = [label.name for label in shard.labels.all()]
397
398 return serialized_shards
399
400
401def add_shard(hostname, label):
402 """Add a shard and start running jobs on it.
403
404 @param hostname: The hostname of the shard to be added; needs to be unique.
405 @param label: A platform label. Jobs of this label will be assigned to the
406 shard.
407
Jakob Juelich8b110ee2014-09-15 16:13:42 -0700408 @raises error.RPCException: If label provided doesn't start with `board:`
409 @raises model_logic.ValidationError: If a shard with the given hostname
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700410 already exists.
Jakob Juelich8b110ee2014-09-15 16:13:42 -0700411 @raises models.Label.DoesNotExist: If the label specified doesn't exist.
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700412 """
Jakob Juelich8b110ee2014-09-15 16:13:42 -0700413 if not label.startswith('board:'):
414 raise error.RPCException('Sharding only supported for `board:.*` '
415 'labels.')
416
417 # Fetch label first, so shard isn't created when label doesn't exist.
418 label = models.Label.smart_get(label)
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700419 shard = models.Shard.add_object(hostname=hostname)
Jakob Juelich8b110ee2014-09-15 16:13:42 -0700420 shard.labels.add(label)
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700421 return shard.id
422
423
424def delete_shard(hostname):
425 """Delete a shard and reclaim all resources from it.
426
427 This claims back all assigned hosts from the shard. To ensure all DUTs are
428 in a sane state, a Repair task is scheduled for them. This reboots the DUTs
429 and therefore clears all running processes that might be left.
430
431 The shard_id of jobs of that shard will be set to None.
432
433 The status of jobs that haven't been reported to be finished yet, will be
434 lost. The master scheduler will pick up the jobs and execute them.
435
436 @param hostname: Hostname of the shard to delete.
437 """
438 shard = rpc_utils.retrieve_shard(shard_hostname=hostname)
439
440 # TODO(beeps): Power off shard
441
442 # For ChromeOS hosts, repair reboots the DUT.
443 # Repair will excalate through multiple repair steps and will verify the
444 # success after each of them. Anyway, it will always run at least the first
445 # one, which includes a reboot.
446 # After a reboot we can be sure no processes from prior tests that were run
447 # by a shard are still running on the DUT.
448 # Important: Don't just set the status to Repair Failed, as that would run
449 # Verify first, before doing any repair measures. Verify would probably
450 # succeed, so this wouldn't change anything on the DUT.
451 for host in models.Host.objects.filter(shard=shard):
452 models.SpecialTask.objects.create(
453 task=models.SpecialTask.Task.REPAIR,
454 host=host,
455 requested_by=models.User.current_user())
456 models.Host.objects.filter(shard=shard).update(shard=None)
457
458 models.Job.objects.filter(shard=shard).update(shard=None)
459
460 shard.labels.clear()
461
462 shard.delete()
Dan Shi6964fa52014-12-18 11:04:27 -0800463
464
465def get_stable_version(board=stable_version_utils.DEFAULT):
466 """Get stable version for the given board.
467
468 @param board: Name of the board.
469 @return: Stable version of the given board. Return global configure value
470 of CROS.stable_cros_version if stable_versinos table does not have
471 entry of board DEFAULT.
472 """
Fang Deng443f1952015-01-02 14:51:49 -0800473 return stable_version_utils.get_version(board)