blob: a54e816a08f40e73d70356290520ad4f4ef2576f [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.
Marc-Antoine Ruele98b1122013-11-05 20:27:57 -05003# Use of this source code is governed under the Apache License, Version 2.0 that
4# can be found in the LICENSE file.
maruel@chromium.org0437a732013-08-27 16:05:52 +00005
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 Ruel05dab5e2013-11-06 15:06:47 -050073 self, isolate_server, isolated_hash, test_name, shards, env,
Marc-Antoine Ruel5d799192013-11-06 15:20:39 -050074 filters, 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.
Marc-Antoine Ruel05dab5e2013-11-06 15:06:47 -050081 env - environment variables to set.
Marc-Antoine Ruel5d799192013-11-06 15:20:39 -050082 filters - dimensions to filter the task on.
maruel@chromium.org0437a732013-08-27 16:05:52 +000083 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
Marc-Antoine Ruel05dab5e2013-11-06 15:06:47 -050097 self._env = env
Marc-Antoine Ruel5d799192013-11-06 15:20:39 -050098 self._filters = filters
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 {
Marc-Antoine Ruel5d799192013-11-06 15:20:39 -0500156 'config_name': 'isolated',
157 'dimensions': self._filters,
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500158 'min_instances': self._shards,
159 'priority': self.priority,
maruel@chromium.org0437a732013-08-27 16:05:52 +0000160 },
161 ],
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500162 'data': [],
163 # TODO: Let the encoding get set from the command line.
164 'encoding': 'UTF-8',
Marc-Antoine Ruel05dab5e2013-11-06 15:06:47 -0500165 'env_vars': self._env,
maruel@chromium.org0437a732013-08-27 16:05:52 +0000166 'restart_on_failure': True,
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500167 'test_case_name': self._test_name,
168 'tests': self._tasks,
169 'working_dir': self._working_dir,
maruel@chromium.org0437a732013-08-27 16:05:52 +0000170 }
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000171 if self._isolate_item:
maruel@chromium.org814d23f2013-10-01 19:08:00 +0000172 test_case['data'].append(
173 [
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000174 self.storage.get_fetch_url(self._isolate_item.digest),
maruel@chromium.org814d23f2013-10-01 19:08:00 +0000175 'swarm_data.zip',
176 ])
maruel@chromium.org0437a732013-08-27 16:05:52 +0000177 return json.dumps(test_case, separators=(',',':'))
178
179
180def now():
181 """Exists so it can be mocked easily."""
182 return time.time()
183
184
185def get_test_keys(swarm_base_url, test_name):
186 """Returns the Swarm test key for each shards of test_name."""
187 key_data = urllib.urlencode([('name', test_name)])
188 url = '%s/get_matching_test_cases?%s' % (swarm_base_url, key_data)
189
vadimsh@chromium.org043b76d2013-09-12 16:15:13 +0000190 for _ in net.retry_loop(max_attempts=net.URL_OPEN_MAX_ATTEMPTS):
191 result = net.url_read(url, retry_404=True)
192 if result is None:
maruel@chromium.org0437a732013-08-27 16:05:52 +0000193 raise Failure(
194 'Error: Unable to find any tests with the name, %s, on swarm server'
195 % test_name)
196
maruel@chromium.org0437a732013-08-27 16:05:52 +0000197 # TODO(maruel): Compare exact string.
198 if 'No matching' in result:
199 logging.warning('Unable to find any tests with the name, %s, on swarm '
200 'server' % test_name)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000201 continue
202 return json.loads(result)
203
204 raise Failure(
205 'Error: Unable to find any tests with the name, %s, on swarm server'
206 % test_name)
207
208
209def retrieve_results(base_url, test_key, timeout, should_stop):
210 """Retrieves results for a single test_key."""
maruel@chromium.org814d23f2013-10-01 19:08:00 +0000211 assert isinstance(timeout, float), timeout
maruel@chromium.org0437a732013-08-27 16:05:52 +0000212 params = [('r', test_key)]
213 result_url = '%s/get_result?%s' % (base_url, urllib.urlencode(params))
214 start = now()
215 while True:
216 if timeout and (now() - start) >= timeout:
217 logging.error('retrieve_results(%s) timed out', base_url)
218 return {}
219 # Do retries ourselves.
vadimsh@chromium.org043b76d2013-09-12 16:15:13 +0000220 response = net.url_read(result_url, retry_404=False, retry_50x=False)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000221 if response is None:
222 # Aggressively poll for results. Do not use retry_404 so
223 # should_stop is polled more often.
224 remaining = min(5, timeout - (now() - start)) if timeout else 5
225 if remaining > 0:
maruel@chromium.org814d23f2013-10-01 19:08:00 +0000226 if should_stop.get():
227 return {}
vadimsh@chromium.org043b76d2013-09-12 16:15:13 +0000228 net.sleep_before_retry(1, remaining)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000229 else:
230 try:
vadimsh@chromium.org043b76d2013-09-12 16:15:13 +0000231 data = json.loads(response) or {}
maruel@chromium.org0437a732013-08-27 16:05:52 +0000232 except (ValueError, TypeError):
233 logging.warning(
234 'Received corrupted data for test_key %s. Retrying.', test_key)
235 else:
236 if data['output']:
237 return data
238 if should_stop.get():
239 return {}
240
241
242def yield_results(swarm_base_url, test_keys, timeout, max_threads):
243 """Yields swarm test results from the swarm server as (index, result).
244
245 Duplicate shards are ignored, the first one to complete is returned.
246
247 max_threads is optional and is used to limit the number of parallel fetches
248 done. Since in general the number of test_keys is in the range <=10, it's not
249 worth normally to limit the number threads. Mostly used for testing purposes.
250 """
251 shards_remaining = range(len(test_keys))
252 number_threads = (
253 min(max_threads, len(test_keys)) if max_threads else len(test_keys))
254 should_stop = threading_utils.Bit()
255 results_remaining = len(test_keys)
256 with threading_utils.ThreadPool(number_threads, number_threads, 0) as pool:
257 try:
258 for test_key in test_keys:
259 pool.add_task(
260 0, retrieve_results, swarm_base_url, test_key, timeout, should_stop)
261 while shards_remaining and results_remaining:
262 result = pool.get_one_result()
263 results_remaining -= 1
264 if not result:
265 # Failed to retrieve one key.
266 logging.error('Failed to retrieve the results for a swarm key')
267 continue
268 shard_index = result['config_instance_index']
269 if shard_index in shards_remaining:
270 shards_remaining.remove(shard_index)
271 yield shard_index, result
272 else:
273 logging.warning('Ignoring duplicate shard index %d', shard_index)
274 # Pop the last entry, there's no such shard.
275 shards_remaining.pop()
276 finally:
277 # Done, kill the remaining threads.
278 should_stop.set()
279
280
281def chromium_setup(manifest):
282 """Sets up the commands to run.
283
284 Highly chromium specific.
285 """
vadimsh@chromium.org6b706212013-08-28 15:03:46 +0000286 # Add uncompressed zip here. It'll be compressed as part of the package sent
287 # to Swarming server.
288 run_test_name = 'run_isolated.zip'
289 manifest.bundle.add_buffer(run_test_name,
290 run_isolated.get_as_zip_package().zip_into_buffer(compress=False))
maruel@chromium.org0437a732013-08-27 16:05:52 +0000291
vadimsh@chromium.org6b706212013-08-28 15:03:46 +0000292 cleanup_script_name = 'swarm_cleanup.py'
293 manifest.bundle.add_file(os.path.join(TOOLS_PATH, cleanup_script_name),
294 cleanup_script_name)
295
maruel@chromium.org0437a732013-08-27 16:05:52 +0000296 run_cmd = [
297 'python', run_test_name,
maruel@chromium.org814d23f2013-10-01 19:08:00 +0000298 '--hash', manifest.isolated_hash,
maruel@chromium.orgb7e79a22013-09-13 01:24:56 +0000299 '--isolate-server', manifest.isolate_server,
maruel@chromium.org0437a732013-08-27 16:05:52 +0000300 ]
301 if manifest.verbose or manifest.profile:
302 # Have it print the profiling section.
303 run_cmd.append('--verbose')
304 manifest.add_task('Run Test', run_cmd)
305
306 # Clean up
307 manifest.add_task('Clean Up', ['python', cleanup_script_name])
308
309
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000310def archive(isolated, isolate_server, os_slave, algo, verbose):
maruel@chromium.org0437a732013-08-27 16:05:52 +0000311 """Archives a .isolated and all the dependencies on the CAC."""
312 tempdir = None
313 try:
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000314 logging.info('archive(%s, %s)', isolated, isolate_server)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000315 cmd = [
316 sys.executable,
317 os.path.join(ROOT_DIR, 'isolate.py'),
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000318 'archive',
maruel@chromium.org0437a732013-08-27 16:05:52 +0000319 '--outdir', isolate_server,
320 '--isolated', isolated,
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000321 '-V', 'OS', PLATFORM_MAPPING_ISOLATE[os_slave],
maruel@chromium.org0437a732013-08-27 16:05:52 +0000322 ]
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000323 cmd.extend(['--verbose'] * verbose)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000324 logging.info(' '.join(cmd))
325 if subprocess.call(cmd, verbose):
326 return
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000327 return isolateserver.hash_file(isolated, algo)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000328 finally:
329 if tempdir:
330 shutil.rmtree(tempdir)
331
332
333def process_manifest(
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500334 swarming, isolate_server, file_hash_or_isolated, test_name, shards,
335 test_filter, slave_os, working_dir, verbose, profile, priority, algo):
maruel@chromium.org0437a732013-08-27 16:05:52 +0000336 """Process the manifest file and send off the swarm test request.
337
338 Optionally archives an .isolated file.
339 """
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000340 if file_hash_or_isolated.endswith('.isolated'):
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000341 file_hash = archive(
342 file_hash_or_isolated, isolate_server, slave_os, algo, verbose)
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000343 if not file_hash:
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000344 tools.report_error('Archival failure %s' % file_hash_or_isolated)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000345 return 1
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000346 elif isolateserver.is_valid_hash(file_hash_or_isolated, algo):
347 file_hash = file_hash_or_isolated
maruel@chromium.org0437a732013-08-27 16:05:52 +0000348 else:
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000349 tools.report_error('Invalid hash %s' % file_hash_or_isolated)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000350 return 1
351
Marc-Antoine Ruel05dab5e2013-11-06 15:06:47 -0500352 env = {}
353 # These flags are googletest specific.
354 if test_filter and test_filter != '*':
355 env['GTEST_FILTER'] = test_filter
356 if shards > 1:
357 env['GTEST_SHARD_INDEX'] = '%(instance_index)s'
358 env['GTEST_TOTAL_SHARDS'] = '%(num_instances)s'
359
Marc-Antoine Ruel5d799192013-11-06 15:20:39 -0500360 filters = {
361 'os': PLATFORM_MAPPING_SWARMING[slave_os],
362 }
maruel@chromium.org0437a732013-08-27 16:05:52 +0000363 try:
364 manifest = Manifest(
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500365 isolate_server=isolate_server,
366 isolated_hash=file_hash,
367 test_name=test_name,
368 shards=shards,
Marc-Antoine Ruel05dab5e2013-11-06 15:06:47 -0500369 env=env,
Marc-Antoine Ruel5d799192013-11-06 15:20:39 -0500370 filters=filters,
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500371 working_dir=working_dir,
372 verbose=verbose,
373 profile=profile,
374 priority=priority,
375 algo=algo)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000376 except ValueError as e:
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000377 tools.report_error('Unable to process %s: %s' % (test_name, e))
maruel@chromium.org0437a732013-08-27 16:05:52 +0000378 return 1
379
380 chromium_setup(manifest)
381
382 # Zip up relevant files.
383 print('Zipping up files...')
384 if not manifest.zip_and_upload():
385 return 1
386
387 # Send test requests off to swarm.
388 print('Sending test requests to swarm.')
389 print('Server: %s' % swarming)
390 print('Job name: %s' % test_name)
391 test_url = swarming + '/test'
392 manifest_text = manifest.to_json()
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000393 result = net.url_read(test_url, data={'request': manifest_text})
maruel@chromium.org0437a732013-08-27 16:05:52 +0000394 if not result:
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000395 tools.report_error(
396 'Failed to send test for %s\n%s' % (test_name, test_url))
maruel@chromium.org0437a732013-08-27 16:05:52 +0000397 return 1
398 try:
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000399 json.loads(result)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000400 except (ValueError, TypeError) as e:
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000401 msg = '\n'.join((
402 'Failed to send test for %s' % test_name,
403 'Manifest: %s' % manifest_text,
404 'Bad response: %s' % result,
405 str(e)))
406 tools.report_error(msg)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000407 return 1
408 return 0
409
410
411def trigger(
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500412 swarming,
413 isolate_server,
maruel@chromium.org0437a732013-08-27 16:05:52 +0000414 slave_os,
415 tasks,
416 task_prefix,
417 working_dir,
maruel@chromium.org0437a732013-08-27 16:05:52 +0000418 verbose,
419 profile,
420 priority):
421 """Sends off the hash swarming test requests."""
422 highest_exit_code = 0
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000423 for (file_hash, test_name, shards, testfilter) in tasks:
maruel@chromium.org0437a732013-08-27 16:05:52 +0000424 # TODO(maruel): It should first create a request manifest object, then pass
425 # it to a function to zip, archive and trigger.
426 exit_code = process_manifest(
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500427 swarming=swarming,
428 isolate_server=isolate_server,
429 file_hash_or_isolated=file_hash,
430 test_name=task_prefix + test_name,
431 shards=int(shards),
432 test_filter=testfilter,
433 slave_os=slave_os,
434 working_dir=working_dir,
435 verbose=verbose,
436 profile=profile,
437 priority=priority,
438 algo=hashlib.sha1)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000439 highest_exit_code = max(highest_exit_code, exit_code)
440 return highest_exit_code
441
442
443def decorate_shard_output(result, shard_exit_code):
444 """Returns wrapped output for swarming task shard."""
445 tag = 'index %s (machine tag: %s, id: %s)' % (
446 result['config_instance_index'],
447 result['machine_id'],
448 result.get('machine_tag', 'unknown'))
449 return (
450 '\n'
451 '================================================================\n'
452 'Begin output from shard %s\n'
453 '================================================================\n'
454 '\n'
455 '%s'
456 '================================================================\n'
457 'End output from shard %s. Return %d\n'
458 '================================================================\n'
459 ) % (tag, result['output'] or NO_OUTPUT_FOUND, tag, shard_exit_code)
460
461
462def collect(url, test_name, timeout, decorate):
463 """Retrieves results of a Swarming job."""
464 test_keys = get_test_keys(url, test_name)
465 if not test_keys:
466 raise Failure('No test keys to get results with.')
467
maruel@chromium.org9c1c7b52013-08-28 19:04:36 +0000468 exit_code = None
maruel@chromium.org0437a732013-08-27 16:05:52 +0000469 for _index, output in yield_results(url, test_keys, timeout, None):
470 shard_exit_codes = (output['exit_codes'] or '1').split(',')
471 shard_exit_code = max(int(i) for i in shard_exit_codes)
472 if decorate:
473 print decorate_shard_output(output, shard_exit_code)
474 else:
475 print(
476 '%s/%s: %s' % (
477 output['machine_id'],
478 output['machine_tag'],
479 output['exit_codes']))
480 print(''.join(' %s\n' % l for l in output['output'].splitlines()))
maruel@chromium.org9c1c7b52013-08-28 19:04:36 +0000481 exit_code = exit_code or shard_exit_code
482 return exit_code if exit_code is not None else 1
maruel@chromium.org0437a732013-08-27 16:05:52 +0000483
484
485def add_trigger_options(parser):
486 """Adds all options to trigger a task on Swarming."""
487 parser.add_option(
488 '-I', '--isolate-server',
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000489 metavar='URL', default='',
490 help='Isolate server to use')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000491 parser.add_option(
492 '-w', '--working_dir', default='swarm_tests',
493 help='Working directory on the swarm slave side. default: %default.')
494 parser.add_option(
495 '-o', '--os', default=sys.platform,
496 help='Swarm OS image to request. Should be one of the valid sys.platform '
497 'values like darwin, linux2 or win32 default: %default.')
498 parser.add_option(
499 '-T', '--task-prefix', default='',
500 help='Prefix to give the swarm test request. default: %default')
501 parser.add_option(
502 '--profile', action='store_true',
503 default=bool(os.environ.get('ISOLATE_DEBUG')),
504 help='Have run_isolated.py print profiling info')
505 parser.add_option(
506 '--priority', type='int', default=100,
507 help='The lower value, the more important the task is')
508
509
510def process_trigger_options(parser, options):
511 options.isolate_server = options.isolate_server.rstrip('/')
512 if not options.isolate_server:
513 parser.error('--isolate-server is required.')
514 if options.os in ('', 'None'):
515 # Use the current OS.
516 options.os = sys.platform
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000517 if not options.os in PLATFORM_MAPPING_SWARMING:
maruel@chromium.org0437a732013-08-27 16:05:52 +0000518 parser.error('Invalid --os option.')
519
520
521def add_collect_options(parser):
522 parser.add_option(
523 '-t', '--timeout',
524 type='float',
525 default=DEFAULT_SHARD_WAIT_TIME,
526 help='Timeout to wait for result, set to 0 for no timeout; default: '
527 '%default s')
528 parser.add_option('--decorate', action='store_true', help='Decorate output')
529
530
531@subcommand.usage('test_name')
532def CMDcollect(parser, args):
533 """Retrieves results of a Swarming job.
534
535 The result can be in multiple part if the execution was sharded. It can
536 potentially have retries.
537 """
538 add_collect_options(parser)
539 (options, args) = parser.parse_args(args)
540 if not args:
541 parser.error('Must specify one test name.')
542 elif len(args) > 1:
543 parser.error('Must specify only one test name.')
544
545 try:
546 return collect(options.swarming, args[0], options.timeout, options.decorate)
547 except Failure as e:
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000548 tools.report_error(e)
549 return 1
maruel@chromium.org0437a732013-08-27 16:05:52 +0000550
551
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000552@subcommand.usage('[hash|isolated ...]')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000553def CMDrun(parser, args):
554 """Triggers a job and wait for the results.
555
556 Basically, does everything to run command(s) remotely.
557 """
558 add_trigger_options(parser)
559 add_collect_options(parser)
560 options, args = parser.parse_args(args)
561
562 if not args:
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000563 parser.error('Must pass at least one .isolated file or its hash (sha1).')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000564 process_trigger_options(parser, options)
565
566 success = []
567 for arg in args:
568 logging.info('Triggering %s', arg)
569 try:
570 result = trigger(
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500571 swarming=options.swarming,
572 isolate_server=options.isolate_server,
573 slave_os=options.os,
574 tasks=[(arg, os.path.basename(arg), '1', '')],
575 task_prefix=options.task_prefix,
576 working_dir=options.working_dir,
577 verbose=options.verbose,
578 profile=options.profile,
579 priority=options.priority)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000580 except Failure as e:
581 result = e.args[0]
582 if result:
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000583 tools.report_error('Failed to trigger %s: %s' % (arg, result))
maruel@chromium.org0437a732013-08-27 16:05:52 +0000584 else:
585 success.append(os.path.basename(arg))
586
587 if not success:
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000588 tools.report_error('Failed to trigger any job.')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000589 return result
590
591 code = 0
592 for arg in success:
593 logging.info('Collecting %s', arg)
594 try:
595 new_code = collect(
596 options.swarming,
597 options.task_prefix + arg,
598 options.timeout,
599 options.decorate)
600 code = max(code, new_code)
601 except Failure as e:
602 code = max(code, 1)
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000603 tools.report_error(e)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000604 return code
605
606
607def CMDtrigger(parser, args):
608 """Triggers Swarm request(s).
609
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000610 Accepts one or multiple --task requests, with either the hash (sha1) of a
611 .isolated file already uploaded or the path to an .isolated file to archive,
612 packages it if needed and sends a Swarm manifest file to the Swarm server.
maruel@chromium.org0437a732013-08-27 16:05:52 +0000613 """
614 add_trigger_options(parser)
615 parser.add_option(
616 '--task', nargs=4, action='append', default=[], dest='tasks',
617 help='Task to trigger. The format is '
618 '(hash|isolated, test_name, shards, test_filter). This may be '
619 'used multiple times to send multiple hashes jobs. If an isolated '
620 'file is specified instead of an hash, it is first archived.')
621 (options, args) = parser.parse_args(args)
622
623 if args:
624 parser.error('Unknown args: %s' % args)
625 process_trigger_options(parser, options)
626 if not options.tasks:
627 parser.error('At least one --task is required.')
628
629 try:
630 return trigger(
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500631 swarming=options.swarming,
632 isolate_server=options.isolate_server,
633 slave_os=options.os,
634 tasks=options.tasks,
635 task_prefix=options.task_prefix,
636 working_dir=options.working_dir,
637 verbose=options.verbose,
638 profile=options.profile,
639 priority=options.priority)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000640 except Failure as e:
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000641 tools.report_error(e)
642 return 1
maruel@chromium.org0437a732013-08-27 16:05:52 +0000643
644
645class OptionParserSwarming(tools.OptionParserWithLogging):
646 def __init__(self, **kwargs):
647 tools.OptionParserWithLogging.__init__(
648 self, prog='swarming.py', **kwargs)
649 self.add_option(
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000650 '-S', '--swarming',
651 metavar='URL', default='',
652 help='Swarming server to use')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000653
654 def parse_args(self, *args, **kwargs):
655 options, args = tools.OptionParserWithLogging.parse_args(
656 self, *args, **kwargs)
657 options.swarming = options.swarming.rstrip('/')
658 if not options.swarming:
659 self.error('--swarming is required.')
660 return options, args
661
662
663def main(args):
664 dispatcher = subcommand.CommandDispatcher(__name__)
665 try:
666 return dispatcher.execute(OptionParserSwarming(version=__version__), args)
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000667 except Exception as e:
668 tools.report_error(e)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000669 return 1
670
671
672if __name__ == '__main__':
673 fix_encoding.fix_encoding()
674 tools.disable_buffering()
675 colorama.init()
676 sys.exit(main(sys.argv[1:]))