blob: cb6a4f78ce68733eda686f35161fabeb3c4da41c [file] [log] [blame]
Dan Shi4df39252013-03-19 13:19:45 -07001# pylint: disable-msg=C0111
2
Chris Masone859fdec2012-01-30 08:38:09 -08003# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
4# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
6
7__author__ = 'cmasone@chromium.org (Chris Masone)'
8
9import common
Chris Masonea8066a92012-05-01 16:52:31 -070010import datetime
Chris Masone859fdec2012-01-30 08:38:09 -080011import logging
Simran Basi71206ef2014-08-13 13:51:18 -070012import os
13import shutil
14import utils
Aviv Keshetd83ef442013-01-16 16:19:35 -080015
16from autotest_lib.client.common_lib import error
Simran Basi71206ef2014-08-13 13:51:18 -070017from autotest_lib.client.common_lib import global_config
Alex Miller7d658cf2013-09-04 16:00:35 -070018from autotest_lib.client.common_lib import priorities
Chris Masone859fdec2012-01-30 08:38:09 -080019from autotest_lib.client.common_lib.cros import dev_server
Simran Basib6ec8ae2014-04-23 12:05:08 -070020from autotest_lib.server import utils
Chris Masone44e4d6c2012-08-15 14:25:53 -070021from autotest_lib.server.cros.dynamic_suite import constants
Chris Masoneb4935552012-08-14 12:05:54 -070022from autotest_lib.server.cros.dynamic_suite import control_file_getter
Chris Masoneb4935552012-08-14 12:05:54 -070023from autotest_lib.server.cros.dynamic_suite import job_status
Chris Masone44e4d6c2012-08-15 14:25:53 -070024from autotest_lib.server.cros.dynamic_suite import tools
Simran Basi71206ef2014-08-13 13:51:18 -070025from autotest_lib.server.hosts import moblab_host
26
27
28_CONFIG = global_config.global_config
29MOBLAB_BOTO_LOCATION = '/home/moblab/.boto'
Chris Masone859fdec2012-01-30 08:38:09 -080030
31
Chris Masonef8b53062012-05-08 22:14:18 -070032# Relevant CrosDynamicSuiteExceptions are defined in client/common_lib/error.py.
Chris Masone859fdec2012-01-30 08:38:09 -080033
34
Chris Masone859fdec2012-01-30 08:38:09 -080035def _rpc_utils():
Chris Masoneb1451a02012-03-12 10:21:14 -070036 """Returns the rpc_utils module. MUST be mocked for unit tests.
37
38 rpc_utils initializes django, which we can't do in unit tests.
39 This layer of indirection allows us to only load that module if we're
40 not running unit tests.
41
42 @return: autotest_lib.frontend.afe.rpc_utils
43 """
44 from autotest_lib.frontend.afe import rpc_utils
Chris Masone859fdec2012-01-30 08:38:09 -080045 return rpc_utils
46
47
Chris Masone62579122012-03-08 15:18:43 -080048def canonicalize_suite_name(suite_name):
49 return 'test_suites/control.%s' % suite_name
50
51
Chris Masoneaa10f8e2012-05-15 13:34:21 -070052def formatted_now():
Chris Masone8d6e6412012-06-28 11:20:56 -070053 return datetime.datetime.now().strftime(job_status.TIME_FMT)
Chris Masoneaa10f8e2012-05-15 13:34:21 -070054
55
Simran Basib6ec8ae2014-04-23 12:05:08 -070056def _get_control_file_contents_by_name(build, ds, suite_name):
Chris Masone8dd27e02012-06-25 15:59:43 -070057 """Return control file contents for |suite_name|.
58
59 Query the dev server at |ds| for the control file |suite_name|, included
60 in |build| for |board|.
61
62 @param build: unique name by which to refer to the image from now on.
Chris Masone8dd27e02012-06-25 15:59:43 -070063 @param ds: a dev_server.DevServer instance to fetch control file with.
64 @param suite_name: canonicalized suite name, e.g. test_suites/control.bvt.
65 @raises ControlFileNotFound if a unique suite control file doesn't exist.
66 @raises NoControlFileList if we can't list the control files at all.
67 @raises ControlFileEmpty if the control file exists on the server, but
68 can't be read.
69
70 @return the contents of the desired control file.
71 """
72 getter = control_file_getter.DevServerGetter.create(build, ds)
73 # Get the control file for the suite.
74 try:
75 control_file_in = getter.get_control_file_contents_by_name(suite_name)
76 except error.CrosDynamicSuiteException as e:
Simran Basib6ec8ae2014-04-23 12:05:08 -070077 raise type(e)("%s while testing %s." % (e, build))
Chris Masone8dd27e02012-06-25 15:59:43 -070078 if not control_file_in:
79 raise error.ControlFileEmpty(
80 "Fetching %s returned no data." % suite_name)
Alex Millera713e252013-03-01 10:45:44 -080081 # Force control files to only contain ascii characters.
82 try:
83 control_file_in.encode('ascii')
84 except UnicodeDecodeError as e:
85 raise error.ControlFileMalformed(str(e))
86
Chris Masone8dd27e02012-06-25 15:59:43 -070087 return control_file_in
88
89
Simran Basib6ec8ae2014-04-23 12:05:08 -070090def _stage_build_artifacts(build):
91 """
92 Ensure components of |build| necessary for installing images are staged.
93
94 @param build image we want to stage.
95
96 @raises StageBuildFailure: if the dev server throws 500 while staging
97 build.
98
99 @return: dev_server.ImageServer instance to use with this build.
100 @return: timings dictionary containing staging start/end times.
101 """
102 timings = {}
103 # Set synchronous to False to allow other components to be downloaded in
104 # the background.
105 ds = dev_server.ImageServer.resolve(build)
106 timings[constants.DOWNLOAD_STARTED_TIME] = formatted_now()
107 try:
108 ds.stage_artifacts(build, ['test_suites'])
109 except dev_server.DevServerException as e:
110 raise error.StageBuildFailure(
111 "Failed to stage %s: %s" % (build, e))
112 timings[constants.PAYLOAD_FINISHED_TIME] = formatted_now()
113 return (ds, timings)
114
115
116def create_suite_job(name='', board='', build='', pool='', control_file='',
117 check_hosts=True, num=None, file_bugs=False, timeout=24,
118 timeout_mins=None, priority=priorities.Priority.DEFAULT,
Fang Deng058860c2014-05-15 15:41:50 -0700119 suite_args=None, wait_for_results=True, job_retry=False,
120 **kwargs):
Chris Masone859fdec2012-01-30 08:38:09 -0800121 """
122 Create a job to run a test suite on the given device with the given image.
123
124 When the timeout specified in the control file is reached, the
125 job is guaranteed to have completed and results will be available.
126
Simran Basib6ec8ae2014-04-23 12:05:08 -0700127 @param name: The test name if control_file is supplied, otherwise the name
128 of the test suite to run, e.g. 'bvt'.
Chris Masone859fdec2012-01-30 08:38:09 -0800129 @param board: the kind of device to run the tests on.
130 @param build: unique name by which to refer to the image from now on.
Scott Zawalski65650172012-02-16 11:48:26 -0500131 @param pool: Specify the pool of machines to use for scheduling
132 purposes.
Chris Masone62579122012-03-08 15:18:43 -0800133 @param check_hosts: require appropriate live hosts to exist in the lab.
Aviv Keshetd83ef442013-01-16 16:19:35 -0800134 @param num: Specify the number of machines to schedule across (integer).
135 Leave unspecified or use None to use default sharding factor.
Alex Millerc577f3e2012-09-27 14:06:07 -0700136 @param file_bugs: File a bug on each test failure in this suite.
Alex Miller139690b2013-09-07 15:35:49 -0700137 @param timeout: The max lifetime of this suite, in hours.
Simran Basi7e605742013-11-12 13:43:36 -0800138 @param timeout_mins: The max lifetime of this suite, in minutes. Takes
139 priority over timeout.
Alex Miller139690b2013-09-07 15:35:49 -0700140 @param priority: Integer denoting priority. Higher is more important.
Aviv Keshet7cd12312013-07-25 10:25:55 -0700141 @param suite_args: Optional arguments which will be parsed by the suite
142 control file. Used by control.test_that_wrapper to
143 determine which tests to run.
Dan Shi95122412013-11-12 16:20:33 -0800144 @param wait_for_results: Set to False to run the suite job without waiting
145 for test jobs to finish. Default is True.
Fang Deng058860c2014-05-15 15:41:50 -0700146 @param job_retry: Set to True to enable job-level retry. Default is False.
Simran Basib6ec8ae2014-04-23 12:05:08 -0700147 @param kwargs: extra keyword args. NOT USED.
Chris Masone859fdec2012-01-30 08:38:09 -0800148
Chris Masone8dd27e02012-06-25 15:59:43 -0700149 @raises ControlFileNotFound: if a unique suite control file doesn't exist.
150 @raises NoControlFileList: if we can't list the control files at all.
151 @raises StageBuildFailure: if the dev server throws 500 while staging build.
152 @raises ControlFileEmpty: if the control file exists on the server, but
153 can't be read.
Chris Masone859fdec2012-01-30 08:38:09 -0800154
155 @return: the job ID of the suite; -1 on error.
156 """
Aviv Keshetd83ef442013-01-16 16:19:35 -0800157 if type(num) is not int and num is not None:
Chris Sosa18c70b32013-02-15 14:12:43 -0800158 raise error.SuiteArgumentException('Ill specified num argument %r. '
159 'Must be an integer or None.' % num)
Aviv Keshetd83ef442013-01-16 16:19:35 -0800160 if num == 0:
161 logging.warning("Can't run on 0 hosts; using default.")
162 num = None
Chris Masonea8066a92012-05-01 16:52:31 -0700163
Simran Basib6ec8ae2014-04-23 12:05:08 -0700164 (ds, timings) = _stage_build_artifacts(build)
Chris Masone859fdec2012-01-30 08:38:09 -0800165
Simran Basib6ec8ae2014-04-23 12:05:08 -0700166 if not control_file:
167 # No control file was supplied so look it up from the build artifacts.
168 suite_name = canonicalize_suite_name(name)
169 control_file = _get_control_file_contents_by_name(build, ds, suite_name)
170 name = '%s-%s' % (build, suite_name)
Chris Masone46d0eb12012-07-27 18:56:39 -0700171
Simran Basi7e605742013-11-12 13:43:36 -0800172 timeout_mins = timeout_mins or timeout * 60
173
Simran Basib6ec8ae2014-04-23 12:05:08 -0700174 if not board:
175 board = utils.ParseBuildName(build)[0]
Chris Masone46d0eb12012-07-27 18:56:39 -0700176
Simran Basib6ec8ae2014-04-23 12:05:08 -0700177 # Prepend build and board to the control file.
Scott Zawalski65650172012-02-16 11:48:26 -0500178 inject_dict = {'board': board,
179 'build': build,
Chris Masone62579122012-03-08 15:18:43 -0800180 'check_hosts': check_hosts,
Chris Masone46d0eb12012-07-27 18:56:39 -0700181 'pool': pool,
Aviv Keshetd83ef442013-01-16 16:19:35 -0800182 'num': num,
Dan Shib8a99112013-06-18 13:46:10 -0700183 'file_bugs': file_bugs,
Alex Miller139690b2013-09-07 15:35:49 -0700184 'timeout': timeout,
Simran Basi7e605742013-11-12 13:43:36 -0800185 'timeout_mins': timeout_mins,
Alex Miller7d658cf2013-09-04 16:00:35 -0700186 'devserver_url': ds.url(),
Aviv Keshet7cd12312013-07-25 10:25:55 -0700187 'priority': priority,
Dan Shi95122412013-11-12 16:20:33 -0800188 'suite_args' : suite_args,
Fang Deng058860c2014-05-15 15:41:50 -0700189 'wait_for_results': wait_for_results,
190 'job_retry': job_retry
Aviv Keshet7cd12312013-07-25 10:25:55 -0700191 }
192
Simran Basib6ec8ae2014-04-23 12:05:08 -0700193 control_file = tools.inject_vars(inject_dict, control_file)
Chris Masone859fdec2012-01-30 08:38:09 -0800194
Simran Basib6ec8ae2014-04-23 12:05:08 -0700195 return _rpc_utils().create_job_common(name,
Alex Miller7d658cf2013-09-04 16:00:35 -0700196 priority=priority,
Simran Basi7e605742013-11-12 13:43:36 -0800197 timeout_mins=timeout_mins,
Alex Miller139690b2013-09-07 15:35:49 -0700198 max_runtime_mins=timeout*60,
Chris Masone859fdec2012-01-30 08:38:09 -0800199 control_type='Server',
200 control_file=control_file,
Chris Masonea8066a92012-05-01 16:52:31 -0700201 hostless=True,
202 keyvals=timings)
Simran Basi71206ef2014-08-13 13:51:18 -0700203
204
205# TODO: hide the following rpcs under is_moblab
206def moblab_only(func):
207 """Ensure moblab specific functions only run on Moblab devices."""
208 def verify(*args, **kwargs):
209 if not utils.is_moblab():
210 raise error.RPCException('RPC: %s can only run on Moblab Systems!',
211 func.__name__)
212 return func(*args, **kwargs)
213 return verify
214
215
216@moblab_only
217def get_config_values():
218 """Returns all config values parsed from global and shadow configs.
219
220 Config values are grouped by sections, and each section is composed of
221 a list of name value pairs.
222 """
223 sections =_CONFIG.get_sections()
224 config_values = {}
225 for section in sections:
226 config_values[section] = _CONFIG.config.items(section)
227 return _rpc_utils().prepare_for_serialization(config_values)
228
229
230@moblab_only
231def update_config_handler(config_values):
232 """
233 Update config values and override shadow config.
234
235 @param config_values: See get_moblab_settings().
236 """
237 for section, config_value_list in config_values.iteritems():
238 for key, value in config_value_list:
239 _CONFIG.override_config_value(section, key, value)
240 if not _CONFIG.shadow_file or not os.path.exists(_CONFIG.shadow_file):
241 raise error.RPCException('Shadow config file does not exist.')
242
243 with open(_CONFIG.shadow_file, 'w') as config_file:
244 _CONFIG.config.write(config_file)
245 # TODO (sbasi) crbug.com/403916 - Remove the reboot command and
246 # instead restart the services that rely on the config values.
247 os.system('sudo reboot')
248
249
250@moblab_only
251def reset_config_settings():
252 with open(_CONFIG.shadow_file, 'w') as config_file:
253 pass
254 os.system('sudo reboot')
255
256
257@moblab_only
258def set_boto_key(boto_key):
259 """Update the boto_key file.
260
261 @param boto_key: File name of boto_key uploaded through handle_file_upload.
262 """
263 if not os.path.exists(boto_key):
264 raise error.RPCException('Boto key: %s does not exist!' % boto_key)
265 shutil.copyfile(boto_key, moblab_host.MOBLAB_BOTO_LOCATION)