blob: f3092da7d9fe199da6449ce27443a7d5917677a2 [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:
305 record('START', None, self._tag)
306 self.schedule(image_name, add_experimental)
307 try:
308 for result in self.wait_for_results():
309 record(*result)
310 record('END GOOD', None, None)
311 except Exception as e:
312 logging.error(e)
313 record('END ERROR', None, None, 'Exception waiting for results')
314 except Exception as e:
315 logging.error(e)
316 record('END ERROR', None, None, 'Exception while scheduling suite')
317
318
319 def schedule(self, image_name, add_experimental=True):
320 """
321 Schedule jobs using |self._afe|.
322
323 frontend.Job objects representing each scheduled job will be put in
324 |self._jobs|.
325
326 @param image_name: the name of an image against which to test.
327 @param add_experimental: schedule experimental tests as well, or not.
328 """
329 for test in self.stable_tests():
330 logging.debug('Scheduling %s', test.name)
331 self._jobs.append(self._create_job(test, image_name))
332
333 if add_experimental:
334 # TODO(cmasone): ensure I can log results from these differently.
335 for test in self.unstable_tests():
336 logging.debug('Scheduling %s', test.name)
337 self._jobs.append(self._create_job(test, image_name))
338
339
340 def _status_is_relevant(self, status):
341 """
342 Indicates whether the status of a given test is meaningful or not.
343
344 @param status: frontend.TestStatus object to look at.
345 @return True if this is a test result worth looking at further.
346 """
347 return not (status.test_name.startswith('SERVER_JOB') or
348 status.test_name.startswith('CLIENT_JOB'))
349
350
351 def _collate_aborted(self, current_value, entry):
352 """
353 reduce() over a list of HostQueueEntries for a job; True if any aborted.
354
355 Functor that can be reduced()ed over a list of
356 HostQueueEntries for a job. If any were aborted
357 (|entry.aborted| exists and is True), then the reduce() will
358 return True.
359
360 Ex:
361 entries = self._afe.run('get_host_queue_entries', job=job.id)
362 reduce(self._collate_aborted, entries, False)
363
364 @param current_value: the current accumulator (a boolean).
365 @param entry: the current entry under consideration.
366 @return the value of |entry.aborted| if it exists, False if not.
367 """
368 return current_value or ('aborted' in entry and entry['aborted'])
369
370
371 def wait_for_results(self):
372 """
373 Wait for results of all tests in all jobs in |self._jobs|.
374
375 Currently polls for results every 5s. When all results are available,
376 @return a list of tuples, one per test: (status, subdir, name, reason)
377 """
378 results = []
379 while self._jobs:
380 for job in list(self._jobs):
381 if not self._afe.get_jobs(id=job.id, finished=True):
382 continue
383
384 self._jobs.remove(job)
385
386 entries = self._afe.run('get_host_queue_entries', job=job.id)
387 if reduce(self._collate_aborted, entries, False):
388 results.append(('ABORT', None, job.name))
389 else:
390 statuses = self._tko.get_status_counts(job=job.id)
391 for s in filter(self._status_is_relevant, statuses):
392 results.append((s.status, None, s.test_name, s.reason))
393 time.sleep(5)
394
395 return results
396
397
Chris Masonefef21382012-01-17 11:16:32 -0800398 @staticmethod
399 def find_and_parse_tests(cf_getter, predicate, add_experimental=False):
Chris Masone6fed6462011-10-20 16:36:43 -0700400 """
401 Function to scan through all tests and find eligible tests.
402
403 Looks at control files returned by _cf_getter.get_control_file_list()
404 for tests that pass self._predicate().
405
406 @param cf_getter: a control_file_getter.ControlFileGetter used to list
407 and fetch the content of control files
408 @param predicate: a function that should return True when run over a
409 ControlData representation of a control file that should be in
410 this Suite.
411 @param add_experimental: add tests with experimental attribute set.
412
413 @return list of ControlData objects that should be run, with control
414 file text added in |text| attribute.
415 """
416 tests = {}
417 files = cf_getter.get_control_file_list()
418 for file in files:
419 text = cf_getter.get_control_file_contents(file)
420 try:
421 found_test = control_data.parse_control_string(text,
422 raise_warnings=True)
423 if not add_experimental and found_test.experimental:
424 continue
425
426 found_test.text = text
427 tests[file] = found_test
428 except control_data.ControlVariableException, e:
429 logging.warn("Skipping %s\n%s", file, e)
430 except Exception, e:
431 logging.error("Bad %s\n%s", file, e)
432
433 return [test for test in tests.itervalues() if predicate(test)]