blob: 935d54b6ba2c6f5bfef669bb1fe957938c956fde [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
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -05008__version__ = '0.2'
maruel@chromium.org0437a732013-08-27 16:05:52 +00009
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 Ruel92f32422013-11-06 18:12:13 -050074 dimensions, 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 Ruel92f32422013-11-06 18:12:13 -050082 dimensions - 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 Ruel92f32422013-11-06 18:12:13 -050097 self._env = env.copy()
98 self._dimensions = dimensions.copy()
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',
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -0500157 'dimensions': self._dimensions,
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
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -0500310def archive(isolated, isolate_server, 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,
321 ]
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000322 cmd.extend(['--verbose'] * verbose)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000323 logging.info(' '.join(cmd))
324 if subprocess.call(cmd, verbose):
325 return
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000326 return isolateserver.hash_file(isolated, algo)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000327 finally:
328 if tempdir:
329 shutil.rmtree(tempdir)
330
331
332def process_manifest(
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500333 swarming, isolate_server, file_hash_or_isolated, test_name, shards,
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -0500334 dimensions, env, working_dir, verbose, profile, priority, algo):
335 """Processes the manifest file and send off the swarming test request.
maruel@chromium.org0437a732013-08-27 16:05:52 +0000336
337 Optionally archives an .isolated file.
338 """
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000339 if file_hash_or_isolated.endswith('.isolated'):
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000340 file_hash = archive(
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -0500341 file_hash_or_isolated, isolate_server, algo, verbose)
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000342 if not file_hash:
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000343 tools.report_error('Archival failure %s' % file_hash_or_isolated)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000344 return 1
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000345 elif isolateserver.is_valid_hash(file_hash_or_isolated, algo):
346 file_hash = file_hash_or_isolated
maruel@chromium.org0437a732013-08-27 16:05:52 +0000347 else:
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000348 tools.report_error('Invalid hash %s' % file_hash_or_isolated)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000349 return 1
maruel@chromium.org0437a732013-08-27 16:05:52 +0000350 try:
351 manifest = Manifest(
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500352 isolate_server=isolate_server,
353 isolated_hash=file_hash,
354 test_name=test_name,
355 shards=shards,
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -0500356 dimensions=dimensions,
Marc-Antoine Ruel05dab5e2013-11-06 15:06:47 -0500357 env=env,
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500358 working_dir=working_dir,
359 verbose=verbose,
360 profile=profile,
361 priority=priority,
362 algo=algo)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000363 except ValueError as e:
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000364 tools.report_error('Unable to process %s: %s' % (test_name, e))
maruel@chromium.org0437a732013-08-27 16:05:52 +0000365 return 1
366
367 chromium_setup(manifest)
368
369 # Zip up relevant files.
370 print('Zipping up files...')
371 if not manifest.zip_and_upload():
372 return 1
373
374 # Send test requests off to swarm.
375 print('Sending test requests to swarm.')
376 print('Server: %s' % swarming)
377 print('Job name: %s' % test_name)
378 test_url = swarming + '/test'
379 manifest_text = manifest.to_json()
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000380 result = net.url_read(test_url, data={'request': manifest_text})
maruel@chromium.org0437a732013-08-27 16:05:52 +0000381 if not result:
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000382 tools.report_error(
383 'Failed to send test for %s\n%s' % (test_name, test_url))
maruel@chromium.org0437a732013-08-27 16:05:52 +0000384 return 1
385 try:
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000386 json.loads(result)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000387 except (ValueError, TypeError) as e:
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000388 msg = '\n'.join((
389 'Failed to send test for %s' % test_name,
390 'Manifest: %s' % manifest_text,
391 'Bad response: %s' % result,
392 str(e)))
393 tools.report_error(msg)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000394 return 1
395 return 0
396
397
398def trigger(
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500399 swarming,
400 isolate_server,
maruel@chromium.org0437a732013-08-27 16:05:52 +0000401 tasks,
402 task_prefix,
403 working_dir,
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -0500404 dimensions,
405 env,
maruel@chromium.org0437a732013-08-27 16:05:52 +0000406 verbose,
407 profile,
408 priority):
409 """Sends off the hash swarming test requests."""
410 highest_exit_code = 0
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -0500411 for (file_hash, test_name, shards, test_filter) in tasks:
412 task_env = env.copy()
413 # These flags are googletest specific.
414 if test_filter and test_filter != '*':
415 task_env['GTEST_FILTER'] = test_filter
416 if int(shards) > 1:
417 task_env['GTEST_SHARD_INDEX'] = '%(instance_index)s'
418 task_env['GTEST_TOTAL_SHARDS'] = '%(num_instances)s'
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(
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500422 swarming=swarming,
423 isolate_server=isolate_server,
424 file_hash_or_isolated=file_hash,
425 test_name=task_prefix + test_name,
426 shards=int(shards),
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -0500427 dimensions=dimensions,
428 env=task_env,
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500429 working_dir=working_dir,
430 verbose=verbose,
431 profile=profile,
432 priority=priority,
433 algo=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."""
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500482 parser.server_group.add_option(
maruel@chromium.org0437a732013-08-27 16:05:52 +0000483 '-I', '--isolate-server',
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000484 metavar='URL', default='',
485 help='Isolate server to use')
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500486
487 parser.filter_group = tools.optparse.OptionGroup(parser, 'Filtering slaves')
488 parser.filter_group.add_option(
maruel@chromium.org0437a732013-08-27 16:05:52 +0000489 '-o', '--os', default=sys.platform,
490 help='Swarm OS image to request. Should be one of the valid sys.platform '
491 'values like darwin, linux2 or win32 default: %default.')
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500492 parser.filter_group.add_option(
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -0500493 '-d', '--dimensions', default=[], action='append', nargs=2,
494 dest='dimensions', metavar='FOO bar',
495 help='dimension to filter on')
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500496 parser.add_option_group(parser.filter_group)
497
498 parser.task_group = tools.optparse.OptionGroup(parser, 'Task properties')
499 parser.task_group.add_option(
500 '-w', '--working_dir', default='swarm_tests',
501 help='Working directory on the swarm slave side. default: %default.')
502 parser.task_group.add_option(
503 '-e', '--env', default=[], action='append', nargs=2, metavar='FOO bar',
504 help='environment variables to set')
505 parser.task_group.add_option(
maruel@chromium.org0437a732013-08-27 16:05:52 +0000506 '-T', '--task-prefix', default='',
507 help='Prefix to give the swarm test request. default: %default')
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500508 parser.task_group.add_option(
509 '--priority', type='int', default=100,
510 help='The lower value, the more important the task is')
511 parser.add_option_group(parser.task_group)
512
513 parser.group_logging.add_option(
maruel@chromium.org0437a732013-08-27 16:05:52 +0000514 '--profile', action='store_true',
515 default=bool(os.environ.get('ISOLATE_DEBUG')),
516 help='Have run_isolated.py print profiling info')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000517
518
519def process_trigger_options(parser, options):
520 options.isolate_server = options.isolate_server.rstrip('/')
521 if not options.isolate_server:
522 parser.error('--isolate-server is required.')
523 if options.os in ('', 'None'):
524 # Use the current OS.
525 options.os = sys.platform
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000526 if not options.os in PLATFORM_MAPPING_SWARMING:
maruel@chromium.org0437a732013-08-27 16:05:52 +0000527 parser.error('Invalid --os option.')
528
529
530def add_collect_options(parser):
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500531 parser.server_group.add_option(
maruel@chromium.org0437a732013-08-27 16:05:52 +0000532 '-t', '--timeout',
533 type='float',
534 default=DEFAULT_SHARD_WAIT_TIME,
535 help='Timeout to wait for result, set to 0 for no timeout; default: '
536 '%default s')
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500537 parser.group_logging.add_option(
538 '--decorate', action='store_true', help='Decorate output')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000539
540
541@subcommand.usage('test_name')
542def CMDcollect(parser, args):
543 """Retrieves results of a Swarming job.
544
545 The result can be in multiple part if the execution was sharded. It can
546 potentially have retries.
547 """
548 add_collect_options(parser)
549 (options, args) = parser.parse_args(args)
550 if not args:
551 parser.error('Must specify one test name.')
552 elif len(args) > 1:
553 parser.error('Must specify only one test name.')
554
555 try:
556 return collect(options.swarming, args[0], options.timeout, options.decorate)
557 except Failure as e:
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000558 tools.report_error(e)
559 return 1
maruel@chromium.org0437a732013-08-27 16:05:52 +0000560
561
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000562@subcommand.usage('[hash|isolated ...]')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000563def CMDrun(parser, args):
564 """Triggers a job and wait for the results.
565
566 Basically, does everything to run command(s) remotely.
567 """
568 add_trigger_options(parser)
569 add_collect_options(parser)
570 options, args = parser.parse_args(args)
571
572 if not args:
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000573 parser.error('Must pass at least one .isolated file or its hash (sha1).')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000574 process_trigger_options(parser, options)
575
576 success = []
577 for arg in args:
578 logging.info('Triggering %s', arg)
579 try:
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -0500580 dimensions = {
581 'os': PLATFORM_MAPPING_SWARMING[options.os],
582 }
583 dimensions.update(dict(options.dimensions))
maruel@chromium.org0437a732013-08-27 16:05:52 +0000584 result = trigger(
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500585 swarming=options.swarming,
586 isolate_server=options.isolate_server,
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500587 tasks=[(arg, os.path.basename(arg), '1', '')],
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -0500588 dimensions=dimensions,
589 env=dict(options.env),
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500590 task_prefix=options.task_prefix,
591 working_dir=options.working_dir,
592 verbose=options.verbose,
593 profile=options.profile,
594 priority=options.priority)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000595 except Failure as e:
596 result = e.args[0]
597 if result:
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000598 tools.report_error('Failed to trigger %s: %s' % (arg, result))
maruel@chromium.org0437a732013-08-27 16:05:52 +0000599 else:
600 success.append(os.path.basename(arg))
601
602 if not success:
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000603 tools.report_error('Failed to trigger any job.')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000604 return result
605
606 code = 0
607 for arg in success:
608 logging.info('Collecting %s', arg)
609 try:
610 new_code = collect(
611 options.swarming,
612 options.task_prefix + arg,
613 options.timeout,
614 options.decorate)
615 code = max(code, new_code)
616 except Failure as e:
617 code = max(code, 1)
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000618 tools.report_error(e)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000619 return code
620
621
622def CMDtrigger(parser, args):
623 """Triggers Swarm request(s).
624
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000625 Accepts one or multiple --task requests, with either the hash (sha1) of a
626 .isolated file already uploaded or the path to an .isolated file to archive,
627 packages it if needed and sends a Swarm manifest file to the Swarm server.
maruel@chromium.org0437a732013-08-27 16:05:52 +0000628 """
629 add_trigger_options(parser)
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500630 parser.task_group.add_option(
maruel@chromium.org0437a732013-08-27 16:05:52 +0000631 '--task', nargs=4, action='append', default=[], dest='tasks',
632 help='Task to trigger. The format is '
633 '(hash|isolated, test_name, shards, test_filter). This may be '
634 'used multiple times to send multiple hashes jobs. If an isolated '
635 'file is specified instead of an hash, it is first archived.')
636 (options, args) = parser.parse_args(args)
637
638 if args:
639 parser.error('Unknown args: %s' % args)
640 process_trigger_options(parser, options)
641 if not options.tasks:
642 parser.error('At least one --task is required.')
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -0500643 dimensions = {
644 'os': PLATFORM_MAPPING_SWARMING[options.os],
645 }
646 dimensions.update(dict(options.dimensions))
maruel@chromium.org0437a732013-08-27 16:05:52 +0000647
648 try:
649 return trigger(
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500650 swarming=options.swarming,
651 isolate_server=options.isolate_server,
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500652 tasks=options.tasks,
653 task_prefix=options.task_prefix,
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -0500654 dimensions=dimensions,
655 env=dict(options.env),
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500656 working_dir=options.working_dir,
657 verbose=options.verbose,
658 profile=options.profile,
659 priority=options.priority)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000660 except Failure as e:
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000661 tools.report_error(e)
662 return 1
maruel@chromium.org0437a732013-08-27 16:05:52 +0000663
664
665class OptionParserSwarming(tools.OptionParserWithLogging):
666 def __init__(self, **kwargs):
667 tools.OptionParserWithLogging.__init__(
668 self, prog='swarming.py', **kwargs)
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500669 self.server_group = tools.optparse.OptionGroup(self, 'Server')
670 self.server_group.add_option(
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000671 '-S', '--swarming',
672 metavar='URL', default='',
673 help='Swarming server to use')
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500674 self.add_option_group(self.server_group)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000675
676 def parse_args(self, *args, **kwargs):
677 options, args = tools.OptionParserWithLogging.parse_args(
678 self, *args, **kwargs)
679 options.swarming = options.swarming.rstrip('/')
680 if not options.swarming:
681 self.error('--swarming is required.')
682 return options, args
683
684
685def main(args):
686 dispatcher = subcommand.CommandDispatcher(__name__)
687 try:
688 return dispatcher.execute(OptionParserSwarming(version=__version__), args)
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000689 except Exception as e:
690 tools.report_error(e)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000691 return 1
692
693
694if __name__ == '__main__':
695 fix_encoding.fix_encoding()
696 tools.disable_buffering()
697 colorama.init()
698 sys.exit(main(sys.argv[1:]))