blob: 78048d11a0e187fc0105cc8c96f6d2e0d1785893 [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
Jakob Juelich9fffe4f2014-08-14 18:07:05 -070020from autotest_lib.frontend.afe import rpc_utils
Simran Basib6ec8ae2014-04-23 12:05:08 -070021from autotest_lib.server import utils
Chris Masone44e4d6c2012-08-15 14:25:53 -070022from autotest_lib.server.cros.dynamic_suite import constants
Chris Masoneb4935552012-08-14 12:05:54 -070023from autotest_lib.server.cros.dynamic_suite import control_file_getter
Chris Masoneb4935552012-08-14 12:05:54 -070024from autotest_lib.server.cros.dynamic_suite import job_status
Chris Masone44e4d6c2012-08-15 14:25:53 -070025from autotest_lib.server.cros.dynamic_suite import tools
Simran Basi71206ef2014-08-13 13:51:18 -070026from autotest_lib.server.hosts import moblab_host
Dan Shi193905e2014-07-25 23:33:09 -070027from autotest_lib.site_utils import job_history
Simran Basi71206ef2014-08-13 13:51:18 -070028
29
30_CONFIG = global_config.global_config
31MOBLAB_BOTO_LOCATION = '/home/moblab/.boto'
Chris Masone859fdec2012-01-30 08:38:09 -080032
33
Chris Masonef8b53062012-05-08 22:14:18 -070034# Relevant CrosDynamicSuiteExceptions are defined in client/common_lib/error.py.
Chris Masone859fdec2012-01-30 08:38:09 -080035
36
Chris Masone62579122012-03-08 15:18:43 -080037def canonicalize_suite_name(suite_name):
38 return 'test_suites/control.%s' % suite_name
39
40
Chris Masoneaa10f8e2012-05-15 13:34:21 -070041def formatted_now():
Chris Masone8d6e6412012-06-28 11:20:56 -070042 return datetime.datetime.now().strftime(job_status.TIME_FMT)
Chris Masoneaa10f8e2012-05-15 13:34:21 -070043
44
Simran Basib6ec8ae2014-04-23 12:05:08 -070045def _get_control_file_contents_by_name(build, ds, suite_name):
Chris Masone8dd27e02012-06-25 15:59:43 -070046 """Return control file contents for |suite_name|.
47
48 Query the dev server at |ds| for the control file |suite_name|, included
49 in |build| for |board|.
50
51 @param build: unique name by which to refer to the image from now on.
Chris Masone8dd27e02012-06-25 15:59:43 -070052 @param ds: a dev_server.DevServer instance to fetch control file with.
53 @param suite_name: canonicalized suite name, e.g. test_suites/control.bvt.
54 @raises ControlFileNotFound if a unique suite control file doesn't exist.
55 @raises NoControlFileList if we can't list the control files at all.
56 @raises ControlFileEmpty if the control file exists on the server, but
57 can't be read.
58
59 @return the contents of the desired control file.
60 """
61 getter = control_file_getter.DevServerGetter.create(build, ds)
62 # Get the control file for the suite.
63 try:
64 control_file_in = getter.get_control_file_contents_by_name(suite_name)
65 except error.CrosDynamicSuiteException as e:
Simran Basib6ec8ae2014-04-23 12:05:08 -070066 raise type(e)("%s while testing %s." % (e, build))
Chris Masone8dd27e02012-06-25 15:59:43 -070067 if not control_file_in:
68 raise error.ControlFileEmpty(
69 "Fetching %s returned no data." % suite_name)
Alex Millera713e252013-03-01 10:45:44 -080070 # Force control files to only contain ascii characters.
71 try:
72 control_file_in.encode('ascii')
73 except UnicodeDecodeError as e:
74 raise error.ControlFileMalformed(str(e))
75
Chris Masone8dd27e02012-06-25 15:59:43 -070076 return control_file_in
77
78
Simran Basib6ec8ae2014-04-23 12:05:08 -070079def _stage_build_artifacts(build):
80 """
81 Ensure components of |build| necessary for installing images are staged.
82
83 @param build image we want to stage.
84
85 @raises StageBuildFailure: if the dev server throws 500 while staging
86 build.
87
88 @return: dev_server.ImageServer instance to use with this build.
89 @return: timings dictionary containing staging start/end times.
90 """
91 timings = {}
92 # Set synchronous to False to allow other components to be downloaded in
93 # the background.
94 ds = dev_server.ImageServer.resolve(build)
95 timings[constants.DOWNLOAD_STARTED_TIME] = formatted_now()
96 try:
97 ds.stage_artifacts(build, ['test_suites'])
98 except dev_server.DevServerException as e:
99 raise error.StageBuildFailure(
100 "Failed to stage %s: %s" % (build, e))
101 timings[constants.PAYLOAD_FINISHED_TIME] = formatted_now()
102 return (ds, timings)
103
104
105def create_suite_job(name='', board='', build='', pool='', control_file='',
106 check_hosts=True, num=None, file_bugs=False, timeout=24,
107 timeout_mins=None, priority=priorities.Priority.DEFAULT,
Fang Deng058860c2014-05-15 15:41:50 -0700108 suite_args=None, wait_for_results=True, job_retry=False,
109 **kwargs):
Chris Masone859fdec2012-01-30 08:38:09 -0800110 """
111 Create a job to run a test suite on the given device with the given image.
112
113 When the timeout specified in the control file is reached, the
114 job is guaranteed to have completed and results will be available.
115
Simran Basib6ec8ae2014-04-23 12:05:08 -0700116 @param name: The test name if control_file is supplied, otherwise the name
117 of the test suite to run, e.g. 'bvt'.
Chris Masone859fdec2012-01-30 08:38:09 -0800118 @param board: the kind of device to run the tests on.
119 @param build: unique name by which to refer to the image from now on.
Scott Zawalski65650172012-02-16 11:48:26 -0500120 @param pool: Specify the pool of machines to use for scheduling
121 purposes.
Chris Masone62579122012-03-08 15:18:43 -0800122 @param check_hosts: require appropriate live hosts to exist in the lab.
Aviv Keshetd83ef442013-01-16 16:19:35 -0800123 @param num: Specify the number of machines to schedule across (integer).
124 Leave unspecified or use None to use default sharding factor.
Alex Millerc577f3e2012-09-27 14:06:07 -0700125 @param file_bugs: File a bug on each test failure in this suite.
Alex Miller139690b2013-09-07 15:35:49 -0700126 @param timeout: The max lifetime of this suite, in hours.
Simran Basi7e605742013-11-12 13:43:36 -0800127 @param timeout_mins: The max lifetime of this suite, in minutes. Takes
128 priority over timeout.
Alex Miller139690b2013-09-07 15:35:49 -0700129 @param priority: Integer denoting priority. Higher is more important.
Aviv Keshet7cd12312013-07-25 10:25:55 -0700130 @param suite_args: Optional arguments which will be parsed by the suite
131 control file. Used by control.test_that_wrapper to
132 determine which tests to run.
Dan Shi95122412013-11-12 16:20:33 -0800133 @param wait_for_results: Set to False to run the suite job without waiting
134 for test jobs to finish. Default is True.
Fang Deng058860c2014-05-15 15:41:50 -0700135 @param job_retry: Set to True to enable job-level retry. Default is False.
Simran Basib6ec8ae2014-04-23 12:05:08 -0700136 @param kwargs: extra keyword args. NOT USED.
Chris Masone859fdec2012-01-30 08:38:09 -0800137
Chris Masone8dd27e02012-06-25 15:59:43 -0700138 @raises ControlFileNotFound: if a unique suite control file doesn't exist.
139 @raises NoControlFileList: if we can't list the control files at all.
140 @raises StageBuildFailure: if the dev server throws 500 while staging build.
141 @raises ControlFileEmpty: if the control file exists on the server, but
142 can't be read.
Chris Masone859fdec2012-01-30 08:38:09 -0800143
144 @return: the job ID of the suite; -1 on error.
145 """
Aviv Keshetd83ef442013-01-16 16:19:35 -0800146 if type(num) is not int and num is not None:
Chris Sosa18c70b32013-02-15 14:12:43 -0800147 raise error.SuiteArgumentException('Ill specified num argument %r. '
148 'Must be an integer or None.' % num)
Aviv Keshetd83ef442013-01-16 16:19:35 -0800149 if num == 0:
150 logging.warning("Can't run on 0 hosts; using default.")
151 num = None
Chris Masonea8066a92012-05-01 16:52:31 -0700152
Simran Basib6ec8ae2014-04-23 12:05:08 -0700153 (ds, timings) = _stage_build_artifacts(build)
Chris Masone859fdec2012-01-30 08:38:09 -0800154
Simran Basib6ec8ae2014-04-23 12:05:08 -0700155 if not control_file:
156 # No control file was supplied so look it up from the build artifacts.
157 suite_name = canonicalize_suite_name(name)
158 control_file = _get_control_file_contents_by_name(build, ds, suite_name)
159 name = '%s-%s' % (build, suite_name)
Chris Masone46d0eb12012-07-27 18:56:39 -0700160
Simran Basi7e605742013-11-12 13:43:36 -0800161 timeout_mins = timeout_mins or timeout * 60
162
Simran Basib6ec8ae2014-04-23 12:05:08 -0700163 if not board:
164 board = utils.ParseBuildName(build)[0]
Chris Masone46d0eb12012-07-27 18:56:39 -0700165
Simran Basib6ec8ae2014-04-23 12:05:08 -0700166 # Prepend build and board to the control file.
Scott Zawalski65650172012-02-16 11:48:26 -0500167 inject_dict = {'board': board,
168 'build': build,
Chris Masone62579122012-03-08 15:18:43 -0800169 'check_hosts': check_hosts,
Chris Masone46d0eb12012-07-27 18:56:39 -0700170 'pool': pool,
Aviv Keshetd83ef442013-01-16 16:19:35 -0800171 'num': num,
Dan Shib8a99112013-06-18 13:46:10 -0700172 'file_bugs': file_bugs,
Alex Miller139690b2013-09-07 15:35:49 -0700173 'timeout': timeout,
Simran Basi7e605742013-11-12 13:43:36 -0800174 'timeout_mins': timeout_mins,
Alex Miller7d658cf2013-09-04 16:00:35 -0700175 'devserver_url': ds.url(),
Aviv Keshet7cd12312013-07-25 10:25:55 -0700176 'priority': priority,
Dan Shi95122412013-11-12 16:20:33 -0800177 'suite_args' : suite_args,
Fang Deng058860c2014-05-15 15:41:50 -0700178 'wait_for_results': wait_for_results,
179 'job_retry': job_retry
Aviv Keshet7cd12312013-07-25 10:25:55 -0700180 }
181
Simran Basib6ec8ae2014-04-23 12:05:08 -0700182 control_file = tools.inject_vars(inject_dict, control_file)
Chris Masone859fdec2012-01-30 08:38:09 -0800183
Jakob Juelich9fffe4f2014-08-14 18:07:05 -0700184 return rpc_utils.create_job_common(name,
Alex Miller7d658cf2013-09-04 16:00:35 -0700185 priority=priority,
Simran Basi7e605742013-11-12 13:43:36 -0800186 timeout_mins=timeout_mins,
Alex Miller139690b2013-09-07 15:35:49 -0700187 max_runtime_mins=timeout*60,
Chris Masone859fdec2012-01-30 08:38:09 -0800188 control_type='Server',
189 control_file=control_file,
Chris Masonea8066a92012-05-01 16:52:31 -0700190 hostless=True,
191 keyvals=timings)
Simran Basi71206ef2014-08-13 13:51:18 -0700192
193
194# TODO: hide the following rpcs under is_moblab
195def moblab_only(func):
196 """Ensure moblab specific functions only run on Moblab devices."""
197 def verify(*args, **kwargs):
198 if not utils.is_moblab():
199 raise error.RPCException('RPC: %s can only run on Moblab Systems!',
200 func.__name__)
201 return func(*args, **kwargs)
202 return verify
203
204
205@moblab_only
206def get_config_values():
207 """Returns all config values parsed from global and shadow configs.
208
209 Config values are grouped by sections, and each section is composed of
210 a list of name value pairs.
211 """
212 sections =_CONFIG.get_sections()
213 config_values = {}
214 for section in sections:
215 config_values[section] = _CONFIG.config.items(section)
Jakob Juelich9fffe4f2014-08-14 18:07:05 -0700216 return rpc_utils.prepare_for_serialization(config_values)
Simran Basi71206ef2014-08-13 13:51:18 -0700217
218
219@moblab_only
220def update_config_handler(config_values):
221 """
222 Update config values and override shadow config.
223
224 @param config_values: See get_moblab_settings().
225 """
226 for section, config_value_list in config_values.iteritems():
227 for key, value in config_value_list:
228 _CONFIG.override_config_value(section, key, value)
229 if not _CONFIG.shadow_file or not os.path.exists(_CONFIG.shadow_file):
230 raise error.RPCException('Shadow config file does not exist.')
231
232 with open(_CONFIG.shadow_file, 'w') as config_file:
233 _CONFIG.config.write(config_file)
234 # TODO (sbasi) crbug.com/403916 - Remove the reboot command and
235 # instead restart the services that rely on the config values.
236 os.system('sudo reboot')
237
238
239@moblab_only
240def reset_config_settings():
241 with open(_CONFIG.shadow_file, 'w') as config_file:
242 pass
243 os.system('sudo reboot')
244
245
246@moblab_only
247def set_boto_key(boto_key):
248 """Update the boto_key file.
249
250 @param boto_key: File name of boto_key uploaded through handle_file_upload.
251 """
252 if not os.path.exists(boto_key):
253 raise error.RPCException('Boto key: %s does not exist!' % boto_key)
254 shutil.copyfile(boto_key, moblab_host.MOBLAB_BOTO_LOCATION)
Dan Shi193905e2014-07-25 23:33:09 -0700255
256
257def get_job_history(**filter_data):
258 """Get history of the job, including the special tasks executed for the job
259
260 @param filter_data: filter for the call, should at least include
261 {'job_id': [job id]}
262 @returns: JSON string of the job's history, including the information such
263 as the hosts run the job and the special tasks executed before
264 and after the job.
265 """
266 job_id = filter_data['job_id']
267 job_info = job_history.get_job_info(job_id)
268 return _rpc_utils().prepare_for_serialization(job_info.get_history())