blob: cc30dc50c7a941a50bf5199746906fa30b1a8392 [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
10import hashlib
11import json
12import logging
13import os
maruel@chromium.org0437a732013-08-27 16:05:52 +000014import shutil
maruel@chromium.org0437a732013-08-27 16:05:52 +000015import subprocess
16import sys
17import time
18import urllib
maruel@chromium.org0437a732013-08-27 16:05:52 +000019
20from third_party import colorama
21from third_party.depot_tools import fix_encoding
22from third_party.depot_tools import subcommand
vadimsh@chromium.org6b706212013-08-28 15:03:46 +000023
24from utils import net
maruel@chromium.org0437a732013-08-27 16:05:52 +000025from utils import threading_utils
vadimsh@chromium.org6b706212013-08-28 15:03:46 +000026from utils import tools
27from utils import zip_package
maruel@chromium.org0437a732013-08-27 16:05:52 +000028
maruel@chromium.org7b844a62013-09-17 13:04:59 +000029import isolateserver
maruel@chromium.org0437a732013-08-27 16:05:52 +000030import run_isolated
31
32
33ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
34TOOLS_PATH = os.path.join(ROOT_DIR, 'tools')
35
36
maruel@chromium.org0437a732013-08-27 16:05:52 +000037# The default time to wait for a shard to finish running.
csharp@chromium.org24758492013-08-28 19:10:54 +000038DEFAULT_SHARD_WAIT_TIME = 80 * 60.
maruel@chromium.org0437a732013-08-27 16:05:52 +000039
40
41NO_OUTPUT_FOUND = (
42 'No output produced by the test, it may have failed to run.\n'
43 '\n')
44
45
maruel@chromium.orge9403ab2013-09-20 18:03:49 +000046# TODO(maruel): cygwin != Windows. If a swarm_bot is running in cygwin, it's
47# different from running in native python.
48PLATFORM_MAPPING_SWARMING = {
maruel@chromium.org0437a732013-08-27 16:05:52 +000049 'cygwin': 'Windows',
50 'darwin': 'Mac',
51 'linux2': 'Linux',
52 'win32': 'Windows',
53}
54
maruel@chromium.orge9403ab2013-09-20 18:03:49 +000055PLATFORM_MAPPING_ISOLATE = {
56 'linux2': 'linux',
57 'darwin': 'mac',
58 'win32': 'win',
59}
60
maruel@chromium.org0437a732013-08-27 16:05:52 +000061
62class Failure(Exception):
63 """Generic failure."""
64 pass
65
66
67class Manifest(object):
68 """Represents a Swarming task manifest.
69
70 Also includes code to zip code and upload itself.
71 """
72 def __init__(
maruel@chromium.org814d23f2013-10-01 19:08:00 +000073 self, isolated_hash, test_name, shards, test_filter, slave_os,
maruel@chromium.org7b844a62013-09-17 13:04:59 +000074 working_dir, isolate_server, verbose, profile, priority, algo):
maruel@chromium.org0437a732013-08-27 16:05:52 +000075 """Populates a manifest object.
76 Args:
maruel@chromium.org814d23f2013-10-01 19:08:00 +000077 isolated_hash - The manifest's sha-1 that the slave is going to fetch.
maruel@chromium.org0437a732013-08-27 16:05:52 +000078 test_name - The name to give the test request.
79 shards - The number of swarm shards to request.
80 test_filter - The gtest filter to apply when running the test.
81 slave_os - OS to run on.
82 working_dir - Relative working directory to start the script.
83 isolate_server - isolate server url.
84 verbose - if True, have the slave print more details.
85 profile - if True, have the slave print more timing data.
maruel@chromium.org7b844a62013-09-17 13:04:59 +000086 priority - int between 0 and 1000, lower the higher priority.
87 algo - hashing algorithm used.
maruel@chromium.org0437a732013-08-27 16:05:52 +000088 """
maruel@chromium.org814d23f2013-10-01 19:08:00 +000089 self.isolated_hash = isolated_hash
vadimsh@chromium.org6b706212013-08-28 15:03:46 +000090 self.bundle = zip_package.ZipPackage(ROOT_DIR)
91
maruel@chromium.org0437a732013-08-27 16:05:52 +000092 self._test_name = test_name
93 self._shards = shards
94 self._test_filter = test_filter
maruel@chromium.org814d23f2013-10-01 19:08:00 +000095 self._target_platform = slave_os
maruel@chromium.org0437a732013-08-27 16:05:52 +000096 self._working_dir = working_dir
97
maruel@chromium.orgb7e79a22013-09-13 01:24:56 +000098 self.isolate_server = isolate_server
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +000099 self.storage = isolateserver.get_storage(isolate_server, 'default')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000100 self.verbose = bool(verbose)
101 self.profile = bool(profile)
102 self.priority = priority
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000103 self._algo = algo
maruel@chromium.org0437a732013-08-27 16:05:52 +0000104
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000105 self._isolate_item = None
maruel@chromium.org0437a732013-08-27 16:05:52 +0000106 self._tasks = []
maruel@chromium.org0437a732013-08-27 16:05:52 +0000107
108 def add_task(self, task_name, actions, time_out=600):
109 """Appends a new task to the swarm manifest file."""
110 # See swarming/src/common/test_request_message.py TestObject constructor for
111 # the valid flags.
112 self._tasks.append(
113 {
114 'action': actions,
115 'decorate_output': self.verbose,
116 'test_name': task_name,
117 'time_out': time_out,
118 })
119
maruel@chromium.org0437a732013-08-27 16:05:52 +0000120 def zip_and_upload(self):
121 """Zips up all the files necessary to run a shard and uploads to Swarming
122 master.
123 """
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000124 assert not self._isolate_item
vadimsh@chromium.org6b706212013-08-28 15:03:46 +0000125
maruel@chromium.org0437a732013-08-27 16:05:52 +0000126 start_time = time.time()
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000127 self._isolate_item = isolateserver.BufferItem(
128 self.bundle.zip_into_buffer(), self._algo, is_isolated=True)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000129 print 'Zipping completed, time elapsed: %f' % (time.time() - start_time)
130
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000131 try:
132 start_time = time.time()
133 uploaded = self.storage.upload_items([self._isolate_item])
134 elapsed = time.time() - start_time
135 except (IOError, OSError) as exc:
136 print >> sys.stderr, 'Failed to upload the zip file: %s' % exc
maruel@chromium.org0437a732013-08-27 16:05:52 +0000137 return False
138
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000139 if self._isolate_item in uploaded:
140 print 'Upload complete, time elapsed: %f' % elapsed
141 else:
142 print 'Zip file already on server, time elapsed: %f' % elapsed
maruel@chromium.org0437a732013-08-27 16:05:52 +0000143
144 return True
145
146 def to_json(self):
147 """Exports the current configuration into a swarm-readable manifest file.
148
149 This function doesn't mutate the object.
150 """
151 test_case = {
152 'test_case_name': self._test_name,
maruel@chromium.org814d23f2013-10-01 19:08:00 +0000153 'data': [],
maruel@chromium.org0437a732013-08-27 16:05:52 +0000154 'tests': self._tasks,
csharp@chromium.orgc788a692013-10-28 14:40:29 +0000155 # TODO: Let the encoding get set from the command line.
156 'encoding': 'UTF-8',
maruel@chromium.org0437a732013-08-27 16:05:52 +0000157 'env_vars': {},
158 'configurations': [
159 {
160 'min_instances': self._shards,
161 'config_name': self._target_platform,
csharp@chromium.org141ef862013-10-24 16:45:45 +0000162 'priority': self.priority,
maruel@chromium.org0437a732013-08-27 16:05:52 +0000163 'dimensions': {
164 'os': self._target_platform,
165 },
166 },
167 ],
168 'working_dir': self._working_dir,
169 'restart_on_failure': True,
170 'cleanup': 'root',
maruel@chromium.org0437a732013-08-27 16:05:52 +0000171 }
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000172 if self._isolate_item:
maruel@chromium.org814d23f2013-10-01 19:08:00 +0000173 test_case['data'].append(
174 [
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000175 self.storage.get_fetch_url(self._isolate_item.digest),
maruel@chromium.org814d23f2013-10-01 19:08:00 +0000176 'swarm_data.zip',
177 ])
maruel@chromium.org0437a732013-08-27 16:05:52 +0000178 # These flags are googletest specific.
179 if self._test_filter and self._test_filter != '*':
180 test_case['env_vars']['GTEST_FILTER'] = self._test_filter
181 if self._shards > 1:
182 test_case['env_vars']['GTEST_SHARD_INDEX'] = '%(instance_index)s'
183 test_case['env_vars']['GTEST_TOTAL_SHARDS'] = '%(num_instances)s'
184
185 return json.dumps(test_case, separators=(',',':'))
186
187
188def now():
189 """Exists so it can be mocked easily."""
190 return time.time()
191
192
193def get_test_keys(swarm_base_url, test_name):
194 """Returns the Swarm test key for each shards of test_name."""
195 key_data = urllib.urlencode([('name', test_name)])
196 url = '%s/get_matching_test_cases?%s' % (swarm_base_url, key_data)
197
vadimsh@chromium.org043b76d2013-09-12 16:15:13 +0000198 for _ in net.retry_loop(max_attempts=net.URL_OPEN_MAX_ATTEMPTS):
199 result = net.url_read(url, retry_404=True)
200 if result is None:
maruel@chromium.org0437a732013-08-27 16:05:52 +0000201 raise Failure(
202 'Error: Unable to find any tests with the name, %s, on swarm server'
203 % test_name)
204
maruel@chromium.org0437a732013-08-27 16:05:52 +0000205 # TODO(maruel): Compare exact string.
206 if 'No matching' in result:
207 logging.warning('Unable to find any tests with the name, %s, on swarm '
208 'server' % test_name)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000209 continue
210 return json.loads(result)
211
212 raise Failure(
213 'Error: Unable to find any tests with the name, %s, on swarm server'
214 % test_name)
215
216
217def retrieve_results(base_url, test_key, timeout, should_stop):
218 """Retrieves results for a single test_key."""
maruel@chromium.org814d23f2013-10-01 19:08:00 +0000219 assert isinstance(timeout, float), timeout
maruel@chromium.org0437a732013-08-27 16:05:52 +0000220 params = [('r', test_key)]
221 result_url = '%s/get_result?%s' % (base_url, urllib.urlencode(params))
222 start = now()
223 while True:
224 if timeout and (now() - start) >= timeout:
225 logging.error('retrieve_results(%s) timed out', base_url)
226 return {}
227 # Do retries ourselves.
vadimsh@chromium.org043b76d2013-09-12 16:15:13 +0000228 response = net.url_read(result_url, retry_404=False, retry_50x=False)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000229 if response is None:
230 # Aggressively poll for results. Do not use retry_404 so
231 # should_stop is polled more often.
232 remaining = min(5, timeout - (now() - start)) if timeout else 5
233 if remaining > 0:
maruel@chromium.org814d23f2013-10-01 19:08:00 +0000234 if should_stop.get():
235 return {}
vadimsh@chromium.org043b76d2013-09-12 16:15:13 +0000236 net.sleep_before_retry(1, remaining)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000237 else:
238 try:
vadimsh@chromium.org043b76d2013-09-12 16:15:13 +0000239 data = json.loads(response) or {}
maruel@chromium.org0437a732013-08-27 16:05:52 +0000240 except (ValueError, TypeError):
241 logging.warning(
242 'Received corrupted data for test_key %s. Retrying.', test_key)
243 else:
244 if data['output']:
245 return data
246 if should_stop.get():
247 return {}
248
249
250def yield_results(swarm_base_url, test_keys, timeout, max_threads):
251 """Yields swarm test results from the swarm server as (index, result).
252
253 Duplicate shards are ignored, the first one to complete is returned.
254
255 max_threads is optional and is used to limit the number of parallel fetches
256 done. Since in general the number of test_keys is in the range <=10, it's not
257 worth normally to limit the number threads. Mostly used for testing purposes.
258 """
259 shards_remaining = range(len(test_keys))
260 number_threads = (
261 min(max_threads, len(test_keys)) if max_threads else len(test_keys))
262 should_stop = threading_utils.Bit()
263 results_remaining = len(test_keys)
264 with threading_utils.ThreadPool(number_threads, number_threads, 0) as pool:
265 try:
266 for test_key in test_keys:
267 pool.add_task(
268 0, retrieve_results, swarm_base_url, test_key, timeout, should_stop)
269 while shards_remaining and results_remaining:
270 result = pool.get_one_result()
271 results_remaining -= 1
272 if not result:
273 # Failed to retrieve one key.
274 logging.error('Failed to retrieve the results for a swarm key')
275 continue
276 shard_index = result['config_instance_index']
277 if shard_index in shards_remaining:
278 shards_remaining.remove(shard_index)
279 yield shard_index, result
280 else:
281 logging.warning('Ignoring duplicate shard index %d', shard_index)
282 # Pop the last entry, there's no such shard.
283 shards_remaining.pop()
284 finally:
285 # Done, kill the remaining threads.
286 should_stop.set()
287
288
289def chromium_setup(manifest):
290 """Sets up the commands to run.
291
292 Highly chromium specific.
293 """
vadimsh@chromium.org6b706212013-08-28 15:03:46 +0000294 # Add uncompressed zip here. It'll be compressed as part of the package sent
295 # to Swarming server.
296 run_test_name = 'run_isolated.zip'
297 manifest.bundle.add_buffer(run_test_name,
298 run_isolated.get_as_zip_package().zip_into_buffer(compress=False))
maruel@chromium.org0437a732013-08-27 16:05:52 +0000299
vadimsh@chromium.org6b706212013-08-28 15:03:46 +0000300 cleanup_script_name = 'swarm_cleanup.py'
301 manifest.bundle.add_file(os.path.join(TOOLS_PATH, cleanup_script_name),
302 cleanup_script_name)
303
maruel@chromium.org0437a732013-08-27 16:05:52 +0000304 run_cmd = [
305 'python', run_test_name,
maruel@chromium.org814d23f2013-10-01 19:08:00 +0000306 '--hash', manifest.isolated_hash,
maruel@chromium.orgb7e79a22013-09-13 01:24:56 +0000307 '--isolate-server', manifest.isolate_server,
maruel@chromium.org0437a732013-08-27 16:05:52 +0000308 ]
309 if manifest.verbose or manifest.profile:
310 # Have it print the profiling section.
311 run_cmd.append('--verbose')
312 manifest.add_task('Run Test', run_cmd)
313
314 # Clean up
315 manifest.add_task('Clean Up', ['python', cleanup_script_name])
316
317
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000318def archive(isolated, isolate_server, os_slave, algo, verbose):
maruel@chromium.org0437a732013-08-27 16:05:52 +0000319 """Archives a .isolated and all the dependencies on the CAC."""
320 tempdir = None
321 try:
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000322 logging.info('archive(%s, %s)', isolated, isolate_server)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000323 cmd = [
324 sys.executable,
325 os.path.join(ROOT_DIR, 'isolate.py'),
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000326 'archive',
maruel@chromium.org0437a732013-08-27 16:05:52 +0000327 '--outdir', isolate_server,
328 '--isolated', isolated,
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000329 '-V', 'OS', PLATFORM_MAPPING_ISOLATE[os_slave],
maruel@chromium.org0437a732013-08-27 16:05:52 +0000330 ]
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000331 cmd.extend(['--verbose'] * verbose)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000332 logging.info(' '.join(cmd))
333 if subprocess.call(cmd, verbose):
334 return
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000335 return isolateserver.hash_file(isolated, algo)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000336 finally:
337 if tempdir:
338 shutil.rmtree(tempdir)
339
340
341def process_manifest(
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000342 file_hash_or_isolated, test_name, shards, test_filter, slave_os,
343 working_dir, isolate_server, swarming, verbose, profile, priority, algo):
maruel@chromium.org0437a732013-08-27 16:05:52 +0000344 """Process the manifest file and send off the swarm test request.
345
346 Optionally archives an .isolated file.
347 """
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000348 if file_hash_or_isolated.endswith('.isolated'):
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000349 file_hash = archive(
350 file_hash_or_isolated, isolate_server, slave_os, algo, verbose)
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000351 if not file_hash:
352 print >> sys.stderr, 'Archival failure %s' % file_hash_or_isolated
maruel@chromium.org0437a732013-08-27 16:05:52 +0000353 return 1
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000354 elif isolateserver.is_valid_hash(file_hash_or_isolated, algo):
355 file_hash = file_hash_or_isolated
maruel@chromium.org0437a732013-08-27 16:05:52 +0000356 else:
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000357 print >> sys.stderr, 'Invalid hash %s' % file_hash_or_isolated
maruel@chromium.org0437a732013-08-27 16:05:52 +0000358 return 1
359
360 try:
361 manifest = Manifest(
maruel@chromium.org814d23f2013-10-01 19:08:00 +0000362 file_hash,
363 test_name,
364 shards,
365 test_filter,
366 PLATFORM_MAPPING_SWARMING[slave_os],
367 working_dir,
368 isolate_server,
369 verbose,
370 profile,
371 priority,
372 algo)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000373 except ValueError as e:
374 print >> sys.stderr, 'Unable to process %s: %s' % (test_name, e)
375 return 1
376
377 chromium_setup(manifest)
378
379 # Zip up relevant files.
380 print('Zipping up files...')
381 if not manifest.zip_and_upload():
382 return 1
383
384 # Send test requests off to swarm.
385 print('Sending test requests to swarm.')
386 print('Server: %s' % swarming)
387 print('Job name: %s' % test_name)
388 test_url = swarming + '/test'
389 manifest_text = manifest.to_json()
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000390 result = net.url_read(test_url, data={'request': manifest_text})
maruel@chromium.org0437a732013-08-27 16:05:52 +0000391 if not result:
392 print >> sys.stderr, 'Failed to send test for %s\n%s' % (
393 test_name, test_url)
394 return 1
395 try:
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000396 json.loads(result)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000397 except (ValueError, TypeError) as e:
398 print >> sys.stderr, 'Failed to send test for %s' % test_name
399 print >> sys.stderr, 'Manifest: %s' % manifest_text
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000400 print >> sys.stderr, 'Bad response: %s' % result
maruel@chromium.org0437a732013-08-27 16:05:52 +0000401 print >> sys.stderr, str(e)
402 return 1
403 return 0
404
405
406def trigger(
407 slave_os,
408 tasks,
409 task_prefix,
410 working_dir,
411 isolate_server,
412 swarming,
413 verbose,
414 profile,
415 priority):
416 """Sends off the hash swarming test requests."""
417 highest_exit_code = 0
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000418 for (file_hash, test_name, shards, testfilter) in tasks:
maruel@chromium.org0437a732013-08-27 16:05:52 +0000419 # TODO(maruel): It should first create a request manifest object, then pass
420 # it to a function to zip, archive and trigger.
421 exit_code = process_manifest(
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000422 file_hash,
maruel@chromium.org0437a732013-08-27 16:05:52 +0000423 task_prefix + test_name,
424 int(shards),
425 testfilter,
426 slave_os,
427 working_dir,
428 isolate_server,
429 swarming,
430 verbose,
431 profile,
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000432 priority,
433 hashlib.sha1)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000434 highest_exit_code = max(highest_exit_code, exit_code)
435 return highest_exit_code
436
437
438def decorate_shard_output(result, shard_exit_code):
439 """Returns wrapped output for swarming task shard."""
440 tag = 'index %s (machine tag: %s, id: %s)' % (
441 result['config_instance_index'],
442 result['machine_id'],
443 result.get('machine_tag', 'unknown'))
444 return (
445 '\n'
446 '================================================================\n'
447 'Begin output from shard %s\n'
448 '================================================================\n'
449 '\n'
450 '%s'
451 '================================================================\n'
452 'End output from shard %s. Return %d\n'
453 '================================================================\n'
454 ) % (tag, result['output'] or NO_OUTPUT_FOUND, tag, shard_exit_code)
455
456
457def collect(url, test_name, timeout, decorate):
458 """Retrieves results of a Swarming job."""
459 test_keys = get_test_keys(url, test_name)
460 if not test_keys:
461 raise Failure('No test keys to get results with.')
462
maruel@chromium.org9c1c7b52013-08-28 19:04:36 +0000463 exit_code = None
maruel@chromium.org0437a732013-08-27 16:05:52 +0000464 for _index, output in yield_results(url, test_keys, timeout, None):
465 shard_exit_codes = (output['exit_codes'] or '1').split(',')
466 shard_exit_code = max(int(i) for i in shard_exit_codes)
467 if decorate:
468 print decorate_shard_output(output, shard_exit_code)
469 else:
470 print(
471 '%s/%s: %s' % (
472 output['machine_id'],
473 output['machine_tag'],
474 output['exit_codes']))
475 print(''.join(' %s\n' % l for l in output['output'].splitlines()))
maruel@chromium.org9c1c7b52013-08-28 19:04:36 +0000476 exit_code = exit_code or shard_exit_code
477 return exit_code if exit_code is not None else 1
maruel@chromium.org0437a732013-08-27 16:05:52 +0000478
479
480def add_trigger_options(parser):
481 """Adds all options to trigger a task on Swarming."""
482 parser.add_option(
483 '-I', '--isolate-server',
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000484 metavar='URL', default='',
485 help='Isolate server to use')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000486 parser.add_option(
487 '-w', '--working_dir', default='swarm_tests',
488 help='Working directory on the swarm slave side. default: %default.')
489 parser.add_option(
490 '-o', '--os', default=sys.platform,
491 help='Swarm OS image to request. Should be one of the valid sys.platform '
492 'values like darwin, linux2 or win32 default: %default.')
493 parser.add_option(
494 '-T', '--task-prefix', default='',
495 help='Prefix to give the swarm test request. default: %default')
496 parser.add_option(
497 '--profile', action='store_true',
498 default=bool(os.environ.get('ISOLATE_DEBUG')),
499 help='Have run_isolated.py print profiling info')
500 parser.add_option(
501 '--priority', type='int', default=100,
502 help='The lower value, the more important the task is')
503
504
505def process_trigger_options(parser, options):
506 options.isolate_server = options.isolate_server.rstrip('/')
507 if not options.isolate_server:
508 parser.error('--isolate-server is required.')
509 if options.os in ('', 'None'):
510 # Use the current OS.
511 options.os = sys.platform
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000512 if not options.os in PLATFORM_MAPPING_SWARMING:
maruel@chromium.org0437a732013-08-27 16:05:52 +0000513 parser.error('Invalid --os option.')
514
515
516def add_collect_options(parser):
517 parser.add_option(
518 '-t', '--timeout',
519 type='float',
520 default=DEFAULT_SHARD_WAIT_TIME,
521 help='Timeout to wait for result, set to 0 for no timeout; default: '
522 '%default s')
523 parser.add_option('--decorate', action='store_true', help='Decorate output')
524
525
526@subcommand.usage('test_name')
527def CMDcollect(parser, args):
528 """Retrieves results of a Swarming job.
529
530 The result can be in multiple part if the execution was sharded. It can
531 potentially have retries.
532 """
533 add_collect_options(parser)
534 (options, args) = parser.parse_args(args)
535 if not args:
536 parser.error('Must specify one test name.')
537 elif len(args) > 1:
538 parser.error('Must specify only one test name.')
539
540 try:
541 return collect(options.swarming, args[0], options.timeout, options.decorate)
542 except Failure as e:
543 parser.error(e.args[0])
544
545
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000546@subcommand.usage('[hash|isolated ...]')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000547def CMDrun(parser, args):
548 """Triggers a job and wait for the results.
549
550 Basically, does everything to run command(s) remotely.
551 """
552 add_trigger_options(parser)
553 add_collect_options(parser)
554 options, args = parser.parse_args(args)
555
556 if not args:
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000557 parser.error('Must pass at least one .isolated file or its hash (sha1).')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000558 process_trigger_options(parser, options)
559
560 success = []
561 for arg in args:
562 logging.info('Triggering %s', arg)
563 try:
564 result = trigger(
565 options.os,
566 [(arg, os.path.basename(arg), '1', '')],
567 options.task_prefix,
568 options.working_dir,
569 options.isolate_server,
570 options.swarming,
571 options.verbose,
572 options.profile,
573 options.priority)
574 except Failure as e:
575 result = e.args[0]
576 if result:
577 print >> sys.stderr, 'Failed to trigger %s: %s' % (arg, result)
578 else:
579 success.append(os.path.basename(arg))
580
581 if not success:
582 print >> sys.stderr, 'Failed to trigger any job.'
583 return result
584
585 code = 0
586 for arg in success:
587 logging.info('Collecting %s', arg)
588 try:
589 new_code = collect(
590 options.swarming,
591 options.task_prefix + arg,
592 options.timeout,
593 options.decorate)
594 code = max(code, new_code)
595 except Failure as e:
596 code = max(code, 1)
597 print >> sys.stderr, e.args[0]
598 return code
599
600
601def CMDtrigger(parser, args):
602 """Triggers Swarm request(s).
603
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000604 Accepts one or multiple --task requests, with either the hash (sha1) of a
605 .isolated file already uploaded or the path to an .isolated file to archive,
606 packages it if needed and sends a Swarm manifest file to the Swarm server.
maruel@chromium.org0437a732013-08-27 16:05:52 +0000607 """
608 add_trigger_options(parser)
609 parser.add_option(
610 '--task', nargs=4, action='append', default=[], dest='tasks',
611 help='Task to trigger. The format is '
612 '(hash|isolated, test_name, shards, test_filter). This may be '
613 'used multiple times to send multiple hashes jobs. If an isolated '
614 'file is specified instead of an hash, it is first archived.')
615 (options, args) = parser.parse_args(args)
616
617 if args:
618 parser.error('Unknown args: %s' % args)
619 process_trigger_options(parser, options)
620 if not options.tasks:
621 parser.error('At least one --task is required.')
622
623 try:
624 return trigger(
625 options.os,
626 options.tasks,
627 options.task_prefix,
628 options.working_dir,
629 options.isolate_server,
630 options.swarming,
631 options.verbose,
632 options.profile,
633 options.priority)
634 except Failure as e:
635 parser.error(e.args[0])
636
637
638class OptionParserSwarming(tools.OptionParserWithLogging):
639 def __init__(self, **kwargs):
640 tools.OptionParserWithLogging.__init__(
641 self, prog='swarming.py', **kwargs)
642 self.add_option(
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000643 '-S', '--swarming',
644 metavar='URL', default='',
645 help='Swarming server to use')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000646
647 def parse_args(self, *args, **kwargs):
648 options, args = tools.OptionParserWithLogging.parse_args(
649 self, *args, **kwargs)
650 options.swarming = options.swarming.rstrip('/')
651 if not options.swarming:
652 self.error('--swarming is required.')
653 return options, args
654
655
656def main(args):
657 dispatcher = subcommand.CommandDispatcher(__name__)
658 try:
659 return dispatcher.execute(OptionParserSwarming(version=__version__), args)
maruel@chromium.org9958e4a2013-09-17 00:01:48 +0000660 except Failure as e:
maruel@chromium.org0437a732013-08-27 16:05:52 +0000661 sys.stderr.write('\nError: ')
662 sys.stderr.write(str(e))
663 sys.stderr.write('\n')
664 return 1
665
666
667if __name__ == '__main__':
668 fix_encoding.fix_encoding()
669 tools.disable_buffering()
670 colorama.init()
671 sys.exit(main(sys.argv[1:]))