blob: b0127866b9463728c41759382c8d602f54ae18ec [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
81class Verify(_SpecialTaskAction):
Alex Miller0516e4c2013-06-03 18:07:48 -070082 """
Alex Miller1968edf2014-02-27 18:11:36 -080083 Tests to verify that the DUT is in a sane, known good state that we can run
84 tests on. Failure to verify leads to running Repair.
Alex Miller0516e4c2013-06-03 18:07:48 -070085 """
Alex Miller1968edf2014-02-27 18:11:36 -080086
87 _actions = {
88 }
89
90 name = 'verify'
91
92
93class Provision(_SpecialTaskAction):
94 """
95 Provisioning runs to change the configuration of the DUT from one state to
96 another. It will only be run on verified DUTs.
97 """
98
99 # TODO(milleral): http://crbug.com/249555
100 # Create some way to discover and register provisioning tests so that we
101 # don't need to hand-maintain a list of all of them.
102 _actions = {
103 CROS_VERSION_PREFIX: 'provision_AutoUpdate',
104 FW_VERSION_PREFIX: 'provision_FirmwareUpdate',
105 }
106
107 name = 'provision'
108
109
110class Cleanup(_SpecialTaskAction):
111 """
112 Cleanup runs after a test fails to try and remove artifacts of tests and
113 ensure the DUT will be in a sane state for the next test run.
114 """
115
116 _actions = {
117 }
118
119 name = 'cleanup'
120
121
122class Repair(_SpecialTaskAction):
123 """
124 Repair runs when one of the other special tasks fails. It should be able
125 to take a component of the DUT that's in an unknown state and restore it to
126 a good state.
127 """
128
129 _actions = {
130 }
131
132 name = 'repair'
133
134
135# For backwards compatibility with old control files, we still need the
136# following:
137
138can_provision = Provision.acts_on
139provisioner_for = Provision.test_for
Alex Miller0516e4c2013-06-03 18:07:48 -0700140
141
142def filter_labels(labels):
143 """
144 Filter a list of labels into two sets: those labels that we know how to
145 change and those that we don't. For the ones we know how to change, split
146 them apart into the name of configuration type and its value.
147
148 @param labels: A list of strings of labels.
149 @returns: A tuple where the first element is a set of unprovisionable
150 labels, and the second element is a set of the provisionable
151 labels.
152
153 >>> filter_labels(['bluetooth', 'cros-version:lumpy-release/R28-3993.0.0'])
154 (set(['bluetooth']), set(['cros-version:lumpy-release/R28-3993.0.0']))
155
156 """
157 capabilities = set()
158 configurations = set()
159
160 for label in labels:
161 if can_provision(label):
162 configurations.add(label)
163 else:
164 capabilities.add(label)
165
166 return capabilities, configurations
167
168
169def split_labels(labels):
170 """
171 Split a list of labels into a dict mapping name to value. All labels must
172 be provisionable labels, or else a ValueError
173
174 @param labels: list of strings of label names
175 @returns: A dict of where the key is the configuration name, and the value
176 is the configuration value.
177 @raises: ValueError if a label is not a provisionable label.
178
179 >>> split_labels(['cros-version:lumpy-release/R28-3993.0.0'])
180 {'cros-version': 'lumpy-release/R28-3993.0.0'}
181 >>> split_labels(['bluetooth'])
182 Traceback (most recent call last):
183 ...
184 ValueError: Unprovisionable label bluetooth
185
186 """
187 configurations = dict()
188
189 for label in labels:
190 if can_provision(label):
191 name, value = label.split(':', 1)
192 configurations[name] = value
193 else:
194 raise ValueError('Unprovisionable label %s' % label)
195
196 return configurations
197
198
Alex Miller2229c9c2013-08-27 15:20:39 -0700199def join(provision_type, provision_value):
200 """
201 Combine the provision type and value into the label name.
202
203 @param provision_type: One of the constants that are the label prefixes.
204 @param provision_value: A string of the value for this provision type.
205 @returns: A string that is the label name for this (type, value) pair.
206
207 >>> join(CROS_VERSION_PREFIX, 'lumpy-release/R27-3773.0.0')
208 'cros-version:lumpy-release/R27-3773.0.0'
209
210 """
211 return '%s:%s' % (provision_type, provision_value)
212
213
Alex Miller667b5f22014-02-28 15:33:39 -0800214class SpecialTaskActionException(Exception):
215 """
216 Exception raised when a special task fails to successfully run a test that
217 is required.
218
219 This is also a literally meaningless exception. It's always just discarded.
220 """
221
222
223def run_special_task_actions(job, host, labels, task):
224 """
225 Iterate through all `label`s and run any tests on `host` that `task` has
226 corresponding to the passed in labels.
227
228 Emits status lines for each run test, and INFO lines for each skipped label.
229
230 @param job: A job object from a control file.
231 @param host: The host to run actions on.
232 @param labels: The list of job labels to work on.
233 @param task: An instance of _SpecialTaskAction.
234 @returns: None
235 @raises: SpecialTaskActionException if a test fails.
236
237 """
238 capabilities, configuration = filter_labels(labels)
239
240 for label in capabilities:
241 if task.acts_on(label):
242 test = task.test_for(label)
243 success = job.run_test(test, host=host)
244 if not success:
245 raise SpecialTaskActionException()
246 else:
247 job.record('INFO', None, task.name,
248 "Can't %s label '%s'." % (task.name, label))
249
250 for name, value in split_labels(configuration).items():
251 if task.acts_on(name):
252 test = task.test_for(name)
253 success = job.run_test(test, host=host, value=value)
254 if not success:
255 raise SpecialTaskActionException()
256 else:
257 job.record('INFO', None, task.name,
258 "Can't %s label '%s:%s'." % (task.name, name, value))
259
260
Alex Miller2229c9c2013-08-27 15:20:39 -0700261# This has been copied out of dynamic_suite's reimager.py, which no longer
262# exists. I'd prefer if this would go away by doing http://crbug.com/249424,
263# so that labels are just automatically made when we try to add them to a host.
Alex Miller0516e4c2013-06-03 18:07:48 -0700264def ensure_label_exists(name):
265 """
266 Ensure that a label called |name| exists in the autotest DB.
267
268 @param name: the label to check for/create.
269 @raises ValidationError: There was an error in the response that was
270 not because the label already existed.
271
272 """
273 afe = frontend.AFE()
274 try:
275 afe.create_label(name=name)
276 except proxy.ValidationError as ve:
277 if ('name' in ve.problem_keys and
278 'This value must be unique' in ve.problem_keys['name']):
279 logging.debug('Version label %s already exists', name)
280 else:
281 raise ve