blob: 1cdeb10adcc783f55ff278032d34238f37fab18e [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
Dan Shi36cfd832014-10-10 13:38:51 -070039from autotest_lib.server.cros.dynamic_suite.suite import Suite
Simran Basi71206ef2014-08-13 13:51:18 -070040from autotest_lib.server.hosts import moblab_host
Dan Shidfea3682014-08-10 23:38:40 -070041from autotest_lib.site_utils import host_history
Dan Shi193905e2014-07-25 23:33:09 -070042from autotest_lib.site_utils import job_history
Dan Shid7bb4f12015-01-06 10:53:50 -080043from autotest_lib.site_utils import server_manager_utils
Dan Shi6964fa52014-12-18 11:04:27 -080044from autotest_lib.site_utils import stable_version_utils
Simran Basi71206ef2014-08-13 13:51:18 -070045
46
47_CONFIG = global_config.global_config
48MOBLAB_BOTO_LOCATION = '/home/moblab/.boto'
Chris Masone859fdec2012-01-30 08:38:09 -080049
Michael Tang9afc74b2016-03-21 10:19:23 -070050# Google Cloud Storage bucket url regex pattern. The pattern is used to extract
51# the bucket name from the bucket URL. For example, "gs://image_bucket/google"
52# should result in a bucket name "image_bucket".
53GOOGLE_STORAGE_BUCKET_URL_PATTERN = re.compile(
54 r'gs://(?P<bucket>[a-zA-Z][a-zA-Z0-9-_]*)/?.*')
55
56# Constants used in JSON RPC field names.
57_USE_EXISTING_BOTO_FILE = 'use_existing_boto_file'
58_GS_ACCESS_KEY_ID = 'gs_access_key_id'
59_GS_SECRETE_ACCESS_KEY = 'gs_secret_access_key'
60_IMAGE_STORAGE_SERVER = 'image_storage_server'
61_RESULT_STORAGE_SERVER = 'results_storage_server'
62
63
Chris Masonef8b53062012-05-08 22:14:18 -070064# Relevant CrosDynamicSuiteExceptions are defined in client/common_lib/error.py.
Chris Masone859fdec2012-01-30 08:38:09 -080065
66
Chris Masone62579122012-03-08 15:18:43 -080067def canonicalize_suite_name(suite_name):
Dan Shi70647ca2015-07-16 22:52:35 -070068 # Do not change this naming convention without updating
69 # site_utils.parse_job_name.
Chris Masone62579122012-03-08 15:18:43 -080070 return 'test_suites/control.%s' % suite_name
71
72
Chris Masoneaa10f8e2012-05-15 13:34:21 -070073def formatted_now():
Dan Shidfea3682014-08-10 23:38:40 -070074 return datetime.datetime.now().strftime(time_utils.TIME_FMT)
Chris Masoneaa10f8e2012-05-15 13:34:21 -070075
76
Simran Basib6ec8ae2014-04-23 12:05:08 -070077def _get_control_file_contents_by_name(build, ds, suite_name):
Chris Masone8dd27e02012-06-25 15:59:43 -070078 """Return control file contents for |suite_name|.
79
80 Query the dev server at |ds| for the control file |suite_name|, included
81 in |build| for |board|.
82
83 @param build: unique name by which to refer to the image from now on.
Chris Masone8dd27e02012-06-25 15:59:43 -070084 @param ds: a dev_server.DevServer instance to fetch control file with.
85 @param suite_name: canonicalized suite name, e.g. test_suites/control.bvt.
86 @raises ControlFileNotFound if a unique suite control file doesn't exist.
87 @raises NoControlFileList if we can't list the control files at all.
88 @raises ControlFileEmpty if the control file exists on the server, but
89 can't be read.
90
91 @return the contents of the desired control file.
92 """
93 getter = control_file_getter.DevServerGetter.create(build, ds)
Gabe Black1e1c41b2015-02-04 23:55:15 -080094 timer = autotest_stats.Timer('control_files.parse.%s.%s' %
95 (ds.get_server_name(ds.url()
96 ).replace('.', '_'),
97 suite_name.rsplit('.')[-1]))
Chris Masone8dd27e02012-06-25 15:59:43 -070098 # Get the control file for the suite.
99 try:
Prashanth Balasubramanianabe3bb72014-11-20 12:00:37 -0800100 with timer:
101 control_file_in = getter.get_control_file_contents_by_name(
102 suite_name)
Chris Masone8dd27e02012-06-25 15:59:43 -0700103 except error.CrosDynamicSuiteException as e:
Simran Basib6ec8ae2014-04-23 12:05:08 -0700104 raise type(e)("%s while testing %s." % (e, build))
Chris Masone8dd27e02012-06-25 15:59:43 -0700105 if not control_file_in:
106 raise error.ControlFileEmpty(
107 "Fetching %s returned no data." % suite_name)
Alex Millera713e252013-03-01 10:45:44 -0800108 # Force control files to only contain ascii characters.
109 try:
110 control_file_in.encode('ascii')
111 except UnicodeDecodeError as e:
112 raise error.ControlFileMalformed(str(e))
113
Chris Masone8dd27e02012-06-25 15:59:43 -0700114 return control_file_in
115
116
Simran Basib6ec8ae2014-04-23 12:05:08 -0700117def _stage_build_artifacts(build):
118 """
119 Ensure components of |build| necessary for installing images are staged.
120
121 @param build image we want to stage.
122
Prashanth B6285f6a2014-05-08 18:01:27 -0700123 @raises StageControlFileFailure: if the dev server throws 500 while staging
124 suite control files.
Simran Basib6ec8ae2014-04-23 12:05:08 -0700125
126 @return: dev_server.ImageServer instance to use with this build.
127 @return: timings dictionary containing staging start/end times.
128 """
129 timings = {}
Prashanth B6285f6a2014-05-08 18:01:27 -0700130 # Ensure components of |build| necessary for installing images are staged
131 # on the dev server. However set synchronous to False to allow other
132 # components to be downloaded in the background.
Dan Shi6450e142016-03-11 11:52:20 -0800133 ds = dev_server.resolve(build)
Simran Basib6ec8ae2014-04-23 12:05:08 -0700134 timings[constants.DOWNLOAD_STARTED_TIME] = formatted_now()
Gabe Black1e1c41b2015-02-04 23:55:15 -0800135 timer = autotest_stats.Timer('control_files.stage.%s' % (
136 ds.get_server_name(ds.url()).replace('.', '_')))
Simran Basib6ec8ae2014-04-23 12:05:08 -0700137 try:
Prashanth Balasubramanianabe3bb72014-11-20 12:00:37 -0800138 with timer:
Dan Shi6450e142016-03-11 11:52:20 -0800139 ds.stage_artifacts(image=build, artifacts=['test_suites'])
Simran Basib6ec8ae2014-04-23 12:05:08 -0700140 except dev_server.DevServerException as e:
Prashanth B6285f6a2014-05-08 18:01:27 -0700141 raise error.StageControlFileFailure(
Simran Basib6ec8ae2014-04-23 12:05:08 -0700142 "Failed to stage %s: %s" % (build, e))
143 timings[constants.PAYLOAD_FINISHED_TIME] = formatted_now()
144 return (ds, timings)
145
146
MK Ryue301eb72015-06-25 12:51:02 -0700147@rpc_utils.route_rpc_to_master
Dan Shi5984d782016-04-05 18:43:51 -0700148def create_suite_job(name='', board='', pool='', control_file='',
Simran Basib6ec8ae2014-04-23 12:05:08 -0700149 check_hosts=True, num=None, file_bugs=False, timeout=24,
150 timeout_mins=None, priority=priorities.Priority.DEFAULT,
Fang Deng058860c2014-05-15 15:41:50 -0700151 suite_args=None, wait_for_results=True, job_retry=False,
Fang Deng443f1952015-01-02 14:51:49 -0800152 max_retries=None, max_runtime_mins=None, suite_min_duts=0,
Dan Shi36cfd832014-10-10 13:38:51 -0700153 offload_failures_only=False, builds={},
Dan Shi059261a2016-02-22 12:06:37 -0800154 test_source_build=None, run_prod_code=False,
155 delay_minutes=0, **kwargs):
Chris Masone859fdec2012-01-30 08:38:09 -0800156 """
157 Create a job to run a test suite on the given device with the given image.
158
159 When the timeout specified in the control file is reached, the
160 job is guaranteed to have completed and results will be available.
161
Simran Basib6ec8ae2014-04-23 12:05:08 -0700162 @param name: The test name if control_file is supplied, otherwise the name
163 of the test suite to run, e.g. 'bvt'.
Chris Masone859fdec2012-01-30 08:38:09 -0800164 @param board: the kind of device to run the tests on.
Dan Shi36cfd832014-10-10 13:38:51 -0700165 @param builds: the builds to install e.g.
166 {'cros-version:': 'x86-alex-release/R18-1655.0.0',
Dan Shi5984d782016-04-05 18:43:51 -0700167 'fwrw-version:': 'x86-alex-firmware/R36-5771.50.0',
Dan Shi36cfd832014-10-10 13:38:51 -0700168 'fwro-version:': 'x86-alex-firmware/R36-5771.49.0'}
169 If builds is given a value, it overrides argument build.
170 @param test_source_build: Build that contains the server-side test code.
Scott Zawalski65650172012-02-16 11:48:26 -0500171 @param pool: Specify the pool of machines to use for scheduling
172 purposes.
Chris Masone62579122012-03-08 15:18:43 -0800173 @param check_hosts: require appropriate live hosts to exist in the lab.
Aviv Keshetd83ef442013-01-16 16:19:35 -0800174 @param num: Specify the number of machines to schedule across (integer).
175 Leave unspecified or use None to use default sharding factor.
Alex Millerc577f3e2012-09-27 14:06:07 -0700176 @param file_bugs: File a bug on each test failure in this suite.
Alex Miller139690b2013-09-07 15:35:49 -0700177 @param timeout: The max lifetime of this suite, in hours.
Simran Basi7e605742013-11-12 13:43:36 -0800178 @param timeout_mins: The max lifetime of this suite, in minutes. Takes
179 priority over timeout.
Alex Miller139690b2013-09-07 15:35:49 -0700180 @param priority: Integer denoting priority. Higher is more important.
Aviv Keshet7cd12312013-07-25 10:25:55 -0700181 @param suite_args: Optional arguments which will be parsed by the suite
182 control file. Used by control.test_that_wrapper to
183 determine which tests to run.
Dan Shi95122412013-11-12 16:20:33 -0800184 @param wait_for_results: Set to False to run the suite job without waiting
185 for test jobs to finish. Default is True.
Fang Deng058860c2014-05-15 15:41:50 -0700186 @param job_retry: Set to True to enable job-level retry. Default is False.
Fang Deng443f1952015-01-02 14:51:49 -0800187 @param max_retries: Integer, maximum job retries allowed at suite level.
188 None for no max.
Simran Basi102e3522014-09-11 11:46:10 -0700189 @param max_runtime_mins: Maximum amount of time a job can be running in
190 minutes.
Fang Dengcbc01212014-11-25 16:09:46 -0800191 @param suite_min_duts: Integer. Scheduler will prioritize getting the
192 minimum number of machines for the suite when it is
193 competing with another suite that has a higher
194 priority but already got minimum machines it needs.
Simran Basi1e10e922015-04-16 15:09:56 -0700195 @param offload_failures_only: Only enable gs_offloading for failed jobs.
Simran Basi5ace6f22016-01-06 17:30:44 -0800196 @param run_prod_code: If True, the suite will run the test code that
197 lives in prod aka the test code currently on the
198 lab servers. If False, the control files and test
199 code for this suite run will be retrieved from the
200 build artifacts.
Dan Shi059261a2016-02-22 12:06:37 -0800201 @param delay_minutes: Delay the creation of test jobs for a given number of
202 minutes.
Simran Basib6ec8ae2014-04-23 12:05:08 -0700203 @param kwargs: extra keyword args. NOT USED.
Chris Masone859fdec2012-01-30 08:38:09 -0800204
Chris Masone8dd27e02012-06-25 15:59:43 -0700205 @raises ControlFileNotFound: if a unique suite control file doesn't exist.
206 @raises NoControlFileList: if we can't list the control files at all.
Prashanth B6285f6a2014-05-08 18:01:27 -0700207 @raises StageControlFileFailure: If the dev server throws 500 while
208 staging test_suites.
Chris Masone8dd27e02012-06-25 15:59:43 -0700209 @raises ControlFileEmpty: if the control file exists on the server, but
210 can't be read.
Chris Masone859fdec2012-01-30 08:38:09 -0800211
212 @return: the job ID of the suite; -1 on error.
213 """
Aviv Keshetd83ef442013-01-16 16:19:35 -0800214 if type(num) is not int and num is not None:
Chris Sosa18c70b32013-02-15 14:12:43 -0800215 raise error.SuiteArgumentException('Ill specified num argument %r. '
216 'Must be an integer or None.' % num)
Aviv Keshetd83ef442013-01-16 16:19:35 -0800217 if num == 0:
218 logging.warning("Can't run on 0 hosts; using default.")
219 num = None
Dan Shi36cfd832014-10-10 13:38:51 -0700220
Dan Shi2121a332016-02-25 14:22:22 -0800221 # Default test source build to CrOS build if it's not specified and
222 # run_prod_code is set to False.
223 if not run_prod_code:
224 test_source_build = Suite.get_test_source_build(
225 builds, test_source_build=test_source_build)
Dan Shi36cfd832014-10-10 13:38:51 -0700226
Simran Basi5ace6f22016-01-06 17:30:44 -0800227 suite_name = canonicalize_suite_name(name)
228 if run_prod_code:
Dan Shi5984d782016-04-05 18:43:51 -0700229 ds = dev_server.resolve(test_source_build)
Simran Basi5ace6f22016-01-06 17:30:44 -0800230 keyvals = {}
231 getter = control_file_getter.FileSystemGetter(
232 [_CONFIG.get_config_value('SCHEDULER',
233 'drone_installation_directory')])
234 control_file = getter.get_control_file_contents_by_name(suite_name)
235 else:
236 (ds, keyvals) = _stage_build_artifacts(test_source_build)
Fang Dengcbc01212014-11-25 16:09:46 -0800237 keyvals[constants.SUITE_MIN_DUTS_KEY] = suite_min_duts
Chris Masone859fdec2012-01-30 08:38:09 -0800238
Simran Basib6ec8ae2014-04-23 12:05:08 -0700239 if not control_file:
Dan Shi36cfd832014-10-10 13:38:51 -0700240 # No control file was supplied so look it up from the build artifacts.
241 suite_name = canonicalize_suite_name(name)
242 control_file = _get_control_file_contents_by_name(test_source_build,
243 ds, suite_name)
Simran Basi86fe9c92016-02-09 17:58:20 -0800244 # Do not change this naming convention without updating
245 # site_utils.parse_job_name.
Dan Shi2121a332016-02-25 14:22:22 -0800246 if not run_prod_code:
247 name = '%s-%s' % (test_source_build, suite_name)
248 else:
249 # If run_prod_code is True, test_source_build is not set, use the
250 # first build in the builds list for the sutie job name.
251 name = '%s-%s' % (builds.values()[0], suite_name)
Chris Masone46d0eb12012-07-27 18:56:39 -0700252
Simran Basi7e605742013-11-12 13:43:36 -0800253 timeout_mins = timeout_mins or timeout * 60
Simran Basi102e3522014-09-11 11:46:10 -0700254 max_runtime_mins = max_runtime_mins or timeout * 60
Simran Basi7e605742013-11-12 13:43:36 -0800255
Simran Basib6ec8ae2014-04-23 12:05:08 -0700256 if not board:
Dan Shid215dbe2015-06-18 16:14:59 -0700257 board = utils.ParseBuildName(builds[provision.CROS_VERSION_PREFIX])[0]
Chris Masone46d0eb12012-07-27 18:56:39 -0700258
Dan Shi5984d782016-04-05 18:43:51 -0700259 # Prepend builds and board to the control file.
Scott Zawalski65650172012-02-16 11:48:26 -0500260 inject_dict = {'board': board,
Dan Shi36cfd832014-10-10 13:38:51 -0700261 'builds': builds,
Chris Masone62579122012-03-08 15:18:43 -0800262 'check_hosts': check_hosts,
Chris Masone46d0eb12012-07-27 18:56:39 -0700263 'pool': pool,
Aviv Keshetd83ef442013-01-16 16:19:35 -0800264 'num': num,
Dan Shib8a99112013-06-18 13:46:10 -0700265 'file_bugs': file_bugs,
Alex Miller139690b2013-09-07 15:35:49 -0700266 'timeout': timeout,
Simran Basi7e605742013-11-12 13:43:36 -0800267 'timeout_mins': timeout_mins,
Alex Miller7d658cf2013-09-04 16:00:35 -0700268 'devserver_url': ds.url(),
Aviv Keshet7cd12312013-07-25 10:25:55 -0700269 'priority': priority,
Dan Shi95122412013-11-12 16:20:33 -0800270 'suite_args' : suite_args,
Fang Deng058860c2014-05-15 15:41:50 -0700271 'wait_for_results': wait_for_results,
Simran Basi102e3522014-09-11 11:46:10 -0700272 'job_retry': job_retry,
Fang Deng443f1952015-01-02 14:51:49 -0800273 'max_retries': max_retries,
Fang Dengcbc01212014-11-25 16:09:46 -0800274 'max_runtime_mins': max_runtime_mins,
Dan Shi36cfd832014-10-10 13:38:51 -0700275 'offload_failures_only': offload_failures_only,
Simran Basi5ace6f22016-01-06 17:30:44 -0800276 'test_source_build': test_source_build,
Dan Shi059261a2016-02-22 12:06:37 -0800277 'run_prod_code': run_prod_code,
278 'delay_minutes': delay_minutes,
Aviv Keshet7cd12312013-07-25 10:25:55 -0700279 }
280
Simran Basib6ec8ae2014-04-23 12:05:08 -0700281 control_file = tools.inject_vars(inject_dict, control_file)
Chris Masone859fdec2012-01-30 08:38:09 -0800282
Jakob Juelich9fffe4f2014-08-14 18:07:05 -0700283 return rpc_utils.create_job_common(name,
Jakob Juelich59cfe542014-09-02 16:37:46 -0700284 priority=priority,
285 timeout_mins=timeout_mins,
286 max_runtime_mins=max_runtime_mins,
287 control_type='Server',
288 control_file=control_file,
289 hostless=True,
Fang Dengcbc01212014-11-25 16:09:46 -0800290 keyvals=keyvals)
Simran Basi71206ef2014-08-13 13:51:18 -0700291
292
293# TODO: hide the following rpcs under is_moblab
294def moblab_only(func):
295 """Ensure moblab specific functions only run on Moblab devices."""
296 def verify(*args, **kwargs):
297 if not utils.is_moblab():
298 raise error.RPCException('RPC: %s can only run on Moblab Systems!',
299 func.__name__)
300 return func(*args, **kwargs)
301 return verify
302
303
304@moblab_only
305def get_config_values():
306 """Returns all config values parsed from global and shadow configs.
307
308 Config values are grouped by sections, and each section is composed of
309 a list of name value pairs.
310 """
311 sections =_CONFIG.get_sections()
312 config_values = {}
313 for section in sections:
314 config_values[section] = _CONFIG.config.items(section)
Jakob Juelich9fffe4f2014-08-14 18:07:05 -0700315 return rpc_utils.prepare_for_serialization(config_values)
Simran Basi71206ef2014-08-13 13:51:18 -0700316
317
Michael Tang9afc74b2016-03-21 10:19:23 -0700318def _write_config_file(config_file, config_values, overwrite=False):
319 """Writes out a configuration file.
Simran Basi71206ef2014-08-13 13:51:18 -0700320
Michael Tang9afc74b2016-03-21 10:19:23 -0700321 @param config_file: The name of the configuration file.
322 @param config_values: The ConfigParser object.
323 @param ovewrite: Flag on if overwriting is allowed.
324 """
325 if not config_file:
326 raise error.RPCException('Empty config file name.')
327 if not overwrite and os.path.exists(config_file):
328 raise error.RPCException('Config file already exists.')
329
330 if config_values:
331 with open(config_file, 'w') as config_file:
332 config_values.write(config_file)
333
334
335def _read_original_config():
336 """Reads the orginal configuratino without shadow.
337
338 @return: A configuration object, see global_config_class.
Simran Basi71206ef2014-08-13 13:51:18 -0700339 """
Simran Basi773a86e2015-05-13 19:15:42 -0700340 original_config = global_config.global_config_class()
341 original_config.set_config_files(shadow_file='')
Michael Tang9afc74b2016-03-21 10:19:23 -0700342 return original_config
343
344
345def _read_raw_config(config_file):
346 """Reads the raw configuration from a configuration file.
347
348 @param: config_file: The path of the configuration file.
349
350 @return: A ConfigParser object.
351 """
352 shadow_config = ConfigParser.RawConfigParser()
353 shadow_config.read(config_file)
354 return shadow_config
355
356
357def _get_shadow_config_from_partial_update(config_values):
358 """Finds out the new shadow configuration based on a partial update.
359
360 Since the input is only a partial config, we should not lose the config
361 data inside the existing shadow config file. We also need to distinguish
362 if the input config info overrides with a new value or reverts back to
363 an original value.
364
365 @param config_values: See get_moblab_settings().
366
367 @return: The new shadow configuration as ConfigParser object.
368 """
369 original_config = _read_original_config()
370 existing_shadow = _read_raw_config(_CONFIG.shadow_file)
371 for section, config_value_list in config_values.iteritems():
372 for key, value in config_value_list:
373 if original_config.get_config_value(section, key,
374 default='',
375 allow_blank=True) != value:
376 if not existing_shadow.has_section(section):
377 existing_shadow.add_section(section)
378 existing_shadow.set(section, key, value)
379 elif existing_shadow.has_option(section, key):
380 existing_shadow.remove_option(section, key)
381 return existing_shadow
382
383
384def _update_partial_config(config_values):
385 """Updates the shadow configuration file with a partial config udpate.
386
387 @param config_values: See get_moblab_settings().
388 """
389 existing_config = _get_shadow_config_from_partial_update(config_values)
390 _write_config_file(_CONFIG.shadow_file, existing_config, True)
391
392
393@moblab_only
394def update_config_handler(config_values):
395 """Update config values and override shadow config.
396
397 @param config_values: See get_moblab_settings().
398 """
399 original_config = _read_original_config()
Simran Basi773a86e2015-05-13 19:15:42 -0700400 new_shadow = ConfigParser.RawConfigParser()
Simran Basi71206ef2014-08-13 13:51:18 -0700401 for section, config_value_list in config_values.iteritems():
402 for key, value in config_value_list:
Simran Basi773a86e2015-05-13 19:15:42 -0700403 if original_config.get_config_value(section, key,
404 default='',
405 allow_blank=True) != value:
406 if not new_shadow.has_section(section):
407 new_shadow.add_section(section)
408 new_shadow.set(section, key, value)
Michael Tang9afc74b2016-03-21 10:19:23 -0700409
Simran Basi71206ef2014-08-13 13:51:18 -0700410 if not _CONFIG.shadow_file or not os.path.exists(_CONFIG.shadow_file):
411 raise error.RPCException('Shadow config file does not exist.')
Michael Tang9afc74b2016-03-21 10:19:23 -0700412 _write_config_file(_CONFIG.shadow_file, new_shadow, True)
Simran Basi71206ef2014-08-13 13:51:18 -0700413
Simran Basi71206ef2014-08-13 13:51:18 -0700414 # TODO (sbasi) crbug.com/403916 - Remove the reboot command and
415 # instead restart the services that rely on the config values.
416 os.system('sudo reboot')
417
418
419@moblab_only
420def reset_config_settings():
421 with open(_CONFIG.shadow_file, 'w') as config_file:
Dan Shi36cfd832014-10-10 13:38:51 -0700422 pass
Simran Basi71206ef2014-08-13 13:51:18 -0700423 os.system('sudo reboot')
424
425
426@moblab_only
427def set_boto_key(boto_key):
428 """Update the boto_key file.
429
430 @param boto_key: File name of boto_key uploaded through handle_file_upload.
431 """
432 if not os.path.exists(boto_key):
433 raise error.RPCException('Boto key: %s does not exist!' % boto_key)
434 shutil.copyfile(boto_key, moblab_host.MOBLAB_BOTO_LOCATION)
Dan Shi193905e2014-07-25 23:33:09 -0700435
436
Dan Shiaec99012016-01-07 09:09:16 -0800437@moblab_only
438def set_launch_control_key(launch_control_key):
439 """Update the launch_control_key file.
440
441 @param launch_control_key: File name of launch_control_key uploaded through
442 handle_file_upload.
443 """
444 if not os.path.exists(launch_control_key):
445 raise error.RPCException('Launch Control key: %s does not exist!' %
446 launch_control_key)
447 shutil.copyfile(launch_control_key,
448 moblab_host.MOBLAB_LAUNCH_CONTROL_KEY_LOCATION)
449 # Restart the devserver service.
450 os.system('sudo restart moblab-devserver-init')
451
452
Michael Tang9afc74b2016-03-21 10:19:23 -0700453###########Moblab Config Wizard RPCs #######################
454def _get_public_ip_address(socket_handle):
455 """Gets the public IP address.
456
457 Connects to Google DNS server using a socket and gets the preferred IP
458 address from the connection.
459
460 @param: socket_handle: a unix socket.
461
462 @return: public ip address as string.
463 """
464 try:
465 socket_handle.settimeout(1)
466 socket_handle.connect(('8.8.8.8', 53))
467 socket_name = socket_handle.getsockname()
468 if socket_name is not None:
469 logging.info('Got socket name from UDP socket.')
470 return socket_name[0]
471 logging.warn('Created UDP socket but with no socket_name.')
472 except socket.error:
473 logging.warn('Could not get socket name from UDP socket.')
474 return None
475
476
477def _get_network_info():
478 """Gets the network information.
479
480 TCP socket is used to test the connectivity. If there is no connectivity, try to
481 get the public IP with UDP socket.
482
483 @return: a tuple as (public_ip_address, connected_to_internet).
484 """
485 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
486 ip = _get_public_ip_address(s)
487 if ip is not None:
488 logging.info('Established TCP connection with well known server.')
489 return (ip, True)
490 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
491 return (_get_public_ip_address(s), False)
492
493
494@moblab_only
495def get_network_info():
496 """Returns the server ip addresses, and if the server connectivity.
497
498 The server ip addresses as an array of strings, and the connectivity as a
499 flag.
500 """
501 network_info = {}
502 info = _get_network_info()
503 if info[0] is not None:
504 network_info['server_ips'] = [info[0]]
505 network_info['is_connected'] = info[1]
506
507 return rpc_utils.prepare_for_serialization(network_info)
508
509
510# Gets the boto configuration.
511def _get_boto_config():
512 """Reads the boto configuration from the boto file.
513
514 @return: Boto configuration as ConfigParser object.
515 """
516 boto_config = ConfigParser.ConfigParser()
517 boto_config.read(MOBLAB_BOTO_LOCATION)
518 return boto_config
519
520
521@moblab_only
522def get_cloud_storage_info():
523 """RPC handler to get the cloud storage access information.
524 """
525 cloud_storage_info = {}
526 value =_CONFIG.get_config_value('CROS', _IMAGE_STORAGE_SERVER)
527 if value is not None:
528 cloud_storage_info[_IMAGE_STORAGE_SERVER] = value
529 value =_CONFIG.get_config_value('CROS', _RESULT_STORAGE_SERVER)
530 if value is not None:
531 cloud_storage_info[_RESULT_STORAGE_SERVER] = value
532
533 boto_config = _get_boto_config()
534 sections = boto_config.sections()
535
536 if sections:
537 cloud_storage_info[_USE_EXISTING_BOTO_FILE] = True
538 else:
539 cloud_storage_info[_USE_EXISTING_BOTO_FILE] = False
540 if 'Credentials' in sections:
541 options = boto_config.options('Credentials')
542 if _GS_ACCESS_KEY_ID in options:
543 value = boto_config.get('Credentials', _GS_ACCESS_KEY_ID)
544 cloud_storage_info[_GS_ACCESS_KEY_ID] = value
545 if _GS_SECRETE_ACCESS_KEY in options:
546 value = boto_config.get('Credentials', _GS_SECRETE_ACCESS_KEY)
547 cloud_storage_info[_GS_SECRETE_ACCESS_KEY] = value
548
549 return rpc_utils.prepare_for_serialization(cloud_storage_info)
550
551
552def _get_bucket_name_from_url(bucket_url):
553 """Gets the bucket name from a bucket url.
554
555 @param: bucket_url: the bucket url string.
556 """
557 if bucket_url:
558 match = GOOGLE_STORAGE_BUCKET_URL_PATTERN.match(bucket_url)
559 if match:
560 return match.group('bucket')
561 return None
562
563
564def _is_valid_boto_key(key_id, key_secret):
565 """Checks if the boto key is valid.
566
567 @param: key_id: The boto key id string.
568 @param: key_secret: The boto key string.
569
570 @return: A tuple as (valid_boolean, details_string).
571 """
572 if not key_id or not key_secret:
573 return (False, "Empty key id or secret.")
574 conn = boto.connect_gs(key_id, key_secret)
575 try:
576 buckets = conn.get_all_buckets()
577 return (True, None)
578 except boto.exception.GSResponseError:
579 details = "The boto access key is not valid"
580 return (False, details)
581 finally:
582 conn.close()
583
584
585def _is_valid_bucket(key_id, key_secret, bucket_name):
586 """Checks if a bucket is valid and accessible.
587
588 @param: key_id: The boto key id string.
589 @param: key_secret: The boto key string.
590 @param: bucket name string.
591
592 @return: A tuple as (valid_boolean, details_string).
593 """
594 if not key_id or not key_secret or not bucket_name:
595 return (False, "Server error: invalid argument")
596 conn = boto.connect_gs(key_id, key_secret)
597 bucket = conn.lookup(bucket_name)
598 conn.close()
599 if bucket:
600 return (True, None)
601 return (False, "Bucket %s does not exist." % bucket_name)
602
603
604def _is_valid_bucket_url(key_id, key_secret, bucket_url):
605 """Validates the bucket url is accessible.
606
607 @param: key_id: The boto key id string.
608 @param: key_secret: The boto key string.
609 @param: bucket url string.
610
611 @return: A tuple as (valid_boolean, details_string).
612 """
613 bucket_name = _get_bucket_name_from_url(bucket_url)
614 if bucket_name:
615 return _is_valid_bucket(key_id, key_secret, bucket_name)
616 return (False, "Bucket url %s is not valid" % bucket_url)
617
618
619def _validate_cloud_storage_info(cloud_storage_info):
620 """Checks if the cloud storage information is valid.
621
622 @param: cloud_storage_info: The JSON RPC object for cloud storage info.
623
624 @return: A tuple as (valid_boolean, details_string).
625 """
626 valid = True
627 details = None
628 if not cloud_storage_info[_USE_EXISTING_BOTO_FILE]:
629 key_id = cloud_storage_info[_GS_ACCESS_KEY_ID]
630 key_secret = cloud_storage_info[_GS_SECRETE_ACCESS_KEY]
631 valid, details = _is_valid_boto_key(key_id, key_secret)
632
633 if valid:
634 valid, details = _is_valid_bucket_url(
635 key_id, key_secret, cloud_storage_info[_IMAGE_STORAGE_SERVER])
636
637 if valid:
638 valid, details = _is_valid_bucket_url(
639 key_id, key_secret, cloud_storage_info[_RESULT_STORAGE_SERVER])
640 return (valid, details)
641
642
643def _create_operation_status_response(is_ok, details):
644 """Helper method to create a operation status reponse.
645
646 @param: is_ok: Boolean for if the operation is ok.
647 @param: details: A detailed string.
648
649 @return: A serialized JSON RPC object.
650 """
651 status_response = {'status_ok': is_ok}
652 if details:
653 status_response['status_details'] = details
654 return rpc_utils.prepare_for_serialization(status_response)
655
656
657@moblab_only
658def validate_cloud_storage_info(cloud_storage_info):
659 """RPC handler to check if the cloud storage info is valid.
660 """
661 valid, details = _validate_cloud_storage_info(cloud_storage_info)
662 return _create_operation_status_response(valid, details)
663
664
665@moblab_only
666def submit_wizard_config_info(cloud_storage_info):
667 """RPC handler to submit the cloud storage info.
668 """
669 valid, details = _validate_cloud_storage_info(cloud_storage_info)
670 if not valid:
671 return _create_operation_status_response(valid, details)
672 config_update = {}
673 config_update['CROS'] = [
674 (_IMAGE_STORAGE_SERVER, cloud_storage_info[_IMAGE_STORAGE_SERVER]),
675 (_RESULT_STORAGE_SERVER, cloud_storage_info[_RESULT_STORAGE_SERVER])
676 ]
677 _update_partial_config(config_update)
678
679 if not cloud_storage_info[_USE_EXISTING_BOTO_FILE]:
680 boto_config = ConfigParser.RawConfigParser()
681 boto_config.add_section('Credentials')
682 boto_config.set('Credentials', _GS_ACCESS_KEY_ID,
683 cloud_storage_info[_GS_ACCESS_KEY_ID])
684 boto_config.set('Credentials', _GS_SECRETE_ACCESS_KEY,
685 cloud_storage_info[_GS_SECRETE_ACCESS_KEY])
686 _write_config_file(MOBLAB_BOTO_LOCATION, boto_config, True)
687
688 _CONFIG.parse_config_file()
689
690 return _create_operation_status_response(True, None)
691
692
Dan Shi193905e2014-07-25 23:33:09 -0700693def get_job_history(**filter_data):
694 """Get history of the job, including the special tasks executed for the job
695
696 @param filter_data: filter for the call, should at least include
697 {'job_id': [job id]}
698 @returns: JSON string of the job's history, including the information such
699 as the hosts run the job and the special tasks executed before
700 and after the job.
701 """
702 job_id = filter_data['job_id']
703 job_info = job_history.get_job_info(job_id)
Dan Shidfea3682014-08-10 23:38:40 -0700704 return rpc_utils.prepare_for_serialization(job_info.get_history())
705
706
707def get_host_history(start_time, end_time, hosts=None, board=None, pool=None):
708 """Get history of a list of host.
709
710 The return is a JSON string of host history for each host, for example,
711 {'172.22.33.51': [{'status': 'Resetting'
712 'start_time': '2014-08-07 10:02:16',
713 'end_time': '2014-08-07 10:03:16',
714 'log_url': 'http://autotest/reset-546546/debug',
715 'dbg_str': 'Task: Special Task 19441991 (host ...)'},
716 {'status': 'Running'
717 'start_time': '2014-08-07 10:03:18',
718 'end_time': '2014-08-07 10:13:00',
719 'log_url': 'http://autotest/reset-546546/debug',
720 'dbg_str': 'HQE: 15305005, for job: 14995562'}
721 ]
722 }
723 @param start_time: start time to search for history, can be string value or
724 epoch time.
725 @param end_time: end time to search for history, can be string value or
726 epoch time.
727 @param hosts: A list of hosts to search for history. Default is None.
728 @param board: board type of hosts. Default is None.
729 @param pool: pool type of hosts. Default is None.
730 @returns: JSON string of the host history.
731 """
732 return rpc_utils.prepare_for_serialization(
733 host_history.get_history_details(
734 start_time=start_time, end_time=end_time,
735 hosts=hosts, board=board, pool=pool,
736 process_pool_size=4))
Jakob Juelich59cfe542014-09-02 16:37:46 -0700737
738
MK Ryu07a109f2015-07-21 17:44:32 -0700739def shard_heartbeat(shard_hostname, jobs=(), hqes=(), known_job_ids=(),
740 known_host_ids=(), known_host_statuses=()):
Jakob Juelich1b525742014-09-30 13:08:07 -0700741 """Receive updates for job statuses from shards and assign hosts and jobs.
Jakob Juelich59cfe542014-09-02 16:37:46 -0700742
743 @param shard_hostname: Hostname of the calling shard
Jakob Juelicha94efe62014-09-18 16:02:49 -0700744 @param jobs: Jobs in serialized form that should be updated with newer
745 status from a shard.
746 @param hqes: Hostqueueentries in serialized form that should be updated with
747 newer status from a shard. Note that for every hostqueueentry
748 the corresponding job must be in jobs.
Jakob Juelich1b525742014-09-30 13:08:07 -0700749 @param known_job_ids: List of ids of jobs the shard already has.
750 @param known_host_ids: List of ids of hosts the shard already has.
MK Ryu07a109f2015-07-21 17:44:32 -0700751 @param known_host_statuses: List of statuses of hosts the shard already has.
Jakob Juelicha94efe62014-09-18 16:02:49 -0700752
Fang Dengf3705992014-12-16 17:32:18 -0800753 @returns: Serialized representations of hosts, jobs, suite job keyvals
754 and their dependencies to be inserted into a shard's database.
Jakob Juelich59cfe542014-09-02 16:37:46 -0700755 """
Jakob Juelich1b525742014-09-30 13:08:07 -0700756 # The following alternatives to sending host and job ids in every heartbeat
757 # have been considered:
758 # 1. Sending the highest known job and host ids. This would work for jobs:
759 # Newer jobs always have larger ids. Also, if a job is not assigned to a
760 # particular shard during a heartbeat, it never will be assigned to this
761 # shard later.
762 # This is not true for hosts though: A host that is leased won't be sent
763 # to the shard now, but might be sent in a future heartbeat. This means
764 # sometimes hosts should be transfered that have a lower id than the
765 # maximum host id the shard knows.
766 # 2. Send the number of jobs/hosts the shard knows to the master in each
767 # heartbeat. Compare these to the number of records that already have
768 # the shard_id set to this shard. In the normal case, they should match.
769 # In case they don't, resend all entities of that type.
770 # This would work well for hosts, because there aren't that many.
771 # Resending all jobs is quite a big overhead though.
772 # Also, this approach might run into edge cases when entities are
773 # ever deleted.
774 # 3. Mixtures of the above: Use 1 for jobs and 2 for hosts.
775 # Using two different approaches isn't consistent and might cause
776 # confusion. Also the issues with the case of deletions might still
777 # occur.
778 #
779 # The overhead of sending all job and host ids in every heartbeat is low:
780 # At peaks one board has about 1200 created but unfinished jobs.
781 # See the numbers here: http://goo.gl/gQCGWH
782 # Assuming that job id's have 6 digits and that json serialization takes a
783 # comma and a space as overhead, the traffic per id sent is about 8 bytes.
784 # If 5000 ids need to be sent, this means 40 kilobytes of traffic.
785 # A NOT IN query with 5000 ids took about 30ms in tests made.
786 # These numbers seem low enough to outweigh the disadvantages of the
787 # solutions described above.
Gabe Black1e1c41b2015-02-04 23:55:15 -0800788 timer = autotest_stats.Timer('shard_heartbeat')
Jakob Juelich59cfe542014-09-02 16:37:46 -0700789 with timer:
790 shard_obj = rpc_utils.retrieve_shard(shard_hostname=shard_hostname)
Jakob Juelicha94efe62014-09-18 16:02:49 -0700791 rpc_utils.persist_records_sent_from_shard(shard_obj, jobs, hqes)
MK Ryu07a109f2015-07-21 17:44:32 -0700792 assert len(known_host_ids) == len(known_host_statuses)
793 for i in range(len(known_host_ids)):
794 host_model = models.Host.objects.get(pk=known_host_ids[i])
795 if host_model.status != known_host_statuses[i]:
796 host_model.status = known_host_statuses[i]
797 host_model.save()
798
Fang Dengf3705992014-12-16 17:32:18 -0800799 hosts, jobs, suite_keyvals = rpc_utils.find_records_for_shard(
MK Ryu07a109f2015-07-21 17:44:32 -0700800 shard_obj, known_job_ids=known_job_ids,
801 known_host_ids=known_host_ids)
Jakob Juelich59cfe542014-09-02 16:37:46 -0700802 return {
803 'hosts': [host.serialize() for host in hosts],
804 'jobs': [job.serialize() for job in jobs],
Fang Dengf3705992014-12-16 17:32:18 -0800805 'suite_keyvals': [kv.serialize() for kv in suite_keyvals],
Jakob Juelich59cfe542014-09-02 16:37:46 -0700806 }
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700807
808
809def get_shards(**filter_data):
810 """Return a list of all shards.
811
812 @returns A sequence of nested dictionaries of shard information.
813 """
814 shards = models.Shard.query_objects(filter_data)
815 serialized_shards = rpc_utils.prepare_rows_as_nested_dicts(shards, ())
816 for serialized, shard in zip(serialized_shards, shards):
817 serialized['labels'] = [label.name for label in shard.labels.all()]
818
819 return serialized_shards
820
821
MK Ryu5dfcc892015-07-16 15:34:04 -0700822def add_shard(hostname, labels):
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700823 """Add a shard and start running jobs on it.
824
825 @param hostname: The hostname of the shard to be added; needs to be unique.
MK Ryu5dfcc892015-07-16 15:34:04 -0700826 @param labels: Board labels separated by a comma. Jobs of one of the labels
827 will be assigned to the shard.
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700828
Jakob Juelich8b110ee2014-09-15 16:13:42 -0700829 @raises error.RPCException: If label provided doesn't start with `board:`
830 @raises model_logic.ValidationError: If a shard with the given hostname
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700831 already exists.
Jakob Juelich8b110ee2014-09-15 16:13:42 -0700832 @raises models.Label.DoesNotExist: If the label specified doesn't exist.
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700833 """
MK Ryu5dfcc892015-07-16 15:34:04 -0700834 labels = labels.split(',')
835 label_models = []
836 for label in labels:
837 if not label.startswith('board:'):
838 raise error.RPCException('Sharding only supports for `board:.*` '
839 'labels.')
840 # Fetch label first, so shard isn't created when label doesn't exist.
841 label_models.append(models.Label.smart_get(label))
Jakob Juelich8b110ee2014-09-15 16:13:42 -0700842
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700843 shard = models.Shard.add_object(hostname=hostname)
MK Ryu5dfcc892015-07-16 15:34:04 -0700844 for label in label_models:
845 shard.labels.add(label)
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700846 return shard.id
847
848
849def delete_shard(hostname):
850 """Delete a shard and reclaim all resources from it.
851
852 This claims back all assigned hosts from the shard. To ensure all DUTs are
xixuan03cb93f2016-03-22 16:21:41 -0700853 in a sane state, a Reboot task with highest priority is scheduled for them.
854 This reboots the DUTs and then all left tasks continue to run in drone of
855 the master.
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700856
xixuan03cb93f2016-03-22 16:21:41 -0700857 The procedure for deleting a shard:
858 * Lock all unlocked hosts on that shard.
859 * Remove shard information .
860 * Assign a reboot task with highest priority to these hosts.
861 * Unlock these hosts, then, the reboot tasks run in front of all other
862 tasks.
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700863
864 The status of jobs that haven't been reported to be finished yet, will be
865 lost. The master scheduler will pick up the jobs and execute them.
866
867 @param hostname: Hostname of the shard to delete.
868 """
869 shard = rpc_utils.retrieve_shard(shard_hostname=hostname)
xixuan03cb93f2016-03-22 16:21:41 -0700870 hostnames_to_lock = [h.hostname for h in
871 models.Host.objects.filter(shard=shard, locked=False)]
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700872
873 # TODO(beeps): Power off shard
xixuan03cb93f2016-03-22 16:21:41 -0700874 # For ChromeOS hosts, a reboot test with the highest priority is added to
875 # the DUT. After a reboot it should be ganranteed that no processes from
876 # prior tests that were run by a shard are still running on.
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700877
xixuan03cb93f2016-03-22 16:21:41 -0700878 # Lock all unlocked hosts.
879 dicts = {'locked': True, 'lock_time': datetime.datetime.now()}
880 models.Host.objects.filter(hostname__in=hostnames_to_lock).update(**dicts)
881
882 # Remove shard information.
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700883 models.Host.objects.filter(shard=shard).update(shard=None)
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700884 models.Job.objects.filter(shard=shard).update(shard=None)
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700885 shard.labels.clear()
Jakob Juelich82b7d1c2014-09-15 16:10:57 -0700886 shard.delete()
Dan Shi6964fa52014-12-18 11:04:27 -0800887
xixuan03cb93f2016-03-22 16:21:41 -0700888 # Assign a reboot task with highest priority: Super.
889 t = models.Test.objects.get(name='platform_BootPerfServer:shard')
890 c = utils.read_file(os.path.join(common.autotest_dir, t.path))
891 if hostnames_to_lock:
892 rpc_utils.create_job_common(
893 'reboot_dut_for_shard_deletion',
894 priority=priorities.Priority.SUPER,
895 control_type='Server',
896 control_file=c, hosts=hostnames_to_lock)
897
898 # Unlock these shard-related hosts.
899 dicts = {'locked': False, 'lock_time': None}
900 models.Host.objects.filter(hostname__in=hostnames_to_lock).update(**dicts)
901
Dan Shi6964fa52014-12-18 11:04:27 -0800902
MK Ryua34e3b12015-08-21 16:20:47 -0700903def get_servers(hostname=None, role=None, status=None):
Dan Shid7bb4f12015-01-06 10:53:50 -0800904 """Get a list of servers with matching role and status.
905
MK Ryua34e3b12015-08-21 16:20:47 -0700906 @param hostname: FQDN of the server.
Dan Shid7bb4f12015-01-06 10:53:50 -0800907 @param role: Name of the server role, e.g., drone, scheduler. Default to
908 None to match any role.
909 @param status: Status of the server, e.g., primary, backup, repair_required.
910 Default to None to match any server status.
911
912 @raises error.RPCException: If server database is not used.
913 @return: A list of server names for servers with matching role and status.
914 """
915 if not server_manager_utils.use_server_db():
916 raise error.RPCException('Server database is not enabled. Please try '
917 'retrieve servers from global config.')
MK Ryua34e3b12015-08-21 16:20:47 -0700918 servers = server_manager_utils.get_servers(hostname=hostname, role=role,
Dan Shid7bb4f12015-01-06 10:53:50 -0800919 status=status)
920 return [s.get_details() for s in servers]
921
922
MK Ryufbb002c2015-06-08 14:13:16 -0700923@rpc_utils.route_rpc_to_master
Simran Basibeb2bb22016-02-03 15:25:48 -0800924def get_stable_version(board=stable_version_utils.DEFAULT, android=False):
Dan Shi6964fa52014-12-18 11:04:27 -0800925 """Get stable version for the given board.
926
927 @param board: Name of the board.
Simran Basibeb2bb22016-02-03 15:25:48 -0800928 @param android: If True, the given board is an Android-based device. If
929 False, assume its a Chrome OS-based device.
930
Dan Shi6964fa52014-12-18 11:04:27 -0800931 @return: Stable version of the given board. Return global configure value
932 of CROS.stable_cros_version if stable_versinos table does not have
933 entry of board DEFAULT.
934 """
Simran Basibeb2bb22016-02-03 15:25:48 -0800935 return stable_version_utils.get(board=board, android=android)
Dan Shi25e1fd42014-12-19 14:36:42 -0800936
937
MK Ryufbb002c2015-06-08 14:13:16 -0700938@rpc_utils.route_rpc_to_master
Dan Shi25e1fd42014-12-19 14:36:42 -0800939def get_all_stable_versions():
940 """Get stable versions for all boards.
941
942 @return: A dictionary of board:version.
943 """
944 return stable_version_utils.get_all()
945
946
MK Ryufbb002c2015-06-08 14:13:16 -0700947@rpc_utils.route_rpc_to_master
Dan Shi25e1fd42014-12-19 14:36:42 -0800948def set_stable_version(version, board=stable_version_utils.DEFAULT):
949 """Modify stable version for the given board.
950
951 @param version: The new value of stable version for given board.
952 @param board: Name of the board, default to value `DEFAULT`.
953 """
954 stable_version_utils.set(version=version, board=board)
955
956
MK Ryufbb002c2015-06-08 14:13:16 -0700957@rpc_utils.route_rpc_to_master
Dan Shi25e1fd42014-12-19 14:36:42 -0800958def delete_stable_version(board):
959 """Modify stable version for the given board.
960
961 Delete a stable version entry in afe_stable_versions table for a given
962 board, so default stable version will be used.
963
964 @param board: Name of the board.
965 """
966 stable_version_utils.delete(board=board)
Matthew Sartorid96fb9b2015-05-19 18:04:58 -0700967
968
969def get_tests_by_build(build):
970 """Get the tests that are available for the specified build.
971
972 @param build: unique name by which to refer to the image.
973
974 @return: A sorted list of all tests that are in the build specified.
975 """
976 # Stage the test artifacts.
977 try:
978 ds = dev_server.ImageServer.resolve(build)
979 build = ds.translate(build)
980 except dev_server.DevServerException as e:
981 raise ValueError('Could not resolve build %s: %s' % (build, e))
982
983 try:
Dan Shi6450e142016-03-11 11:52:20 -0800984 ds.stage_artifacts(image=build, artifacts=['test_suites'])
Matthew Sartorid96fb9b2015-05-19 18:04:58 -0700985 except dev_server.DevServerException as e:
986 raise error.StageControlFileFailure(
987 'Failed to stage %s: %s' % (build, e))
988
989 # Collect the control files specified in this build
990 cfile_getter = control_file_getter.DevServerGetter.create(build, ds)
991 control_file_list = cfile_getter.get_control_file_list()
992
993 test_objects = []
994 _id = 0
995 for control_file_path in control_file_list:
996 # Read and parse the control file
997 control_file = cfile_getter.get_control_file_contents(
998 control_file_path)
999 control_obj = control_data.parse_control_string(control_file)
1000
1001 # Extract the values needed for the AFE from the control_obj.
1002 # The keys list represents attributes in the control_obj that
1003 # are required by the AFE
1004 keys = ['author', 'doc', 'name', 'time', 'test_type', 'experimental',
1005 'test_category', 'test_class', 'dependencies', 'run_verify',
1006 'sync_count', 'job_retries', 'retries', 'path']
1007
1008 test_object = {}
1009 for key in keys:
1010 test_object[key] = getattr(control_obj, key) if hasattr(
1011 control_obj, key) else ''
1012
1013 # Unfortunately, the AFE expects different key-names for certain
1014 # values, these must be corrected to avoid the risk of tests
1015 # being omitted by the AFE.
1016 # The 'id' is an additional value used in the AFE.
Matthew Sartori10438092015-06-24 14:30:18 -07001017 # The control_data parsing does not reference 'run_reset', but it
1018 # is also used in the AFE and defaults to True.
Matthew Sartorid96fb9b2015-05-19 18:04:58 -07001019 test_object['id'] = _id
Matthew Sartori10438092015-06-24 14:30:18 -07001020 test_object['run_reset'] = True
Matthew Sartorid96fb9b2015-05-19 18:04:58 -07001021 test_object['description'] = test_object.get('doc', '')
1022 test_object['test_time'] = test_object.get('time', 0)
1023 test_object['test_retry'] = test_object.get('retries', 0)
1024
1025 # Fix the test name to be consistent with the current presentation
1026 # of test names in the AFE.
1027 testpath, subname = os.path.split(control_file_path)
1028 testname = os.path.basename(testpath)
1029 subname = subname.split('.')[1:]
1030 if subname:
1031 testname = '%s:%s' % (testname, ':'.join(subname))
1032
1033 test_object['name'] = testname
1034
Matthew Sartori10438092015-06-24 14:30:18 -07001035 # Correct the test path as parse_control_string sets an empty string.
1036 test_object['path'] = control_file_path
1037
Matthew Sartorid96fb9b2015-05-19 18:04:58 -07001038 _id += 1
1039 test_objects.append(test_object)
1040
Matthew Sartori10438092015-06-24 14:30:18 -07001041 test_objects = sorted(test_objects, key=lambda x: x.get('name'))
Matthew Sartorid96fb9b2015-05-19 18:04:58 -07001042 return rpc_utils.prepare_for_serialization(test_objects)