blob: d21ca9e17561ab985da7a79115ef4f0777a6b8fc [file] [log] [blame]
Chris Masone8ac66712012-02-15 14:21:02 -08001# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
Chris Masone6fed6462011-10-20 16:36:43 -07002# 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 Masoneab3e7332012-02-29 18:54:58 -08007from autotest_lib.client.common_lib import base_job, control_data, global_config
8from autotest_lib.client.common_lib import error, utils
Chris Masone8b7cd422012-02-22 13:16:11 -08009from autotest_lib.client.common_lib.cros import dev_server
Chris Masone47c9e642012-04-25 14:22:18 -070010from autotest_lib.frontend.afe.json_rpc import proxy
Chris Masone8ac66712012-02-15 14:21:02 -080011from autotest_lib.server.cros import control_file_getter, frontend_wrappers
Chris Masone6fed6462011-10-20 16:36:43 -070012from autotest_lib.server import frontend
13
14
Scott Zawalski65650172012-02-16 11:48:26 -050015VERSION_PREFIX = 'cros-version:'
Chris Masone2ef1d4e2011-12-20 11:06:53 -080016CONFIG = global_config.global_config
17
18
Chris Sosa6b288c82012-03-29 15:31:06 -070019class AsynchronousBuildFailure(Exception):
20 """Raised when the dev server throws 500 while finishing staging of a build.
21 """
22 pass
23
24
Chris Masoneab3e7332012-02-29 18:54:58 -080025class SuiteArgumentException(Exception):
26 """Raised when improper arguments are used to run a suite."""
27 pass
28
29
Chris Masone5374c672012-03-05 15:11:39 -080030class InadequateHostsException(Exception):
31 """Raised when there are too few hosts to run a suite."""
32 pass
33
34
Chris Masone502b71e2012-04-10 10:41:35 -070035class NoHostsException(Exception):
36 """Raised when there are no healthy hosts to run a suite."""
37 pass
38
39
Chris Masoneab3e7332012-02-29 18:54:58 -080040def reimage_and_run(**dargs):
41 """
42 Backward-compatible API for dynamic_suite.
43
44 Will re-image a number of devices (of the specified board) with the
45 provided build, and then run the indicated test suite on them.
46 Guaranteed to be compatible with any build from stable to dev.
47
48 Currently required args:
49 @param build: the build to install e.g.
50 x86-alex-release/R18-1655.0.0-a1-b1584.
51 @param board: which kind of devices to reimage.
52 @param name: a value of the SUITE control file variable to search for.
53 @param job: an instance of client.common_lib.base_job representing the
54 currently running suite job.
55
56 Currently supported optional args:
57 @param pool: specify the pool of machines to use for scheduling purposes.
58 Default: None
59 @param num: how many devices to reimage.
60 Default in global_config
Chris Masone62579122012-03-08 15:18:43 -080061 @param check_hosts: require appropriate hosts to be available now.
Chris Masoneab3e7332012-02-29 18:54:58 -080062 @param skip_reimage: skip reimaging, used for testing purposes.
63 Default: False
64 @param add_experimental: schedule experimental tests as well, or not.
65 Default: True
Chris Sosa6b288c82012-03-29 15:31:06 -070066 @raises AsynchronousBuildFailure: if there was an issue finishing staging
67 from the devserver.
Chris Masoneab3e7332012-02-29 18:54:58 -080068 """
Chris Masone62579122012-03-08 15:18:43 -080069 (build, board, name, job, pool, num, check_hosts, skip_reimage,
70 add_experimental) = _vet_reimage_and_run_args(**dargs)
Chris Masone5374c672012-03-05 15:11:39 -080071 board = 'board:%s' % board
72 if pool:
73 pool = 'pool:%s' % pool
Chris Masone9f13ff22012-03-05 13:45:25 -080074 reimager = Reimager(job.autodir, pool=pool, results_dir=job.resultdir)
Chris Masoned368cc42012-03-07 15:16:59 -080075
Chris Masone62579122012-03-08 15:18:43 -080076 if skip_reimage or reimager.attempt(build, board, job.record, check_hosts,
77 num=num):
Chris Sosa6b288c82012-03-29 15:31:06 -070078
79 # Ensure that the image's artifacts have completed downloading.
80 ds = dev_server.DevServer.create()
81 if not ds.finish_download(build):
82 raise AsynchronousBuildFailure(
83 "Server error completing staging for " + build)
84
Chris Masoneab3e7332012-02-29 18:54:58 -080085 suite = Suite.create_from_name(name, build, pool=pool,
86 results_dir=job.resultdir)
87 suite.run_and_wait(job.record, add_experimental=add_experimental)
88
Chris Masoned368cc42012-03-07 15:16:59 -080089 reimager.clear_reimaged_host_state(build)
90
Chris Masoneab3e7332012-02-29 18:54:58 -080091
92def _vet_reimage_and_run_args(build=None, board=None, name=None, job=None,
Chris Masone62579122012-03-08 15:18:43 -080093 pool=None, num=None, check_hosts=True,
94 skip_reimage=False, add_experimental=True,
95 **dargs):
Chris Masoneab3e7332012-02-29 18:54:58 -080096 """
97 Vets arguments for reimage_and_run().
98
99 Currently required args:
100 @param build: the build to install e.g.
101 x86-alex-release/R18-1655.0.0-a1-b1584.
102 @param board: which kind of devices to reimage.
103 @param name: a value of the SUITE control file variable to search for.
104 @param job: an instance of client.common_lib.base_job representing the
105 currently running suite job.
106
107 Currently supported optional args:
108 @param pool: specify the pool of machines to use for scheduling purposes.
109 Default: None
110 @param num: how many devices to reimage.
111 Default in global_config
Chris Masone62579122012-03-08 15:18:43 -0800112 @param check_hosts: require appropriate hosts to be available now.
Chris Masoneab3e7332012-02-29 18:54:58 -0800113 @param skip_reimage: skip reimaging, used for testing purposes.
114 Default: False
115 @param add_experimental: schedule experimental tests as well, or not.
116 Default: True
117 @return a tuple of args set to provided (or default) values.
118 """
119 required_keywords = {'build': str,
120 'board': str,
121 'name': str,
122 'job': base_job.base_job}
123 for key, expected in required_keywords.iteritems():
124 value = locals().get(key)
125 if not value or not isinstance(value, expected):
126 raise SuiteArgumentException("reimage_and_run() needs %s=<%r>" % (
127 key, expected))
Chris Masone62579122012-03-08 15:18:43 -0800128 return (build, board, name, job, pool, num, check_hosts, skip_reimage,
129 add_experimental)
Chris Masoneab3e7332012-02-29 18:54:58 -0800130
131
Chris Masone8b764252012-01-17 11:12:51 -0800132def inject_vars(vars, control_file_in):
133 """
Chris Masoneab3e7332012-02-29 18:54:58 -0800134 Inject the contents of |vars| into |control_file_in|.
Chris Masone8b764252012-01-17 11:12:51 -0800135
136 @param vars: a dict to shoehorn into the provided control file string.
137 @param control_file_in: the contents of a control file to munge.
138 @return the modified control file string.
139 """
140 control_file = ''
141 for key, value in vars.iteritems():
Chris Masone6cb0d0d2012-03-05 15:37:49 -0800142 # None gets injected as 'None' without this check; same for digits.
143 if isinstance(value, str):
144 control_file += "%s='%s'\n" % (key, value)
145 else:
146 control_file += "%s=%r\n" % (key, value)
Chris Masone8b764252012-01-17 11:12:51 -0800147 return control_file + control_file_in
148
149
Chris Masone2ef1d4e2011-12-20 11:06:53 -0800150def _image_url_pattern():
151 return CONFIG.get_config_value('CROS', 'image_url_pattern', type=str)
152
153
154def _package_url_pattern():
155 return CONFIG.get_config_value('CROS', 'package_url_pattern', type=str)
156
Chris Masone6fed6462011-10-20 16:36:43 -0700157
Chris Masoneab3e7332012-02-29 18:54:58 -0800158def skip_reimage(g):
159 return g.get('SKIP_IMAGE')
160
161
Chris Masone6fed6462011-10-20 16:36:43 -0700162class Reimager(object):
163 """
164 A class that can run jobs to reimage devices.
165
166 @var _afe: a frontend.AFE instance used to talk to autotest.
167 @var _tko: a frontend.TKO instance used to query the autotest results db.
168 @var _cf_getter: a ControlFileGetter used to get the AU control file.
169 """
170
171
Chris Masone9f13ff22012-03-05 13:45:25 -0800172 def __init__(self, autotest_dir, afe=None, tko=None, pool=None,
173 results_dir=None):
Chris Masone6fed6462011-10-20 16:36:43 -0700174 """
175 Constructor
176
177 @param autotest_dir: the place to find autotests.
178 @param afe: an instance of AFE as defined in server/frontend.py.
179 @param tko: an instance of TKO as defined in server/frontend.py.
Scott Zawalski65650172012-02-16 11:48:26 -0500180 @param pool: Specify the pool of machines to use for scheduling
181 purposes.
Chris Masone9f13ff22012-03-05 13:45:25 -0800182 @param results_dir: The directory where the job can write results to.
183 This must be set if you want job_id of sub-jobs
184 list in the job keyvals.
Chris Masone6fed6462011-10-20 16:36:43 -0700185 """
Chris Masone8ac66712012-02-15 14:21:02 -0800186 self._afe = afe or frontend_wrappers.RetryingAFE(timeout_min=30,
187 delay_sec=10,
188 debug=False)
189 self._tko = tko or frontend_wrappers.RetryingTKO(timeout_min=30,
190 delay_sec=10,
191 debug=False)
Scott Zawalski65650172012-02-16 11:48:26 -0500192 self._pool = pool
Chris Masone9f13ff22012-03-05 13:45:25 -0800193 self._results_dir = results_dir
Chris Masoned368cc42012-03-07 15:16:59 -0800194 self._reimaged_hosts = {}
Chris Masone6fed6462011-10-20 16:36:43 -0700195 self._cf_getter = control_file_getter.FileSystemGetter(
196 [os.path.join(autotest_dir, 'server/site_tests')])
197
198
Chris Masone2ef1d4e2011-12-20 11:06:53 -0800199 def skip(self, g):
Chris Masoneab3e7332012-02-29 18:54:58 -0800200 """Deprecated in favor of dynamic_suite.skip_reimage()."""
Chris Masone2ef1d4e2011-12-20 11:06:53 -0800201 return 'SKIP_IMAGE' in g and g['SKIP_IMAGE']
202
203
Chris Masone62579122012-03-08 15:18:43 -0800204 def attempt(self, build, board, record, check_hosts, num=None):
Chris Masone6fed6462011-10-20 16:36:43 -0700205 """
206 Synchronously attempt to reimage some machines.
207
208 Fire off attempts to reimage |num| machines of type |board|, using an
Chris Masone8abb6fc2012-01-31 09:27:36 -0800209 image at |url| called |build|. Wait for completion, polling every
Chris Masone6fed6462011-10-20 16:36:43 -0700210 10s, and log results with |record| upon completion.
211
Chris Masone8abb6fc2012-01-31 09:27:36 -0800212 @param build: the build to install e.g.
213 x86-alex-release/R18-1655.0.0-a1-b1584.
Chris Masone6fed6462011-10-20 16:36:43 -0700214 @param board: which kind of devices to reimage.
215 @param record: callable that records job status.
Chris Masone796fcf12012-02-22 16:53:31 -0800216 prototype:
217 record(status, subdir, name, reason)
Chris Masone62579122012-03-08 15:18:43 -0800218 @param check_hosts: require appropriate hosts to be available now.
Chris Masone5552dd72012-02-15 15:01:04 -0800219 @param num: how many devices to reimage.
Chris Masone6fed6462011-10-20 16:36:43 -0700220 @return True if all reimaging jobs succeed, false otherwise.
221 """
Chris Masone5552dd72012-02-15 15:01:04 -0800222 if not num:
223 num = CONFIG.get_config_value('CROS', 'sharding_factor', type=int)
Scott Zawalski65650172012-02-16 11:48:26 -0500224 logging.debug("scheduling reimaging across %d machines", num)
Chris Masone9f13ff22012-03-05 13:45:25 -0800225 wrapper_job_name = 'try_new_image'
Chris Masone73f65022012-01-31 14:00:43 -0800226 record('START', None, wrapper_job_name)
Chris Masone796fcf12012-02-22 16:53:31 -0800227 try:
Chris Masone62579122012-03-08 15:18:43 -0800228 self._ensure_version_label(VERSION_PREFIX + build)
229
230 if check_hosts:
231 self._ensure_enough_hosts(board, self._pool, num)
Chris Masone5374c672012-03-05 15:11:39 -0800232
Chris Masoned368cc42012-03-07 15:16:59 -0800233 # Schedule job and record job metadata.
Chris Masoned368cc42012-03-07 15:16:59 -0800234 canary_job = self._schedule_reimage_job(build, num, board)
235 self._record_job_if_possible(wrapper_job_name, canary_job)
236 logging.debug('Created re-imaging job: %d', canary_job.id)
237
238 # Poll until reimaging is complete.
239 self._wait_for_job_to_start(canary_job.id)
240 self._wait_for_job_to_finish(canary_job.id)
241
242 # Gather job results.
243 canary_job.result = self._afe.poll_job_results(self._tko,
244 canary_job,
245 0)
Chris Masone5374c672012-03-05 15:11:39 -0800246 except InadequateHostsException as e:
247 logging.warning(e)
248 record('END WARN', None, wrapper_job_name, str(e))
249 return False
Chris Masone796fcf12012-02-22 16:53:31 -0800250 except Exception as e:
251 # catch Exception so we record the job as terminated no matter what.
252 logging.error(e)
253 record('END ERROR', None, wrapper_job_name, str(e))
254 return False
Chris Masone6fed6462011-10-20 16:36:43 -0700255
Chris Masoned368cc42012-03-07 15:16:59 -0800256 self._remember_reimaged_hosts(build, canary_job)
257
258 if canary_job.result is True:
259 self._report_results(canary_job, record)
Chris Masone73f65022012-01-31 14:00:43 -0800260 record('END GOOD', None, wrapper_job_name)
Chris Masone6fed6462011-10-20 16:36:43 -0700261 return True
262
Chris Masoned368cc42012-03-07 15:16:59 -0800263 if canary_job.result is None:
264 record('FAIL', None, canary_job.name, 'reimaging tasks did not run')
265 else: # canary_job.result is False
266 self._report_results(canary_job, record)
Chris Masone6fed6462011-10-20 16:36:43 -0700267
Chris Masone73f65022012-01-31 14:00:43 -0800268 record('END FAIL', None, wrapper_job_name)
Chris Masone6fed6462011-10-20 16:36:43 -0700269 return False
270
271
Chris Masone62579122012-03-08 15:18:43 -0800272 def _ensure_enough_hosts(self, board, pool, num):
273 """
274 Determine if there are enough working hosts to run on.
275
276 Raises exception if there are not enough hosts.
277
278 @param board: which kind of devices to reimage.
279 @param pool: the pool of machines to use for scheduling purposes.
280 @param num: how many devices to reimage.
281 @raises InadequateHostsException: if too few working hosts.
282 """
283 labels = [l for l in [board, pool] if l is not None]
Chris Masone502b71e2012-04-10 10:41:35 -0700284 available = self._count_usable_hosts(labels)
285 if available == 0:
286 raise NoHostsException('All hosts with %r are dead!' % labels)
287 elif num > available:
Chris Masone62579122012-03-08 15:18:43 -0800288 raise InadequateHostsException('Too few hosts with %r' % labels)
289
290
Chris Masoned368cc42012-03-07 15:16:59 -0800291 def _wait_for_job_to_start(self, job_id):
292 """
293 Wait for the job specified by |job_id| to start.
294
295 @param job_id: the job ID to poll on.
296 """
297 while len(self._afe.get_jobs(id=job_id, not_yet_run=True)) > 0:
298 time.sleep(10)
299 logging.debug('Re-imaging job running.')
300
301
302 def _wait_for_job_to_finish(self, job_id):
303 """
304 Wait for the job specified by |job_id| to finish.
305
306 @param job_id: the job ID to poll on.
307 """
308 while len(self._afe.get_jobs(id=job_id, finished=True)) == 0:
309 time.sleep(10)
310 logging.debug('Re-imaging job finished.')
311
312
313 def _remember_reimaged_hosts(self, build, canary_job):
314 """
315 Remember hosts that were reimaged with |build| as a part |canary_job|.
316
317 @param build: the build that was installed e.g.
318 x86-alex-release/R18-1655.0.0-a1-b1584.
319 @param canary_job: a completed frontend.Job object, possibly populated
320 by frontend.AFE.poll_job_results.
321 """
322 if not hasattr(canary_job, 'results_platform_map'):
323 return
324 if not self._reimaged_hosts.get('build'):
325 self._reimaged_hosts[build] = []
326 for platform in canary_job.results_platform_map:
327 for host in canary_job.results_platform_map[platform]['Total']:
328 self._reimaged_hosts[build].append(host)
329
330
331 def clear_reimaged_host_state(self, build):
332 """
333 Clear per-host state created in the autotest DB for this job.
334
335 After reimaging a host, we label it and set some host attributes on it
336 that are then used by the suite scheduling code. This call cleans
337 that up.
338
339 @param build: the build whose hosts we want to clean up e.g.
340 x86-alex-release/R18-1655.0.0-a1-b1584.
341 """
Chris Masoned368cc42012-03-07 15:16:59 -0800342 for host in self._reimaged_hosts.get('build', []):
343 self._clear_build_state(host)
344
345
346 def _clear_build_state(self, machine):
347 """
348 Clear all build-specific labels, attributes from the target.
349
350 @param machine: the host to clear labels, attributes from.
351 """
352 self._afe.set_host_attribute('job_repo_url', None, hostname=machine)
353
354
Chris Masone9f13ff22012-03-05 13:45:25 -0800355 def _record_job_if_possible(self, test_name, job):
356 """
357 Record job id as keyval, if possible, so it can be referenced later.
358
359 If |self._results_dir| is None, then this is a NOOP.
Chris Masone5374c672012-03-05 15:11:39 -0800360
361 @param test_name: the test to record id/owner for.
362 @param job: the job object to pull info from.
Chris Masone9f13ff22012-03-05 13:45:25 -0800363 """
364 if self._results_dir:
365 job_id_owner = '%s-%s' % (job.id, job.owner)
366 utils.write_keyval(self._results_dir, {test_name: job_id_owner})
367
368
Chris Masone5374c672012-03-05 15:11:39 -0800369 def _count_usable_hosts(self, host_spec):
370 """
371 Given a set of host labels, count the live hosts that have them all.
372
373 @param host_spec: list of labels specifying a set of hosts.
374 @return the number of live hosts that satisfy |host_spec|.
375 """
376 count = 0
377 for h in self._afe.get_hosts(multiple_labels=host_spec):
378 if h.status not in ['Repair Failed', 'Repairing']:
379 count += 1
380 return count
381
382
Chris Masone6fed6462011-10-20 16:36:43 -0700383 def _ensure_version_label(self, name):
384 """
385 Ensure that a label called |name| exists in the autotest DB.
386
387 @param name: the label to check for/create.
388 """
Chris Masone47c9e642012-04-25 14:22:18 -0700389 try:
Chris Masone6fed6462011-10-20 16:36:43 -0700390 self._afe.create_label(name=name)
Chris Masone47c9e642012-04-25 14:22:18 -0700391 except proxy.ValidationError as ve:
392 if ('name' in ve.problem_keys and
393 'This value must be unique' in ve.problem_keys['name']):
394 logging.debug('Version label %s already exists', name)
395 else:
396 raise ve
Chris Masone6fed6462011-10-20 16:36:43 -0700397
398
Chris Masone8abb6fc2012-01-31 09:27:36 -0800399 def _schedule_reimage_job(self, build, num_machines, board):
Chris Masone6fed6462011-10-20 16:36:43 -0700400 """
401 Schedules the reimaging of |num_machines| |board| devices with |image|.
402
403 Sends an RPC to the autotest frontend to enqueue reimaging jobs on
404 |num_machines| devices of type |board|
405
Chris Masone8abb6fc2012-01-31 09:27:36 -0800406 @param build: the build to install (must be unique).
Chris Masone2ef1d4e2011-12-20 11:06:53 -0800407 @param num_machines: how many devices to reimage.
Chris Masone6fed6462011-10-20 16:36:43 -0700408 @param board: which kind of devices to reimage.
409 @return a frontend.Job object for the reimaging job we scheduled.
410 """
Chris Masone8b764252012-01-17 11:12:51 -0800411 control_file = inject_vars(
Chris Masone8abb6fc2012-01-31 09:27:36 -0800412 {'image_url': _image_url_pattern() % build, 'image_name': build},
Chris Masone6fed6462011-10-20 16:36:43 -0700413 self._cf_getter.get_control_file_contents_by_name('autoupdate'))
Scott Zawalski65650172012-02-16 11:48:26 -0500414 job_deps = []
415 if self._pool:
Chris Masone5374c672012-03-05 15:11:39 -0800416 meta_host = self._pool
417 board_label = board
Scott Zawalski65650172012-02-16 11:48:26 -0500418 job_deps.append(board_label)
419 else:
420 # No pool specified use board.
Chris Masone5374c672012-03-05 15:11:39 -0800421 meta_host = board
Chris Masone6fed6462011-10-20 16:36:43 -0700422
Chris Masone2ef1d4e2011-12-20 11:06:53 -0800423 return self._afe.create_job(control_file=control_file,
Chris Masone8abb6fc2012-01-31 09:27:36 -0800424 name=build + '-try',
Chris Masone2ef1d4e2011-12-20 11:06:53 -0800425 control_type='Server',
Chris Masone97325362012-04-26 16:19:13 -0700426 priority='Low',
Scott Zawalski65650172012-02-16 11:48:26 -0500427 meta_hosts=[meta_host] * num_machines,
428 dependencies=job_deps)
Chris Masone6fed6462011-10-20 16:36:43 -0700429
430
431 def _report_results(self, job, record):
432 """
433 Record results from a completed frontend.Job object.
434
435 @param job: a completed frontend.Job object populated by
436 frontend.AFE.poll_job_results.
437 @param record: callable that records job status.
438 prototype:
439 record(status, subdir, name, reason)
440 """
441 if job.result == True:
442 record('GOOD', None, job.name)
443 return
444
445 for platform in job.results_platform_map:
446 for status in job.results_platform_map[platform]:
447 if status == 'Total':
448 continue
449 for host in job.results_platform_map[platform][status]:
450 if host not in job.test_status:
451 record('ERROR', None, host, 'Job failed to run.')
452 elif status == 'Failed':
453 for test_status in job.test_status[host].fail:
454 record('FAIL', None, host, test_status.reason)
455 elif status == 'Aborted':
456 for test_status in job.test_status[host].fail:
457 record('ABORT', None, host, test_status.reason)
458 elif status == 'Completed':
459 record('GOOD', None, host)
460
461
462class Suite(object):
463 """
464 A suite of tests, defined by some predicate over control file variables.
465
466 Given a place to search for control files a predicate to match the desired
467 tests, can gather tests and fire off jobs to run them, and then wait for
468 results.
469
470 @var _predicate: a function that should return True when run over a
471 ControlData representation of a control file that should be in
472 this Suite.
473 @var _tag: a string with which to tag jobs run in this suite.
Chris Masone8b7cd422012-02-22 13:16:11 -0800474 @var _build: the build on which we're running this suite.
Chris Masone6fed6462011-10-20 16:36:43 -0700475 @var _afe: an instance of AFE as defined in server/frontend.py.
476 @var _tko: an instance of TKO as defined in server/frontend.py.
477 @var _jobs: currently scheduled jobs, if any.
478 @var _cf_getter: a control_file_getter.ControlFileGetter
479 """
480
481
Chris Masonefef21382012-01-17 11:16:32 -0800482 @staticmethod
Chris Masoned6f38c82012-02-22 14:53:42 -0800483 def create_ds_getter(build):
Chris Masonefef21382012-01-17 11:16:32 -0800484 """
Chris Masone8b7cd422012-02-22 13:16:11 -0800485 @param build: the build on which we're running this suite.
Chris Masonefef21382012-01-17 11:16:32 -0800486 @return a FileSystemGetter instance that looks under |autotest_dir|.
487 """
Chris Masone8b7cd422012-02-22 13:16:11 -0800488 return control_file_getter.DevServerGetter(
489 build, dev_server.DevServer.create())
Chris Masonefef21382012-01-17 11:16:32 -0800490
491
492 @staticmethod
Chris Masoned6f38c82012-02-22 14:53:42 -0800493 def create_fs_getter(autotest_dir):
494 """
495 @param autotest_dir: the place to find autotests.
496 @return a FileSystemGetter instance that looks under |autotest_dir|.
497 """
498 # currently hard-coded places to look for tests.
499 subpaths = ['server/site_tests', 'client/site_tests',
500 'server/tests', 'client/tests']
501 directories = [os.path.join(autotest_dir, p) for p in subpaths]
502 return control_file_getter.FileSystemGetter(directories)
503
504
505 @staticmethod
Zdenek Behan849db052012-02-29 19:16:28 +0100506 def parse_tag(tag):
507 """Splits a string on ',' optionally surrounded by whitespace."""
508 return map(lambda x: x.strip(), tag.split(','))
509
510
511 @staticmethod
Chris Masone84564792012-02-23 10:52:42 -0800512 def name_in_tag_predicate(name):
513 """Returns predicate that takes a control file and looks for |name|.
514
515 Builds a predicate that takes in a parsed control file (a ControlData)
516 and returns True if the SUITE tag is present and contains |name|.
517
518 @param name: the suite name to base the predicate on.
519 @return a callable that takes a ControlData and looks for |name| in that
520 ControlData object's suite member.
521 """
Zdenek Behan849db052012-02-29 19:16:28 +0100522 return lambda t: hasattr(t, 'suite') and \
523 name in Suite.parse_tag(t.suite)
Chris Masone84564792012-02-23 10:52:42 -0800524
Zdenek Behan849db052012-02-29 19:16:28 +0100525
526 @staticmethod
527 def list_all_suites(build, cf_getter=None):
528 """
529 Parses all ControlData objects with a SUITE tag and extracts all
530 defined suite names.
531
532 @param cf_getter: control_file_getter.ControlFileGetter. Defaults to
533 using DevServerGetter.
534
535 @return list of suites
536 """
537 if cf_getter is None:
538 cf_getter = Suite.create_ds_getter(build)
539
540 suites = set()
541 predicate = lambda t: hasattr(t, 'suite')
542 for test in Suite.find_and_parse_tests(cf_getter, predicate):
543 suites.update(Suite.parse_tag(test.suite))
544 return list(suites)
Chris Masone84564792012-02-23 10:52:42 -0800545
546
547 @staticmethod
Scott Zawalski9ece6532012-02-28 14:10:47 -0500548 def create_from_name(name, build, cf_getter=None, afe=None, tko=None,
549 pool=None, results_dir=None):
Chris Masone6fed6462011-10-20 16:36:43 -0700550 """
551 Create a Suite using a predicate based on the SUITE control file var.
552
553 Makes a predicate based on |name| and uses it to instantiate a Suite
554 that looks for tests in |autotest_dir| and will schedule them using
Chris Masoned6f38c82012-02-22 14:53:42 -0800555 |afe|. Pulls control files from the default dev server.
556 Results will be pulled from |tko| upon completion.
Chris Masone6fed6462011-10-20 16:36:43 -0700557
558 @param name: a value of the SUITE control file variable to search for.
Chris Masone8b7cd422012-02-22 13:16:11 -0800559 @param build: the build on which we're running this suite.
Chris Masoned6f38c82012-02-22 14:53:42 -0800560 @param cf_getter: a control_file_getter.ControlFileGetter.
561 If None, default to using a DevServerGetter.
Chris Masone6fed6462011-10-20 16:36:43 -0700562 @param afe: an instance of AFE as defined in server/frontend.py.
563 @param tko: an instance of TKO as defined in server/frontend.py.
Scott Zawalski65650172012-02-16 11:48:26 -0500564 @param pool: Specify the pool of machines to use for scheduling
Chris Masoned6f38c82012-02-22 14:53:42 -0800565 purposes.
Scott Zawalski9ece6532012-02-28 14:10:47 -0500566 @param results_dir: The directory where the job can write results to.
567 This must be set if you want job_id of sub-jobs
568 list in the job keyvals.
Chris Masone6fed6462011-10-20 16:36:43 -0700569 @return a Suite instance.
570 """
Chris Masoned6f38c82012-02-22 14:53:42 -0800571 if cf_getter is None:
572 cf_getter = Suite.create_ds_getter(build)
Chris Masone84564792012-02-23 10:52:42 -0800573 return Suite(Suite.name_in_tag_predicate(name),
Scott Zawalski9ece6532012-02-28 14:10:47 -0500574 name, build, cf_getter, afe, tko, pool, results_dir)
Chris Masone6fed6462011-10-20 16:36:43 -0700575
576
Chris Masoned6f38c82012-02-22 14:53:42 -0800577 def __init__(self, predicate, tag, build, cf_getter, afe=None, tko=None,
Scott Zawalski9ece6532012-02-28 14:10:47 -0500578 pool=None, results_dir=None):
Chris Masone6fed6462011-10-20 16:36:43 -0700579 """
580 Constructor
581
582 @param predicate: a function that should return True when run over a
583 ControlData representation of a control file that should be in
584 this Suite.
585 @param tag: a string with which to tag jobs run in this suite.
Chris Masone8b7cd422012-02-22 13:16:11 -0800586 @param build: the build on which we're running this suite.
Chris Masoned6f38c82012-02-22 14:53:42 -0800587 @param cf_getter: a control_file_getter.ControlFileGetter
Chris Masone6fed6462011-10-20 16:36:43 -0700588 @param afe: an instance of AFE as defined in server/frontend.py.
589 @param tko: an instance of TKO as defined in server/frontend.py.
Scott Zawalski65650172012-02-16 11:48:26 -0500590 @param pool: Specify the pool of machines to use for scheduling
591 purposes.
Scott Zawalski9ece6532012-02-28 14:10:47 -0500592 @param results_dir: The directory where the job can write results to.
593 This must be set if you want job_id of sub-jobs
594 list in the job keyvals.
Chris Masone6fed6462011-10-20 16:36:43 -0700595 """
596 self._predicate = predicate
597 self._tag = tag
Chris Masone8b7cd422012-02-22 13:16:11 -0800598 self._build = build
Chris Masoned6f38c82012-02-22 14:53:42 -0800599 self._cf_getter = cf_getter
Scott Zawalski9ece6532012-02-28 14:10:47 -0500600 self._results_dir = results_dir
Chris Masone8ac66712012-02-15 14:21:02 -0800601 self._afe = afe or frontend_wrappers.RetryingAFE(timeout_min=30,
602 delay_sec=10,
603 debug=False)
604 self._tko = tko or frontend_wrappers.RetryingTKO(timeout_min=30,
605 delay_sec=10,
606 debug=False)
Scott Zawalski65650172012-02-16 11:48:26 -0500607 self._pool = pool
Chris Masone6fed6462011-10-20 16:36:43 -0700608 self._jobs = []
Chris Masone6fed6462011-10-20 16:36:43 -0700609 self._tests = Suite.find_and_parse_tests(self._cf_getter,
610 self._predicate,
611 add_experimental=True)
612
613
614 @property
615 def tests(self):
616 """
617 A list of ControlData objects in the suite, with added |text| attr.
618 """
619 return self._tests
620
621
622 def stable_tests(self):
623 """
624 |self.tests|, filtered for non-experimental tests.
625 """
626 return filter(lambda t: not t.experimental, self.tests)
627
628
629 def unstable_tests(self):
630 """
631 |self.tests|, filtered for experimental tests.
632 """
633 return filter(lambda t: t.experimental, self.tests)
634
635
Chris Masone8b7cd422012-02-22 13:16:11 -0800636 def _create_job(self, test):
Chris Masone6fed6462011-10-20 16:36:43 -0700637 """
638 Thin wrapper around frontend.AFE.create_job().
639
640 @param test: ControlData object for a test to run.
Scott Zawalskie5bb1c52012-02-29 13:15:50 -0500641 @return a frontend.Job object with an added test_name member.
642 test_name is used to preserve the higher level TEST_NAME
643 name of the job.
Chris Masone6fed6462011-10-20 16:36:43 -0700644 """
Scott Zawalski65650172012-02-16 11:48:26 -0500645 job_deps = []
646 if self._pool:
Chris Masone5374c672012-03-05 15:11:39 -0800647 meta_hosts = self._pool
Chris Masone8b7cd422012-02-22 13:16:11 -0800648 cros_label = VERSION_PREFIX + self._build
Scott Zawalski65650172012-02-16 11:48:26 -0500649 job_deps.append(cros_label)
650 else:
651 # No pool specified use any machines with the following label.
Chris Masone8b7cd422012-02-22 13:16:11 -0800652 meta_hosts = VERSION_PREFIX + self._build
Scott Zawalskie5bb1c52012-02-29 13:15:50 -0500653 test_obj = self._afe.create_job(
Chris Masone6fed6462011-10-20 16:36:43 -0700654 control_file=test.text,
Chris Masone8b7cd422012-02-22 13:16:11 -0800655 name='/'.join([self._build, self._tag, test.name]),
Chris Masone6fed6462011-10-20 16:36:43 -0700656 control_type=test.test_type.capitalize(),
Scott Zawalski65650172012-02-16 11:48:26 -0500657 meta_hosts=[meta_hosts],
658 dependencies=job_deps)
Chris Masone6fed6462011-10-20 16:36:43 -0700659
Scott Zawalskie5bb1c52012-02-29 13:15:50 -0500660 setattr(test_obj, 'test_name', test.name)
661
662 return test_obj
663
Chris Masone6fed6462011-10-20 16:36:43 -0700664
Chris Masone8b7cd422012-02-22 13:16:11 -0800665 def run_and_wait(self, record, add_experimental=True):
Chris Masone6fed6462011-10-20 16:36:43 -0700666 """
667 Synchronously run tests in |self.tests|.
668
Chris Masone8b7cd422012-02-22 13:16:11 -0800669 Schedules tests against a device running image |self._build|, and
Chris Masone6fed6462011-10-20 16:36:43 -0700670 then polls for status, using |record| to print status when each
671 completes.
672
673 Tests returned by self.stable_tests() will always be run, while tests
674 in self.unstable_tests() will only be run if |add_experimental| is true.
675
Chris Masone6fed6462011-10-20 16:36:43 -0700676 @param record: callable that records job status.
677 prototype:
678 record(status, subdir, name, reason)
679 @param add_experimental: schedule experimental tests as well, or not.
680 """
681 try:
Scott Zawalskiab25bd62012-02-10 18:29:12 -0500682 record('INFO', None, 'Start %s' % self._tag)
Chris Masone8b7cd422012-02-22 13:16:11 -0800683 self.schedule(add_experimental)
Chris Masone6fed6462011-10-20 16:36:43 -0700684 try:
685 for result in self.wait_for_results():
Scott Zawalskiab25bd62012-02-10 18:29:12 -0500686 # |result| will be a tuple of a maximum of 4 entries and a
687 # minimum of 3. We use the first 3 for START and END
688 # entries so we separate those variables out for legible
689 # variable names, nothing more.
690 status = result[0]
691 test_name = result[2]
692 record('START', None, test_name)
Chris Masone6fed6462011-10-20 16:36:43 -0700693 record(*result)
Scott Zawalskiab25bd62012-02-10 18:29:12 -0500694 record('END %s' % status, None, test_name)
Chris Masone6fed6462011-10-20 16:36:43 -0700695 except Exception as e:
696 logging.error(e)
Scott Zawalskiab25bd62012-02-10 18:29:12 -0500697 record('FAIL', None, self._tag,
698 'Exception waiting for results')
Chris Masone6fed6462011-10-20 16:36:43 -0700699 except Exception as e:
700 logging.error(e)
Scott Zawalskiab25bd62012-02-10 18:29:12 -0500701 record('FAIL', None, self._tag,
702 'Exception while scheduling suite')
Chris Masone6fed6462011-10-20 16:36:43 -0700703
704
Chris Masone8b7cd422012-02-22 13:16:11 -0800705 def schedule(self, add_experimental=True):
Chris Masone6fed6462011-10-20 16:36:43 -0700706 """
707 Schedule jobs using |self._afe|.
708
709 frontend.Job objects representing each scheduled job will be put in
710 |self._jobs|.
711
Chris Masone6fed6462011-10-20 16:36:43 -0700712 @param add_experimental: schedule experimental tests as well, or not.
713 """
714 for test in self.stable_tests():
715 logging.debug('Scheduling %s', test.name)
Chris Masone8b7cd422012-02-22 13:16:11 -0800716 self._jobs.append(self._create_job(test))
Chris Masone6fed6462011-10-20 16:36:43 -0700717
718 if add_experimental:
719 # TODO(cmasone): ensure I can log results from these differently.
720 for test in self.unstable_tests():
Zdenek Behan150fbd62012-04-06 17:20:01 +0200721 logging.debug('Scheduling experimental %s', test.name)
722 test.name = 'experimental_' + test.name
Chris Masone8b7cd422012-02-22 13:16:11 -0800723 self._jobs.append(self._create_job(test))
Scott Zawalski9ece6532012-02-28 14:10:47 -0500724 if self._results_dir:
725 self._record_scheduled_jobs()
726
727
728 def _record_scheduled_jobs(self):
729 """
730 Record scheduled job ids as keyvals, so they can be referenced later.
Scott Zawalski9ece6532012-02-28 14:10:47 -0500731 """
732 for job in self._jobs:
733 job_id_owner = '%s-%s' % (job.id, job.owner)
Scott Zawalskie5bb1c52012-02-29 13:15:50 -0500734 utils.write_keyval(self._results_dir, {job.test_name: job_id_owner})
Chris Masone6fed6462011-10-20 16:36:43 -0700735
736
737 def _status_is_relevant(self, status):
738 """
739 Indicates whether the status of a given test is meaningful or not.
740
741 @param status: frontend.TestStatus object to look at.
742 @return True if this is a test result worth looking at further.
743 """
744 return not (status.test_name.startswith('SERVER_JOB') or
745 status.test_name.startswith('CLIENT_JOB'))
746
747
748 def _collate_aborted(self, current_value, entry):
749 """
750 reduce() over a list of HostQueueEntries for a job; True if any aborted.
751
752 Functor that can be reduced()ed over a list of
753 HostQueueEntries for a job. If any were aborted
754 (|entry.aborted| exists and is True), then the reduce() will
755 return True.
756
757 Ex:
758 entries = self._afe.run('get_host_queue_entries', job=job.id)
759 reduce(self._collate_aborted, entries, False)
760
761 @param current_value: the current accumulator (a boolean).
762 @param entry: the current entry under consideration.
763 @return the value of |entry.aborted| if it exists, False if not.
764 """
765 return current_value or ('aborted' in entry and entry['aborted'])
766
767
768 def wait_for_results(self):
769 """
770 Wait for results of all tests in all jobs in |self._jobs|.
771
772 Currently polls for results every 5s. When all results are available,
773 @return a list of tuples, one per test: (status, subdir, name, reason)
774 """
Chris Masone6fed6462011-10-20 16:36:43 -0700775 while self._jobs:
776 for job in list(self._jobs):
777 if not self._afe.get_jobs(id=job.id, finished=True):
778 continue
779
780 self._jobs.remove(job)
781
782 entries = self._afe.run('get_host_queue_entries', job=job.id)
783 if reduce(self._collate_aborted, entries, False):
Scott Zawalskiab25bd62012-02-10 18:29:12 -0500784 yield('ABORT', None, job.name)
Chris Masone6fed6462011-10-20 16:36:43 -0700785 else:
786 statuses = self._tko.get_status_counts(job=job.id)
787 for s in filter(self._status_is_relevant, statuses):
Scott Zawalskiab25bd62012-02-10 18:29:12 -0500788 yield(s.status, None, s.test_name, s.reason)
Chris Masone6fed6462011-10-20 16:36:43 -0700789 time.sleep(5)
790
Chris Masone6fed6462011-10-20 16:36:43 -0700791
Chris Masonefef21382012-01-17 11:16:32 -0800792 @staticmethod
793 def find_and_parse_tests(cf_getter, predicate, add_experimental=False):
Chris Masone6fed6462011-10-20 16:36:43 -0700794 """
795 Function to scan through all tests and find eligible tests.
796
797 Looks at control files returned by _cf_getter.get_control_file_list()
798 for tests that pass self._predicate().
799
800 @param cf_getter: a control_file_getter.ControlFileGetter used to list
801 and fetch the content of control files
802 @param predicate: a function that should return True when run over a
803 ControlData representation of a control file that should be in
804 this Suite.
805 @param add_experimental: add tests with experimental attribute set.
806
807 @return list of ControlData objects that should be run, with control
808 file text added in |text| attribute.
809 """
810 tests = {}
811 files = cf_getter.get_control_file_list()
812 for file in files:
813 text = cf_getter.get_control_file_contents(file)
814 try:
815 found_test = control_data.parse_control_string(text,
816 raise_warnings=True)
817 if not add_experimental and found_test.experimental:
818 continue
819
820 found_test.text = text
Chris Masonee8a4eff2012-02-28 16:33:43 -0800821 found_test.path = file
Chris Masone6fed6462011-10-20 16:36:43 -0700822 tests[file] = found_test
823 except control_data.ControlVariableException, e:
824 logging.warn("Skipping %s\n%s", file, e)
825 except Exception, e:
826 logging.error("Bad %s\n%s", file, e)
827
828 return [test for test in tests.itervalues() if predicate(test)]