blob: ac4f403018b8661dedd6840156697c00c7df738b [file] [log] [blame]
maruel@chromium.org0437a732013-08-27 16:05:52 +00001#!/usr/bin/env python
2# Copyright 2013 The Chromium Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6"""Client tool to trigger tasks or retrieve results from a Swarming server."""
7
8__version__ = '0.1'
9
vadimsh@chromium.org6b706212013-08-28 15:03:46 +000010import binascii
maruel@chromium.org0437a732013-08-27 16:05:52 +000011import hashlib
12import json
13import logging
14import os
maruel@chromium.org0437a732013-08-27 16:05:52 +000015import shutil
maruel@chromium.org0437a732013-08-27 16:05:52 +000016import subprocess
17import sys
18import time
19import urllib
maruel@chromium.org0437a732013-08-27 16:05:52 +000020
21from third_party import colorama
22from third_party.depot_tools import fix_encoding
23from third_party.depot_tools import subcommand
vadimsh@chromium.org6b706212013-08-28 15:03:46 +000024
25from utils import net
maruel@chromium.org0437a732013-08-27 16:05:52 +000026from utils import threading_utils
vadimsh@chromium.org6b706212013-08-28 15:03:46 +000027from utils import tools
28from utils import zip_package
maruel@chromium.org0437a732013-08-27 16:05:52 +000029
maruel@chromium.org7b844a62013-09-17 13:04:59 +000030import isolateserver
maruel@chromium.org0437a732013-08-27 16:05:52 +000031import run_isolated
32
33
34ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
35TOOLS_PATH = os.path.join(ROOT_DIR, 'tools')
36
37
maruel@chromium.org0437a732013-08-27 16:05:52 +000038# The default time to wait for a shard to finish running.
csharp@chromium.org24758492013-08-28 19:10:54 +000039DEFAULT_SHARD_WAIT_TIME = 80 * 60.
maruel@chromium.org0437a732013-08-27 16:05:52 +000040
41
42NO_OUTPUT_FOUND = (
43 'No output produced by the test, it may have failed to run.\n'
44 '\n')
45
46
maruel@chromium.orge9403ab2013-09-20 18:03:49 +000047# TODO(maruel): cygwin != Windows. If a swarm_bot is running in cygwin, it's
48# different from running in native python.
49PLATFORM_MAPPING_SWARMING = {
maruel@chromium.org0437a732013-08-27 16:05:52 +000050 'cygwin': 'Windows',
51 'darwin': 'Mac',
52 'linux2': 'Linux',
53 'win32': 'Windows',
54}
55
maruel@chromium.orge9403ab2013-09-20 18:03:49 +000056PLATFORM_MAPPING_ISOLATE = {
57 'linux2': 'linux',
58 'darwin': 'mac',
59 'win32': 'win',
60}
61
maruel@chromium.org0437a732013-08-27 16:05:52 +000062
63class Failure(Exception):
64 """Generic failure."""
65 pass
66
67
68class Manifest(object):
69 """Represents a Swarming task manifest.
70
71 Also includes code to zip code and upload itself.
72 """
73 def __init__(
74 self, manifest_hash, test_name, shards, test_filter, slave_os,
maruel@chromium.org7b844a62013-09-17 13:04:59 +000075 working_dir, isolate_server, verbose, profile, priority, algo):
maruel@chromium.org0437a732013-08-27 16:05:52 +000076 """Populates a manifest object.
77 Args:
78 manifest_hash - The manifest's sha-1 that the slave is going to fetch.
79 test_name - The name to give the test request.
80 shards - The number of swarm shards to request.
81 test_filter - The gtest filter to apply when running the test.
82 slave_os - OS to run on.
83 working_dir - Relative working directory to start the script.
84 isolate_server - isolate server url.
85 verbose - if True, have the slave print more details.
86 profile - if True, have the slave print more timing data.
maruel@chromium.org7b844a62013-09-17 13:04:59 +000087 priority - int between 0 and 1000, lower the higher priority.
88 algo - hashing algorithm used.
maruel@chromium.org0437a732013-08-27 16:05:52 +000089 """
90 self.manifest_hash = manifest_hash
vadimsh@chromium.org6b706212013-08-28 15:03:46 +000091 self.bundle = zip_package.ZipPackage(ROOT_DIR)
92
maruel@chromium.org0437a732013-08-27 16:05:52 +000093 self._test_name = test_name
94 self._shards = shards
95 self._test_filter = test_filter
maruel@chromium.orge9403ab2013-09-20 18:03:49 +000096 self._target_platform = PLATFORM_MAPPING_SWARMING[slave_os]
maruel@chromium.org0437a732013-08-27 16:05:52 +000097 self._working_dir = working_dir
98
maruel@chromium.orgb7e79a22013-09-13 01:24:56 +000099 self.isolate_server = isolate_server
100 self._data_server_retrieval = isolate_server + '/content/retrieve/default/'
maruel@chromium.org0437a732013-08-27 16:05:52 +0000101 self._data_server_storage = isolate_server + '/content/store/default/'
102 self._data_server_has = isolate_server + '/content/contains/default'
103 self._data_server_get_token = isolate_server + '/content/get_token'
104
105 self.verbose = bool(verbose)
106 self.profile = bool(profile)
107 self.priority = priority
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000108 self._algo = algo
maruel@chromium.org0437a732013-08-27 16:05:52 +0000109
110 self._zip_file_hash = ''
111 self._tasks = []
112 self._files = {}
113 self._token_cache = None
114
115 def _token(self):
116 if not self._token_cache:
vadimsh@chromium.org6b706212013-08-28 15:03:46 +0000117 result = net.url_open(self._data_server_get_token)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000118 if not result:
119 # TODO(maruel): Implement authentication.
120 raise Failure('Failed to get token, need authentication')
121 # Quote it right away, so creating the urls is simpler.
122 self._token_cache = urllib.quote(result.read())
123 return self._token_cache
124
125 def add_task(self, task_name, actions, time_out=600):
126 """Appends a new task to the swarm manifest file."""
127 # See swarming/src/common/test_request_message.py TestObject constructor for
128 # the valid flags.
129 self._tasks.append(
130 {
131 'action': actions,
132 'decorate_output': self.verbose,
133 'test_name': task_name,
134 'time_out': time_out,
135 })
136
maruel@chromium.org0437a732013-08-27 16:05:52 +0000137 def zip_and_upload(self):
138 """Zips up all the files necessary to run a shard and uploads to Swarming
139 master.
140 """
141 assert not self._zip_file_hash
vadimsh@chromium.org6b706212013-08-28 15:03:46 +0000142
maruel@chromium.org0437a732013-08-27 16:05:52 +0000143 start_time = time.time()
vadimsh@chromium.org6b706212013-08-28 15:03:46 +0000144 zip_contents = self.bundle.zip_into_buffer()
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000145 self._zip_file_hash = self._algo(zip_contents).hexdigest()
maruel@chromium.org0437a732013-08-27 16:05:52 +0000146 print 'Zipping completed, time elapsed: %f' % (time.time() - start_time)
147
vadimsh@chromium.org6b706212013-08-28 15:03:46 +0000148 response = net.url_open(
maruel@chromium.org0437a732013-08-27 16:05:52 +0000149 self._data_server_has + '?token=%s' % self._token(),
vadimsh@chromium.org6b706212013-08-28 15:03:46 +0000150 data=binascii.unhexlify(self._zip_file_hash),
maruel@chromium.org0437a732013-08-27 16:05:52 +0000151 content_type='application/octet-stream')
152 if response is None:
153 print >> sys.stderr, (
154 'Unable to query server for zip file presence, aborting.')
155 return False
156
157 if response.read(1) == chr(1):
158 print 'Zip file already on server, no need to reupload.'
159 return True
160
161 print 'Zip file not on server, starting uploading.'
162
163 url = '%s%s?priority=0&token=%s' % (
164 self._data_server_storage, self._zip_file_hash, self._token())
vadimsh@chromium.org6b706212013-08-28 15:03:46 +0000165 response = net.url_open(
maruel@chromium.org0437a732013-08-27 16:05:52 +0000166 url, data=zip_contents, content_type='application/octet-stream')
167 if response is None:
168 print >> sys.stderr, 'Failed to upload the zip file: %s' % url
169 return False
170
171 return True
172
173 def to_json(self):
174 """Exports the current configuration into a swarm-readable manifest file.
175
176 This function doesn't mutate the object.
177 """
178 test_case = {
179 'test_case_name': self._test_name,
180 'data': [
maruel@chromium.orgb7e79a22013-09-13 01:24:56 +0000181 [self._data_server_retrieval + urllib.quote(self._zip_file_hash),
maruel@chromium.org0437a732013-08-27 16:05:52 +0000182 'swarm_data.zip'],
183 ],
184 'tests': self._tasks,
185 'env_vars': {},
186 'configurations': [
187 {
188 'min_instances': self._shards,
189 'config_name': self._target_platform,
190 'dimensions': {
191 'os': self._target_platform,
192 },
193 },
194 ],
195 'working_dir': self._working_dir,
196 'restart_on_failure': True,
197 'cleanup': 'root',
198 'priority': self.priority,
199 }
200
201 # These flags are googletest specific.
202 if self._test_filter and self._test_filter != '*':
203 test_case['env_vars']['GTEST_FILTER'] = self._test_filter
204 if self._shards > 1:
205 test_case['env_vars']['GTEST_SHARD_INDEX'] = '%(instance_index)s'
206 test_case['env_vars']['GTEST_TOTAL_SHARDS'] = '%(num_instances)s'
207
208 return json.dumps(test_case, separators=(',',':'))
209
210
211def now():
212 """Exists so it can be mocked easily."""
213 return time.time()
214
215
216def get_test_keys(swarm_base_url, test_name):
217 """Returns the Swarm test key for each shards of test_name."""
218 key_data = urllib.urlencode([('name', test_name)])
219 url = '%s/get_matching_test_cases?%s' % (swarm_base_url, key_data)
220
vadimsh@chromium.org043b76d2013-09-12 16:15:13 +0000221 for _ in net.retry_loop(max_attempts=net.URL_OPEN_MAX_ATTEMPTS):
222 result = net.url_read(url, retry_404=True)
223 if result is None:
maruel@chromium.org0437a732013-08-27 16:05:52 +0000224 raise Failure(
225 'Error: Unable to find any tests with the name, %s, on swarm server'
226 % test_name)
227
maruel@chromium.org0437a732013-08-27 16:05:52 +0000228 # TODO(maruel): Compare exact string.
229 if 'No matching' in result:
230 logging.warning('Unable to find any tests with the name, %s, on swarm '
231 'server' % test_name)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000232 continue
233 return json.loads(result)
234
235 raise Failure(
236 'Error: Unable to find any tests with the name, %s, on swarm server'
237 % test_name)
238
239
240def retrieve_results(base_url, test_key, timeout, should_stop):
241 """Retrieves results for a single test_key."""
242 assert isinstance(timeout, float)
243 params = [('r', test_key)]
244 result_url = '%s/get_result?%s' % (base_url, urllib.urlencode(params))
245 start = now()
246 while True:
247 if timeout and (now() - start) >= timeout:
248 logging.error('retrieve_results(%s) timed out', base_url)
249 return {}
250 # Do retries ourselves.
vadimsh@chromium.org043b76d2013-09-12 16:15:13 +0000251 response = net.url_read(result_url, retry_404=False, retry_50x=False)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000252 if response is None:
253 # Aggressively poll for results. Do not use retry_404 so
254 # should_stop is polled more often.
255 remaining = min(5, timeout - (now() - start)) if timeout else 5
256 if remaining > 0:
vadimsh@chromium.org043b76d2013-09-12 16:15:13 +0000257 net.sleep_before_retry(1, remaining)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000258 else:
259 try:
vadimsh@chromium.org043b76d2013-09-12 16:15:13 +0000260 data = json.loads(response) or {}
maruel@chromium.org0437a732013-08-27 16:05:52 +0000261 except (ValueError, TypeError):
262 logging.warning(
263 'Received corrupted data for test_key %s. Retrying.', test_key)
264 else:
265 if data['output']:
266 return data
267 if should_stop.get():
268 return {}
269
270
271def yield_results(swarm_base_url, test_keys, timeout, max_threads):
272 """Yields swarm test results from the swarm server as (index, result).
273
274 Duplicate shards are ignored, the first one to complete is returned.
275
276 max_threads is optional and is used to limit the number of parallel fetches
277 done. Since in general the number of test_keys is in the range <=10, it's not
278 worth normally to limit the number threads. Mostly used for testing purposes.
279 """
280 shards_remaining = range(len(test_keys))
281 number_threads = (
282 min(max_threads, len(test_keys)) if max_threads else len(test_keys))
283 should_stop = threading_utils.Bit()
284 results_remaining = len(test_keys)
285 with threading_utils.ThreadPool(number_threads, number_threads, 0) as pool:
286 try:
287 for test_key in test_keys:
288 pool.add_task(
289 0, retrieve_results, swarm_base_url, test_key, timeout, should_stop)
290 while shards_remaining and results_remaining:
291 result = pool.get_one_result()
292 results_remaining -= 1
293 if not result:
294 # Failed to retrieve one key.
295 logging.error('Failed to retrieve the results for a swarm key')
296 continue
297 shard_index = result['config_instance_index']
298 if shard_index in shards_remaining:
299 shards_remaining.remove(shard_index)
300 yield shard_index, result
301 else:
302 logging.warning('Ignoring duplicate shard index %d', shard_index)
303 # Pop the last entry, there's no such shard.
304 shards_remaining.pop()
305 finally:
306 # Done, kill the remaining threads.
307 should_stop.set()
308
309
310def chromium_setup(manifest):
311 """Sets up the commands to run.
312
313 Highly chromium specific.
314 """
vadimsh@chromium.org6b706212013-08-28 15:03:46 +0000315 # Add uncompressed zip here. It'll be compressed as part of the package sent
316 # to Swarming server.
317 run_test_name = 'run_isolated.zip'
318 manifest.bundle.add_buffer(run_test_name,
319 run_isolated.get_as_zip_package().zip_into_buffer(compress=False))
maruel@chromium.org0437a732013-08-27 16:05:52 +0000320
vadimsh@chromium.org6b706212013-08-28 15:03:46 +0000321 cleanup_script_name = 'swarm_cleanup.py'
322 manifest.bundle.add_file(os.path.join(TOOLS_PATH, cleanup_script_name),
323 cleanup_script_name)
324
maruel@chromium.org0437a732013-08-27 16:05:52 +0000325 run_cmd = [
326 'python', run_test_name,
327 '--hash', manifest.manifest_hash,
maruel@chromium.orgb7e79a22013-09-13 01:24:56 +0000328 '--isolate-server', manifest.isolate_server,
maruel@chromium.org0437a732013-08-27 16:05:52 +0000329 ]
330 if manifest.verbose or manifest.profile:
331 # Have it print the profiling section.
332 run_cmd.append('--verbose')
333 manifest.add_task('Run Test', run_cmd)
334
335 # Clean up
336 manifest.add_task('Clean Up', ['python', cleanup_script_name])
337
338
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000339def archive(isolated, isolate_server, os_slave, algo, verbose):
maruel@chromium.org0437a732013-08-27 16:05:52 +0000340 """Archives a .isolated and all the dependencies on the CAC."""
341 tempdir = None
342 try:
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000343 logging.info('archive(%s, %s)', isolated, isolate_server)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000344 cmd = [
345 sys.executable,
346 os.path.join(ROOT_DIR, 'isolate.py'),
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000347 'archive',
maruel@chromium.org0437a732013-08-27 16:05:52 +0000348 '--outdir', isolate_server,
349 '--isolated', isolated,
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000350 '-V', 'OS', PLATFORM_MAPPING_ISOLATE[os_slave],
maruel@chromium.org0437a732013-08-27 16:05:52 +0000351 ]
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000352 cmd.extend(['--verbose'] * verbose)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000353 logging.info(' '.join(cmd))
354 if subprocess.call(cmd, verbose):
355 return
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000356 return isolateserver.hash_file(isolated, algo)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000357 finally:
358 if tempdir:
359 shutil.rmtree(tempdir)
360
361
362def process_manifest(
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000363 file_hash_or_isolated, test_name, shards, test_filter, slave_os,
364 working_dir, isolate_server, swarming, verbose, profile, priority, algo):
maruel@chromium.org0437a732013-08-27 16:05:52 +0000365 """Process the manifest file and send off the swarm test request.
366
367 Optionally archives an .isolated file.
368 """
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000369 if file_hash_or_isolated.endswith('.isolated'):
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000370 file_hash = archive(
371 file_hash_or_isolated, isolate_server, slave_os, algo, verbose)
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000372 if not file_hash:
373 print >> sys.stderr, 'Archival failure %s' % file_hash_or_isolated
maruel@chromium.org0437a732013-08-27 16:05:52 +0000374 return 1
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000375 elif isolateserver.is_valid_hash(file_hash_or_isolated, algo):
376 file_hash = file_hash_or_isolated
maruel@chromium.org0437a732013-08-27 16:05:52 +0000377 else:
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000378 print >> sys.stderr, 'Invalid hash %s' % file_hash_or_isolated
maruel@chromium.org0437a732013-08-27 16:05:52 +0000379 return 1
380
381 try:
382 manifest = Manifest(
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000383 file_hash, test_name, shards, test_filter, slave_os,
384 working_dir, isolate_server, verbose, profile, priority, algo)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000385 except ValueError as e:
386 print >> sys.stderr, 'Unable to process %s: %s' % (test_name, e)
387 return 1
388
389 chromium_setup(manifest)
390
391 # Zip up relevant files.
392 print('Zipping up files...')
393 if not manifest.zip_and_upload():
394 return 1
395
396 # Send test requests off to swarm.
397 print('Sending test requests to swarm.')
398 print('Server: %s' % swarming)
399 print('Job name: %s' % test_name)
400 test_url = swarming + '/test'
401 manifest_text = manifest.to_json()
vadimsh@chromium.org6b706212013-08-28 15:03:46 +0000402 result = net.url_open(test_url, data={'request': manifest_text})
maruel@chromium.org0437a732013-08-27 16:05:52 +0000403 if not result:
404 print >> sys.stderr, 'Failed to send test for %s\n%s' % (
405 test_name, test_url)
406 return 1
407 try:
408 json.load(result)
409 except (ValueError, TypeError) as e:
410 print >> sys.stderr, 'Failed to send test for %s' % test_name
411 print >> sys.stderr, 'Manifest: %s' % manifest_text
412 print >> sys.stderr, str(e)
413 return 1
414 return 0
415
416
417def trigger(
418 slave_os,
419 tasks,
420 task_prefix,
421 working_dir,
422 isolate_server,
423 swarming,
424 verbose,
425 profile,
426 priority):
427 """Sends off the hash swarming test requests."""
428 highest_exit_code = 0
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000429 for (file_hash, test_name, shards, testfilter) in tasks:
maruel@chromium.org0437a732013-08-27 16:05:52 +0000430 # TODO(maruel): It should first create a request manifest object, then pass
431 # it to a function to zip, archive and trigger.
432 exit_code = process_manifest(
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000433 file_hash,
maruel@chromium.org0437a732013-08-27 16:05:52 +0000434 task_prefix + test_name,
435 int(shards),
436 testfilter,
437 slave_os,
438 working_dir,
439 isolate_server,
440 swarming,
441 verbose,
442 profile,
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000443 priority,
444 hashlib.sha1)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000445 highest_exit_code = max(highest_exit_code, exit_code)
446 return highest_exit_code
447
448
449def decorate_shard_output(result, shard_exit_code):
450 """Returns wrapped output for swarming task shard."""
451 tag = 'index %s (machine tag: %s, id: %s)' % (
452 result['config_instance_index'],
453 result['machine_id'],
454 result.get('machine_tag', 'unknown'))
455 return (
456 '\n'
457 '================================================================\n'
458 'Begin output from shard %s\n'
459 '================================================================\n'
460 '\n'
461 '%s'
462 '================================================================\n'
463 'End output from shard %s. Return %d\n'
464 '================================================================\n'
465 ) % (tag, result['output'] or NO_OUTPUT_FOUND, tag, shard_exit_code)
466
467
468def collect(url, test_name, timeout, decorate):
469 """Retrieves results of a Swarming job."""
470 test_keys = get_test_keys(url, test_name)
471 if not test_keys:
472 raise Failure('No test keys to get results with.')
473
maruel@chromium.org9c1c7b52013-08-28 19:04:36 +0000474 exit_code = None
maruel@chromium.org0437a732013-08-27 16:05:52 +0000475 for _index, output in yield_results(url, test_keys, timeout, None):
476 shard_exit_codes = (output['exit_codes'] or '1').split(',')
477 shard_exit_code = max(int(i) for i in shard_exit_codes)
478 if decorate:
479 print decorate_shard_output(output, shard_exit_code)
480 else:
481 print(
482 '%s/%s: %s' % (
483 output['machine_id'],
484 output['machine_tag'],
485 output['exit_codes']))
486 print(''.join(' %s\n' % l for l in output['output'].splitlines()))
maruel@chromium.org9c1c7b52013-08-28 19:04:36 +0000487 exit_code = exit_code or shard_exit_code
488 return exit_code if exit_code is not None else 1
maruel@chromium.org0437a732013-08-27 16:05:52 +0000489
490
491def add_trigger_options(parser):
492 """Adds all options to trigger a task on Swarming."""
493 parser.add_option(
494 '-I', '--isolate-server',
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000495 metavar='URL', default='',
496 help='Isolate server to use')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000497 parser.add_option(
498 '-w', '--working_dir', default='swarm_tests',
499 help='Working directory on the swarm slave side. default: %default.')
500 parser.add_option(
501 '-o', '--os', default=sys.platform,
502 help='Swarm OS image to request. Should be one of the valid sys.platform '
503 'values like darwin, linux2 or win32 default: %default.')
504 parser.add_option(
505 '-T', '--task-prefix', default='',
506 help='Prefix to give the swarm test request. default: %default')
507 parser.add_option(
508 '--profile', action='store_true',
509 default=bool(os.environ.get('ISOLATE_DEBUG')),
510 help='Have run_isolated.py print profiling info')
511 parser.add_option(
512 '--priority', type='int', default=100,
513 help='The lower value, the more important the task is')
514
515
516def process_trigger_options(parser, options):
517 options.isolate_server = options.isolate_server.rstrip('/')
518 if not options.isolate_server:
519 parser.error('--isolate-server is required.')
520 if options.os in ('', 'None'):
521 # Use the current OS.
522 options.os = sys.platform
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000523 if not options.os in PLATFORM_MAPPING_SWARMING:
maruel@chromium.org0437a732013-08-27 16:05:52 +0000524 parser.error('Invalid --os option.')
525
526
527def add_collect_options(parser):
528 parser.add_option(
529 '-t', '--timeout',
530 type='float',
531 default=DEFAULT_SHARD_WAIT_TIME,
532 help='Timeout to wait for result, set to 0 for no timeout; default: '
533 '%default s')
534 parser.add_option('--decorate', action='store_true', help='Decorate output')
535
536
537@subcommand.usage('test_name')
538def CMDcollect(parser, args):
539 """Retrieves results of a Swarming job.
540
541 The result can be in multiple part if the execution was sharded. It can
542 potentially have retries.
543 """
544 add_collect_options(parser)
545 (options, args) = parser.parse_args(args)
546 if not args:
547 parser.error('Must specify one test name.')
548 elif len(args) > 1:
549 parser.error('Must specify only one test name.')
550
551 try:
552 return collect(options.swarming, args[0], options.timeout, options.decorate)
553 except Failure as e:
554 parser.error(e.args[0])
555
556
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000557@subcommand.usage('[hash|isolated ...]')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000558def CMDrun(parser, args):
559 """Triggers a job and wait for the results.
560
561 Basically, does everything to run command(s) remotely.
562 """
563 add_trigger_options(parser)
564 add_collect_options(parser)
565 options, args = parser.parse_args(args)
566
567 if not args:
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000568 parser.error('Must pass at least one .isolated file or its hash (sha1).')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000569 process_trigger_options(parser, options)
570
571 success = []
572 for arg in args:
573 logging.info('Triggering %s', arg)
574 try:
575 result = trigger(
576 options.os,
577 [(arg, os.path.basename(arg), '1', '')],
578 options.task_prefix,
579 options.working_dir,
580 options.isolate_server,
581 options.swarming,
582 options.verbose,
583 options.profile,
584 options.priority)
585 except Failure as e:
586 result = e.args[0]
587 if result:
588 print >> sys.stderr, 'Failed to trigger %s: %s' % (arg, result)
589 else:
590 success.append(os.path.basename(arg))
591
592 if not success:
593 print >> sys.stderr, 'Failed to trigger any job.'
594 return result
595
596 code = 0
597 for arg in success:
598 logging.info('Collecting %s', arg)
599 try:
600 new_code = collect(
601 options.swarming,
602 options.task_prefix + arg,
603 options.timeout,
604 options.decorate)
605 code = max(code, new_code)
606 except Failure as e:
607 code = max(code, 1)
608 print >> sys.stderr, e.args[0]
609 return code
610
611
612def CMDtrigger(parser, args):
613 """Triggers Swarm request(s).
614
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000615 Accepts one or multiple --task requests, with either the hash (sha1) of a
616 .isolated file already uploaded or the path to an .isolated file to archive,
617 packages it if needed and sends a Swarm manifest file to the Swarm server.
maruel@chromium.org0437a732013-08-27 16:05:52 +0000618 """
619 add_trigger_options(parser)
620 parser.add_option(
621 '--task', nargs=4, action='append', default=[], dest='tasks',
622 help='Task to trigger. The format is '
623 '(hash|isolated, test_name, shards, test_filter). This may be '
624 'used multiple times to send multiple hashes jobs. If an isolated '
625 'file is specified instead of an hash, it is first archived.')
626 (options, args) = parser.parse_args(args)
627
628 if args:
629 parser.error('Unknown args: %s' % args)
630 process_trigger_options(parser, options)
631 if not options.tasks:
632 parser.error('At least one --task is required.')
633
634 try:
635 return trigger(
636 options.os,
637 options.tasks,
638 options.task_prefix,
639 options.working_dir,
640 options.isolate_server,
641 options.swarming,
642 options.verbose,
643 options.profile,
644 options.priority)
645 except Failure as e:
646 parser.error(e.args[0])
647
648
649class OptionParserSwarming(tools.OptionParserWithLogging):
650 def __init__(self, **kwargs):
651 tools.OptionParserWithLogging.__init__(
652 self, prog='swarming.py', **kwargs)
653 self.add_option(
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000654 '-S', '--swarming',
655 metavar='URL', default='',
656 help='Swarming server to use')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000657
658 def parse_args(self, *args, **kwargs):
659 options, args = tools.OptionParserWithLogging.parse_args(
660 self, *args, **kwargs)
661 options.swarming = options.swarming.rstrip('/')
662 if not options.swarming:
663 self.error('--swarming is required.')
664 return options, args
665
666
667def main(args):
668 dispatcher = subcommand.CommandDispatcher(__name__)
669 try:
670 return dispatcher.execute(OptionParserSwarming(version=__version__), args)
maruel@chromium.org9958e4a2013-09-17 00:01:48 +0000671 except Failure as e:
maruel@chromium.org0437a732013-08-27 16:05:52 +0000672 sys.stderr.write('\nError: ')
673 sys.stderr.write(str(e))
674 sys.stderr.write('\n')
675 return 1
676
677
678if __name__ == '__main__':
679 fix_encoding.fix_encoding()
680 tools.disable_buffering()
681 colorama.init()
682 sys.exit(main(sys.argv[1:]))