blob: 844846278e0c5d797bbed9070b5bef1e8e77fb0f [file] [log] [blame]
Alex Miller0516e4c2013-06-03 18:07:48 -07001# Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5
Alex Miller1968edf2014-02-27 18:11:36 -08006import abc
Alex Miller0516e4c2013-06-03 18:07:48 -07007import logging
8
9import common
10from autotest_lib.frontend.afe.json_rpc import proxy
11from autotest_lib.server import frontend
12
13
14### Constants for label prefixes
15CROS_VERSION_PREFIX = 'cros-version'
Fang Dengdbc86322013-08-09 16:17:30 -070016FW_VERSION_PREFIX = 'fw-version'
Alex Miller0516e4c2013-06-03 18:07:48 -070017
18
19### Helpers to convert value to label
20def cros_version_to_label(image):
21 """
22 Returns the proper label name for a ChromeOS build of |image|.
23
24 @param image: A string of the form 'lumpy-release/R28-3993.0.0'
25 @returns: A string that is the appropriate label name.
26
27 """
28 return CROS_VERSION_PREFIX + ':' + image
29
30
Alex Miller1968edf2014-02-27 18:11:36 -080031class _SpecialTaskAction(object):
Alex Miller0516e4c2013-06-03 18:07:48 -070032 """
Alex Miller1968edf2014-02-27 18:11:36 -080033 Base class to give a template for mapping labels to tests.
Alex Miller0516e4c2013-06-03 18:07:48 -070034 """
Alex Miller1968edf2014-02-27 18:11:36 -080035
36 __metaclass__ = abc.ABCMeta
Alex Miller0516e4c2013-06-03 18:07:48 -070037
38
Alex Miller1968edf2014-02-27 18:11:36 -080039 # One cannot do
40 # @abc.abstractproperty
41 # _actions = {}
42 # so this is the next best thing
43 @abc.abstractproperty
44 def _actions(self):
45 """A dictionary mapping labels to test names."""
46 pass
47
48
49 @abc.abstractproperty
50 def name(self):
51 """The name of this special task to be used in output."""
52 pass
53
54
55 @classmethod
56 def acts_on(cls, label):
57 """
58 Returns True if the label is a label that we recognize as something we
59 know how to act on, given our _actions.
60
61 @param label: The label as a string.
62 @returns: True if there exists a test to run for this label.
63
64 """
65 return label.split(':')[0] in cls._actions
66
67
68 @classmethod
69 def test_for(cls, label):
70 """
71 Returns the test associated with the given (string) label name.
72
73 @param label: The label for which the action is being requested.
74 @returns: The string name of the test that should be run.
75 @raises KeyError: If the name was not recognized as one we care about.
76
77 """
78 return cls._actions[label]
79
80
Alex Milleraa772002014-04-10 17:51:21 -070081 @classmethod
82 def partition(cls, labels):
83 """
84 Filter a list of labels into two sets: those labels that we know how to
85 act on and those that we don't know how to act on.
86
87 @param labels: A list of strings of labels.
88 @returns: A tuple where the first element is a set of unactionable
89 labels, and the second element is a set of the actionable
90 labels.
91 """
92 capabilities = set()
93 configurations = set()
94
95 for label in labels:
96 if cls.acts_on(label):
97 configurations.add(label)
98 else:
99 capabilities.add(label)
100
101 return capabilities, configurations
102
103
Alex Miller1968edf2014-02-27 18:11:36 -0800104class Verify(_SpecialTaskAction):
Alex Miller0516e4c2013-06-03 18:07:48 -0700105 """
Alex Miller1968edf2014-02-27 18:11:36 -0800106 Tests to verify that the DUT is in a sane, known good state that we can run
107 tests on. Failure to verify leads to running Repair.
Alex Miller0516e4c2013-06-03 18:07:48 -0700108 """
Alex Miller1968edf2014-02-27 18:11:36 -0800109
110 _actions = {
harpreetafdf4d92014-04-04 12:03:50 -0700111 'modem_repair': 'cellular_StaleModemReboot'
Alex Miller1968edf2014-02-27 18:11:36 -0800112 }
113
114 name = 'verify'
115
116
117class Provision(_SpecialTaskAction):
118 """
119 Provisioning runs to change the configuration of the DUT from one state to
120 another. It will only be run on verified DUTs.
121 """
122
123 # TODO(milleral): http://crbug.com/249555
124 # Create some way to discover and register provisioning tests so that we
125 # don't need to hand-maintain a list of all of them.
126 _actions = {
127 CROS_VERSION_PREFIX: 'provision_AutoUpdate',
128 FW_VERSION_PREFIX: 'provision_FirmwareUpdate',
129 }
130
131 name = 'provision'
132
133
134class Cleanup(_SpecialTaskAction):
135 """
136 Cleanup runs after a test fails to try and remove artifacts of tests and
137 ensure the DUT will be in a sane state for the next test run.
138 """
139
140 _actions = {
Alex Millerf47db9c2014-04-18 18:36:36 -0700141 'cleanup-reboot': 'generic_RebootTest',
Alex Miller1968edf2014-02-27 18:11:36 -0800142 }
143
144 name = 'cleanup'
145
146
147class Repair(_SpecialTaskAction):
148 """
149 Repair runs when one of the other special tasks fails. It should be able
150 to take a component of the DUT that's in an unknown state and restore it to
151 a good state.
152 """
153
154 _actions = {
155 }
156
157 name = 'repair'
158
159
Alex Miller1968edf2014-02-27 18:11:36 -0800160
Alex Milleraa772002014-04-10 17:51:21 -0700161# TODO(milleral): crbug.com/364273
162# Label doesn't really mean label in this context. We're putting things into
163# DEPENDENCIES that really aren't DEPENDENCIES, and we should probably stop
164# doing that.
165def is_for_special_action(label):
166 """
167 If any special task handles the label specially, then we're using the label
168 to communicate that we want an action, and not as an actual dependency that
169 the test has.
170
171 @param label: A string label name.
172 @return True if any special task handles this label specially,
173 False if no special task handles this label.
174 """
175 return (Verify.acts_on(label) or
176 Provision.acts_on(label) or
177 Cleanup.acts_on(label) or
178 Repair.acts_on(label))
Alex Miller0516e4c2013-06-03 18:07:48 -0700179
180
181def filter_labels(labels):
182 """
183 Filter a list of labels into two sets: those labels that we know how to
184 change and those that we don't. For the ones we know how to change, split
185 them apart into the name of configuration type and its value.
186
187 @param labels: A list of strings of labels.
188 @returns: A tuple where the first element is a set of unprovisionable
189 labels, and the second element is a set of the provisionable
190 labels.
191
192 >>> filter_labels(['bluetooth', 'cros-version:lumpy-release/R28-3993.0.0'])
193 (set(['bluetooth']), set(['cros-version:lumpy-release/R28-3993.0.0']))
194
195 """
Alex Milleraa772002014-04-10 17:51:21 -0700196 return Provision.partition(labels)
Alex Miller0516e4c2013-06-03 18:07:48 -0700197
198
199def split_labels(labels):
200 """
201 Split a list of labels into a dict mapping name to value. All labels must
202 be provisionable labels, or else a ValueError
203
204 @param labels: list of strings of label names
205 @returns: A dict of where the key is the configuration name, and the value
206 is the configuration value.
207 @raises: ValueError if a label is not a provisionable label.
208
209 >>> split_labels(['cros-version:lumpy-release/R28-3993.0.0'])
210 {'cros-version': 'lumpy-release/R28-3993.0.0'}
211 >>> split_labels(['bluetooth'])
212 Traceback (most recent call last):
213 ...
214 ValueError: Unprovisionable label bluetooth
215
216 """
217 configurations = dict()
218
219 for label in labels:
Alex Milleraa772002014-04-10 17:51:21 -0700220 if Provision.acts_on(label):
Alex Miller0516e4c2013-06-03 18:07:48 -0700221 name, value = label.split(':', 1)
222 configurations[name] = value
223 else:
224 raise ValueError('Unprovisionable label %s' % label)
225
226 return configurations
227
228
Alex Miller2229c9c2013-08-27 15:20:39 -0700229def join(provision_type, provision_value):
230 """
231 Combine the provision type and value into the label name.
232
233 @param provision_type: One of the constants that are the label prefixes.
234 @param provision_value: A string of the value for this provision type.
235 @returns: A string that is the label name for this (type, value) pair.
236
237 >>> join(CROS_VERSION_PREFIX, 'lumpy-release/R27-3773.0.0')
238 'cros-version:lumpy-release/R27-3773.0.0'
239
240 """
241 return '%s:%s' % (provision_type, provision_value)
242
243
Alex Miller667b5f22014-02-28 15:33:39 -0800244class SpecialTaskActionException(Exception):
245 """
246 Exception raised when a special task fails to successfully run a test that
247 is required.
248
249 This is also a literally meaningless exception. It's always just discarded.
250 """
251
252
253def run_special_task_actions(job, host, labels, task):
254 """
255 Iterate through all `label`s and run any tests on `host` that `task` has
256 corresponding to the passed in labels.
257
258 Emits status lines for each run test, and INFO lines for each skipped label.
259
260 @param job: A job object from a control file.
261 @param host: The host to run actions on.
262 @param labels: The list of job labels to work on.
263 @param task: An instance of _SpecialTaskAction.
264 @returns: None
265 @raises: SpecialTaskActionException if a test fails.
266
267 """
268 capabilities, configuration = filter_labels(labels)
269
270 for label in capabilities:
271 if task.acts_on(label):
272 test = task.test_for(label)
273 success = job.run_test(test, host=host)
274 if not success:
275 raise SpecialTaskActionException()
276 else:
277 job.record('INFO', None, task.name,
278 "Can't %s label '%s'." % (task.name, label))
279
280 for name, value in split_labels(configuration).items():
281 if task.acts_on(name):
282 test = task.test_for(name)
283 success = job.run_test(test, host=host, value=value)
284 if not success:
285 raise SpecialTaskActionException()
286 else:
287 job.record('INFO', None, task.name,
288 "Can't %s label '%s:%s'." % (task.name, name, value))
289
290
Alex Miller2229c9c2013-08-27 15:20:39 -0700291# This has been copied out of dynamic_suite's reimager.py, which no longer
292# exists. I'd prefer if this would go away by doing http://crbug.com/249424,
293# so that labels are just automatically made when we try to add them to a host.
Alex Miller0516e4c2013-06-03 18:07:48 -0700294def ensure_label_exists(name):
295 """
296 Ensure that a label called |name| exists in the autotest DB.
297
298 @param name: the label to check for/create.
299 @raises ValidationError: There was an error in the response that was
300 not because the label already existed.
301
302 """
303 afe = frontend.AFE()
304 try:
305 afe.create_label(name=name)
306 except proxy.ValidationError as ve:
307 if ('name' in ve.problem_keys and
308 'This value must be unique' in ve.problem_keys['name']):
309 logging.debug('Version label %s already exists', name)
310 else:
311 raise ve