blob: fa6cb15073a49298837b0f802afcd74b25bcf133 [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
27
28
29_CONFIG = global_config.global_config
30MOBLAB_BOTO_LOCATION = '/home/moblab/.boto'
Chris Masone859fdec2012-01-30 08:38:09 -080031
32
Chris Masonef8b53062012-05-08 22:14:18 -070033# Relevant CrosDynamicSuiteExceptions are defined in client/common_lib/error.py.
Chris Masone859fdec2012-01-30 08:38:09 -080034
35
Chris Masone62579122012-03-08 15:18:43 -080036def canonicalize_suite_name(suite_name):
37 return 'test_suites/control.%s' % suite_name
38
39
Chris Masoneaa10f8e2012-05-15 13:34:21 -070040def formatted_now():
Chris Masone8d6e6412012-06-28 11:20:56 -070041 return datetime.datetime.now().strftime(job_status.TIME_FMT)
Chris Masoneaa10f8e2012-05-15 13:34:21 -070042
43
Simran Basib6ec8ae2014-04-23 12:05:08 -070044def _get_control_file_contents_by_name(build, ds, suite_name):
Chris Masone8dd27e02012-06-25 15:59:43 -070045 """Return control file contents for |suite_name|.
46
47 Query the dev server at |ds| for the control file |suite_name|, included
48 in |build| for |board|.
49
50 @param build: unique name by which to refer to the image from now on.
Chris Masone8dd27e02012-06-25 15:59:43 -070051 @param ds: a dev_server.DevServer instance to fetch control file with.
52 @param suite_name: canonicalized suite name, e.g. test_suites/control.bvt.
53 @raises ControlFileNotFound if a unique suite control file doesn't exist.
54 @raises NoControlFileList if we can't list the control files at all.
55 @raises ControlFileEmpty if the control file exists on the server, but
56 can't be read.
57
58 @return the contents of the desired control file.
59 """
60 getter = control_file_getter.DevServerGetter.create(build, ds)
61 # Get the control file for the suite.
62 try:
63 control_file_in = getter.get_control_file_contents_by_name(suite_name)
64 except error.CrosDynamicSuiteException as e:
Simran Basib6ec8ae2014-04-23 12:05:08 -070065 raise type(e)("%s while testing %s." % (e, build))
Chris Masone8dd27e02012-06-25 15:59:43 -070066 if not control_file_in:
67 raise error.ControlFileEmpty(
68 "Fetching %s returned no data." % suite_name)
Alex Millera713e252013-03-01 10:45:44 -080069 # Force control files to only contain ascii characters.
70 try:
71 control_file_in.encode('ascii')
72 except UnicodeDecodeError as e:
73 raise error.ControlFileMalformed(str(e))
74
Chris Masone8dd27e02012-06-25 15:59:43 -070075 return control_file_in
76
77
Simran Basib6ec8ae2014-04-23 12:05:08 -070078def _stage_build_artifacts(build):
79 """
80 Ensure components of |build| necessary for installing images are staged.
81
82 @param build image we want to stage.
83
84 @raises StageBuildFailure: if the dev server throws 500 while staging
85 build.
86
87 @return: dev_server.ImageServer instance to use with this build.
88 @return: timings dictionary containing staging start/end times.
89 """
90 timings = {}
91 # Set synchronous to False to allow other components to be downloaded in
92 # the background.
93 ds = dev_server.ImageServer.resolve(build)
94 timings[constants.DOWNLOAD_STARTED_TIME] = formatted_now()
95 try:
96 ds.stage_artifacts(build, ['test_suites'])
97 except dev_server.DevServerException as e:
98 raise error.StageBuildFailure(
99 "Failed to stage %s: %s" % (build, e))
100 timings[constants.PAYLOAD_FINISHED_TIME] = formatted_now()
101 return (ds, timings)
102
103
104def create_suite_job(name='', board='', build='', pool='', control_file='',
105 check_hosts=True, num=None, file_bugs=False, timeout=24,
106 timeout_mins=None, priority=priorities.Priority.DEFAULT,
Fang Deng058860c2014-05-15 15:41:50 -0700107 suite_args=None, wait_for_results=True, job_retry=False,
108 **kwargs):
Chris Masone859fdec2012-01-30 08:38:09 -0800109 """
110 Create a job to run a test suite on the given device with the given image.
111
112 When the timeout specified in the control file is reached, the
113 job is guaranteed to have completed and results will be available.
114
Simran Basib6ec8ae2014-04-23 12:05:08 -0700115 @param name: The test name if control_file is supplied, otherwise the name
116 of the test suite to run, e.g. 'bvt'.
Chris Masone859fdec2012-01-30 08:38:09 -0800117 @param board: the kind of device to run the tests on.
118 @param build: unique name by which to refer to the image from now on.
Scott Zawalski65650172012-02-16 11:48:26 -0500119 @param pool: Specify the pool of machines to use for scheduling
120 purposes.
Chris Masone62579122012-03-08 15:18:43 -0800121 @param check_hosts: require appropriate live hosts to exist in the lab.
Aviv Keshetd83ef442013-01-16 16:19:35 -0800122 @param num: Specify the number of machines to schedule across (integer).
123 Leave unspecified or use None to use default sharding factor.
Alex Millerc577f3e2012-09-27 14:06:07 -0700124 @param file_bugs: File a bug on each test failure in this suite.
Alex Miller139690b2013-09-07 15:35:49 -0700125 @param timeout: The max lifetime of this suite, in hours.
Simran Basi7e605742013-11-12 13:43:36 -0800126 @param timeout_mins: The max lifetime of this suite, in minutes. Takes
127 priority over timeout.
Alex Miller139690b2013-09-07 15:35:49 -0700128 @param priority: Integer denoting priority. Higher is more important.
Aviv Keshet7cd12312013-07-25 10:25:55 -0700129 @param suite_args: Optional arguments which will be parsed by the suite
130 control file. Used by control.test_that_wrapper to
131 determine which tests to run.
Dan Shi95122412013-11-12 16:20:33 -0800132 @param wait_for_results: Set to False to run the suite job without waiting
133 for test jobs to finish. Default is True.
Fang Deng058860c2014-05-15 15:41:50 -0700134 @param job_retry: Set to True to enable job-level retry. Default is False.
Simran Basib6ec8ae2014-04-23 12:05:08 -0700135 @param kwargs: extra keyword args. NOT USED.
Chris Masone859fdec2012-01-30 08:38:09 -0800136
Chris Masone8dd27e02012-06-25 15:59:43 -0700137 @raises ControlFileNotFound: if a unique suite control file doesn't exist.
138 @raises NoControlFileList: if we can't list the control files at all.
139 @raises StageBuildFailure: if the dev server throws 500 while staging build.
140 @raises ControlFileEmpty: if the control file exists on the server, but
141 can't be read.
Chris Masone859fdec2012-01-30 08:38:09 -0800142
143 @return: the job ID of the suite; -1 on error.
144 """
Aviv Keshetd83ef442013-01-16 16:19:35 -0800145 if type(num) is not int and num is not None:
Chris Sosa18c70b32013-02-15 14:12:43 -0800146 raise error.SuiteArgumentException('Ill specified num argument %r. '
147 'Must be an integer or None.' % num)
Aviv Keshetd83ef442013-01-16 16:19:35 -0800148 if num == 0:
149 logging.warning("Can't run on 0 hosts; using default.")
150 num = None
Chris Masonea8066a92012-05-01 16:52:31 -0700151
Simran Basib6ec8ae2014-04-23 12:05:08 -0700152 (ds, timings) = _stage_build_artifacts(build)
Chris Masone859fdec2012-01-30 08:38:09 -0800153
Simran Basib6ec8ae2014-04-23 12:05:08 -0700154 if not control_file:
155 # No control file was supplied so look it up from the build artifacts.
156 suite_name = canonicalize_suite_name(name)
157 control_file = _get_control_file_contents_by_name(build, ds, suite_name)
158 name = '%s-%s' % (build, suite_name)
Chris Masone46d0eb12012-07-27 18:56:39 -0700159
Simran Basi7e605742013-11-12 13:43:36 -0800160 timeout_mins = timeout_mins or timeout * 60
161
Simran Basib6ec8ae2014-04-23 12:05:08 -0700162 if not board:
163 board = utils.ParseBuildName(build)[0]
Chris Masone46d0eb12012-07-27 18:56:39 -0700164
Simran Basib6ec8ae2014-04-23 12:05:08 -0700165 # Prepend build and board to the control file.
Scott Zawalski65650172012-02-16 11:48:26 -0500166 inject_dict = {'board': board,
167 'build': build,
Chris Masone62579122012-03-08 15:18:43 -0800168 'check_hosts': check_hosts,
Chris Masone46d0eb12012-07-27 18:56:39 -0700169 'pool': pool,
Aviv Keshetd83ef442013-01-16 16:19:35 -0800170 'num': num,
Dan Shib8a99112013-06-18 13:46:10 -0700171 'file_bugs': file_bugs,
Alex Miller139690b2013-09-07 15:35:49 -0700172 'timeout': timeout,
Simran Basi7e605742013-11-12 13:43:36 -0800173 'timeout_mins': timeout_mins,
Alex Miller7d658cf2013-09-04 16:00:35 -0700174 'devserver_url': ds.url(),
Aviv Keshet7cd12312013-07-25 10:25:55 -0700175 'priority': priority,
Dan Shi95122412013-11-12 16:20:33 -0800176 'suite_args' : suite_args,
Fang Deng058860c2014-05-15 15:41:50 -0700177 'wait_for_results': wait_for_results,
178 'job_retry': job_retry
Aviv Keshet7cd12312013-07-25 10:25:55 -0700179 }
180
Simran Basib6ec8ae2014-04-23 12:05:08 -0700181 control_file = tools.inject_vars(inject_dict, control_file)
Chris Masone859fdec2012-01-30 08:38:09 -0800182
Jakob Juelich9fffe4f2014-08-14 18:07:05 -0700183 return rpc_utils.create_job_common(name,
Alex Miller7d658cf2013-09-04 16:00:35 -0700184 priority=priority,
Simran Basi7e605742013-11-12 13:43:36 -0800185 timeout_mins=timeout_mins,
Alex Miller139690b2013-09-07 15:35:49 -0700186 max_runtime_mins=timeout*60,
Chris Masone859fdec2012-01-30 08:38:09 -0800187 control_type='Server',
188 control_file=control_file,
Chris Masonea8066a92012-05-01 16:52:31 -0700189 hostless=True,
190 keyvals=timings)
Simran Basi71206ef2014-08-13 13:51:18 -0700191
192
193# TODO: hide the following rpcs under is_moblab
194def moblab_only(func):
195 """Ensure moblab specific functions only run on Moblab devices."""
196 def verify(*args, **kwargs):
197 if not utils.is_moblab():
198 raise error.RPCException('RPC: %s can only run on Moblab Systems!',
199 func.__name__)
200 return func(*args, **kwargs)
201 return verify
202
203
204@moblab_only
205def get_config_values():
206 """Returns all config values parsed from global and shadow configs.
207
208 Config values are grouped by sections, and each section is composed of
209 a list of name value pairs.
210 """
211 sections =_CONFIG.get_sections()
212 config_values = {}
213 for section in sections:
214 config_values[section] = _CONFIG.config.items(section)
Jakob Juelich9fffe4f2014-08-14 18:07:05 -0700215 return rpc_utils.prepare_for_serialization(config_values)
Simran Basi71206ef2014-08-13 13:51:18 -0700216
217
218@moblab_only
219def update_config_handler(config_values):
220 """
221 Update config values and override shadow config.
222
223 @param config_values: See get_moblab_settings().
224 """
225 for section, config_value_list in config_values.iteritems():
226 for key, value in config_value_list:
227 _CONFIG.override_config_value(section, key, value)
228 if not _CONFIG.shadow_file or not os.path.exists(_CONFIG.shadow_file):
229 raise error.RPCException('Shadow config file does not exist.')
230
231 with open(_CONFIG.shadow_file, 'w') as config_file:
232 _CONFIG.config.write(config_file)
233 # TODO (sbasi) crbug.com/403916 - Remove the reboot command and
234 # instead restart the services that rely on the config values.
235 os.system('sudo reboot')
236
237
238@moblab_only
239def reset_config_settings():
240 with open(_CONFIG.shadow_file, 'w') as config_file:
241 pass
242 os.system('sudo reboot')
243
244
245@moblab_only
246def set_boto_key(boto_key):
247 """Update the boto_key file.
248
249 @param boto_key: File name of boto_key uploaded through handle_file_upload.
250 """
251 if not os.path.exists(boto_key):
252 raise error.RPCException('Boto key: %s does not exist!' % boto_key)
253 shutil.copyfile(boto_key, moblab_host.MOBLAB_BOTO_LOCATION)