blob: fbdd9a0d998d7989f6873760f81e8b7bb32bc6bf [file] [log] [blame]
Chris Masone6fed6462011-10-20 16:36:43 -07001# Copyright (c) 2011 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
5import common
6import compiler, logging, os, random, re, time
Chris Masone2ef1d4e2011-12-20 11:06:53 -08007from autotest_lib.client.common_lib import control_data, global_config, error
8from autotest_lib.client.common_lib import utils
Chris Masone6fed6462011-10-20 16:36:43 -07009from autotest_lib.server.cros import control_file_getter
10from autotest_lib.server import frontend
11
12
13VERSION_PREFIX = 'cros-version-'
Chris Masone2ef1d4e2011-12-20 11:06:53 -080014CONFIG = global_config.global_config
15
16
Chris Masone8b764252012-01-17 11:12:51 -080017def inject_vars(vars, control_file_in):
18 """
19 Inject the contents of |vars| into |control_file_in|
20
21 @param vars: a dict to shoehorn into the provided control file string.
22 @param control_file_in: the contents of a control file to munge.
23 @return the modified control file string.
24 """
25 control_file = ''
26 for key, value in vars.iteritems():
27 control_file += "%s='%s'\n" % (key, value)
28 return control_file + control_file_in
29
30
Chris Masone2ef1d4e2011-12-20 11:06:53 -080031def _image_url_pattern():
32 return CONFIG.get_config_value('CROS', 'image_url_pattern', type=str)
33
34
35def _package_url_pattern():
36 return CONFIG.get_config_value('CROS', 'package_url_pattern', type=str)
37
Chris Masone6fed6462011-10-20 16:36:43 -070038
39class Reimager(object):
40 """
41 A class that can run jobs to reimage devices.
42
43 @var _afe: a frontend.AFE instance used to talk to autotest.
44 @var _tko: a frontend.TKO instance used to query the autotest results db.
45 @var _cf_getter: a ControlFileGetter used to get the AU control file.
46 """
47
48
49 def __init__(self, autotest_dir, afe=None, tko=None):
50 """
51 Constructor
52
53 @param autotest_dir: the place to find autotests.
54 @param afe: an instance of AFE as defined in server/frontend.py.
55 @param tko: an instance of TKO as defined in server/frontend.py.
56 """
57 self._afe = afe or frontend.AFE(debug=False)
58 self._tko = tko or frontend.TKO(debug=False)
59 self._cf_getter = control_file_getter.FileSystemGetter(
60 [os.path.join(autotest_dir, 'server/site_tests')])
61
62
Chris Masone2ef1d4e2011-12-20 11:06:53 -080063 def skip(self, g):
64 return 'SKIP_IMAGE' in g and g['SKIP_IMAGE']
65
66
Chris Masone8abb6fc2012-01-31 09:27:36 -080067 def attempt(self, build, num, board, record):
Chris Masone6fed6462011-10-20 16:36:43 -070068 """
69 Synchronously attempt to reimage some machines.
70
71 Fire off attempts to reimage |num| machines of type |board|, using an
Chris Masone8abb6fc2012-01-31 09:27:36 -080072 image at |url| called |build|. Wait for completion, polling every
Chris Masone6fed6462011-10-20 16:36:43 -070073 10s, and log results with |record| upon completion.
74
Chris Masone8abb6fc2012-01-31 09:27:36 -080075 @param build: the build to install e.g.
76 x86-alex-release/R18-1655.0.0-a1-b1584.
Chris Masone6fed6462011-10-20 16:36:43 -070077 @param num: how many devices to reimage.
78 @param board: which kind of devices to reimage.
79 @param record: callable that records job status.
80 prototype:
81 record(status, subdir, name, reason)
82 @return True if all reimaging jobs succeed, false otherwise.
83 """
Chris Masone73f65022012-01-31 14:00:43 -080084 wrapper_job_name = 'try new image'
85 record('START', None, wrapper_job_name)
Chris Masone8abb6fc2012-01-31 09:27:36 -080086 self._ensure_version_label(VERSION_PREFIX + build)
87 canary = self._schedule_reimage_job(build, num, board)
Chris Masone6fed6462011-10-20 16:36:43 -070088 logging.debug('Created re-imaging job: %d', canary.id)
89 while len(self._afe.get_jobs(id=canary.id, not_yet_run=True)) > 0:
90 time.sleep(10)
91 logging.debug('Re-imaging job running.')
92 while len(self._afe.get_jobs(id=canary.id, finished=True)) == 0:
93 time.sleep(10)
94 logging.debug('Re-imaging job finished.')
95 canary.result = self._afe.poll_job_results(self._tko, canary, 0)
96
97 if canary.result is True:
98 self._report_results(canary, record)
Chris Masone73f65022012-01-31 14:00:43 -080099 record('END GOOD', None, wrapper_job_name)
Chris Masone6fed6462011-10-20 16:36:43 -0700100 return True
101
102 if canary.result is None:
103 record('FAIL', None, canary.name, 're-imaging tasks did not run')
104 else: # canary.result is False
105 self._report_results(canary, record)
106
Chris Masone73f65022012-01-31 14:00:43 -0800107 record('END FAIL', None, wrapper_job_name)
Chris Masone6fed6462011-10-20 16:36:43 -0700108 return False
109
110
111 def _ensure_version_label(self, name):
112 """
113 Ensure that a label called |name| exists in the autotest DB.
114
115 @param name: the label to check for/create.
116 """
117 labels = self._afe.get_labels(name=name)
118 if len(labels) == 0:
119 self._afe.create_label(name=name)
120
121
Chris Masone8abb6fc2012-01-31 09:27:36 -0800122 def _schedule_reimage_job(self, build, num_machines, board):
Chris Masone6fed6462011-10-20 16:36:43 -0700123 """
124 Schedules the reimaging of |num_machines| |board| devices with |image|.
125
126 Sends an RPC to the autotest frontend to enqueue reimaging jobs on
127 |num_machines| devices of type |board|
128
Chris Masone8abb6fc2012-01-31 09:27:36 -0800129 @param build: the build to install (must be unique).
Chris Masone2ef1d4e2011-12-20 11:06:53 -0800130 @param num_machines: how many devices to reimage.
Chris Masone6fed6462011-10-20 16:36:43 -0700131 @param board: which kind of devices to reimage.
132 @return a frontend.Job object for the reimaging job we scheduled.
133 """
Chris Masone8b764252012-01-17 11:12:51 -0800134 control_file = inject_vars(
Chris Masone8abb6fc2012-01-31 09:27:36 -0800135 {'image_url': _image_url_pattern() % build, 'image_name': build},
Chris Masone6fed6462011-10-20 16:36:43 -0700136 self._cf_getter.get_control_file_contents_by_name('autoupdate'))
137
Chris Masone2ef1d4e2011-12-20 11:06:53 -0800138 return self._afe.create_job(control_file=control_file,
Chris Masone8abb6fc2012-01-31 09:27:36 -0800139 name=build + '-try',
Chris Masone2ef1d4e2011-12-20 11:06:53 -0800140 control_type='Server',
141 meta_hosts=[board] * num_machines)
Chris Masone6fed6462011-10-20 16:36:43 -0700142
143
144 def _report_results(self, job, record):
145 """
146 Record results from a completed frontend.Job object.
147
148 @param job: a completed frontend.Job object populated by
149 frontend.AFE.poll_job_results.
150 @param record: callable that records job status.
151 prototype:
152 record(status, subdir, name, reason)
153 """
154 if job.result == True:
155 record('GOOD', None, job.name)
156 return
157
158 for platform in job.results_platform_map:
159 for status in job.results_platform_map[platform]:
160 if status == 'Total':
161 continue
162 for host in job.results_platform_map[platform][status]:
163 if host not in job.test_status:
164 record('ERROR', None, host, 'Job failed to run.')
165 elif status == 'Failed':
166 for test_status in job.test_status[host].fail:
167 record('FAIL', None, host, test_status.reason)
168 elif status == 'Aborted':
169 for test_status in job.test_status[host].fail:
170 record('ABORT', None, host, test_status.reason)
171 elif status == 'Completed':
172 record('GOOD', None, host)
173
174
175class Suite(object):
176 """
177 A suite of tests, defined by some predicate over control file variables.
178
179 Given a place to search for control files a predicate to match the desired
180 tests, can gather tests and fire off jobs to run them, and then wait for
181 results.
182
183 @var _predicate: a function that should return True when run over a
184 ControlData representation of a control file that should be in
185 this Suite.
186 @var _tag: a string with which to tag jobs run in this suite.
187 @var _afe: an instance of AFE as defined in server/frontend.py.
188 @var _tko: an instance of TKO as defined in server/frontend.py.
189 @var _jobs: currently scheduled jobs, if any.
190 @var _cf_getter: a control_file_getter.ControlFileGetter
191 """
192
193
Chris Masonefef21382012-01-17 11:16:32 -0800194 @staticmethod
195 def create_fs_getter(autotest_dir):
196 """
197 @param autotest_dir: the place to find autotests.
198 @return a FileSystemGetter instance that looks under |autotest_dir|.
199 """
200 # currently hard-coded places to look for tests.
201 subpaths = ['server/site_tests', 'client/site_tests']
202 directories = [os.path.join(autotest_dir, p) for p in subpaths]
203 return control_file_getter.FileSystemGetter(directories)
204
205
206 @staticmethod
207 def create_from_name(name, autotest_dir, afe=None, tko=None):
Chris Masone6fed6462011-10-20 16:36:43 -0700208 """
209 Create a Suite using a predicate based on the SUITE control file var.
210
211 Makes a predicate based on |name| and uses it to instantiate a Suite
212 that looks for tests in |autotest_dir| and will schedule them using
213 |afe|. Results will be pulled from |tko| upon completion
214
215 @param name: a value of the SUITE control file variable to search for.
216 @param autotest_dir: the place to find autotests.
217 @param afe: an instance of AFE as defined in server/frontend.py.
218 @param tko: an instance of TKO as defined in server/frontend.py.
219 @return a Suite instance.
220 """
221 return Suite(lambda t: hasattr(t, 'suite') and t.suite == name,
222 name, autotest_dir, afe, tko)
223
224
225 def __init__(self, predicate, tag, autotest_dir, afe=None, tko=None):
226 """
227 Constructor
228
229 @param predicate: a function that should return True when run over a
230 ControlData representation of a control file that should be in
231 this Suite.
232 @param tag: a string with which to tag jobs run in this suite.
233 @param autotest_dir: the place to find autotests.
234 @param afe: an instance of AFE as defined in server/frontend.py.
235 @param tko: an instance of TKO as defined in server/frontend.py.
236 """
237 self._predicate = predicate
238 self._tag = tag
239 self._afe = afe or frontend.AFE(debug=False)
240 self._tko = tko or frontend.TKO(debug=False)
241 self._jobs = []
242
Chris Masonefef21382012-01-17 11:16:32 -0800243 self._cf_getter = Suite.create_fs_getter(autotest_dir)
Chris Masone6fed6462011-10-20 16:36:43 -0700244
245 self._tests = Suite.find_and_parse_tests(self._cf_getter,
246 self._predicate,
247 add_experimental=True)
248
249
250 @property
251 def tests(self):
252 """
253 A list of ControlData objects in the suite, with added |text| attr.
254 """
255 return self._tests
256
257
258 def stable_tests(self):
259 """
260 |self.tests|, filtered for non-experimental tests.
261 """
262 return filter(lambda t: not t.experimental, self.tests)
263
264
265 def unstable_tests(self):
266 """
267 |self.tests|, filtered for experimental tests.
268 """
269 return filter(lambda t: t.experimental, self.tests)
270
271
272 def _create_job(self, test, image_name):
273 """
274 Thin wrapper around frontend.AFE.create_job().
275
276 @param test: ControlData object for a test to run.
277 @param image_name: the name of an image against which to test.
278 @return frontend.Job object for the job just scheduled.
279 """
280 return self._afe.create_job(
281 control_file=test.text,
282 name='/'.join([image_name, self._tag, test.name]),
283 control_type=test.test_type.capitalize(),
284 meta_hosts=[VERSION_PREFIX+image_name])
285
286
287 def run_and_wait(self, image_name, record, add_experimental=True):
288 """
289 Synchronously run tests in |self.tests|.
290
291 Schedules tests against a device running image |image_name|, and
292 then polls for status, using |record| to print status when each
293 completes.
294
295 Tests returned by self.stable_tests() will always be run, while tests
296 in self.unstable_tests() will only be run if |add_experimental| is true.
297
298 @param image_name: the name of an image against which to test.
299 @param record: callable that records job status.
300 prototype:
301 record(status, subdir, name, reason)
302 @param add_experimental: schedule experimental tests as well, or not.
303 """
304 try:
Scott Zawalskiab25bd62012-02-10 18:29:12 -0500305 record('INFO', None, 'Start %s' % self._tag)
Chris Masone6fed6462011-10-20 16:36:43 -0700306 self.schedule(image_name, add_experimental)
307 try:
308 for result in self.wait_for_results():
Scott Zawalskiab25bd62012-02-10 18:29:12 -0500309 # |result| will be a tuple of a maximum of 4 entries and a
310 # minimum of 3. We use the first 3 for START and END
311 # entries so we separate those variables out for legible
312 # variable names, nothing more.
313 status = result[0]
314 test_name = result[2]
315 record('START', None, test_name)
Chris Masone6fed6462011-10-20 16:36:43 -0700316 record(*result)
Scott Zawalskiab25bd62012-02-10 18:29:12 -0500317 record('END %s' % status, None, test_name)
Chris Masone6fed6462011-10-20 16:36:43 -0700318 except Exception as e:
319 logging.error(e)
Scott Zawalskiab25bd62012-02-10 18:29:12 -0500320 record('FAIL', None, self._tag,
321 'Exception waiting for results')
Chris Masone6fed6462011-10-20 16:36:43 -0700322 except Exception as e:
323 logging.error(e)
Scott Zawalskiab25bd62012-02-10 18:29:12 -0500324 record('FAIL', None, self._tag,
325 'Exception while scheduling suite')
Chris Masone6fed6462011-10-20 16:36:43 -0700326
327
328 def schedule(self, image_name, add_experimental=True):
329 """
330 Schedule jobs using |self._afe|.
331
332 frontend.Job objects representing each scheduled job will be put in
333 |self._jobs|.
334
335 @param image_name: the name of an image against which to test.
336 @param add_experimental: schedule experimental tests as well, or not.
337 """
338 for test in self.stable_tests():
339 logging.debug('Scheduling %s', test.name)
340 self._jobs.append(self._create_job(test, image_name))
341
342 if add_experimental:
343 # TODO(cmasone): ensure I can log results from these differently.
344 for test in self.unstable_tests():
345 logging.debug('Scheduling %s', test.name)
346 self._jobs.append(self._create_job(test, image_name))
347
348
349 def _status_is_relevant(self, status):
350 """
351 Indicates whether the status of a given test is meaningful or not.
352
353 @param status: frontend.TestStatus object to look at.
354 @return True if this is a test result worth looking at further.
355 """
356 return not (status.test_name.startswith('SERVER_JOB') or
357 status.test_name.startswith('CLIENT_JOB'))
358
359
360 def _collate_aborted(self, current_value, entry):
361 """
362 reduce() over a list of HostQueueEntries for a job; True if any aborted.
363
364 Functor that can be reduced()ed over a list of
365 HostQueueEntries for a job. If any were aborted
366 (|entry.aborted| exists and is True), then the reduce() will
367 return True.
368
369 Ex:
370 entries = self._afe.run('get_host_queue_entries', job=job.id)
371 reduce(self._collate_aborted, entries, False)
372
373 @param current_value: the current accumulator (a boolean).
374 @param entry: the current entry under consideration.
375 @return the value of |entry.aborted| if it exists, False if not.
376 """
377 return current_value or ('aborted' in entry and entry['aborted'])
378
379
380 def wait_for_results(self):
381 """
382 Wait for results of all tests in all jobs in |self._jobs|.
383
384 Currently polls for results every 5s. When all results are available,
385 @return a list of tuples, one per test: (status, subdir, name, reason)
386 """
Chris Masone6fed6462011-10-20 16:36:43 -0700387 while self._jobs:
388 for job in list(self._jobs):
389 if not self._afe.get_jobs(id=job.id, finished=True):
390 continue
391
392 self._jobs.remove(job)
393
394 entries = self._afe.run('get_host_queue_entries', job=job.id)
395 if reduce(self._collate_aborted, entries, False):
Scott Zawalskiab25bd62012-02-10 18:29:12 -0500396 yield('ABORT', None, job.name)
Chris Masone6fed6462011-10-20 16:36:43 -0700397 else:
398 statuses = self._tko.get_status_counts(job=job.id)
399 for s in filter(self._status_is_relevant, statuses):
Scott Zawalskiab25bd62012-02-10 18:29:12 -0500400 yield(s.status, None, s.test_name, s.reason)
Chris Masone6fed6462011-10-20 16:36:43 -0700401 time.sleep(5)
402
Chris Masone6fed6462011-10-20 16:36:43 -0700403
Chris Masonefef21382012-01-17 11:16:32 -0800404 @staticmethod
405 def find_and_parse_tests(cf_getter, predicate, add_experimental=False):
Chris Masone6fed6462011-10-20 16:36:43 -0700406 """
407 Function to scan through all tests and find eligible tests.
408
409 Looks at control files returned by _cf_getter.get_control_file_list()
410 for tests that pass self._predicate().
411
412 @param cf_getter: a control_file_getter.ControlFileGetter used to list
413 and fetch the content of control files
414 @param predicate: a function that should return True when run over a
415 ControlData representation of a control file that should be in
416 this Suite.
417 @param add_experimental: add tests with experimental attribute set.
418
419 @return list of ControlData objects that should be run, with control
420 file text added in |text| attribute.
421 """
422 tests = {}
423 files = cf_getter.get_control_file_list()
424 for file in files:
425 text = cf_getter.get_control_file_contents(file)
426 try:
427 found_test = control_data.parse_control_string(text,
428 raise_warnings=True)
429 if not add_experimental and found_test.experimental:
430 continue
431
432 found_test.text = text
433 tests[file] = found_test
434 except control_data.ControlVariableException, e:
435 logging.warn("Skipping %s\n%s", file, e)
436 except Exception, e:
437 logging.error("Bad %s\n%s", file, e)
438
439 return [test for test in tests.itervalues() if predicate(test)]