blob: 83f8e80f934ee3e33fe04828770e0618c2151200 [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
Fang Deng23b28952014-09-12 23:14:49 +000014import 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,
Simran Basi102e3522014-09-11 11:46:10 -0700109 max_runtime_mins=None, **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 Basi102e3522014-09-11 11:46:10 -0700136 @param max_runtime_mins: Maximum amount of time a job can be running in
137 minutes.
Simran Basib6ec8ae2014-04-23 12:05:08 -0700138 @param kwargs: extra keyword args. NOT USED.
Chris Masone859fdec2012-01-30 08:38:09 -0800139
Chris Masone8dd27e02012-06-25 15:59:43 -0700140 @raises ControlFileNotFound: if a unique suite control file doesn't exist.
141 @raises NoControlFileList: if we can't list the control files at all.
142 @raises StageBuildFailure: if the dev server throws 500 while staging build.
143 @raises ControlFileEmpty: if the control file exists on the server, but
144 can't be read.
Chris Masone859fdec2012-01-30 08:38:09 -0800145
146 @return: the job ID of the suite; -1 on error.
147 """
Aviv Keshetd83ef442013-01-16 16:19:35 -0800148 if type(num) is not int and num is not None:
Chris Sosa18c70b32013-02-15 14:12:43 -0800149 raise error.SuiteArgumentException('Ill specified num argument %r. '
150 'Must be an integer or None.' % num)
Aviv Keshetd83ef442013-01-16 16:19:35 -0800151 if num == 0:
152 logging.warning("Can't run on 0 hosts; using default.")
153 num = None
Chris Masonea8066a92012-05-01 16:52:31 -0700154
Simran Basib6ec8ae2014-04-23 12:05:08 -0700155 (ds, timings) = _stage_build_artifacts(build)
Chris Masone859fdec2012-01-30 08:38:09 -0800156
Simran Basib6ec8ae2014-04-23 12:05:08 -0700157 if not control_file:
158 # No control file was supplied so look it up from the build artifacts.
159 suite_name = canonicalize_suite_name(name)
160 control_file = _get_control_file_contents_by_name(build, ds, suite_name)
161 name = '%s-%s' % (build, suite_name)
Chris Masone46d0eb12012-07-27 18:56:39 -0700162
Simran Basi7e605742013-11-12 13:43:36 -0800163 timeout_mins = timeout_mins or timeout * 60
Simran Basi102e3522014-09-11 11:46:10 -0700164 max_runtime_mins = max_runtime_mins or timeout * 60
Simran Basi7e605742013-11-12 13:43:36 -0800165
Simran Basib6ec8ae2014-04-23 12:05:08 -0700166 if not board:
167 board = utils.ParseBuildName(build)[0]
Chris Masone46d0eb12012-07-27 18:56:39 -0700168
Simran Basib6ec8ae2014-04-23 12:05:08 -0700169 # Prepend build and board to the control file.
Scott Zawalski65650172012-02-16 11:48:26 -0500170 inject_dict = {'board': board,
171 'build': build,
Chris Masone62579122012-03-08 15:18:43 -0800172 'check_hosts': check_hosts,
Chris Masone46d0eb12012-07-27 18:56:39 -0700173 'pool': pool,
Aviv Keshetd83ef442013-01-16 16:19:35 -0800174 'num': num,
Dan Shib8a99112013-06-18 13:46:10 -0700175 'file_bugs': file_bugs,
Alex Miller139690b2013-09-07 15:35:49 -0700176 'timeout': timeout,
Simran Basi7e605742013-11-12 13:43:36 -0800177 'timeout_mins': timeout_mins,
Alex Miller7d658cf2013-09-04 16:00:35 -0700178 'devserver_url': ds.url(),
Aviv Keshet7cd12312013-07-25 10:25:55 -0700179 'priority': priority,
Dan Shi95122412013-11-12 16:20:33 -0800180 'suite_args' : suite_args,
Fang Deng058860c2014-05-15 15:41:50 -0700181 'wait_for_results': wait_for_results,
Simran Basi102e3522014-09-11 11:46:10 -0700182 'job_retry': job_retry,
183 'max_runtime_mins': max_runtime_mins
Aviv Keshet7cd12312013-07-25 10:25:55 -0700184 }
185
Simran Basib6ec8ae2014-04-23 12:05:08 -0700186 control_file = tools.inject_vars(inject_dict, control_file)
Chris Masone859fdec2012-01-30 08:38:09 -0800187
Jakob Juelich9fffe4f2014-08-14 18:07:05 -0700188 return rpc_utils.create_job_common(name,
Fang Deng23b28952014-09-12 23:14:49 +0000189 priority=priority,
190 timeout_mins=timeout_mins,
Simran Basi102e3522014-09-11 11:46:10 -0700191 max_runtime_mins=max_runtime_mins,
Fang Deng23b28952014-09-12 23:14:49 +0000192 control_type='Server',
193 control_file=control_file,
194 hostless=True,
195 keyvals=timings)
Simran Basi71206ef2014-08-13 13:51:18 -0700196
197
198# TODO: hide the following rpcs under is_moblab
199def moblab_only(func):
200 """Ensure moblab specific functions only run on Moblab devices."""
201 def verify(*args, **kwargs):
202 if not utils.is_moblab():
203 raise error.RPCException('RPC: %s can only run on Moblab Systems!',
204 func.__name__)
205 return func(*args, **kwargs)
206 return verify
207
208
209@moblab_only
210def get_config_values():
211 """Returns all config values parsed from global and shadow configs.
212
213 Config values are grouped by sections, and each section is composed of
214 a list of name value pairs.
215 """
216 sections =_CONFIG.get_sections()
217 config_values = {}
218 for section in sections:
219 config_values[section] = _CONFIG.config.items(section)
Jakob Juelich9fffe4f2014-08-14 18:07:05 -0700220 return rpc_utils.prepare_for_serialization(config_values)
Simran Basi71206ef2014-08-13 13:51:18 -0700221
222
223@moblab_only
224def update_config_handler(config_values):
225 """
226 Update config values and override shadow config.
227
228 @param config_values: See get_moblab_settings().
229 """
230 for section, config_value_list in config_values.iteritems():
231 for key, value in config_value_list:
232 _CONFIG.override_config_value(section, key, value)
233 if not _CONFIG.shadow_file or not os.path.exists(_CONFIG.shadow_file):
234 raise error.RPCException('Shadow config file does not exist.')
235
236 with open(_CONFIG.shadow_file, 'w') as config_file:
237 _CONFIG.config.write(config_file)
238 # TODO (sbasi) crbug.com/403916 - Remove the reboot command and
239 # instead restart the services that rely on the config values.
240 os.system('sudo reboot')
241
242
243@moblab_only
244def reset_config_settings():
245 with open(_CONFIG.shadow_file, 'w') as config_file:
246 pass
247 os.system('sudo reboot')
248
249
250@moblab_only
251def set_boto_key(boto_key):
252 """Update the boto_key file.
253
254 @param boto_key: File name of boto_key uploaded through handle_file_upload.
255 """
256 if not os.path.exists(boto_key):
257 raise error.RPCException('Boto key: %s does not exist!' % boto_key)
258 shutil.copyfile(boto_key, moblab_host.MOBLAB_BOTO_LOCATION)
Dan Shi193905e2014-07-25 23:33:09 -0700259
260
261def get_job_history(**filter_data):
262 """Get history of the job, including the special tasks executed for the job
263
264 @param filter_data: filter for the call, should at least include
265 {'job_id': [job id]}
266 @returns: JSON string of the job's history, including the information such
267 as the hosts run the job and the special tasks executed before
268 and after the job.
269 """
270 job_id = filter_data['job_id']
271 job_info = job_history.get_job_info(job_id)
272 return _rpc_utils().prepare_for_serialization(job_info.get_history())