blob: 90b49c7a1043412078d434af7c0f8acf9c7438a0 [file] [log] [blame]
maruel@chromium.org0437a732013-08-27 16:05:52 +00001#!/usr/bin/env python
Marc-Antoine Ruel8add1242013-11-05 17:28:27 -05002# Copyright 2013 The Swarming Authors. All rights reserved.
3# Use of this source code is governed by the Apache v2.0 license that can be
maruel@chromium.org0437a732013-08-27 16:05:52 +00004# 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__(
Marc-Antoine Ruela7049872013-11-05 19:28:35 -050073 self, isolate_server, isolated_hash, test_name, shards, test_filter,
74 slave_os, working_dir, verbose, profile, priority, algo):
maruel@chromium.org0437a732013-08-27 16:05:52 +000075 """Populates a manifest object.
76 Args:
Marc-Antoine Ruela7049872013-11-05 19:28:35 -050077 isolate_server - isolate server url.
maruel@chromium.org814d23f2013-10-01 19:08:00 +000078 isolated_hash - The manifest's sha-1 that the slave is going to fetch.
maruel@chromium.org0437a732013-08-27 16:05:52 +000079 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.
maruel@chromium.org0437a732013-08-27 16:05:52 +000084 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 """
Marc-Antoine Ruela7049872013-11-05 19:28:35 -050089 self.isolate_server = isolate_server
90 self.storage = isolateserver.get_storage(isolate_server, 'default')
91
maruel@chromium.org814d23f2013-10-01 19:08:00 +000092 self.isolated_hash = isolated_hash
vadimsh@chromium.org6b706212013-08-28 15:03:46 +000093 self.bundle = zip_package.ZipPackage(ROOT_DIR)
94
maruel@chromium.org0437a732013-08-27 16:05:52 +000095 self._test_name = test_name
96 self._shards = shards
97 self._test_filter = test_filter
maruel@chromium.org814d23f2013-10-01 19:08:00 +000098 self._target_platform = slave_os
maruel@chromium.org0437a732013-08-27 16:05:52 +000099 self._working_dir = working_dir
100
maruel@chromium.org0437a732013-08-27 16:05:52 +0000101 self.verbose = bool(verbose)
102 self.profile = bool(profile)
103 self.priority = priority
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000104 self._algo = algo
maruel@chromium.org0437a732013-08-27 16:05:52 +0000105
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000106 self._isolate_item = None
maruel@chromium.org0437a732013-08-27 16:05:52 +0000107 self._tasks = []
maruel@chromium.org0437a732013-08-27 16:05:52 +0000108
109 def add_task(self, task_name, actions, time_out=600):
110 """Appends a new task to the swarm manifest file."""
111 # See swarming/src/common/test_request_message.py TestObject constructor for
112 # the valid flags.
113 self._tasks.append(
114 {
115 'action': actions,
116 'decorate_output': self.verbose,
117 'test_name': task_name,
118 'time_out': time_out,
119 })
120
maruel@chromium.org0437a732013-08-27 16:05:52 +0000121 def zip_and_upload(self):
122 """Zips up all the files necessary to run a shard and uploads to Swarming
123 master.
124 """
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000125 assert not self._isolate_item
vadimsh@chromium.org6b706212013-08-28 15:03:46 +0000126
maruel@chromium.org0437a732013-08-27 16:05:52 +0000127 start_time = time.time()
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000128 self._isolate_item = isolateserver.BufferItem(
129 self.bundle.zip_into_buffer(), self._algo, is_isolated=True)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000130 print 'Zipping completed, time elapsed: %f' % (time.time() - start_time)
131
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000132 try:
133 start_time = time.time()
134 uploaded = self.storage.upload_items([self._isolate_item])
135 elapsed = time.time() - start_time
136 except (IOError, OSError) as exc:
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000137 tools.report_error('Failed to upload the zip file: %s' % exc)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000138 return False
139
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000140 if self._isolate_item in uploaded:
141 print 'Upload complete, time elapsed: %f' % elapsed
142 else:
143 print 'Zip file already on server, time elapsed: %f' % elapsed
maruel@chromium.org0437a732013-08-27 16:05:52 +0000144
145 return True
146
147 def to_json(self):
148 """Exports the current configuration into a swarm-readable manifest file.
149
150 This function doesn't mutate the object.
151 """
152 test_case = {
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500153 'cleanup': 'root',
maruel@chromium.org0437a732013-08-27 16:05:52 +0000154 'configurations': [
155 {
maruel@chromium.org0437a732013-08-27 16:05:52 +0000156 'config_name': self._target_platform,
157 'dimensions': {
158 'os': self._target_platform,
159 },
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500160 'min_instances': self._shards,
161 'priority': self.priority,
maruel@chromium.org0437a732013-08-27 16:05:52 +0000162 },
163 ],
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500164 'data': [],
165 # TODO: Let the encoding get set from the command line.
166 'encoding': 'UTF-8',
167 'env_vars': {},
maruel@chromium.org0437a732013-08-27 16:05:52 +0000168 'restart_on_failure': True,
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500169 'test_case_name': self._test_name,
170 'tests': self._tasks,
171 'working_dir': self._working_dir,
maruel@chromium.org0437a732013-08-27 16:05:52 +0000172 }
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000173 if self._isolate_item:
maruel@chromium.org814d23f2013-10-01 19:08:00 +0000174 test_case['data'].append(
175 [
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000176 self.storage.get_fetch_url(self._isolate_item.digest),
maruel@chromium.org814d23f2013-10-01 19:08:00 +0000177 'swarm_data.zip',
178 ])
maruel@chromium.org0437a732013-08-27 16:05:52 +0000179 # These flags are googletest specific.
180 if self._test_filter and self._test_filter != '*':
181 test_case['env_vars']['GTEST_FILTER'] = self._test_filter
182 if self._shards > 1:
183 test_case['env_vars']['GTEST_SHARD_INDEX'] = '%(instance_index)s'
184 test_case['env_vars']['GTEST_TOTAL_SHARDS'] = '%(num_instances)s'
185
186 return json.dumps(test_case, separators=(',',':'))
187
188
189def now():
190 """Exists so it can be mocked easily."""
191 return time.time()
192
193
194def get_test_keys(swarm_base_url, test_name):
195 """Returns the Swarm test key for each shards of test_name."""
196 key_data = urllib.urlencode([('name', test_name)])
197 url = '%s/get_matching_test_cases?%s' % (swarm_base_url, key_data)
198
vadimsh@chromium.org043b76d2013-09-12 16:15:13 +0000199 for _ in net.retry_loop(max_attempts=net.URL_OPEN_MAX_ATTEMPTS):
200 result = net.url_read(url, retry_404=True)
201 if result is None:
maruel@chromium.org0437a732013-08-27 16:05:52 +0000202 raise Failure(
203 'Error: Unable to find any tests with the name, %s, on swarm server'
204 % test_name)
205
maruel@chromium.org0437a732013-08-27 16:05:52 +0000206 # TODO(maruel): Compare exact string.
207 if 'No matching' in result:
208 logging.warning('Unable to find any tests with the name, %s, on swarm '
209 'server' % test_name)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000210 continue
211 return json.loads(result)
212
213 raise Failure(
214 'Error: Unable to find any tests with the name, %s, on swarm server'
215 % test_name)
216
217
218def retrieve_results(base_url, test_key, timeout, should_stop):
219 """Retrieves results for a single test_key."""
maruel@chromium.org814d23f2013-10-01 19:08:00 +0000220 assert isinstance(timeout, float), timeout
maruel@chromium.org0437a732013-08-27 16:05:52 +0000221 params = [('r', test_key)]
222 result_url = '%s/get_result?%s' % (base_url, urllib.urlencode(params))
223 start = now()
224 while True:
225 if timeout and (now() - start) >= timeout:
226 logging.error('retrieve_results(%s) timed out', base_url)
227 return {}
228 # Do retries ourselves.
vadimsh@chromium.org043b76d2013-09-12 16:15:13 +0000229 response = net.url_read(result_url, retry_404=False, retry_50x=False)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000230 if response is None:
231 # Aggressively poll for results. Do not use retry_404 so
232 # should_stop is polled more often.
233 remaining = min(5, timeout - (now() - start)) if timeout else 5
234 if remaining > 0:
maruel@chromium.org814d23f2013-10-01 19:08:00 +0000235 if should_stop.get():
236 return {}
vadimsh@chromium.org043b76d2013-09-12 16:15:13 +0000237 net.sleep_before_retry(1, remaining)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000238 else:
239 try:
vadimsh@chromium.org043b76d2013-09-12 16:15:13 +0000240 data = json.loads(response) or {}
maruel@chromium.org0437a732013-08-27 16:05:52 +0000241 except (ValueError, TypeError):
242 logging.warning(
243 'Received corrupted data for test_key %s. Retrying.', test_key)
244 else:
245 if data['output']:
246 return data
247 if should_stop.get():
248 return {}
249
250
251def yield_results(swarm_base_url, test_keys, timeout, max_threads):
252 """Yields swarm test results from the swarm server as (index, result).
253
254 Duplicate shards are ignored, the first one to complete is returned.
255
256 max_threads is optional and is used to limit the number of parallel fetches
257 done. Since in general the number of test_keys is in the range <=10, it's not
258 worth normally to limit the number threads. Mostly used for testing purposes.
259 """
260 shards_remaining = range(len(test_keys))
261 number_threads = (
262 min(max_threads, len(test_keys)) if max_threads else len(test_keys))
263 should_stop = threading_utils.Bit()
264 results_remaining = len(test_keys)
265 with threading_utils.ThreadPool(number_threads, number_threads, 0) as pool:
266 try:
267 for test_key in test_keys:
268 pool.add_task(
269 0, retrieve_results, swarm_base_url, test_key, timeout, should_stop)
270 while shards_remaining and results_remaining:
271 result = pool.get_one_result()
272 results_remaining -= 1
273 if not result:
274 # Failed to retrieve one key.
275 logging.error('Failed to retrieve the results for a swarm key')
276 continue
277 shard_index = result['config_instance_index']
278 if shard_index in shards_remaining:
279 shards_remaining.remove(shard_index)
280 yield shard_index, result
281 else:
282 logging.warning('Ignoring duplicate shard index %d', shard_index)
283 # Pop the last entry, there's no such shard.
284 shards_remaining.pop()
285 finally:
286 # Done, kill the remaining threads.
287 should_stop.set()
288
289
290def chromium_setup(manifest):
291 """Sets up the commands to run.
292
293 Highly chromium specific.
294 """
vadimsh@chromium.org6b706212013-08-28 15:03:46 +0000295 # Add uncompressed zip here. It'll be compressed as part of the package sent
296 # to Swarming server.
297 run_test_name = 'run_isolated.zip'
298 manifest.bundle.add_buffer(run_test_name,
299 run_isolated.get_as_zip_package().zip_into_buffer(compress=False))
maruel@chromium.org0437a732013-08-27 16:05:52 +0000300
vadimsh@chromium.org6b706212013-08-28 15:03:46 +0000301 cleanup_script_name = 'swarm_cleanup.py'
302 manifest.bundle.add_file(os.path.join(TOOLS_PATH, cleanup_script_name),
303 cleanup_script_name)
304
maruel@chromium.org0437a732013-08-27 16:05:52 +0000305 run_cmd = [
306 'python', run_test_name,
maruel@chromium.org814d23f2013-10-01 19:08:00 +0000307 '--hash', manifest.isolated_hash,
maruel@chromium.orgb7e79a22013-09-13 01:24:56 +0000308 '--isolate-server', manifest.isolate_server,
maruel@chromium.org0437a732013-08-27 16:05:52 +0000309 ]
310 if manifest.verbose or manifest.profile:
311 # Have it print the profiling section.
312 run_cmd.append('--verbose')
313 manifest.add_task('Run Test', run_cmd)
314
315 # Clean up
316 manifest.add_task('Clean Up', ['python', cleanup_script_name])
317
318
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000319def archive(isolated, isolate_server, os_slave, algo, verbose):
maruel@chromium.org0437a732013-08-27 16:05:52 +0000320 """Archives a .isolated and all the dependencies on the CAC."""
321 tempdir = None
322 try:
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000323 logging.info('archive(%s, %s)', isolated, isolate_server)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000324 cmd = [
325 sys.executable,
326 os.path.join(ROOT_DIR, 'isolate.py'),
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000327 'archive',
maruel@chromium.org0437a732013-08-27 16:05:52 +0000328 '--outdir', isolate_server,
329 '--isolated', isolated,
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000330 '-V', 'OS', PLATFORM_MAPPING_ISOLATE[os_slave],
maruel@chromium.org0437a732013-08-27 16:05:52 +0000331 ]
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000332 cmd.extend(['--verbose'] * verbose)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000333 logging.info(' '.join(cmd))
334 if subprocess.call(cmd, verbose):
335 return
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000336 return isolateserver.hash_file(isolated, algo)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000337 finally:
338 if tempdir:
339 shutil.rmtree(tempdir)
340
341
342def process_manifest(
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500343 swarming, isolate_server, file_hash_or_isolated, test_name, shards,
344 test_filter, slave_os, working_dir, verbose, profile, priority, algo):
maruel@chromium.org0437a732013-08-27 16:05:52 +0000345 """Process the manifest file and send off the swarm test request.
346
347 Optionally archives an .isolated file.
348 """
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000349 if file_hash_or_isolated.endswith('.isolated'):
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000350 file_hash = archive(
351 file_hash_or_isolated, isolate_server, slave_os, algo, verbose)
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000352 if not file_hash:
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000353 tools.report_error('Archival failure %s' % file_hash_or_isolated)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000354 return 1
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000355 elif isolateserver.is_valid_hash(file_hash_or_isolated, algo):
356 file_hash = file_hash_or_isolated
maruel@chromium.org0437a732013-08-27 16:05:52 +0000357 else:
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000358 tools.report_error('Invalid hash %s' % file_hash_or_isolated)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000359 return 1
360
361 try:
362 manifest = Manifest(
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500363 isolate_server=isolate_server,
364 isolated_hash=file_hash,
365 test_name=test_name,
366 shards=shards,
367 test_filter=test_filter,
368 slave_os=PLATFORM_MAPPING_SWARMING[slave_os],
369 working_dir=working_dir,
370 verbose=verbose,
371 profile=profile,
372 priority=priority,
373 algo=algo)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000374 except ValueError as e:
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000375 tools.report_error('Unable to process %s: %s' % (test_name, e))
maruel@chromium.org0437a732013-08-27 16:05:52 +0000376 return 1
377
378 chromium_setup(manifest)
379
380 # Zip up relevant files.
381 print('Zipping up files...')
382 if not manifest.zip_and_upload():
383 return 1
384
385 # Send test requests off to swarm.
386 print('Sending test requests to swarm.')
387 print('Server: %s' % swarming)
388 print('Job name: %s' % test_name)
389 test_url = swarming + '/test'
390 manifest_text = manifest.to_json()
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000391 result = net.url_read(test_url, data={'request': manifest_text})
maruel@chromium.org0437a732013-08-27 16:05:52 +0000392 if not result:
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000393 tools.report_error(
394 'Failed to send test for %s\n%s' % (test_name, test_url))
maruel@chromium.org0437a732013-08-27 16:05:52 +0000395 return 1
396 try:
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000397 json.loads(result)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000398 except (ValueError, TypeError) as e:
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000399 msg = '\n'.join((
400 'Failed to send test for %s' % test_name,
401 'Manifest: %s' % manifest_text,
402 'Bad response: %s' % result,
403 str(e)))
404 tools.report_error(msg)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000405 return 1
406 return 0
407
408
409def trigger(
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500410 swarming,
411 isolate_server,
maruel@chromium.org0437a732013-08-27 16:05:52 +0000412 slave_os,
413 tasks,
414 task_prefix,
415 working_dir,
maruel@chromium.org0437a732013-08-27 16:05:52 +0000416 verbose,
417 profile,
418 priority):
419 """Sends off the hash swarming test requests."""
420 highest_exit_code = 0
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000421 for (file_hash, test_name, shards, testfilter) in tasks:
maruel@chromium.org0437a732013-08-27 16:05:52 +0000422 # TODO(maruel): It should first create a request manifest object, then pass
423 # it to a function to zip, archive and trigger.
424 exit_code = process_manifest(
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500425 swarming=swarming,
426 isolate_server=isolate_server,
427 file_hash_or_isolated=file_hash,
428 test_name=task_prefix + test_name,
429 shards=int(shards),
430 test_filter=testfilter,
431 slave_os=slave_os,
432 working_dir=working_dir,
433 verbose=verbose,
434 profile=profile,
435 priority=priority,
436 algo=hashlib.sha1)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000437 highest_exit_code = max(highest_exit_code, exit_code)
438 return highest_exit_code
439
440
441def decorate_shard_output(result, shard_exit_code):
442 """Returns wrapped output for swarming task shard."""
443 tag = 'index %s (machine tag: %s, id: %s)' % (
444 result['config_instance_index'],
445 result['machine_id'],
446 result.get('machine_tag', 'unknown'))
447 return (
448 '\n'
449 '================================================================\n'
450 'Begin output from shard %s\n'
451 '================================================================\n'
452 '\n'
453 '%s'
454 '================================================================\n'
455 'End output from shard %s. Return %d\n'
456 '================================================================\n'
457 ) % (tag, result['output'] or NO_OUTPUT_FOUND, tag, shard_exit_code)
458
459
460def collect(url, test_name, timeout, decorate):
461 """Retrieves results of a Swarming job."""
462 test_keys = get_test_keys(url, test_name)
463 if not test_keys:
464 raise Failure('No test keys to get results with.')
465
maruel@chromium.org9c1c7b52013-08-28 19:04:36 +0000466 exit_code = None
maruel@chromium.org0437a732013-08-27 16:05:52 +0000467 for _index, output in yield_results(url, test_keys, timeout, None):
468 shard_exit_codes = (output['exit_codes'] or '1').split(',')
469 shard_exit_code = max(int(i) for i in shard_exit_codes)
470 if decorate:
471 print decorate_shard_output(output, shard_exit_code)
472 else:
473 print(
474 '%s/%s: %s' % (
475 output['machine_id'],
476 output['machine_tag'],
477 output['exit_codes']))
478 print(''.join(' %s\n' % l for l in output['output'].splitlines()))
maruel@chromium.org9c1c7b52013-08-28 19:04:36 +0000479 exit_code = exit_code or shard_exit_code
480 return exit_code if exit_code is not None else 1
maruel@chromium.org0437a732013-08-27 16:05:52 +0000481
482
483def add_trigger_options(parser):
484 """Adds all options to trigger a task on Swarming."""
485 parser.add_option(
486 '-I', '--isolate-server',
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000487 metavar='URL', default='',
488 help='Isolate server to use')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000489 parser.add_option(
490 '-w', '--working_dir', default='swarm_tests',
491 help='Working directory on the swarm slave side. default: %default.')
492 parser.add_option(
493 '-o', '--os', default=sys.platform,
494 help='Swarm OS image to request. Should be one of the valid sys.platform '
495 'values like darwin, linux2 or win32 default: %default.')
496 parser.add_option(
497 '-T', '--task-prefix', default='',
498 help='Prefix to give the swarm test request. default: %default')
499 parser.add_option(
500 '--profile', action='store_true',
501 default=bool(os.environ.get('ISOLATE_DEBUG')),
502 help='Have run_isolated.py print profiling info')
503 parser.add_option(
504 '--priority', type='int', default=100,
505 help='The lower value, the more important the task is')
506
507
508def process_trigger_options(parser, options):
509 options.isolate_server = options.isolate_server.rstrip('/')
510 if not options.isolate_server:
511 parser.error('--isolate-server is required.')
512 if options.os in ('', 'None'):
513 # Use the current OS.
514 options.os = sys.platform
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000515 if not options.os in PLATFORM_MAPPING_SWARMING:
maruel@chromium.org0437a732013-08-27 16:05:52 +0000516 parser.error('Invalid --os option.')
517
518
519def add_collect_options(parser):
520 parser.add_option(
521 '-t', '--timeout',
522 type='float',
523 default=DEFAULT_SHARD_WAIT_TIME,
524 help='Timeout to wait for result, set to 0 for no timeout; default: '
525 '%default s')
526 parser.add_option('--decorate', action='store_true', help='Decorate output')
527
528
529@subcommand.usage('test_name')
530def CMDcollect(parser, args):
531 """Retrieves results of a Swarming job.
532
533 The result can be in multiple part if the execution was sharded. It can
534 potentially have retries.
535 """
536 add_collect_options(parser)
537 (options, args) = parser.parse_args(args)
538 if not args:
539 parser.error('Must specify one test name.')
540 elif len(args) > 1:
541 parser.error('Must specify only one test name.')
542
543 try:
544 return collect(options.swarming, args[0], options.timeout, options.decorate)
545 except Failure as e:
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000546 tools.report_error(e)
547 return 1
maruel@chromium.org0437a732013-08-27 16:05:52 +0000548
549
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000550@subcommand.usage('[hash|isolated ...]')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000551def CMDrun(parser, args):
552 """Triggers a job and wait for the results.
553
554 Basically, does everything to run command(s) remotely.
555 """
556 add_trigger_options(parser)
557 add_collect_options(parser)
558 options, args = parser.parse_args(args)
559
560 if not args:
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000561 parser.error('Must pass at least one .isolated file or its hash (sha1).')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000562 process_trigger_options(parser, options)
563
564 success = []
565 for arg in args:
566 logging.info('Triggering %s', arg)
567 try:
568 result = trigger(
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500569 swarming=options.swarming,
570 isolate_server=options.isolate_server,
571 slave_os=options.os,
572 tasks=[(arg, os.path.basename(arg), '1', '')],
573 task_prefix=options.task_prefix,
574 working_dir=options.working_dir,
575 verbose=options.verbose,
576 profile=options.profile,
577 priority=options.priority)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000578 except Failure as e:
579 result = e.args[0]
580 if result:
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000581 tools.report_error('Failed to trigger %s: %s' % (arg, result))
maruel@chromium.org0437a732013-08-27 16:05:52 +0000582 else:
583 success.append(os.path.basename(arg))
584
585 if not success:
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000586 tools.report_error('Failed to trigger any job.')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000587 return result
588
589 code = 0
590 for arg in success:
591 logging.info('Collecting %s', arg)
592 try:
593 new_code = collect(
594 options.swarming,
595 options.task_prefix + arg,
596 options.timeout,
597 options.decorate)
598 code = max(code, new_code)
599 except Failure as e:
600 code = max(code, 1)
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000601 tools.report_error(e)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000602 return code
603
604
605def CMDtrigger(parser, args):
606 """Triggers Swarm request(s).
607
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000608 Accepts one or multiple --task requests, with either the hash (sha1) of a
609 .isolated file already uploaded or the path to an .isolated file to archive,
610 packages it if needed and sends a Swarm manifest file to the Swarm server.
maruel@chromium.org0437a732013-08-27 16:05:52 +0000611 """
612 add_trigger_options(parser)
613 parser.add_option(
614 '--task', nargs=4, action='append', default=[], dest='tasks',
615 help='Task to trigger. The format is '
616 '(hash|isolated, test_name, shards, test_filter). This may be '
617 'used multiple times to send multiple hashes jobs. If an isolated '
618 'file is specified instead of an hash, it is first archived.')
619 (options, args) = parser.parse_args(args)
620
621 if args:
622 parser.error('Unknown args: %s' % args)
623 process_trigger_options(parser, options)
624 if not options.tasks:
625 parser.error('At least one --task is required.')
626
627 try:
628 return trigger(
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500629 swarming=options.swarming,
630 isolate_server=options.isolate_server,
631 slave_os=options.os,
632 tasks=options.tasks,
633 task_prefix=options.task_prefix,
634 working_dir=options.working_dir,
635 verbose=options.verbose,
636 profile=options.profile,
637 priority=options.priority)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000638 except Failure as e:
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000639 tools.report_error(e)
640 return 1
maruel@chromium.org0437a732013-08-27 16:05:52 +0000641
642
643class OptionParserSwarming(tools.OptionParserWithLogging):
644 def __init__(self, **kwargs):
645 tools.OptionParserWithLogging.__init__(
646 self, prog='swarming.py', **kwargs)
647 self.add_option(
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000648 '-S', '--swarming',
649 metavar='URL', default='',
650 help='Swarming server to use')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000651
652 def parse_args(self, *args, **kwargs):
653 options, args = tools.OptionParserWithLogging.parse_args(
654 self, *args, **kwargs)
655 options.swarming = options.swarming.rstrip('/')
656 if not options.swarming:
657 self.error('--swarming is required.')
658 return options, args
659
660
661def main(args):
662 dispatcher = subcommand.CommandDispatcher(__name__)
663 try:
664 return dispatcher.execute(OptionParserSwarming(version=__version__), args)
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000665 except Exception as e:
666 tools.report_error(e)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000667 return 1
668
669
670if __name__ == '__main__':
671 fix_encoding.fix_encoding()
672 tools.disable_buffering()
673 colorama.init()
674 sys.exit(main(sys.argv[1:]))