blob: a629f58ab1be4af01495138c55f7388e2bcc4de5 [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
Michael Tang9afc74b2016-03-21 10:19:23 -07009# The boto module is only available/used in Moblab for validation of cloud
10# storage access. The module is not available in the test lab environment,
11# and the import error is handled.
12try:
13 import boto
14except ImportError:
15 boto = None
Chris Masone859fdec2012-01-30 08:38:09 -080016import common
Simran Basi773a86e2015-05-13 19:15:42 -070017import ConfigParser
Chris Masonea8066a92012-05-01 16:52:31 -070018import datetime
Chris Masone859fdec2012-01-30 08:38:09 -080019import logging
Simran Basi71206ef2014-08-13 13:51:18 -070020import os
Michael Tang9afc74b2016-03-21 10:19:23 -070021import re
Simran Basi71206ef2014-08-13 13:51:18 -070022import shutil
Michael Tang9afc74b2016-03-21 10:19:23 -070023import socket
Aviv Keshetd83ef442013-01-16 16:19:35 -080024
Jakob Juelich82b7d1c2014-09-15 16:10:57 -070025from autotest_lib.frontend.afe import models
Matthew Sartorid96fb9b2015-05-19 18:04:58 -070026from autotest_lib.client.common_lib import control_data
Aviv Keshetd83ef442013-01-16 16:19:35 -080027from autotest_lib.client.common_lib import error
Simran Basi71206ef2014-08-13 13:51:18 -070028from autotest_lib.client.common_lib import global_config
Alex Miller7d658cf2013-09-04 16:00:35 -070029from autotest_lib.client.common_lib import priorities
Dan Shidfea3682014-08-10 23:38:40 -070030from autotest_lib.client.common_lib import time_utils
Chris Masone859fdec2012-01-30 08:38:09 -080031from autotest_lib.client.common_lib.cros import dev_server
Gabe Black1e1c41b2015-02-04 23:55:15 -080032from autotest_lib.client.common_lib.cros.graphite import autotest_stats
Jakob Juelich9fffe4f2014-08-14 18:07:05 -070033from autotest_lib.frontend.afe import rpc_utils
Simran Basib6ec8ae2014-04-23 12:05:08 -070034from autotest_lib.server import utils
Dan Shi36cfd832014-10-10 13:38:51 -070035from autotest_lib.server.cros import provision
Chris Masone44e4d6c2012-08-15 14:25:53 -070036from autotest_lib.server.cros.dynamic_suite import constants
Chris Masoneb4935552012-08-14 12:05:54 -070037from autotest_lib.server.cros.dynamic_suite import control_file_getter
Chris Masone44e4d6c2012-08-15 14:25:53 -070038from autotest_lib.server.cros.dynamic_suite import tools
xixuan0f7755d2016-04-18 14:49:12 -070039from autotest_lib.server.cros.dynamic_suite import suite as SuiteBase
Dan Shi36cfd832014-10-10 13:38:51 -070040from autotest_lib.server.cros.dynamic_suite.suite import Suite
Simran Basi71206ef2014-08-13 13:51:18 -070041from autotest_lib.server.hosts import moblab_host
Dan Shidfea3682014-08-10 23:38:40 -070042from autotest_lib.site_utils import host_history
Dan Shi193905e2014-07-25 23:33:09 -070043from autotest_lib.site_utils import job_history
Dan Shid7bb4f12015-01-06 10:53:50 -080044from autotest_lib.site_utils import server_manager_utils
Dan Shi6964fa52014-12-18 11:04:27 -080045from autotest_lib.site_utils import stable_version_utils
Simran Basi71206ef2014-08-13 13:51:18 -070046
47
48_CONFIG = global_config.global_config
49MOBLAB_BOTO_LOCATION = '/home/moblab/.boto'
Chris Masone859fdec2012-01-30 08:38:09 -080050
Michael Tang9afc74b2016-03-21 10:19:23 -070051# Google Cloud Storage bucket url regex pattern. The pattern is used to extract
52# the bucket name from the bucket URL. For example, "gs://image_bucket/google"
53# should result in a bucket name "image_bucket".
54GOOGLE_STORAGE_BUCKET_URL_PATTERN = re.compile(
55 r'gs://(?P<bucket>[a-zA-Z][a-zA-Z0-9-_]*)/?.*')
56
57# Constants used in JSON RPC field names.
58_USE_EXISTING_BOTO_FILE = 'use_existing_boto_file'
59_GS_ACCESS_KEY_ID = 'gs_access_key_id'
60_GS_SECRETE_ACCESS_KEY = 'gs_secret_access_key'
61_IMAGE_STORAGE_SERVER = 'image_storage_server'
62_RESULT_STORAGE_SERVER = 'results_storage_server'
Chris Masonef8b53062012-05-08 22:14:18 -070063# Relevant CrosDynamicSuiteExceptions are defined in client/common_lib/error.py.
Chris Masone859fdec2012-01-30 08:38:09 -080064
65
Chris Masone62579122012-03-08 15:18:43 -080066def canonicalize_suite_name(suite_name):
Dan Shi70647ca2015-07-16 22:52:35 -070067 # Do not change this naming convention without updating
68 # site_utils.parse_job_name.
Chris Masone62579122012-03-08 15:18:43 -080069 return 'test_suites/control.%s' % suite_name
70
71
Chris Masoneaa10f8e2012-05-15 13:34:21 -070072def formatted_now():
Dan Shidfea3682014-08-10 23:38:40 -070073 return datetime.datetime.now().strftime(time_utils.TIME_FMT)
Chris Masoneaa10f8e2012-05-15 13:34:21 -070074
75
Simran Basib6ec8ae2014-04-23 12:05:08 -070076def _get_control_file_contents_by_name(build, ds, suite_name):
Chris Masone8dd27e02012-06-25 15:59:43 -070077 """Return control file contents for |suite_name|.
78
79 Query the dev server at |ds| for the control file |suite_name|, included
80 in |build| for |board|.
81
82 @param build: unique name by which to refer to the image from now on.
Chris Masone8dd27e02012-06-25 15:59:43 -070083 @param ds: a dev_server.DevServer instance to fetch control file with.
84 @param suite_name: canonicalized suite name, e.g. test_suites/control.bvt.
85 @raises ControlFileNotFound if a unique suite control file doesn't exist.
86 @raises NoControlFileList if we can't list the control files at all.
87 @raises ControlFileEmpty if the control file exists on the server, but
88 can't be read.
89
90 @return the contents of the desired control file.
91 """
92 getter = control_file_getter.DevServerGetter.create(build, ds)
Gabe Black1e1c41b2015-02-04 23:55:15 -080093 timer = autotest_stats.Timer('control_files.parse.%s.%s' %
94 (ds.get_server_name(ds.url()
95 ).replace('.', '_'),
96 suite_name.rsplit('.')[-1]))
Chris Masone8dd27e02012-06-25 15:59:43 -070097 # Get the control file for the suite.
98 try:
Prashanth Balasubramanianabe3bb72014-11-20 12:00:37 -080099 with timer:
100 control_file_in = getter.get_control_file_contents_by_name(
101 suite_name)
Chris Masone8dd27e02012-06-25 15:59:43 -0700102 except error.CrosDynamicSuiteException as e:
Simran Basib6ec8ae2014-04-23 12:05:08 -0700103 raise type(e)("%s while testing %s." % (e, build))
Chris Masone8dd27e02012-06-25 15:59:43 -0700104 if not control_file_in:
105 raise error.ControlFileEmpty(
106 "Fetching %s returned no data." % suite_name)
Alex Millera713e252013-03-01 10:45:44 -0800107 # Force control files to only contain ascii characters.
108 try:
109 control_file_in.encode('ascii')
110 except UnicodeDecodeError as e:
111 raise error.ControlFileMalformed(str(e))
112
Chris Masone8dd27e02012-06-25 15:59:43 -0700113 return control_file_in
114
115
Dan Shi5e8fa182016-04-15 11:04:36 -0700116def _stage_build_artifacts(build, hostname=None):
Simran Basib6ec8ae2014-04-23 12:05:08 -0700117 """
118 Ensure components of |build| necessary for installing images are staged.
119
120 @param build image we want to stage.
Dan Shi5e8fa182016-04-15 11:04:36 -0700121 @param hostname hostname of a dut may run test on. This is to help to locate
122 a devserver closer to duts if needed. Default is None.
Simran Basib6ec8ae2014-04-23 12:05:08 -0700123
Prashanth B6285f6a2014-05-08 18:01:27 -0700124 @raises StageControlFileFailure: if the dev server throws 500 while staging
125 suite control files.
Simran Basib6ec8ae2014-04-23 12:05:08 -0700126
127 @return: dev_server.ImageServer instance to use with this build.
128 @return: timings dictionary containing staging start/end times.
129 """
130 timings = {}
Prashanth B6285f6a2014-05-08 18:01:27 -0700131 # Ensure components of |build| necessary for installing images are staged
132 # on the dev server. However set synchronous to False to allow other
133 # components to be downloaded in the background.
Dan Shi5e8fa182016-04-15 11:04:36 -0700134 ds = dev_server.resolve(build, hostname=hostname)
Simran Basib6ec8ae2014-04-23 12:05:08 -0700135 timings[constants.DOWNLOAD_STARTED_TIME] = formatted_now()
Gabe Black1e1c41b2015-02-04 23:55:15 -0800136 timer = autotest_stats.Timer('control_files.stage.%s' % (
137 ds.get_server_name(ds.url()).replace('.', '_')))
Simran Basib6ec8ae2014-04-23 12:05:08 -0700138 try:
Prashanth Balasubramanianabe3bb72014-11-20 12:00:37 -0800139 with timer:
Dan Shi6450e142016-03-11 11:52:20 -0800140 ds.stage_artifacts(image=build, artifacts=['test_suites'])
Simran Basib6ec8ae2014-04-23 12:05:08 -0700141 except dev_server.DevServerException as e:
Prashanth B6285f6a2014-05-08 18:01:27 -0700142 raise error.StageControlFileFailure(
Simran Basib6ec8ae2014-04-23 12:05:08 -0700143 "Failed to stage %s: %s" % (build, e))
144 timings[constants.PAYLOAD_FINISHED_TIME] = formatted_now()
145 return (ds, timings)
146
147
MK Ryue301eb72015-06-25 12:51:02 -0700148@rpc_utils.route_rpc_to_master
Dan Shi5984d782016-04-05 18:43:51 -0700149def create_suite_job(name='', board='', pool='', control_file='',
Simran Basib6ec8ae2014-04-23 12:05:08 -0700150 check_hosts=True, num=None, file_bugs=False, timeout=24,
151 timeout_mins=None, priority=priorities.Priority.DEFAULT,
Fang Deng058860c2014-05-15 15:41:50 -0700152 suite_args=None, wait_for_results=True, job_retry=False,
Fang Deng443f1952015-01-02 14:51:49 -0800153 max_retries=None, max_runtime_mins=None, suite_min_duts=0,
Dan Shi36cfd832014-10-10 13:38:51 -0700154 offload_failures_only=False, builds={},
Dan Shi059261a2016-02-22 12:06:37 -0800155 test_source_build=None, run_prod_code=False,
156 delay_minutes=0, **kwargs):
Chris Masone859fdec2012-01-30 08:38:09 -0800157 """
158 Create a job to run a test suite on the given device with the given image.
159
160 When the timeout specified in the control file is reached, the
161 job is guaranteed to have completed and results will be available.
162
Simran Basib6ec8ae2014-04-23 12:05:08 -0700163 @param name: The test name if control_file is supplied, otherwise the name
164 of the test suite to run, e.g. 'bvt'.
Chris Masone859fdec2012-01-30 08:38:09 -0800165 @param board: the kind of device to run the tests on.
Dan Shi36cfd832014-10-10 13:38:51 -0700166 @param builds: the builds to install e.g.
167 {'cros-version:': 'x86-alex-release/R18-1655.0.0',
Dan Shi5984d782016-04-05 18:43:51 -0700168 'fwrw-version:': 'x86-alex-firmware/R36-5771.50.0',
Dan Shi36cfd832014-10-10 13:38:51 -0700169 'fwro-version:': 'x86-alex-firmware/R36-5771.49.0'}
170 If builds is given a value, it overrides argument build.
171 @param test_source_build: Build that contains the server-side test code.
Scott Zawalski65650172012-02-16 11:48:26 -0500172 @param pool: Specify the pool of machines to use for scheduling
173 purposes.
Chris Masone62579122012-03-08 15:18:43 -0800174 @param check_hosts: require appropriate live hosts to exist in the lab.
Aviv Keshetd83ef442013-01-16 16:19:35 -0800175 @param num: Specify the number of machines to schedule across (integer).
176 Leave unspecified or use None to use default sharding factor.
Alex Millerc577f3e2012-09-27 14:06:07 -0700177 @param file_bugs: File a bug on each test failure in this suite.
Alex Miller139690b2013-09-07 15:35:49 -0700178 @param timeout: The max lifetime of this suite, in hours.
Simran Basi7e605742013-11-12 13:43:36 -0800179 @param timeout_mins: The max lifetime of this suite, in minutes. Takes
180 priority over timeout.
Alex Miller139690b2013-09-07 15:35:49 -0700181 @param priority: Integer denoting priority. Higher is more important.
Aviv Keshet7cd12312013-07-25 10:25:55 -0700182 @param suite_args: Optional arguments which will be parsed by the suite
183 control file. Used by control.test_that_wrapper to
184 determine which tests to run.
Dan Shi95122412013-11-12 16:20:33 -0800185 @param wait_for_results: Set to False to run the suite job without waiting
186 for test jobs to finish. Default is True.
Fang Deng058860c2014-05-15 15:41:50 -0700187 @param job_retry: Set to True to enable job-level retry. Default is False.
Fang Deng443f1952015-01-02 14:51:49 -0800188 @param max_retries: Integer, maximum job retries allowed at suite level.
189 None for no max.
Simran Basi102e3522014-09-11 11:46:10 -0700190 @param max_runtime_mins: Maximum amount of time a job can be running in
191 minutes.
Fang Dengcbc01212014-11-25 16:09:46 -0800192 @param suite_min_duts: Integer. Scheduler will prioritize getting the
193 minimum number of machines for the suite when it is
194 competing with another suite that has a higher
195 priority but already got minimum machines it needs.
Simran Basi1e10e922015-04-16 15:09:56 -0700196 @param offload_failures_only: Only enable gs_offloading for failed jobs.
Simran Basi5ace6f22016-01-06 17:30:44 -0800197 @param run_prod_code: If True, the suite will run the test code that
198 lives in prod aka the test code currently on the
199 lab servers. If False, the control files and test
200 code for this suite run will be retrieved from the
201 build artifacts.
Dan Shi059261a2016-02-22 12:06:37 -0800202 @param delay_minutes: Delay the creation of test jobs for a given number of
203 minutes.
Simran Basib6ec8ae2014-04-23 12:05:08 -0700204 @param kwargs: extra keyword args. NOT USED.
Chris Masone859fdec2012-01-30 08:38:09 -0800205
Chris Masone8dd27e02012-06-25 15:59:43 -0700206 @raises ControlFileNotFound: if a unique suite control file doesn't exist.
207 @raises NoControlFileList: if we can't list the control files at all.
Prashanth B6285f6a2014-05-08 18:01:27 -0700208 @raises StageControlFileFailure: If the dev server throws 500 while
209 staging test_suites.
Chris Masone8dd27e02012-06-25 15:59:43 -0700210 @raises ControlFileEmpty: if the control file exists on the server, but
211 can't be read.
Chris Masone859fdec2012-01-30 08:38:09 -0800212
213 @return: the job ID of the suite; -1 on error.
214 """
Aviv Keshetd83ef442013-01-16 16:19:35 -0800215 if type(num) is not int and num is not None:
Chris Sosa18c70b32013-02-15 14:12:43 -0800216 raise error.SuiteArgumentException('Ill specified num argument %r. '
217 'Must be an integer or None.' % num)
Aviv Keshetd83ef442013-01-16 16:19:35 -0800218 if num == 0:
219 logging.warning("Can't run on 0 hosts; using default.")
220 num = None
Dan Shi36cfd832014-10-10 13:38:51 -0700221
Dan Shi2121a332016-02-25 14:22:22 -0800222 # Default test source build to CrOS build if it's not specified and
223 # run_prod_code is set to False.
224 if not run_prod_code:
225 test_source_build = Suite.get_test_source_build(
226 builds, test_source_build=test_source_build)
Dan Shi36cfd832014-10-10 13:38:51 -0700227
Dan Shi5e8fa182016-04-15 11:04:36 -0700228 # If 'prefer_local_devserver' is True in global setting, and both board
229 # and pool are specified, pick a dut in the given board and pool, and
230 # use that to help to pick a devserver in the same subnet of the duts
231 # to be used to run tests.
232 if dev_server.PREFER_LOCAL_DEVSERVER and pool and board:
233 sample_dut = rpc_utils.get_sample_dut(board, pool)
234 else:
235 sample_dut = None
236
Simran Basi5ace6f22016-01-06 17:30:44 -0800237 suite_name = canonicalize_suite_name(name)
238 if run_prod_code:
Dan Shi5e8fa182016-04-15 11:04:36 -0700239 ds = dev_server.resolve(test_source_build, hostname=sample_dut)
Simran Basi5ace6f22016-01-06 17:30:44 -0800240 keyvals = {}
241 getter = control_file_getter.FileSystemGetter(
242 [_CONFIG.get_config_value('SCHEDULER',
243 'drone_installation_directory')])
244 control_file = getter.get_control_file_contents_by_name(suite_name)
245 else:
Dan Shi5e8fa182016-04-15 11:04:36 -0700246 (ds, keyvals) = _stage_build_artifacts(
247 test_source_build, hostname=sample_dut)
Fang Dengcbc01212014-11-25 16:09:46 -0800248 keyvals[constants.SUITE_MIN_DUTS_KEY] = suite_min_duts
Chris Masone859fdec2012-01-30 08:38:09 -0800249
Simran Basib6ec8ae2014-04-23 12:05:08 -0700250 if not control_file:
Dan Shi36cfd832014-10-10 13:38:51 -0700251 # No control file was supplied so look it up from the build artifacts.
252 suite_name = canonicalize_suite_name(name)
253 control_file = _get_control_file_contents_by_name(test_source_build,
254 ds, suite_name)
Simran Basi86fe9c92016-02-09 17:58:20 -0800255 # Do not change this naming convention without updating
256 # site_utils.parse_job_name.
Dan Shi2121a332016-02-25 14:22:22 -0800257 if not run_prod_code:
258 name = '%s-%s' % (test_source_build, suite_name)
259 else:
260 # If run_prod_code is True, test_source_build is not set, use the
261 # first build in the builds list for the sutie job name.
262 name = '%s-%s' % (builds.values()[0], suite_name)
Chris Masone46d0eb12012-07-27 18:56:39 -0700263
Simran Basi7e605742013-11-12 13:43:36 -0800264 timeout_mins = timeout_mins or timeout * 60
Simran Basi102e3522014-09-11 11:46:10 -0700265 max_runtime_mins = max_runtime_mins or timeout * 60
Simran Basi7e605742013-11-12 13:43:36 -0800266
Simran Basib6ec8ae2014-04-23 12:05:08 -0700267 if not board:
Dan Shid215dbe2015-06-18 16:14:59 -0700268 board = utils.ParseBuildName(builds[provision.CROS_VERSION_PREFIX])[0]
Chris Masone46d0eb12012-07-27 18:56:39 -0700269
Dan Shi5984d782016-04-05 18:43:51 -0700270 # Prepend builds and board to the control file.
Scott Zawalski65650172012-02-16 11:48:26 -0500271 inject_dict = {'board': board,
Dan Shi6dc22d12016-04-06 22:10:04 -0700272 # `build` is needed for suites like AU to stage image inside
273 # suite control file.
274 'build': test_source_build,
Dan Shi36cfd832014-10-10 13:38:51 -0700275 'builds': builds,
Chris Masone62579122012-03-08 15:18:43 -0800276 'check_hosts': check_hosts,
Chris Masone46d0eb12012-07-27 18:56:39 -0700277 'pool': pool,
Aviv Keshetd83ef442013-01-16 16:19:35 -0800278 'num': num,
Dan Shib8a99112013-06-18 13:46:10 -0700279 'file_bugs': file_bugs,
Alex Miller139690b2013-09-07 15:35:49 -0700280 'timeout': timeout,
Simran Basi7e605742013-11-12 13:43:36 -0800281 'timeout_mins': timeout_mins,
Alex Miller7d658cf2013-09-04 16:00:35 -0700282 'devserver_url': ds.url(),
Aviv Keshet7cd12312013-07-25 10:25:55 -0700283 'priority': priority,
Dan Shi95122412013-11-12 16:20:33 -0800284 'suite_args' : suite_args,
Fang Deng058860c2014-05-15 15:41:50 -0700285 'wait_for_results': wait_for_results,
Simran Basi102e3522014-09-11 11:46:10 -0700286 'job_retry': job_retry,
Fang Deng443f1952015-01-02 14:51:49 -0800287 'max_retries': max_retries,
Fang Dengcbc01212014-11-25 16:09:46 -0800288 'max_runtime_mins': max_runtime_mins,
Dan Shi36cfd832014-10-10 13:38:51 -0700289 'offload_failures_only': offload_failures_only,
Simran Basi5ace6f22016-01-06 17:30:44 -0800290 'test_source_build': test_source_build,
Dan Shi059261a2016-02-22 12:06:37 -0800291 'run_prod_code': run_prod_code,
292 'delay_minutes': delay_minutes,
Aviv Keshet7cd12312013-07-25 10:25:55 -0700293 }
294
Simran Basib6ec8ae2014-04-23 12:05:08 -0700295 control_file = tools.inject_vars(inject_dict, control_file)
Chris Masone859fdec2012-01-30 08:38:09 -0800296
Jakob Juelich9fffe4f2014-08-14 18:07:05 -0700297 return rpc_utils.create_job_common(name,
Jakob Juelich59cfe542014-09-02 16:37:46 -0700298 priority=priority,
299 timeout_mins=timeout_mins,
300 max_runtime_mins=max_runtime_mins,
301 control_type='Server',
302 control_file=control_file,
303 hostless=True,
Fang Dengcbc01212014-11-25 16:09:46 -0800304 keyvals=keyvals)
Simran Basi71206ef2014-08-13 13:51:18 -0700305
306
307# TODO: hide the following rpcs under is_moblab
308def moblab_only(func):
309 """Ensure moblab specific functions only run on Moblab devices."""
310 def verify(*args, **kwargs):
311 if not utils.is_moblab():
312 raise error.RPCException('RPC: %s can only run on Moblab Systems!',
313 func.__name__)
314 return func(*args, **kwargs)
315 return verify
316
317
318@moblab_only
319def get_config_values():
320 """Returns all config values parsed from global and shadow configs.
321
322 Config values are grouped by sections, and each section is composed of
323 a list of name value pairs.
324 """
325 sections =_CONFIG.get_sections()
326 config_values = {}
327 for section in sections:
328 config_values[section] = _CONFIG.config.items(section)
Jakob Juelich9fffe4f2014-08-14 18:07:05 -0700329 return rpc_utils.prepare_for_serialization(config_values)
Simran Basi71206ef2014-08-13 13:51:18 -0700330
331
Michael Tang9afc74b2016-03-21 10:19:23 -0700332def _write_config_file(config_file, config_values, overwrite=False):
333 """Writes out a configuration file.
Simran Basi71206ef2014-08-13 13:51:18 -0700334
Michael Tang9afc74b2016-03-21 10:19:23 -0700335 @param config_file: The name of the configuration file.
336 @param config_values: The ConfigParser object.
337 @param ovewrite: Flag on if overwriting is allowed.
338 """
339 if not config_file:
340 raise error.RPCException('Empty config file name.')
341 if not overwrite and os.path.exists(config_file):
342 raise error.RPCException('Config file already exists.')
343
344 if config_values:
345 with open(config_file, 'w') as config_file:
346 config_values.write(config_file)
347
348
349def _read_original_config():
350 """Reads the orginal configuratino without shadow.
351
352 @return: A configuration object, see global_config_class.
Simran Basi71206ef2014-08-13 13:51:18 -0700353 """
Simran Basi773a86e2015-05-13 19:15:42 -0700354 original_config = global_config.global_config_class()
355 original_config.set_config_files(shadow_file='')
Michael Tang9afc74b2016-03-21 10:19:23 -0700356 return original_config
357
358
359def _read_raw_config(config_file):
360 """Reads the raw configuration from a configuration file.
361
362 @param: config_file: The path of the configuration file.
363
364 @return: A ConfigParser object.
365 """
366 shadow_config = ConfigParser.RawConfigParser()
367 shadow_config.read(config_file)
368 return shadow_config
369
370
371def _get_shadow_config_from_partial_update(config_values):
372 """Finds out the new shadow configuration based on a partial update.
373
374 Since the input is only a partial config, we should not lose the config
375 data inside the existing shadow config file. We also need to distinguish
376 if the input config info overrides with a new value or reverts back to
377 an original value.
378
379 @param config_values: See get_moblab_settings().
380
381 @return: The new shadow configuration as ConfigParser object.
382 """
383 original_config = _read_original_config()
384 existing_shadow = _read_raw_config(_CONFIG.shadow_file)
385 for section, config_value_list in config_values.iteritems():
386 for key, value in config_value_list:
387 if original_config.get_config_value(section, key,
388 default='',
389 allow_blank=True) != value:
390 if not existing_shadow.has_section(section):
391 existing_shadow.add_section(section)
392 existing_shadow.set(section, key, value)
393 elif existing_shadow.has_option(section, key):
394 existing_shadow.remove_option(section, key)
395 return existing_shadow
396
397
398def _update_partial_config(config_values):
399 """Updates the shadow configuration file with a partial config udpate.
400
401 @param config_values: See get_moblab_settings().
402 """
403 existing_config = _get_shadow_config_from_partial_update(config_values)
404 _write_config_file(_CONFIG.shadow_file, existing_config, True)
405
406
407@moblab_only
408def update_config_handler(config_values):
409 """Update config values and override shadow config.
410
411 @param config_values: See get_moblab_settings().
412 """
413 original_config = _read_original_config()
Simran Basi773a86e2015-05-13 19:15:42 -0700414 new_shadow = ConfigParser.RawConfigParser()
Simran Basi71206ef2014-08-13 13:51:18 -0700415 for section, config_value_list in config_values.iteritems():
416 for key, value in config_value_list:
Simran Basi773a86e2015-05-13 19:15:42 -0700417 if original_config.get_config_value(section, key,
418 default='',
419 allow_blank=True) != value:
420 if not new_shadow.has_section(section):
421 new_shadow.add_section(section)
422 new_shadow.set(section, key, value)
Michael Tang9afc74b2016-03-21 10:19:23 -0700423
Simran Basi71206ef2014-08-13 13:51:18 -0700424 if not _CONFIG.shadow_file or not os.path.exists(_CONFIG.shadow_file):
425 raise error.RPCException('Shadow config file does not exist.')
Michael Tang9afc74b2016-03-21 10:19:23 -0700426 _write_config_file(_CONFIG.shadow_file, new_shadow, True)
Simran Basi71206ef2014-08-13 13:51:18 -0700427
Simran Basi71206ef2014-08-13 13:51:18 -0700428 # TODO (sbasi) crbug.com/403916 - Remove the reboot command and
429 # instead restart the services that rely on the config values.
430 os.system('sudo reboot')
431
432
433@moblab_only
434def reset_config_settings():
435 with open(_CONFIG.shadow_file, 'w') as config_file:
Dan Shi36cfd832014-10-10 13:38:51 -0700436 pass
Simran Basi71206ef2014-08-13 13:51:18 -0700437 os.system('sudo reboot')
438
439
440@moblab_only
Michael Tangc05c9ef2016-03-25 14:31:14 -0700441def reboot_moblab():
442 """Simply reboot the device."""
443 os.system('sudo reboot')
444
445@moblab_only
Simran Basi71206ef2014-08-13 13:51:18 -0700446def set_boto_key(boto_key):
447 """Update the boto_key file.
448
449 @param boto_key: File name of boto_key uploaded through handle_file_upload.
450 """
451 if not os.path.exists(boto_key):
452 raise error.RPCException('Boto key: %s does not exist!' % boto_key)
453 shutil.copyfile(boto_key, moblab_host.MOBLAB_BOTO_LOCATION)
Dan Shi193905e2014-07-25 23:33:09 -0700454
455
Dan Shiaec99012016-01-07 09:09:16 -0800456@moblab_only
457def set_launch_control_key(launch_control_key):
458 """Update the launch_control_key file.
459
460 @param launch_control_key: File name of launch_control_key uploaded through
461 handle_file_upload.
462 """
463 if not os.path.exists(launch_control_key):
464 raise error.RPCException('Launch Control key: %s does not exist!' %
465 launch_control_key)
466 shutil.copyfile(launch_control_key,
467 moblab_host.MOBLAB_LAUNCH_CONTROL_KEY_LOCATION)
468 # Restart the devserver service.
469 os.system('sudo restart moblab-devserver-init')
470
471
Michael Tang9afc74b2016-03-21 10:19:23 -0700472###########Moblab Config Wizard RPCs #######################
473def _get_public_ip_address(socket_handle):
474 """Gets the public IP address.
475
476 Connects to Google DNS server using a socket and gets the preferred IP
477 address from the connection.
478
479 @param: socket_handle: a unix socket.
480
481 @return: public ip address as string.
482 """
483 try:
484 socket_handle.settimeout(1)
485 socket_handle.connect(('8.8.8.8', 53))
486 socket_name = socket_handle.getsockname()
487 if socket_name is not None:
488 logging.info('Got socket name from UDP socket.')
489 return socket_name[0]
490 logging.warn('Created UDP socket but with no socket_name.')
491 except socket.error:
492 logging.warn('Could not get socket name from UDP socket.')
493 return None
494
495
496def _get_network_info():
497 """Gets the network information.
498
499 TCP socket is used to test the connectivity. If there is no connectivity, try to
500 get the public IP with UDP socket.
501
502 @return: a tuple as (public_ip_address, connected_to_internet).
503 """
504 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
505 ip = _get_public_ip_address(s)
506 if ip is not None:
507 logging.info('Established TCP connection with well known server.')
508 return (ip, True)
509 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
510 return (_get_public_ip_address(s), False)
511
512
513@moblab_only
514def get_network_info():
515 """Returns the server ip addresses, and if the server connectivity.
516
517 The server ip addresses as an array of strings, and the connectivity as a
518 flag.
519 """
520 network_info = {}
521 info = _get_network_info()
522 if info[0] is not None:
523 network_info['server_ips'] = [info[0]]
524 network_info['is_connected'] = info[1]
525
526 return rpc_utils.prepare_for_serialization(network_info)
527
528
529# Gets the boto configuration.
530def _get_boto_config():
531 """Reads the boto configuration from the boto file.
532
533 @return: Boto configuration as ConfigParser object.
534 """
535 boto_config = ConfigParser.ConfigParser()
536 boto_config.read(MOBLAB_BOTO_LOCATION)
537 return boto_config
538
539
540@moblab_only
541def get_cloud_storage_info():
542 """RPC handler to get the cloud storage access information.
543 """
544 cloud_storage_info = {}
545 value =_CONFIG.get_config_value('CROS', _IMAGE_STORAGE_SERVER)
546 if value is not None:
547 cloud_storage_info[_IMAGE_STORAGE_SERVER] = value
548 value =_CONFIG.get_config_value('CROS', _RESULT_STORAGE_SERVER)
549 if value is not None:
550 cloud_storage_info[_RESULT_STORAGE_SERVER] = value
551
552 boto_config = _get_boto_config()
553 sections = boto_config.sections()
554
555 if sections:
556 cloud_storage_info[_USE_EXISTING_BOTO_FILE] = True
557 else:
558 cloud_storage_info[_USE_EXISTING_BOTO_FILE] = False
559 if 'Credentials' in sections:
560 options = boto_config.options('Credentials')
561 if _GS_ACCESS_KEY_ID in options:
562 value = boto_config.get('Credentials', _GS_ACCESS_KEY_ID)
563 cloud_storage_info[_GS_ACCESS_KEY_ID] = value
564 if _GS_SECRETE_ACCESS_KEY in options:
565 value = boto_config.get('Credentials', _GS_SECRETE_ACCESS_KEY)
566 cloud_storage_info[_GS_SECRETE_ACCESS_KEY] = value
567
568 return rpc_utils.prepare_for_serialization(cloud_storage_info)
569
570
571def _get_bucket_name_from_url(bucket_url):
572 """Gets the bucket name from a bucket url.
573
574 @param: bucket_url: the bucket url string.
575 """
576 if bucket_url:
577 match = GOOGLE_STORAGE_BUCKET_URL_PATTERN.match(bucket_url)
578 if match:
579 return match.group('bucket')
580 return None
581
582
583def _is_valid_boto_key(key_id, key_secret):
584 """Checks if the boto key is valid.
585
586 @param: key_id: The boto key id string.
587 @param: key_secret: The boto key string.
588
589 @return: A tuple as (valid_boolean, details_string).
590 """
591 if not key_id or not key_secret:
592 return (False, "Empty key id or secret.")
593 conn = boto.connect_gs(key_id, key_secret)
594 try:
595 buckets = conn.get_all_buckets()
596 return (True, None)
597 except boto.exception.GSResponseError:
598 details = "The boto access key is not valid"
599 return (False, details)
600 finally:
601 conn.close()
602
603
604def _is_valid_bucket(key_id, key_secret, bucket_name):
605 """Checks if a bucket is valid and accessible.
606
607 @param: key_id: The boto key id string.
608 @param: key_secret: The boto key string.
609 @param: bucket name string.
610
611 @return: A tuple as (valid_boolean, details_string).
612 """
613 if not key_id or not key_secret or not bucket_name:
614 return (False, "Server error: invalid argument")
615 conn = boto.connect_gs(key_id, key_secret)
616 bucket = conn.lookup(bucket_name)
617 conn.close()
618 if bucket:
619 return (True, None)
620 return (False, "Bucket %s does not exist." % bucket_name)
621
622
623def _is_valid_bucket_url(key_id, key_secret, bucket_url):
624 """Validates the bucket url is accessible.
625
626 @param: key_id: The boto key id string.
627 @param: key_secret: The boto key string.
628 @param: bucket url string.
629
630 @return: A tuple as (valid_boolean, details_string).
631 """
632 bucket_name = _get_bucket_name_from_url(bucket_url)
633 if bucket_name:
634 return _is_valid_bucket(key_id, key_secret, bucket_name)
635 return (False, "Bucket url %s is not valid" % bucket_url)
636
637
638def _validate_cloud_storage_info(cloud_storage_info):
639 """Checks if the cloud storage information is valid.
640
641 @param: cloud_storage_info: The JSON RPC object for cloud storage info.
642
643 @return: A tuple as (valid_boolean, details_string).
644 """
645 valid = True
646 details = None
647 if not cloud_storage_info[_USE_EXISTING_BOTO_FILE]:
648 key_id = cloud_storage_info[_GS_ACCESS_KEY_ID]
649 key_secret = cloud_storage_info[_GS_SECRETE_ACCESS_KEY]
650 valid, details = _is_valid_boto_key(key_id, key_secret)
651
652 if valid:
653 valid, details = _is_valid_bucket_url(
654 key_id, key_secret, cloud_storage_info[_IMAGE_STORAGE_SERVER])
655
656 if valid:
657 valid, details = _is_valid_bucket_url(
658 key_id, key_secret, cloud_storage_info[_RESULT_STORAGE_SERVER])
659 return (valid, details)
660
661
662def _create_operation_status_response(is_ok, details):
663 """Helper method to create a operation status reponse.
664
665 @param: is_ok: Boolean for if the operation is ok.
666 @param: details: A detailed string.
667
668 @return: A serialized JSON RPC object.
669 """
670 status_response = {'status_ok': is_ok}
671 if details:
672 status_response['status_details'] = details
673 return rpc_utils.prepare_for_serialization(status_response)
674
675
676@moblab_only
677def validate_cloud_storage_info(cloud_storage_info):
678 """RPC handler to check if the cloud storage info is valid.
679 """
680 valid, details = _validate_cloud_storage_info(cloud_storage_info)
681 return _create_operation_status_response(valid, details)
682
683
684@moblab_only
685def submit_wizard_config_info(cloud_storage_info):
686 """RPC handler to submit the cloud storage info.
687 """
688 valid, details = _validate_cloud_storage_info(cloud_storage_info)
689 if not valid:
690 return _create_operation_status_response(valid, details)
691 config_update = {}
692 config_update['CROS'] = [
693 (_IMAGE_STORAGE_SERVER, cloud_storage_info[_IMAGE_STORAGE_SERVER]),
694 (_RESULT_STORAGE_SERVER, cloud_storage_info[_RESULT_STORAGE_SERVER])
695 ]
696 _update_partial_config(config_update)
697
698 if not cloud_storage_info[_USE_EXISTING_BOTO_FILE]:
699 boto_config = ConfigParser.RawConfigParser()
700 boto_config.add_section('Credentials')
701 boto_config.set('Credentials', _GS_ACCESS_KEY_ID,
702 cloud_storage_info[_GS_ACCESS_KEY_ID])
703 boto_config.set('Credentials', _GS_SECRETE_ACCESS_KEY,
704 cloud_storage_info[_GS_SECRETE_ACCESS_KEY])
705 _write_config_file(MOBLAB_BOTO_LOCATION, boto_config, True)
706
707 _CONFIG.parse_config_file()
708
Michael Tangc05c9ef2016-03-25 14:31:14 -0700709 # TODO(ntang): replace reboot with less intrusive reloading.
710 os.system('sudo reboot')
711
Michael Tang9afc74b2016-03-21 10:19:23 -0700712 return _create_operation_status_response(True, None)
713
714
Dan Shi193905e2014-07-25 23:33:09 -0700715def get_job_history(**filter_data):
716 """Get history of the job, including the special tasks executed for the job
717
718 @param filter_data: filter for the call, should at least include
719 {'job_id': [job id]}
720 @returns: JSON string of the job's history, including the information such
721 as the hosts run the job and the special tasks executed before
722 and after the job.
723 """
724 job_id = filter_data['job_id']
725 job_info = job_history.get_job_info(job_id)
Dan Shidfea3682014-08-10 23:38:40 -0700726 return rpc_utils.prepare_for_serialization(job_info.get_history())
727
728
729def get_host_history(start_time, end_time, hosts=None, board=None, pool=None):
730 """Get history of a list of host.
731
732 The return is a JSON string of host history for each host, for example,
733 {'172.22.33.51': [{'status': 'Resetting'
734 'start_time': '2014-08-07 10:02:16',
735 'end_time': '2014-08-07 10:03:16',
736 'log_url': 'http://autotest/reset-546546/debug',
737 'dbg_str': 'Task: Special Task 19441991 (host ...)'},
738 {'status': 'Running'
739 'start_time': '2014-08-07 10:03:18',
740 'end_time': '2014-08-07 10:13:00',
741 'log_url': 'http://autotest/reset-546546/debug',
742 'dbg_str': 'HQE: 15305005, for job: 14995562'}
743 ]
744 }
745 @param start_time: start time to search for history, can be string value or
746 epoch time.
747 @param end_time: end time to search for history, can be string value or
748 epoch time.
749 @param hosts: A list of hosts to search for history. Default is None.
750 @param board: board type of hosts. Default is None.
751 @param pool: pool type of hosts. Default is None.
752 @returns: JSON string of the host history.
753 """
754 return rpc_utils.prepare_for_serialization(
755 host_history.get_history_details(
756 start_time=start_time, end_time=end_time,
757 hosts=hosts, board=board, pool=pool,
758 process_pool_size=4))
Jakob Juelich59cfe542014-09-02 16:37:46 -0700759
760
MK Ryu07a109f2015-07-21 17:44:32 -0700761def shard_heartbeat(shard_hostname, jobs=(), hqes=(), known_job_ids=(),
762 known_host_ids=(), known_host_statuses=()):
Jakob Juelich1b525742014-09-30 13:08:07 -0700763 """Receive updates for job statuses from shards and assign hosts and jobs.
Jakob Juelich59cfe542014-09-02 16:37:46 -0700764
765 @param shard_hostname: Hostname of the calling shard
Jakob Juelicha94efe62014-09-18 16:02:49 -0700766 @param jobs: Jobs in serialized form that should be updated with newer
767 status from a shard.
768 @param hqes: Hostqueueentries in serialized form that should be updated with
769 newer status from a shard. Note that for every hostqueueentry
770 the corresponding job must be in jobs.
Jakob Juelich1b525742014-09-30 13:08:07 -0700771 @param known_job_ids: List of ids of jobs the shard already has.
772 @param known_host_ids: List of ids of hosts the shard already has.
MK Ryu07a109f2015-07-21 17:44:32 -0700773 @param known_host_statuses: List of statuses of hosts the shard already has.
Jakob Juelicha94efe62014-09-18 16:02:49 -0700774
Fang Dengf3705992014-12-16 17:32:18 -0800775 @returns: Serialized representations of hosts, jobs, suite job keyvals
776 and their dependencies to be inserted into a shard's database.
Jakob Juelich59cfe542014-09-02 16:37:46 -0700777 """
Jakob Juelich1b525742014-09-30 13:08:07 -0700778 # The following alternatives to sending host and job ids in every heartbeat
779 # have been considered:
780 # 1. Sending the highest known job and host ids. This would work for jobs:
781 # Newer jobs always have larger ids. Also, if a job is not assigned to a
782 # particular shard during a heartbeat, it never will be assigned to this
783 # shard later.
784 # This is not true for hosts though: A host that is leased won't be sent
785 # to the shard now, but might be sent in a future heartbeat. This means
786 # sometimes hosts should be transfered that have a lower id than the
787 # maximum host id the shard knows.
788 # 2. Send the number of jobs/hosts the shard knows to the master in each
789 # heartbeat. Compare these to the number of records that already have
790 # the shard_id set to this shard. In the normal case, they should match.
791 # In case they don't, resend all entities of that type.
792 # This would work well for hosts, because there aren't that many.
793 # Resending all jobs is quite a big overhead though.
794 # Also, this approach might run into edge cases when entities are
795 # ever deleted.
796 # 3. Mixtures of the above: Use 1 for jobs and 2 for hosts.
797 # Using two different approaches isn't consistent and might cause
798 # confusion. Also the issues with the case of deletions might still
799 # occur.
800 #
801 # The overhead of sending all job and host ids in every heartbeat is low:
802 # At peaks one board has about 1200 created but unfinished jobs.
803 # See the numbers here: http://goo.gl/gQCGWH
804 # Assuming that job id's have 6 digits and that json serialization takes a
805 # comma and a space as overhead, the traffic per id sent is about 8 bytes.
806 # If 5000 ids need to be sent, this means 40 kilobytes of traffic.
807 # A NOT IN query with 5000 ids took about 30ms in tests made.
808 # These numbers seem low enough to outweigh the disadvantages of the
809 # solutions described above.
Gabe Black1e1c41b2015-02-04 23:55:15 -0800810 timer = autotest_stats.Timer('shard_heartbeat')
Jakob Juelich59cfe542014-09-02 16:37:46 -0700811 with timer:
812 shard_obj = rpc_utils.retrieve_shard(shard_hostname=shard_hostname)
Jakob Juelicha94efe62014-09-18 16:02:49 -0700813 rpc_utils.persist_records_sent_from_shard(shard_obj, jobs, hqes)
MK Ryu07a109f2015-07-21 17:44:32 -0700814 assert len(known_host_ids) == len(known_host_statuses)
815 for i in range(len(known_host_ids)):
816 host_model = models.Host.objects.get(pk=known_host_ids[i])
817 if host_model.status != known_host_statuses[i]:
818 host_model.status = known_host_statuses[i]
819 host_model.save()
820
Fang Dengf3705992014-12-16 17:32:18 -0800821 hosts, jobs, suite_keyvals = rpc_utils.find_records_for_shard(
MK Ryu07a109f2015-07-21 17:44:32 -0700822 shard_obj, known_job_ids=known_job_ids,
823 known_host_ids=known_host_ids)
Jakob Juelich59cfe542014-09-02 16:37:46 -0700824 return {
825 'hosts': [host.serialize() for host in hosts],
826 'jobs': [job.serialize() for job in jobs],
Fang Dengf3705992014-12-16 17:32:18 -0800827 'suite_keyvals': [kv.serialize() for kv in suite_keyvals],
Jakob Juelich59cfe542014-09-02 16:37:46 -0700828 }
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700829
830
831def get_shards(**filter_data):
832 """Return a list of all shards.
833
834 @returns A sequence of nested dictionaries of shard information.
835 """
836 shards = models.Shard.query_objects(filter_data)
837 serialized_shards = rpc_utils.prepare_rows_as_nested_dicts(shards, ())
838 for serialized, shard in zip(serialized_shards, shards):
839 serialized['labels'] = [label.name for label in shard.labels.all()]
840
841 return serialized_shards
842
843
MK Ryu5dfcc892015-07-16 15:34:04 -0700844def add_shard(hostname, labels):
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700845 """Add a shard and start running jobs on it.
846
847 @param hostname: The hostname of the shard to be added; needs to be unique.
MK Ryu5dfcc892015-07-16 15:34:04 -0700848 @param labels: Board labels separated by a comma. Jobs of one of the labels
849 will be assigned to the shard.
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700850
Jakob Juelich8b110ee2014-09-15 16:13:42 -0700851 @raises error.RPCException: If label provided doesn't start with `board:`
852 @raises model_logic.ValidationError: If a shard with the given hostname
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700853 already exists.
Jakob Juelich8b110ee2014-09-15 16:13:42 -0700854 @raises models.Label.DoesNotExist: If the label specified doesn't exist.
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700855 """
MK Ryu5dfcc892015-07-16 15:34:04 -0700856 labels = labels.split(',')
857 label_models = []
858 for label in labels:
859 if not label.startswith('board:'):
860 raise error.RPCException('Sharding only supports for `board:.*` '
861 'labels.')
862 # Fetch label first, so shard isn't created when label doesn't exist.
863 label_models.append(models.Label.smart_get(label))
Jakob Juelich8b110ee2014-09-15 16:13:42 -0700864
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700865 shard = models.Shard.add_object(hostname=hostname)
MK Ryu5dfcc892015-07-16 15:34:04 -0700866 for label in label_models:
867 shard.labels.add(label)
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700868 return shard.id
869
870
871def delete_shard(hostname):
872 """Delete a shard and reclaim all resources from it.
873
874 This claims back all assigned hosts from the shard. To ensure all DUTs are
xixuan03cb93f2016-03-22 16:21:41 -0700875 in a sane state, a Reboot task with highest priority is scheduled for them.
876 This reboots the DUTs and then all left tasks continue to run in drone of
877 the master.
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700878
xixuan03cb93f2016-03-22 16:21:41 -0700879 The procedure for deleting a shard:
880 * Lock all unlocked hosts on that shard.
881 * Remove shard information .
882 * Assign a reboot task with highest priority to these hosts.
883 * Unlock these hosts, then, the reboot tasks run in front of all other
884 tasks.
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700885
886 The status of jobs that haven't been reported to be finished yet, will be
887 lost. The master scheduler will pick up the jobs and execute them.
888
889 @param hostname: Hostname of the shard to delete.
890 """
891 shard = rpc_utils.retrieve_shard(shard_hostname=hostname)
xixuan03cb93f2016-03-22 16:21:41 -0700892 hostnames_to_lock = [h.hostname for h in
893 models.Host.objects.filter(shard=shard, locked=False)]
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700894
895 # TODO(beeps): Power off shard
xixuan03cb93f2016-03-22 16:21:41 -0700896 # For ChromeOS hosts, a reboot test with the highest priority is added to
897 # the DUT. After a reboot it should be ganranteed that no processes from
898 # prior tests that were run by a shard are still running on.
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700899
xixuan03cb93f2016-03-22 16:21:41 -0700900 # Lock all unlocked hosts.
901 dicts = {'locked': True, 'lock_time': datetime.datetime.now()}
902 models.Host.objects.filter(hostname__in=hostnames_to_lock).update(**dicts)
903
904 # Remove shard information.
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700905 models.Host.objects.filter(shard=shard).update(shard=None)
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700906 models.Job.objects.filter(shard=shard).update(shard=None)
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700907 shard.labels.clear()
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700908 shard.delete()
Dan Shi6964fa52014-12-18 11:04:27 -0800909
xixuan03cb93f2016-03-22 16:21:41 -0700910 # Assign a reboot task with highest priority: Super.
911 t = models.Test.objects.get(name='platform_BootPerfServer:shard')
912 c = utils.read_file(os.path.join(common.autotest_dir, t.path))
913 if hostnames_to_lock:
914 rpc_utils.create_job_common(
915 'reboot_dut_for_shard_deletion',
916 priority=priorities.Priority.SUPER,
917 control_type='Server',
918 control_file=c, hosts=hostnames_to_lock)
919
920 # Unlock these shard-related hosts.
921 dicts = {'locked': False, 'lock_time': None}
922 models.Host.objects.filter(hostname__in=hostnames_to_lock).update(**dicts)
923
Dan Shi6964fa52014-12-18 11:04:27 -0800924
MK Ryua34e3b12015-08-21 16:20:47 -0700925def get_servers(hostname=None, role=None, status=None):
Dan Shid7bb4f12015-01-06 10:53:50 -0800926 """Get a list of servers with matching role and status.
927
MK Ryua34e3b12015-08-21 16:20:47 -0700928 @param hostname: FQDN of the server.
Dan Shid7bb4f12015-01-06 10:53:50 -0800929 @param role: Name of the server role, e.g., drone, scheduler. Default to
930 None to match any role.
931 @param status: Status of the server, e.g., primary, backup, repair_required.
932 Default to None to match any server status.
933
934 @raises error.RPCException: If server database is not used.
935 @return: A list of server names for servers with matching role and status.
936 """
937 if not server_manager_utils.use_server_db():
938 raise error.RPCException('Server database is not enabled. Please try '
939 'retrieve servers from global config.')
MK Ryua34e3b12015-08-21 16:20:47 -0700940 servers = server_manager_utils.get_servers(hostname=hostname, role=role,
Dan Shid7bb4f12015-01-06 10:53:50 -0800941 status=status)
942 return [s.get_details() for s in servers]
943
944
MK Ryufbb002c2015-06-08 14:13:16 -0700945@rpc_utils.route_rpc_to_master
Simran Basibeb2bb22016-02-03 15:25:48 -0800946def get_stable_version(board=stable_version_utils.DEFAULT, android=False):
Dan Shi6964fa52014-12-18 11:04:27 -0800947 """Get stable version for the given board.
948
949 @param board: Name of the board.
Simran Basibeb2bb22016-02-03 15:25:48 -0800950 @param android: If True, the given board is an Android-based device. If
951 False, assume its a Chrome OS-based device.
952
Dan Shi6964fa52014-12-18 11:04:27 -0800953 @return: Stable version of the given board. Return global configure value
954 of CROS.stable_cros_version if stable_versinos table does not have
955 entry of board DEFAULT.
956 """
Simran Basibeb2bb22016-02-03 15:25:48 -0800957 return stable_version_utils.get(board=board, android=android)
Dan Shi25e1fd42014-12-19 14:36:42 -0800958
959
MK Ryufbb002c2015-06-08 14:13:16 -0700960@rpc_utils.route_rpc_to_master
Dan Shi25e1fd42014-12-19 14:36:42 -0800961def get_all_stable_versions():
962 """Get stable versions for all boards.
963
964 @return: A dictionary of board:version.
965 """
966 return stable_version_utils.get_all()
967
968
MK Ryufbb002c2015-06-08 14:13:16 -0700969@rpc_utils.route_rpc_to_master
Dan Shi25e1fd42014-12-19 14:36:42 -0800970def set_stable_version(version, board=stable_version_utils.DEFAULT):
971 """Modify stable version for the given board.
972
973 @param version: The new value of stable version for given board.
974 @param board: Name of the board, default to value `DEFAULT`.
975 """
976 stable_version_utils.set(version=version, board=board)
977
978
MK Ryufbb002c2015-06-08 14:13:16 -0700979@rpc_utils.route_rpc_to_master
Dan Shi25e1fd42014-12-19 14:36:42 -0800980def delete_stable_version(board):
981 """Modify stable version for the given board.
982
983 Delete a stable version entry in afe_stable_versions table for a given
984 board, so default stable version will be used.
985
986 @param board: Name of the board.
987 """
988 stable_version_utils.delete(board=board)
Matthew Sartorid96fb9b2015-05-19 18:04:58 -0700989
990
Michael Tang340efe32016-04-16 12:15:17 -0700991def get_tests_by_build(build, ignore_invalid_tests=False):
Matthew Sartorid96fb9b2015-05-19 18:04:58 -0700992 """Get the tests that are available for the specified build.
993
994 @param build: unique name by which to refer to the image.
Michael Tang340efe32016-04-16 12:15:17 -0700995 @param ignore_invalid_tests: flag on if unparsable tests are ignored.
Matthew Sartorid96fb9b2015-05-19 18:04:58 -0700996
997 @return: A sorted list of all tests that are in the build specified.
998 """
999 # Stage the test artifacts.
1000 try:
1001 ds = dev_server.ImageServer.resolve(build)
1002 build = ds.translate(build)
1003 except dev_server.DevServerException as e:
1004 raise ValueError('Could not resolve build %s: %s' % (build, e))
1005
1006 try:
Dan Shi6450e142016-03-11 11:52:20 -08001007 ds.stage_artifacts(image=build, artifacts=['test_suites'])
Matthew Sartorid96fb9b2015-05-19 18:04:58 -07001008 except dev_server.DevServerException as e:
1009 raise error.StageControlFileFailure(
1010 'Failed to stage %s: %s' % (build, e))
1011
1012 # Collect the control files specified in this build
1013 cfile_getter = control_file_getter.DevServerGetter.create(build, ds)
xixuan0f7755d2016-04-18 14:49:12 -07001014 if SuiteBase.ENABLE_CONTROLS_IN_BATCH:
1015 control_file_info_list = cfile_getter.get_suite_info()
1016 control_file_list = control_file_info_list.keys()
1017 else:
1018 control_file_list = cfile_getter.get_control_file_list()
Matthew Sartorid96fb9b2015-05-19 18:04:58 -07001019
1020 test_objects = []
1021 _id = 0
1022 for control_file_path in control_file_list:
1023 # Read and parse the control file
xixuan0f7755d2016-04-18 14:49:12 -07001024 if SuiteBase.ENABLE_CONTROLS_IN_BATCH:
1025 control_file = control_file_info_list[control_file_path]
1026 else:
1027 control_file = cfile_getter.get_control_file_contents(
1028 control_file_path)
Michael Tang340efe32016-04-16 12:15:17 -07001029 try:
1030 control_obj = control_data.parse_control_string(control_file)
1031 except:
1032 logging.info('Failed to parse congtrol file: %s', control_file_path)
1033 if not ignore_invalid_tests:
1034 raise
Matthew Sartorid96fb9b2015-05-19 18:04:58 -07001035
1036 # Extract the values needed for the AFE from the control_obj.
1037 # The keys list represents attributes in the control_obj that
1038 # are required by the AFE
1039 keys = ['author', 'doc', 'name', 'time', 'test_type', 'experimental',
1040 'test_category', 'test_class', 'dependencies', 'run_verify',
1041 'sync_count', 'job_retries', 'retries', 'path']
1042
1043 test_object = {}
1044 for key in keys:
1045 test_object[key] = getattr(control_obj, key) if hasattr(
1046 control_obj, key) else ''
1047
1048 # Unfortunately, the AFE expects different key-names for certain
1049 # values, these must be corrected to avoid the risk of tests
1050 # being omitted by the AFE.
1051 # The 'id' is an additional value used in the AFE.
Matthew Sartori10438092015-06-24 14:30:18 -07001052 # The control_data parsing does not reference 'run_reset', but it
1053 # is also used in the AFE and defaults to True.
Matthew Sartorid96fb9b2015-05-19 18:04:58 -07001054 test_object['id'] = _id
Matthew Sartori10438092015-06-24 14:30:18 -07001055 test_object['run_reset'] = True
Matthew Sartorid96fb9b2015-05-19 18:04:58 -07001056 test_object['description'] = test_object.get('doc', '')
1057 test_object['test_time'] = test_object.get('time', 0)
1058 test_object['test_retry'] = test_object.get('retries', 0)
1059
1060 # Fix the test name to be consistent with the current presentation
1061 # of test names in the AFE.
1062 testpath, subname = os.path.split(control_file_path)
1063 testname = os.path.basename(testpath)
1064 subname = subname.split('.')[1:]
1065 if subname:
1066 testname = '%s:%s' % (testname, ':'.join(subname))
1067
1068 test_object['name'] = testname
1069
Matthew Sartori10438092015-06-24 14:30:18 -07001070 # Correct the test path as parse_control_string sets an empty string.
1071 test_object['path'] = control_file_path
1072
Matthew Sartorid96fb9b2015-05-19 18:04:58 -07001073 _id += 1
1074 test_objects.append(test_object)
1075
Matthew Sartori10438092015-06-24 14:30:18 -07001076 test_objects = sorted(test_objects, key=lambda x: x.get('name'))
Matthew Sartorid96fb9b2015-05-19 18:04:58 -07001077 return rpc_utils.prepare_for_serialization(test_objects)