blob: 17e70f3989b8ba78352c2812de277a71d694887c [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
Chris Masone11aae452012-05-21 16:08:39 -07006import compiler, datetime, hashlib, logging, os, random, re, time, traceback
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 Masone8ac66712012-02-15 14:21:02 -080010from autotest_lib.server.cros import control_file_getter, frontend_wrappers
Chris Masone8d6e6412012-06-28 11:20:56 -070011from autotest_lib.server.cros import job_status
Chris Masone6fed6462011-10-20 16:36:43 -070012from autotest_lib.server import frontend
Chris Masonef8b53062012-05-08 22:14:18 -070013from autotest_lib.frontend.afe.json_rpc import proxy
Chris Masone6fed6462011-10-20 16:36:43 -070014
Chris Masone6cfb7122012-05-02 11:36:28 -070015"""CrOS dynamic test suite generation and execution module.
16
17This module implements runtime-generated test suites for CrOS.
18Design doc: http://goto.google.com/suitesv2
19
20Individual tests can declare themselves as a part of one or more
21suites, and the code here enables control files to be written
22that can refer to these "dynamic suites" by name. We also provide
23support for reimaging devices with a given build and running a
24dynamic suite across all reimaged devices.
25
26The public API for defining a suite includes one method: reimage_and_run().
27A suite control file can be written by importing this module and making
28an appropriate call to this single method. In normal usage, this control
29file will be run in a 'hostless' server-side autotest job, scheduling
30sub-jobs to do the needed reimaging and test running.
31
32Example control file:
33
34import common
35from autotest_lib.server.cros import dynamic_suite
36
37dynamic_suite.reimage_and_run(
38 build=build, board=board, name='bvt', job=job, pool=pool,
39 check_hosts=check_hosts, add_experimental=True, num=4,
40 skip_reimage=dynamic_suite.skip_reimage(globals()))
41
42This will -- at runtime -- find all control files that contain "bvt"
43in their "SUITE=" clause, schedule jobs to reimage 4 devices in the
44specified pool of the specified board with the specified build and,
45upon completion of those jobs, schedule and wait for jobs that run all
46the tests it discovered across those 4 machines.
47
48Suites can be run by using the atest command-line tool:
49 atest suite create -b <board> -i <build/name> <suite>
50e.g.
51 atest suite create -b x86-mario -i x86-mario/R20-2203.0.0 bvt
52
53-------------------------------------------------------------------------
54Implementation details
55
56In addition to the create_suite_job() RPC defined in the autotest frontend,
57there are two main classes defined here: Suite and Reimager.
58
59A Suite instance represents a single test suite, defined by some predicate
60run over all known control files. The simplest example is creating a Suite
61by 'name'.
62
63The Reimager class provides support for reimaging a heterogenous set
64of devices with an appropriate build, in preparation for a test run.
65One could use a single Reimager, followed by the instantiation and use
66of multiple Suite objects.
67
68create_suite_job() takes the parameters needed to define a suite run (board,
69build to test, machine pool, and which suite to run), ensures important
70preconditions are met, finds the appropraite suite control file, and then
71schedules the hostless job that will do the rest of the work.
72
73reimage_and_run() works by creating a Reimager, using it to perform the
74requested installs, and then instantiating a Suite and running it on the
75machines that were just reimaged. We'll go through this process in stages.
76
77- create_suite_job()
78The primary role of create_suite_job() is to ensure that the required
79artifacts for the build to be tested are staged on the dev server. This
80includes payloads required to autoupdate machines to the desired build, as
81well as the autotest control files appropriate for that build. Then, the
82RPC pulls the control file for the suite to be run from the dev server and
83uses it to create the suite job with the autotest frontend.
84
85 +----------------+
86 | Google Storage | Client
87 +----------------+ |
88 | ^ | create_suite_job()
89 payloads/ | | |
90 control files | | request |
91 V | V
92 +-------------+ download request +--------------------------+
93 | |<----------------------| |
94 | Dev Server | | Autotest Frontend (AFE) |
95 | |---------------------->| |
96 +-------------+ suite control file +--------------------------+
97 |
98 V
99 Suite Job (hostless)
100
101- The Reimaging process
102In short, the Reimager schedules and waits for a number of autoupdate 'test'
103jobs that perform image installation and make sure the device comes back up.
104It labels the machines that it reimages with the newly-installed CrOS version,
105so that later steps in the can refer to the machines by version and board,
106instead of having to keep track of hostnames or some such.
107
108The number of machines to use is called the 'sharding_factor', and the default
109is defined in the [CROS] section of global_config.ini. This can be overridden
110by passing a 'num=N' parameter to reimage_and_run() as shown in the example
111above.
112
113Step by step:
1141) Schedule autoupdate 'tests' across N devices of the appropriate board.
115 - Technically, one job that has N tests across N hosts.
116 - This 'test' is in server/site_tests/autoupdate/
117 - The control file is modified at runtime to inject the name of the build
118 to install, and the URL to get said build from.
119 - This is the _TOT_ version of the autoupdate test; it must be able to run
120 successfully on all currently supported branches at all times.
1212) Wait for this job to get kicked off and run to completion.
1223) Label successfully reimaged devices with a 'cros-version' label
123 - This is actually done by the autoupdate 'test' control file.
1244) Add a host attribute ('job_repo_url') to each reimaged host indicating
125 the URL where packages should be downloaded for subsequent tests
126 - This is actually done by the autoupdate 'test' control file
127 - This information is consumed in server/site_autotest.py
128 - job_repo_url points to some location on the dev server, where build
129 artifacts are staged -- including autotest packages.
1305) Return success or failure.
131
132 +------------+ +--------------------------+
133 | | | |
134 | Dev Server | | Autotest Frontend (AFE) |
135 | | | [Suite Job] |
136 +------------+ +--------------------------+
137 | payloads | | | |
138 V V autoupdate test | | |
139 +--------+ +--------+ <-----+----------------+ | |
140 | Host 1 |<------| Host 2 |-------+ | |
141 +--------+ +--------+ label | |
142 VersLabel VersLabel <-----------------------+ |
143 job_repo_url job_repo_url <-----------------------------+
144 host-attribute
145
146To sum up, after re-imaging, we have the following assumptions:
147- |num| devices of type |board| have |build| installed.
148- These devices are labeled appropriately
149- They have a host attribute called 'job_repo_url' dictating where autotest
150 packages can be downloaded for test runs.
151
152
153- Running Suites
154A Suite instance uses the labels created by the Reimager to schedule test jobs
155across all the hosts that were just reimaged. It then waits for all these jobs.
156
157Step by step:
1581) At instantiation time, find all appropriate control files for this suite
159 that were included in the build to be tested. To do this, we consult the
160 Dev Server, where all these control files are staged.
161
162 +------------+ control files? +--------------------------+
163 | |<----------------------| |
164 | Dev Server | | Autotest Frontend (AFE) |
165 | |---------------------->| [Suite Job] |
166 +------------+ control files! +--------------------------+
167
1682) Now that the Suite instance exists, it schedules jobs for every control
169 file it deemed appropriate, to be run on the hosts that were labeled
170 by the Reimager. We stuff keyvals into these jobs, indicating what
171 build they were testing and which suite they were for.
172
173 +--------------------------+ Job for VersLabel +--------+
174 | |------------------------>| Host 1 | VersLabel
175 | Autotest Frontend (AFE) | +--------+ +--------+
176 | [Suite Job] |----------->| Host 2 |
177 +--------------------------+ Job for +--------+
178 | ^ VersLabel VersLabel
179 | |
180 +----------------+
181 One job per test
182 {'build': build/name,
183 'suite': suite_name}
184
1853) Now that all jobs are scheduled, they'll be doled out as labeled hosts
186 finish their assigned work and become available again.
1874) As we clean up each job, we check to see if any crashes occurred. If they
188 did, we look at the 'build' keyval in the job to see which build's debug
189 symbols we'll need to symbolicate the crash dump we just found.
1905) Using this info, we tell the Dev Server to stage the required debug symbols.
191 Once that's done, we ask the dev server to use those symbols to symbolicate
192 the crash dump in question.
193
194 +----------------+
195 | Google Storage |
196 +----------------+
197 | ^
198 symbols! | | symbols?
199 V |
200 +------------+ stage symbols for build +--------------------------+
201 | |<--------------------------| |
202 | | | |
203 | Dev Server | dump to symbolicate | Autotest Frontend (AFE) |
204 | |<--------------------------| [Suite Job] |
205 | |-------------------------->| |
206 +------------+ symbolicated dump +--------------------------+
207
2086) As jobs finish, we record their success or failure in the status of the suite
209 job. We also record a 'job keyval' in the suite job for each test, noting
210 the job ID and job owner. This can be used to refer to test logs later.
2117) Once all jobs are complete, status is recorded for the suite job, and the
212 job_repo_url host attribute is removed from all hosts used by the suite.
213
214"""
215
Chris Masone6fed6462011-10-20 16:36:43 -0700216
Chris Masoneaa10f8e2012-05-15 13:34:21 -0700217# Job keyvals for finding debug symbols when processing crash dumps.
218JOB_BUILD_KEY = 'build'
219JOB_SUITE_KEY = 'suite'
220
221# Job attribute and label names
222JOB_REPO_URL = 'job_repo_url'
Scott Zawalski65650172012-02-16 11:48:26 -0500223VERSION_PREFIX = 'cros-version:'
Chris Masoneaa10f8e2012-05-15 13:34:21 -0700224EXPERIMENTAL_PREFIX = 'experimental_'
225REIMAGE_JOB_NAME = 'try_new_image'
226
227# Timings
228ARTIFACT_FINISHED_TIME = 'artifact_finished_time'
229DOWNLOAD_STARTED_TIME = 'download_started_time'
230PAYLOAD_FINISHED_TIME = 'payload_finished_time'
Chris Masoneaa10f8e2012-05-15 13:34:21 -0700231
Chris Masone2ef1d4e2011-12-20 11:06:53 -0800232CONFIG = global_config.global_config
233
234
Chris Masonef8b53062012-05-08 22:14:18 -0700235# Relevant CrosDynamicSuiteExceptions are defined in client/common_lib/error.py.
Chris Masone502b71e2012-04-10 10:41:35 -0700236
237
Chris Masoneab3e7332012-02-29 18:54:58 -0800238def reimage_and_run(**dargs):
239 """
240 Backward-compatible API for dynamic_suite.
241
242 Will re-image a number of devices (of the specified board) with the
243 provided build, and then run the indicated test suite on them.
244 Guaranteed to be compatible with any build from stable to dev.
245
246 Currently required args:
247 @param build: the build to install e.g.
248 x86-alex-release/R18-1655.0.0-a1-b1584.
249 @param board: which kind of devices to reimage.
250 @param name: a value of the SUITE control file variable to search for.
251 @param job: an instance of client.common_lib.base_job representing the
252 currently running suite job.
253
254 Currently supported optional args:
255 @param pool: specify the pool of machines to use for scheduling purposes.
256 Default: None
257 @param num: how many devices to reimage.
258 Default in global_config
Chris Masone62579122012-03-08 15:18:43 -0800259 @param check_hosts: require appropriate hosts to be available now.
Chris Masoneab3e7332012-02-29 18:54:58 -0800260 @param skip_reimage: skip reimaging, used for testing purposes.
261 Default: False
262 @param add_experimental: schedule experimental tests as well, or not.
263 Default: True
Chris Sosa6b288c82012-03-29 15:31:06 -0700264 @raises AsynchronousBuildFailure: if there was an issue finishing staging
265 from the devserver.
Chris Masoneab3e7332012-02-29 18:54:58 -0800266 """
Chris Masone62579122012-03-08 15:18:43 -0800267 (build, board, name, job, pool, num, check_hosts, skip_reimage,
268 add_experimental) = _vet_reimage_and_run_args(**dargs)
Chris Masone5374c672012-03-05 15:11:39 -0800269 board = 'board:%s' % board
270 if pool:
271 pool = 'pool:%s' % pool
Chris Masonec43448f2012-05-31 12:55:59 -0700272 reimager = Reimager(job.autodir, results_dir=job.resultdir)
Chris Masoned368cc42012-03-07 15:16:59 -0800273
Chris Masonec43448f2012-05-31 12:55:59 -0700274 if skip_reimage or reimager.attempt(build, board, pool, job.record,
275 check_hosts, num=num):
Chris Sosa6b288c82012-03-29 15:31:06 -0700276
277 # Ensure that the image's artifacts have completed downloading.
Chris Masonef70650c2012-05-16 08:52:12 -0700278 try:
279 ds = dev_server.DevServer.create()
280 ds.finish_download(build)
281 except dev_server.DevServerException as e:
282 raise error.AsynchronousBuildFailure(e)
283
Chris Masone8d6e6412012-06-28 11:20:56 -0700284 timestamp = datetime.datetime.now().strftime(job_status.TIME_FMT)
Chris Masonea8066a92012-05-01 16:52:31 -0700285 utils.write_keyval(job.resultdir,
Chris Masoneaa10f8e2012-05-15 13:34:21 -0700286 {ARTIFACT_FINISHED_TIME: timestamp})
Chris Sosa6b288c82012-03-29 15:31:06 -0700287
Chris Masoneab3e7332012-02-29 18:54:58 -0800288 suite = Suite.create_from_name(name, build, pool=pool,
289 results_dir=job.resultdir)
Chris Masone99378582012-04-30 13:10:58 -0700290 suite.run_and_wait(job.record_entry, add_experimental=add_experimental)
Chris Masoneab3e7332012-02-29 18:54:58 -0800291
Chris Masoned368cc42012-03-07 15:16:59 -0800292 reimager.clear_reimaged_host_state(build)
293
Chris Masoneab3e7332012-02-29 18:54:58 -0800294
295def _vet_reimage_and_run_args(build=None, board=None, name=None, job=None,
Chris Masone62579122012-03-08 15:18:43 -0800296 pool=None, num=None, check_hosts=True,
297 skip_reimage=False, add_experimental=True,
298 **dargs):
Chris Masoneab3e7332012-02-29 18:54:58 -0800299 """
300 Vets arguments for reimage_and_run().
301
302 Currently required args:
303 @param build: the build to install e.g.
304 x86-alex-release/R18-1655.0.0-a1-b1584.
305 @param board: which kind of devices to reimage.
306 @param name: a value of the SUITE control file variable to search for.
307 @param job: an instance of client.common_lib.base_job representing the
308 currently running suite job.
309
310 Currently supported optional args:
311 @param pool: specify the pool of machines to use for scheduling purposes.
312 Default: None
313 @param num: how many devices to reimage.
314 Default in global_config
Chris Masone62579122012-03-08 15:18:43 -0800315 @param check_hosts: require appropriate hosts to be available now.
Chris Masoneab3e7332012-02-29 18:54:58 -0800316 @param skip_reimage: skip reimaging, used for testing purposes.
317 Default: False
318 @param add_experimental: schedule experimental tests as well, or not.
319 Default: True
320 @return a tuple of args set to provided (or default) values.
321 """
322 required_keywords = {'build': str,
323 'board': str,
324 'name': str,
325 'job': base_job.base_job}
326 for key, expected in required_keywords.iteritems():
327 value = locals().get(key)
328 if not value or not isinstance(value, expected):
Chris Masonef8b53062012-05-08 22:14:18 -0700329 raise error.SuiteArgumentException(
330 "reimage_and_run() needs %s=<%r>" % (key, expected))
Chris Masone62579122012-03-08 15:18:43 -0800331 return (build, board, name, job, pool, num, check_hosts, skip_reimage,
332 add_experimental)
Chris Masoneab3e7332012-02-29 18:54:58 -0800333
334
Chris Masone8b764252012-01-17 11:12:51 -0800335def inject_vars(vars, control_file_in):
336 """
Chris Masoneab3e7332012-02-29 18:54:58 -0800337 Inject the contents of |vars| into |control_file_in|.
Chris Masone8b764252012-01-17 11:12:51 -0800338
339 @param vars: a dict to shoehorn into the provided control file string.
340 @param control_file_in: the contents of a control file to munge.
341 @return the modified control file string.
342 """
343 control_file = ''
344 for key, value in vars.iteritems():
Chris Masone6cb0d0d2012-03-05 15:37:49 -0800345 # None gets injected as 'None' without this check; same for digits.
346 if isinstance(value, str):
347 control_file += "%s='%s'\n" % (key, value)
348 else:
349 control_file += "%s=%r\n" % (key, value)
Chris Masone8b764252012-01-17 11:12:51 -0800350 return control_file + control_file_in
351
352
Chris Masone2ef1d4e2011-12-20 11:06:53 -0800353def _image_url_pattern():
354 return CONFIG.get_config_value('CROS', 'image_url_pattern', type=str)
355
356
357def _package_url_pattern():
358 return CONFIG.get_config_value('CROS', 'package_url_pattern', type=str)
359
Chris Masone6fed6462011-10-20 16:36:43 -0700360
Chris Masoneab3e7332012-02-29 18:54:58 -0800361def skip_reimage(g):
362 return g.get('SKIP_IMAGE')
363
364
Chris Masone6fed6462011-10-20 16:36:43 -0700365class Reimager(object):
366 """
367 A class that can run jobs to reimage devices.
368
369 @var _afe: a frontend.AFE instance used to talk to autotest.
370 @var _tko: a frontend.TKO instance used to query the autotest results db.
371 @var _cf_getter: a ControlFileGetter used to get the AU control file.
372 """
373
374
Chris Masonec43448f2012-05-31 12:55:59 -0700375 def __init__(self, autotest_dir, afe=None, tko=None, results_dir=None):
Chris Masone6fed6462011-10-20 16:36:43 -0700376 """
377 Constructor
378
379 @param autotest_dir: the place to find autotests.
380 @param afe: an instance of AFE as defined in server/frontend.py.
381 @param tko: an instance of TKO as defined in server/frontend.py.
Chris Masone9f13ff22012-03-05 13:45:25 -0800382 @param results_dir: The directory where the job can write results to.
383 This must be set if you want job_id of sub-jobs
384 list in the job keyvals.
Chris Masone6fed6462011-10-20 16:36:43 -0700385 """
Chris Masone8ac66712012-02-15 14:21:02 -0800386 self._afe = afe or frontend_wrappers.RetryingAFE(timeout_min=30,
387 delay_sec=10,
388 debug=False)
389 self._tko = tko or frontend_wrappers.RetryingTKO(timeout_min=30,
390 delay_sec=10,
391 debug=False)
Chris Masone9f13ff22012-03-05 13:45:25 -0800392 self._results_dir = results_dir
Chris Masoned368cc42012-03-07 15:16:59 -0800393 self._reimaged_hosts = {}
Chris Masone6fed6462011-10-20 16:36:43 -0700394 self._cf_getter = control_file_getter.FileSystemGetter(
395 [os.path.join(autotest_dir, 'server/site_tests')])
396
397
Chris Masone2ef1d4e2011-12-20 11:06:53 -0800398 def skip(self, g):
Chris Masoneab3e7332012-02-29 18:54:58 -0800399 """Deprecated in favor of dynamic_suite.skip_reimage()."""
Chris Masone2ef1d4e2011-12-20 11:06:53 -0800400 return 'SKIP_IMAGE' in g and g['SKIP_IMAGE']
401
402
Chris Masonec43448f2012-05-31 12:55:59 -0700403 def attempt(self, build, board, pool, record, check_hosts, num=None):
Chris Masone6fed6462011-10-20 16:36:43 -0700404 """
405 Synchronously attempt to reimage some machines.
406
407 Fire off attempts to reimage |num| machines of type |board|, using an
Chris Masone8abb6fc2012-01-31 09:27:36 -0800408 image at |url| called |build|. Wait for completion, polling every
Chris Masone6fed6462011-10-20 16:36:43 -0700409 10s, and log results with |record| upon completion.
410
Chris Masone8abb6fc2012-01-31 09:27:36 -0800411 @param build: the build to install e.g.
412 x86-alex-release/R18-1655.0.0-a1-b1584.
Chris Masone6fed6462011-10-20 16:36:43 -0700413 @param board: which kind of devices to reimage.
Chris Masonec43448f2012-05-31 12:55:59 -0700414 @param pool: Specify the pool of machines to use for scheduling
415 purposes.
Chris Masone6fed6462011-10-20 16:36:43 -0700416 @param record: callable that records job status.
Chris Masone796fcf12012-02-22 16:53:31 -0800417 prototype:
418 record(status, subdir, name, reason)
Chris Masone62579122012-03-08 15:18:43 -0800419 @param check_hosts: require appropriate hosts to be available now.
Chris Masone5552dd72012-02-15 15:01:04 -0800420 @param num: how many devices to reimage.
Chris Masone6fed6462011-10-20 16:36:43 -0700421 @return True if all reimaging jobs succeed, false otherwise.
422 """
Chris Masone5552dd72012-02-15 15:01:04 -0800423 if not num:
424 num = CONFIG.get_config_value('CROS', 'sharding_factor', type=int)
Scott Zawalski65650172012-02-16 11:48:26 -0500425 logging.debug("scheduling reimaging across %d machines", num)
Chris Masoneaa10f8e2012-05-15 13:34:21 -0700426 record('START', None, REIMAGE_JOB_NAME)
Chris Masone796fcf12012-02-22 16:53:31 -0800427 try:
Chris Masone62579122012-03-08 15:18:43 -0800428 self._ensure_version_label(VERSION_PREFIX + build)
429
430 if check_hosts:
Chris Masonec43448f2012-05-31 12:55:59 -0700431 # TODO make DEPENDENCIES-aware
432 self._ensure_enough_hosts(board, pool, num)
Chris Masone5374c672012-03-05 15:11:39 -0800433
Chris Masoned368cc42012-03-07 15:16:59 -0800434 # Schedule job and record job metadata.
Chris Masonec43448f2012-05-31 12:55:59 -0700435 # TODO make DEPENDENCIES-aware
436 canary_job = self._schedule_reimage_job(build, board, pool, num)
Chris Masoneaa10f8e2012-05-15 13:34:21 -0700437 self._record_job_if_possible(REIMAGE_JOB_NAME, canary_job)
Chris Masoned368cc42012-03-07 15:16:59 -0800438 logging.debug('Created re-imaging job: %d', canary_job.id)
439
440 # Poll until reimaging is complete.
441 self._wait_for_job_to_start(canary_job.id)
442 self._wait_for_job_to_finish(canary_job.id)
443
444 # Gather job results.
445 canary_job.result = self._afe.poll_job_results(self._tko,
446 canary_job,
447 0)
Chris Masonef8b53062012-05-08 22:14:18 -0700448 except error.InadequateHostsException as e:
Chris Masone5374c672012-03-05 15:11:39 -0800449 logging.warning(e)
Chris Masoneaa10f8e2012-05-15 13:34:21 -0700450 record('END WARN', None, REIMAGE_JOB_NAME, str(e))
Chris Masone5374c672012-03-05 15:11:39 -0800451 return False
Chris Masone796fcf12012-02-22 16:53:31 -0800452 except Exception as e:
453 # catch Exception so we record the job as terminated no matter what.
454 logging.error(e)
Chris Masoneaa10f8e2012-05-15 13:34:21 -0700455 record('END ERROR', None, REIMAGE_JOB_NAME, str(e))
Chris Masone796fcf12012-02-22 16:53:31 -0800456 return False
Chris Masone6fed6462011-10-20 16:36:43 -0700457
Chris Masoned368cc42012-03-07 15:16:59 -0800458 self._remember_reimaged_hosts(build, canary_job)
459
460 if canary_job.result is True:
461 self._report_results(canary_job, record)
Chris Masoneaa10f8e2012-05-15 13:34:21 -0700462 record('END GOOD', None, REIMAGE_JOB_NAME)
Chris Masone6fed6462011-10-20 16:36:43 -0700463 return True
464
Chris Masoned368cc42012-03-07 15:16:59 -0800465 if canary_job.result is None:
466 record('FAIL', None, canary_job.name, 'reimaging tasks did not run')
467 else: # canary_job.result is False
468 self._report_results(canary_job, record)
Chris Masone6fed6462011-10-20 16:36:43 -0700469
Chris Masoneaa10f8e2012-05-15 13:34:21 -0700470 record('END FAIL', None, REIMAGE_JOB_NAME)
Chris Masone6fed6462011-10-20 16:36:43 -0700471 return False
472
473
Chris Masone62579122012-03-08 15:18:43 -0800474 def _ensure_enough_hosts(self, board, pool, num):
475 """
476 Determine if there are enough working hosts to run on.
477
478 Raises exception if there are not enough hosts.
479
480 @param board: which kind of devices to reimage.
481 @param pool: the pool of machines to use for scheduling purposes.
482 @param num: how many devices to reimage.
Chris Masonef8b53062012-05-08 22:14:18 -0700483 @raises NoHostsException: if no working hosts.
Chris Masone62579122012-03-08 15:18:43 -0800484 @raises InadequateHostsException: if too few working hosts.
485 """
486 labels = [l for l in [board, pool] if l is not None]
Chris Masone502b71e2012-04-10 10:41:35 -0700487 available = self._count_usable_hosts(labels)
488 if available == 0:
Chris Masonef8b53062012-05-08 22:14:18 -0700489 raise error.NoHostsException('All hosts with %r are dead!' % labels)
Chris Masone502b71e2012-04-10 10:41:35 -0700490 elif num > available:
Chris Masonef8b53062012-05-08 22:14:18 -0700491 raise error.InadequateHostsException(
492 'Too few hosts with %r' % labels)
Chris Masone62579122012-03-08 15:18:43 -0800493
494
Chris Masoned368cc42012-03-07 15:16:59 -0800495 def _wait_for_job_to_start(self, job_id):
496 """
497 Wait for the job specified by |job_id| to start.
498
499 @param job_id: the job ID to poll on.
500 """
501 while len(self._afe.get_jobs(id=job_id, not_yet_run=True)) > 0:
502 time.sleep(10)
503 logging.debug('Re-imaging job running.')
504
505
506 def _wait_for_job_to_finish(self, job_id):
507 """
508 Wait for the job specified by |job_id| to finish.
509
510 @param job_id: the job ID to poll on.
511 """
512 while len(self._afe.get_jobs(id=job_id, finished=True)) == 0:
513 time.sleep(10)
514 logging.debug('Re-imaging job finished.')
515
516
517 def _remember_reimaged_hosts(self, build, canary_job):
518 """
519 Remember hosts that were reimaged with |build| as a part |canary_job|.
520
521 @param build: the build that was installed e.g.
522 x86-alex-release/R18-1655.0.0-a1-b1584.
523 @param canary_job: a completed frontend.Job object, possibly populated
524 by frontend.AFE.poll_job_results.
525 """
526 if not hasattr(canary_job, 'results_platform_map'):
527 return
528 if not self._reimaged_hosts.get('build'):
529 self._reimaged_hosts[build] = []
530 for platform in canary_job.results_platform_map:
531 for host in canary_job.results_platform_map[platform]['Total']:
532 self._reimaged_hosts[build].append(host)
533
534
535 def clear_reimaged_host_state(self, build):
536 """
537 Clear per-host state created in the autotest DB for this job.
538
539 After reimaging a host, we label it and set some host attributes on it
540 that are then used by the suite scheduling code. This call cleans
541 that up.
542
543 @param build: the build whose hosts we want to clean up e.g.
544 x86-alex-release/R18-1655.0.0-a1-b1584.
545 """
Chris Masoned368cc42012-03-07 15:16:59 -0800546 for host in self._reimaged_hosts.get('build', []):
547 self._clear_build_state(host)
548
549
550 def _clear_build_state(self, machine):
551 """
552 Clear all build-specific labels, attributes from the target.
553
554 @param machine: the host to clear labels, attributes from.
555 """
Chris Masoneaa10f8e2012-05-15 13:34:21 -0700556 self._afe.set_host_attribute(JOB_REPO_URL, None, hostname=machine)
Chris Masoned368cc42012-03-07 15:16:59 -0800557
558
Chris Masone9f13ff22012-03-05 13:45:25 -0800559 def _record_job_if_possible(self, test_name, job):
560 """
561 Record job id as keyval, if possible, so it can be referenced later.
562
563 If |self._results_dir| is None, then this is a NOOP.
Chris Masone5374c672012-03-05 15:11:39 -0800564
565 @param test_name: the test to record id/owner for.
566 @param job: the job object to pull info from.
Chris Masone9f13ff22012-03-05 13:45:25 -0800567 """
568 if self._results_dir:
569 job_id_owner = '%s-%s' % (job.id, job.owner)
Chris Masone11aae452012-05-21 16:08:39 -0700570 utils.write_keyval(
571 self._results_dir,
572 {hashlib.md5(test_name).hexdigest(): job_id_owner})
Chris Masone9f13ff22012-03-05 13:45:25 -0800573
574
Chris Masone5374c672012-03-05 15:11:39 -0800575 def _count_usable_hosts(self, host_spec):
576 """
577 Given a set of host labels, count the live hosts that have them all.
578
579 @param host_spec: list of labels specifying a set of hosts.
580 @return the number of live hosts that satisfy |host_spec|.
581 """
582 count = 0
583 for h in self._afe.get_hosts(multiple_labels=host_spec):
584 if h.status not in ['Repair Failed', 'Repairing']:
585 count += 1
586 return count
587
588
Chris Masone6fed6462011-10-20 16:36:43 -0700589 def _ensure_version_label(self, name):
590 """
591 Ensure that a label called |name| exists in the autotest DB.
592
593 @param name: the label to check for/create.
594 """
Chris Masone47c9e642012-04-25 14:22:18 -0700595 try:
Chris Masone6fed6462011-10-20 16:36:43 -0700596 self._afe.create_label(name=name)
Chris Masone47c9e642012-04-25 14:22:18 -0700597 except proxy.ValidationError as ve:
598 if ('name' in ve.problem_keys and
599 'This value must be unique' in ve.problem_keys['name']):
600 logging.debug('Version label %s already exists', name)
601 else:
602 raise ve
Chris Masone6fed6462011-10-20 16:36:43 -0700603
604
Chris Masonec43448f2012-05-31 12:55:59 -0700605 def _schedule_reimage_job(self, build, board, pool, num_machines):
Chris Masone6fed6462011-10-20 16:36:43 -0700606 """
607 Schedules the reimaging of |num_machines| |board| devices with |image|.
608
609 Sends an RPC to the autotest frontend to enqueue reimaging jobs on
610 |num_machines| devices of type |board|
611
Chris Masone8abb6fc2012-01-31 09:27:36 -0800612 @param build: the build to install (must be unique).
Chris Masone6fed6462011-10-20 16:36:43 -0700613 @param board: which kind of devices to reimage.
Chris Masonec43448f2012-05-31 12:55:59 -0700614 @param pool: the pool of machines to use for scheduling purposes.
615 @param num_machines: how many devices to reimage.
Chris Masone6fed6462011-10-20 16:36:43 -0700616 @return a frontend.Job object for the reimaging job we scheduled.
617 """
Chris Masone8b764252012-01-17 11:12:51 -0800618 control_file = inject_vars(
Chris Masone8abb6fc2012-01-31 09:27:36 -0800619 {'image_url': _image_url_pattern() % build, 'image_name': build},
Chris Masone6fed6462011-10-20 16:36:43 -0700620 self._cf_getter.get_control_file_contents_by_name('autoupdate'))
Scott Zawalski65650172012-02-16 11:48:26 -0500621 job_deps = []
Chris Masonec43448f2012-05-31 12:55:59 -0700622 if pool:
623 meta_host = pool
Chris Masone5374c672012-03-05 15:11:39 -0800624 board_label = board
Scott Zawalski65650172012-02-16 11:48:26 -0500625 job_deps.append(board_label)
626 else:
627 # No pool specified use board.
Chris Masone5374c672012-03-05 15:11:39 -0800628 meta_host = board
Chris Masone6fed6462011-10-20 16:36:43 -0700629
Chris Masone2ef1d4e2011-12-20 11:06:53 -0800630 return self._afe.create_job(control_file=control_file,
Chris Masone8abb6fc2012-01-31 09:27:36 -0800631 name=build + '-try',
Chris Masone2ef1d4e2011-12-20 11:06:53 -0800632 control_type='Server',
Chris Masone97325362012-04-26 16:19:13 -0700633 priority='Low',
Scott Zawalski65650172012-02-16 11:48:26 -0500634 meta_hosts=[meta_host] * num_machines,
635 dependencies=job_deps)
Chris Masone6fed6462011-10-20 16:36:43 -0700636
637
638 def _report_results(self, job, record):
639 """
640 Record results from a completed frontend.Job object.
641
642 @param job: a completed frontend.Job object populated by
643 frontend.AFE.poll_job_results.
644 @param record: callable that records job status.
645 prototype:
646 record(status, subdir, name, reason)
647 """
648 if job.result == True:
649 record('GOOD', None, job.name)
650 return
651
652 for platform in job.results_platform_map:
653 for status in job.results_platform_map[platform]:
654 if status == 'Total':
655 continue
656 for host in job.results_platform_map[platform][status]:
657 if host not in job.test_status:
658 record('ERROR', None, host, 'Job failed to run.')
659 elif status == 'Failed':
660 for test_status in job.test_status[host].fail:
661 record('FAIL', None, host, test_status.reason)
662 elif status == 'Aborted':
663 for test_status in job.test_status[host].fail:
664 record('ABORT', None, host, test_status.reason)
665 elif status == 'Completed':
666 record('GOOD', None, host)
667
668
669class Suite(object):
670 """
671 A suite of tests, defined by some predicate over control file variables.
672
673 Given a place to search for control files a predicate to match the desired
674 tests, can gather tests and fire off jobs to run them, and then wait for
675 results.
676
677 @var _predicate: a function that should return True when run over a
678 ControlData representation of a control file that should be in
679 this Suite.
680 @var _tag: a string with which to tag jobs run in this suite.
Chris Masone8b7cd422012-02-22 13:16:11 -0800681 @var _build: the build on which we're running this suite.
Chris Masone6fed6462011-10-20 16:36:43 -0700682 @var _afe: an instance of AFE as defined in server/frontend.py.
683 @var _tko: an instance of TKO as defined in server/frontend.py.
684 @var _jobs: currently scheduled jobs, if any.
685 @var _cf_getter: a control_file_getter.ControlFileGetter
686 """
687
688
Chris Masonefef21382012-01-17 11:16:32 -0800689 @staticmethod
Chris Masoned6f38c82012-02-22 14:53:42 -0800690 def create_ds_getter(build):
Chris Masonefef21382012-01-17 11:16:32 -0800691 """
Chris Masone8b7cd422012-02-22 13:16:11 -0800692 @param build: the build on which we're running this suite.
Chris Masonefef21382012-01-17 11:16:32 -0800693 @return a FileSystemGetter instance that looks under |autotest_dir|.
694 """
Chris Masone8b7cd422012-02-22 13:16:11 -0800695 return control_file_getter.DevServerGetter(
696 build, dev_server.DevServer.create())
Chris Masonefef21382012-01-17 11:16:32 -0800697
698
699 @staticmethod
Chris Masoned6f38c82012-02-22 14:53:42 -0800700 def create_fs_getter(autotest_dir):
701 """
702 @param autotest_dir: the place to find autotests.
703 @return a FileSystemGetter instance that looks under |autotest_dir|.
704 """
705 # currently hard-coded places to look for tests.
706 subpaths = ['server/site_tests', 'client/site_tests',
707 'server/tests', 'client/tests']
708 directories = [os.path.join(autotest_dir, p) for p in subpaths]
709 return control_file_getter.FileSystemGetter(directories)
710
711
712 @staticmethod
Zdenek Behan849db052012-02-29 19:16:28 +0100713 def parse_tag(tag):
714 """Splits a string on ',' optionally surrounded by whitespace."""
715 return map(lambda x: x.strip(), tag.split(','))
716
717
718 @staticmethod
Chris Masone84564792012-02-23 10:52:42 -0800719 def name_in_tag_predicate(name):
720 """Returns predicate that takes a control file and looks for |name|.
721
722 Builds a predicate that takes in a parsed control file (a ControlData)
723 and returns True if the SUITE tag is present and contains |name|.
724
725 @param name: the suite name to base the predicate on.
726 @return a callable that takes a ControlData and looks for |name| in that
727 ControlData object's suite member.
728 """
Zdenek Behan849db052012-02-29 19:16:28 +0100729 return lambda t: hasattr(t, 'suite') and \
730 name in Suite.parse_tag(t.suite)
Chris Masone84564792012-02-23 10:52:42 -0800731
Zdenek Behan849db052012-02-29 19:16:28 +0100732
733 @staticmethod
734 def list_all_suites(build, cf_getter=None):
735 """
736 Parses all ControlData objects with a SUITE tag and extracts all
737 defined suite names.
738
739 @param cf_getter: control_file_getter.ControlFileGetter. Defaults to
740 using DevServerGetter.
741
742 @return list of suites
743 """
744 if cf_getter is None:
745 cf_getter = Suite.create_ds_getter(build)
746
747 suites = set()
748 predicate = lambda t: hasattr(t, 'suite')
Scott Zawalskif22b75d2012-05-10 16:54:37 -0400749 for test in Suite.find_and_parse_tests(cf_getter, predicate,
750 add_experimental=True):
Zdenek Behan849db052012-02-29 19:16:28 +0100751 suites.update(Suite.parse_tag(test.suite))
752 return list(suites)
Chris Masone84564792012-02-23 10:52:42 -0800753
754
755 @staticmethod
Scott Zawalski9ece6532012-02-28 14:10:47 -0500756 def create_from_name(name, build, cf_getter=None, afe=None, tko=None,
757 pool=None, results_dir=None):
Chris Masone6fed6462011-10-20 16:36:43 -0700758 """
759 Create a Suite using a predicate based on the SUITE control file var.
760
761 Makes a predicate based on |name| and uses it to instantiate a Suite
762 that looks for tests in |autotest_dir| and will schedule them using
Chris Masoned6f38c82012-02-22 14:53:42 -0800763 |afe|. Pulls control files from the default dev server.
764 Results will be pulled from |tko| upon completion.
Chris Masone6fed6462011-10-20 16:36:43 -0700765
766 @param name: a value of the SUITE control file variable to search for.
Chris Masone8b7cd422012-02-22 13:16:11 -0800767 @param build: the build on which we're running this suite.
Chris Masoned6f38c82012-02-22 14:53:42 -0800768 @param cf_getter: a control_file_getter.ControlFileGetter.
769 If None, default to using a DevServerGetter.
Chris Masone6fed6462011-10-20 16:36:43 -0700770 @param afe: an instance of AFE as defined in server/frontend.py.
771 @param tko: an instance of TKO as defined in server/frontend.py.
Scott Zawalski65650172012-02-16 11:48:26 -0500772 @param pool: Specify the pool of machines to use for scheduling
Chris Masoned6f38c82012-02-22 14:53:42 -0800773 purposes.
Scott Zawalski9ece6532012-02-28 14:10:47 -0500774 @param results_dir: The directory where the job can write results to.
775 This must be set if you want job_id of sub-jobs
776 list in the job keyvals.
Chris Masone6fed6462011-10-20 16:36:43 -0700777 @return a Suite instance.
778 """
Chris Masoned6f38c82012-02-22 14:53:42 -0800779 if cf_getter is None:
780 cf_getter = Suite.create_ds_getter(build)
Chris Masone84564792012-02-23 10:52:42 -0800781 return Suite(Suite.name_in_tag_predicate(name),
Scott Zawalski9ece6532012-02-28 14:10:47 -0500782 name, build, cf_getter, afe, tko, pool, results_dir)
Chris Masone6fed6462011-10-20 16:36:43 -0700783
784
Chris Masoned6f38c82012-02-22 14:53:42 -0800785 def __init__(self, predicate, tag, build, cf_getter, afe=None, tko=None,
Scott Zawalski9ece6532012-02-28 14:10:47 -0500786 pool=None, results_dir=None):
Chris Masone6fed6462011-10-20 16:36:43 -0700787 """
788 Constructor
789
790 @param predicate: a function that should return True when run over a
791 ControlData representation of a control file that should be in
792 this Suite.
793 @param tag: a string with which to tag jobs run in this suite.
Chris Masone8b7cd422012-02-22 13:16:11 -0800794 @param build: the build on which we're running this suite.
Chris Masoned6f38c82012-02-22 14:53:42 -0800795 @param cf_getter: a control_file_getter.ControlFileGetter
Chris Masone6fed6462011-10-20 16:36:43 -0700796 @param afe: an instance of AFE as defined in server/frontend.py.
797 @param tko: an instance of TKO as defined in server/frontend.py.
Scott Zawalski65650172012-02-16 11:48:26 -0500798 @param pool: Specify the pool of machines to use for scheduling
799 purposes.
Scott Zawalski9ece6532012-02-28 14:10:47 -0500800 @param results_dir: The directory where the job can write results to.
801 This must be set if you want job_id of sub-jobs
802 list in the job keyvals.
Chris Masone6fed6462011-10-20 16:36:43 -0700803 """
804 self._predicate = predicate
805 self._tag = tag
Chris Masone8b7cd422012-02-22 13:16:11 -0800806 self._build = build
Chris Masoned6f38c82012-02-22 14:53:42 -0800807 self._cf_getter = cf_getter
Scott Zawalski9ece6532012-02-28 14:10:47 -0500808 self._results_dir = results_dir
Chris Masone8ac66712012-02-15 14:21:02 -0800809 self._afe = afe or frontend_wrappers.RetryingAFE(timeout_min=30,
810 delay_sec=10,
811 debug=False)
812 self._tko = tko or frontend_wrappers.RetryingTKO(timeout_min=30,
813 delay_sec=10,
814 debug=False)
Scott Zawalski65650172012-02-16 11:48:26 -0500815 self._pool = pool
Chris Masone6fed6462011-10-20 16:36:43 -0700816 self._jobs = []
Chris Masone6fed6462011-10-20 16:36:43 -0700817 self._tests = Suite.find_and_parse_tests(self._cf_getter,
818 self._predicate,
819 add_experimental=True)
820
821
822 @property
823 def tests(self):
824 """
825 A list of ControlData objects in the suite, with added |text| attr.
826 """
827 return self._tests
828
829
830 def stable_tests(self):
831 """
832 |self.tests|, filtered for non-experimental tests.
833 """
834 return filter(lambda t: not t.experimental, self.tests)
835
836
837 def unstable_tests(self):
838 """
839 |self.tests|, filtered for experimental tests.
840 """
841 return filter(lambda t: t.experimental, self.tests)
842
843
Chris Masone8b7cd422012-02-22 13:16:11 -0800844 def _create_job(self, test):
Chris Masone6fed6462011-10-20 16:36:43 -0700845 """
846 Thin wrapper around frontend.AFE.create_job().
847
848 @param test: ControlData object for a test to run.
Scott Zawalskie5bb1c52012-02-29 13:15:50 -0500849 @return a frontend.Job object with an added test_name member.
850 test_name is used to preserve the higher level TEST_NAME
851 name of the job.
Chris Masone6fed6462011-10-20 16:36:43 -0700852 """
Chris Masonec43448f2012-05-31 12:55:59 -0700853 job_deps = [] # TODO(cmasone): init from test.dependencies.
Scott Zawalski65650172012-02-16 11:48:26 -0500854 if self._pool:
Chris Masone5374c672012-03-05 15:11:39 -0800855 meta_hosts = self._pool
Chris Masone8b7cd422012-02-22 13:16:11 -0800856 cros_label = VERSION_PREFIX + self._build
Scott Zawalski65650172012-02-16 11:48:26 -0500857 job_deps.append(cros_label)
858 else:
859 # No pool specified use any machines with the following label.
Chris Masone8b7cd422012-02-22 13:16:11 -0800860 meta_hosts = VERSION_PREFIX + self._build
Scott Zawalskie5bb1c52012-02-29 13:15:50 -0500861 test_obj = self._afe.create_job(
Chris Masone6fed6462011-10-20 16:36:43 -0700862 control_file=test.text,
Chris Masone8b7cd422012-02-22 13:16:11 -0800863 name='/'.join([self._build, self._tag, test.name]),
Chris Masone6fed6462011-10-20 16:36:43 -0700864 control_type=test.test_type.capitalize(),
Scott Zawalski65650172012-02-16 11:48:26 -0500865 meta_hosts=[meta_hosts],
Chris Masonebafbbb02012-05-16 13:41:36 -0700866 dependencies=job_deps,
Chris Masoneaa10f8e2012-05-15 13:34:21 -0700867 keyvals={JOB_BUILD_KEY: self._build, JOB_SUITE_KEY: self._tag})
Chris Masone6fed6462011-10-20 16:36:43 -0700868
Scott Zawalskie5bb1c52012-02-29 13:15:50 -0500869 setattr(test_obj, 'test_name', test.name)
870
871 return test_obj
872
Chris Masone6fed6462011-10-20 16:36:43 -0700873
Chris Masone8b7cd422012-02-22 13:16:11 -0800874 def run_and_wait(self, record, add_experimental=True):
Chris Masone6fed6462011-10-20 16:36:43 -0700875 """
876 Synchronously run tests in |self.tests|.
877
Chris Masone8b7cd422012-02-22 13:16:11 -0800878 Schedules tests against a device running image |self._build|, and
Chris Masone6fed6462011-10-20 16:36:43 -0700879 then polls for status, using |record| to print status when each
880 completes.
881
882 Tests returned by self.stable_tests() will always be run, while tests
883 in self.unstable_tests() will only be run if |add_experimental| is true.
884
Chris Masone6fed6462011-10-20 16:36:43 -0700885 @param record: callable that records job status.
886 prototype:
887 record(status, subdir, name, reason)
888 @param add_experimental: schedule experimental tests as well, or not.
889 """
Chris Masoneed356392012-05-08 14:07:13 -0700890 logging.debug('Discovered %d stable tests.', len(self.stable_tests()))
891 logging.debug('Discovered %d unstable tests.',
892 len(self.unstable_tests()))
Chris Masone6fed6462011-10-20 16:36:43 -0700893 try:
Chris Masone8d6e6412012-06-28 11:20:56 -0700894 job_status.Status('INFO',
895 'Start %s' % self._tag).record_result(record)
Chris Masone8b7cd422012-02-22 13:16:11 -0800896 self.schedule(add_experimental)
Chris Masone6fed6462011-10-20 16:36:43 -0700897 try:
Chris Masone8d6e6412012-06-28 11:20:56 -0700898 for result in job_status.wait_for_results(self._afe,
899 self._tko,
900 self._jobs):
Chris Masone99378582012-04-30 13:10:58 -0700901 result.record_start(record)
902 result.record_result(record)
903 result.record_end(record)
Chris Masone6fed6462011-10-20 16:36:43 -0700904 except Exception as e:
Chris Masone99378582012-04-30 13:10:58 -0700905 logging.error(traceback.format_exc())
Chris Masone8d6e6412012-06-28 11:20:56 -0700906 job_status.Status('FAIL', self._tag,
Chris Masone99378582012-04-30 13:10:58 -0700907 'Exception waiting for results').record_result(record)
Chris Masone6fed6462011-10-20 16:36:43 -0700908 except Exception as e:
Chris Masone99378582012-04-30 13:10:58 -0700909 logging.error(traceback.format_exc())
Chris Masone8d6e6412012-06-28 11:20:56 -0700910 job_status.Status('FAIL', self._tag,
Chris Masone99378582012-04-30 13:10:58 -0700911 'Exception while scheduling suite').record_result(record)
Chris Masoneed356392012-05-08 14:07:13 -0700912 # Sanity check
913 tests_at_end = self.find_and_parse_tests(self._cf_getter,
914 self._predicate,
915 add_experimental=True)
916 if len(self.tests) != len(tests_at_end):
917 msg = 'Dev Server enumerated %d tests at start, %d at end.' % (
918 len(self.tests), len(tests_at_end))
Chris Masone8d6e6412012-06-28 11:20:56 -0700919 job_status.Status('FAIL', self._tag, msg).record_result(record)
Chris Masone6fed6462011-10-20 16:36:43 -0700920
921
Chris Masone8b7cd422012-02-22 13:16:11 -0800922 def schedule(self, add_experimental=True):
Chris Masone6fed6462011-10-20 16:36:43 -0700923 """
924 Schedule jobs using |self._afe|.
925
926 frontend.Job objects representing each scheduled job will be put in
927 |self._jobs|.
928
Chris Masone6fed6462011-10-20 16:36:43 -0700929 @param add_experimental: schedule experimental tests as well, or not.
930 """
931 for test in self.stable_tests():
932 logging.debug('Scheduling %s', test.name)
Chris Masone8b7cd422012-02-22 13:16:11 -0800933 self._jobs.append(self._create_job(test))
Chris Masone6fed6462011-10-20 16:36:43 -0700934
935 if add_experimental:
Chris Masone6fed6462011-10-20 16:36:43 -0700936 for test in self.unstable_tests():
Zdenek Behan150fbd62012-04-06 17:20:01 +0200937 logging.debug('Scheduling experimental %s', test.name)
Chris Masoneaa10f8e2012-05-15 13:34:21 -0700938 test.name = EXPERIMENTAL_PREFIX + test.name
Chris Masone8b7cd422012-02-22 13:16:11 -0800939 self._jobs.append(self._create_job(test))
Scott Zawalski9ece6532012-02-28 14:10:47 -0500940 if self._results_dir:
941 self._record_scheduled_jobs()
942
943
944 def _record_scheduled_jobs(self):
945 """
946 Record scheduled job ids as keyvals, so they can be referenced later.
Scott Zawalski9ece6532012-02-28 14:10:47 -0500947 """
948 for job in self._jobs:
949 job_id_owner = '%s-%s' % (job.id, job.owner)
Chris Masone11aae452012-05-21 16:08:39 -0700950 utils.write_keyval(
951 self._results_dir,
952 {hashlib.md5(job.test_name).hexdigest(): job_id_owner})
Chris Masone6fed6462011-10-20 16:36:43 -0700953
954
Chris Masonefef21382012-01-17 11:16:32 -0800955 @staticmethod
956 def find_and_parse_tests(cf_getter, predicate, add_experimental=False):
Chris Masone6fed6462011-10-20 16:36:43 -0700957 """
958 Function to scan through all tests and find eligible tests.
959
960 Looks at control files returned by _cf_getter.get_control_file_list()
961 for tests that pass self._predicate().
962
963 @param cf_getter: a control_file_getter.ControlFileGetter used to list
964 and fetch the content of control files
965 @param predicate: a function that should return True when run over a
966 ControlData representation of a control file that should be in
967 this Suite.
968 @param add_experimental: add tests with experimental attribute set.
969
970 @return list of ControlData objects that should be run, with control
971 file text added in |text| attribute.
972 """
973 tests = {}
974 files = cf_getter.get_control_file_list()
Chris Masone75a20612012-05-08 12:37:31 -0700975 matcher = re.compile(r'[^/]+/(deps|profilers)/.+')
976 for file in filter(lambda f: not matcher.match(f), files):
Chris Masoneed356392012-05-08 14:07:13 -0700977 logging.debug('Considering %s', file)
Chris Masone6fed6462011-10-20 16:36:43 -0700978 text = cf_getter.get_control_file_contents(file)
979 try:
Chris Masoneed356392012-05-08 14:07:13 -0700980 found_test = control_data.parse_control_string(
981 text, raise_warnings=True)
Chris Masone6fed6462011-10-20 16:36:43 -0700982 if not add_experimental and found_test.experimental:
983 continue
984
985 found_test.text = text
Chris Masonee8a4eff2012-02-28 16:33:43 -0800986 found_test.path = file
Chris Masone6fed6462011-10-20 16:36:43 -0700987 tests[file] = found_test
988 except control_data.ControlVariableException, e:
989 logging.warn("Skipping %s\n%s", file, e)
990 except Exception, e:
991 logging.error("Bad %s\n%s", file, e)
992
993 return [test for test in tests.itervalues() if predicate(test)]