blob: 0485536ab9413774b2e9cc9575ded4dd8277e366 [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 Ruelb39e8cf2014-01-20 10:39:31 -05008__version__ = '0.4'
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
Vadim Shtayurae34e13a2014-02-02 11:23:26 -080029import auth
maruel@chromium.org7b844a62013-09-17 13:04:59 +000030import isolateserver
maruel@chromium.org0437a732013-08-27 16:05:52 +000031import run_isolated
32
33
34ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
35TOOLS_PATH = os.path.join(ROOT_DIR, 'tools')
36
37
maruel@chromium.org0437a732013-08-27 16:05:52 +000038# The default time to wait for a shard to finish running.
csharp@chromium.org24758492013-08-28 19:10:54 +000039DEFAULT_SHARD_WAIT_TIME = 80 * 60.
maruel@chromium.org0437a732013-08-27 16:05:52 +000040
41
42NO_OUTPUT_FOUND = (
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -050043 'No output produced by the task, it may have failed to run.\n'
maruel@chromium.org0437a732013-08-27 16:05:52 +000044 '\n')
45
46
maruel@chromium.org0437a732013-08-27 16:05:52 +000047class Failure(Exception):
48 """Generic failure."""
49 pass
50
51
52class Manifest(object):
53 """Represents a Swarming task manifest.
54
55 Also includes code to zip code and upload itself.
56 """
57 def __init__(
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -050058 self, isolate_server, isolated_hash, task_name, shards, env,
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -050059 dimensions, working_dir, verbose, profile, priority, algo):
maruel@chromium.org0437a732013-08-27 16:05:52 +000060 """Populates a manifest object.
61 Args:
Marc-Antoine Ruela7049872013-11-05 19:28:35 -050062 isolate_server - isolate server url.
maruel@chromium.org814d23f2013-10-01 19:08:00 +000063 isolated_hash - The manifest's sha-1 that the slave is going to fetch.
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -050064 task_name - The name to give the task request.
65 shards - The number of swarming shards to request.
Marc-Antoine Ruel05dab5e2013-11-06 15:06:47 -050066 env - environment variables to set.
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -050067 dimensions - dimensions to filter the task on.
maruel@chromium.org0437a732013-08-27 16:05:52 +000068 working_dir - Relative working directory to start the script.
maruel@chromium.org0437a732013-08-27 16:05:52 +000069 verbose - if True, have the slave print more details.
70 profile - if True, have the slave print more timing data.
maruel@chromium.org7b844a62013-09-17 13:04:59 +000071 priority - int between 0 and 1000, lower the higher priority.
72 algo - hashing algorithm used.
maruel@chromium.org0437a732013-08-27 16:05:52 +000073 """
Marc-Antoine Ruela7049872013-11-05 19:28:35 -050074 self.isolate_server = isolate_server
75 self.storage = isolateserver.get_storage(isolate_server, 'default')
76
maruel@chromium.org814d23f2013-10-01 19:08:00 +000077 self.isolated_hash = isolated_hash
vadimsh@chromium.org6b706212013-08-28 15:03:46 +000078 self.bundle = zip_package.ZipPackage(ROOT_DIR)
79
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -050080 self._task_name = task_name
maruel@chromium.org0437a732013-08-27 16:05:52 +000081 self._shards = shards
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -050082 self._env = env.copy()
83 self._dimensions = dimensions.copy()
maruel@chromium.org0437a732013-08-27 16:05:52 +000084 self._working_dir = working_dir
85
maruel@chromium.org0437a732013-08-27 16:05:52 +000086 self.verbose = bool(verbose)
87 self.profile = bool(profile)
88 self.priority = priority
maruel@chromium.org7b844a62013-09-17 13:04:59 +000089 self._algo = algo
maruel@chromium.org0437a732013-08-27 16:05:52 +000090
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +000091 self._isolate_item = None
maruel@chromium.org0437a732013-08-27 16:05:52 +000092 self._tasks = []
maruel@chromium.org0437a732013-08-27 16:05:52 +000093
94 def add_task(self, task_name, actions, time_out=600):
Marc-Antoine Ruelcd629732013-12-20 15:00:42 -050095 """Appends a new task to the swarming manifest file.
96
97 Tasks cannot be added once the manifest was uploaded.
98 """
99 assert not self._isolate_item
maruel@chromium.org0437a732013-08-27 16:05:52 +0000100 # See swarming/src/common/test_request_message.py TestObject constructor for
101 # the valid flags.
102 self._tasks.append(
103 {
104 'action': actions,
105 'decorate_output': self.verbose,
106 'test_name': task_name,
107 'time_out': time_out,
108 })
109
maruel@chromium.org0437a732013-08-27 16:05:52 +0000110 def to_json(self):
111 """Exports the current configuration into a swarm-readable manifest file.
112
113 This function doesn't mutate the object.
114 """
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500115 request = {
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500116 'cleanup': 'root',
maruel@chromium.org0437a732013-08-27 16:05:52 +0000117 'configurations': [
118 {
Marc-Antoine Ruel5d799192013-11-06 15:20:39 -0500119 'config_name': 'isolated',
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -0500120 'dimensions': self._dimensions,
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500121 'min_instances': self._shards,
122 'priority': self.priority,
maruel@chromium.org0437a732013-08-27 16:05:52 +0000123 },
124 ],
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500125 'data': [],
126 # TODO: Let the encoding get set from the command line.
127 'encoding': 'UTF-8',
Marc-Antoine Ruel05dab5e2013-11-06 15:06:47 -0500128 'env_vars': self._env,
maruel@chromium.org0437a732013-08-27 16:05:52 +0000129 'restart_on_failure': True,
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500130 'test_case_name': self._task_name,
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500131 'tests': self._tasks,
132 'working_dir': self._working_dir,
maruel@chromium.org0437a732013-08-27 16:05:52 +0000133 }
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000134 if self._isolate_item:
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500135 request['data'].append(
maruel@chromium.org814d23f2013-10-01 19:08:00 +0000136 [
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000137 self.storage.get_fetch_url(self._isolate_item.digest),
maruel@chromium.org814d23f2013-10-01 19:08:00 +0000138 'swarm_data.zip',
139 ])
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500140 return json.dumps(request, sort_keys=True, separators=(',',':'))
maruel@chromium.org0437a732013-08-27 16:05:52 +0000141
Marc-Antoine Ruelcd629732013-12-20 15:00:42 -0500142 @property
143 def isolate_item(self):
144 """Calling this property 'closes' the manifest and it can't be modified
145 afterward.
146 """
147 if self._isolate_item is None:
148 self._isolate_item = isolateserver.BufferItem(
149 self.bundle.zip_into_buffer(), self._algo, is_isolated=True)
150 return self._isolate_item
151
152
153def zip_and_upload(manifest):
154 """Zips up all the files necessary to run a manifest and uploads to Swarming
155 master.
156 """
157 try:
158 start_time = time.time()
159 with manifest.storage:
160 uploaded = manifest.storage.upload_items([manifest.isolate_item])
161 elapsed = time.time() - start_time
162 except (IOError, OSError) as exc:
163 tools.report_error('Failed to upload the zip file: %s' % exc)
164 return False
165
166 if manifest.isolate_item in uploaded:
167 logging.info('Upload complete, time elapsed: %f', elapsed)
168 else:
169 logging.info('Zip file already on server, time elapsed: %f', elapsed)
170 return True
171
maruel@chromium.org0437a732013-08-27 16:05:52 +0000172
173def now():
174 """Exists so it can be mocked easily."""
175 return time.time()
176
177
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500178def get_task_keys(swarm_base_url, task_name):
179 """Returns the Swarming task key for each shards of task_name."""
180 key_data = urllib.urlencode([('name', task_name)])
maruel@chromium.org0437a732013-08-27 16:05:52 +0000181 url = '%s/get_matching_test_cases?%s' % (swarm_base_url, key_data)
182
vadimsh@chromium.org043b76d2013-09-12 16:15:13 +0000183 for _ in net.retry_loop(max_attempts=net.URL_OPEN_MAX_ATTEMPTS):
184 result = net.url_read(url, retry_404=True)
185 if result is None:
maruel@chromium.org0437a732013-08-27 16:05:52 +0000186 raise Failure(
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500187 'Error: Unable to find any task with the name, %s, on swarming server'
188 % task_name)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000189
maruel@chromium.org0437a732013-08-27 16:05:52 +0000190 # TODO(maruel): Compare exact string.
191 if 'No matching' in result:
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500192 logging.warning('Unable to find any task with the name, %s, on swarming '
193 'server' % task_name)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000194 continue
195 return json.loads(result)
196
197 raise Failure(
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500198 'Error: Unable to find any task with the name, %s, on swarming server'
199 % task_name)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000200
201
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500202def retrieve_results(base_url, task_key, timeout, should_stop):
203 """Retrieves results for a single task_key."""
maruel@chromium.org814d23f2013-10-01 19:08:00 +0000204 assert isinstance(timeout, float), timeout
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500205 params = [('r', task_key)]
maruel@chromium.org0437a732013-08-27 16:05:52 +0000206 result_url = '%s/get_result?%s' % (base_url, urllib.urlencode(params))
207 start = now()
208 while True:
209 if timeout and (now() - start) >= timeout:
210 logging.error('retrieve_results(%s) timed out', base_url)
211 return {}
212 # Do retries ourselves.
vadimsh@chromium.org043b76d2013-09-12 16:15:13 +0000213 response = net.url_read(result_url, retry_404=False, retry_50x=False)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000214 if response is None:
215 # Aggressively poll for results. Do not use retry_404 so
216 # should_stop is polled more often.
217 remaining = min(5, timeout - (now() - start)) if timeout else 5
218 if remaining > 0:
maruel@chromium.org814d23f2013-10-01 19:08:00 +0000219 if should_stop.get():
220 return {}
vadimsh@chromium.org043b76d2013-09-12 16:15:13 +0000221 net.sleep_before_retry(1, remaining)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000222 else:
223 try:
vadimsh@chromium.org043b76d2013-09-12 16:15:13 +0000224 data = json.loads(response) or {}
maruel@chromium.org0437a732013-08-27 16:05:52 +0000225 except (ValueError, TypeError):
226 logging.warning(
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500227 'Received corrupted data for task_key %s. Retrying.', task_key)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000228 else:
229 if data['output']:
230 return data
231 if should_stop.get():
232 return {}
233
234
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500235def yield_results(swarm_base_url, task_keys, timeout, max_threads):
236 """Yields swarming task results from the swarming server as (index, result).
maruel@chromium.org0437a732013-08-27 16:05:52 +0000237
238 Duplicate shards are ignored, the first one to complete is returned.
239
240 max_threads is optional and is used to limit the number of parallel fetches
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500241 done. Since in general the number of task_keys is in the range <=10, it's not
maruel@chromium.org0437a732013-08-27 16:05:52 +0000242 worth normally to limit the number threads. Mostly used for testing purposes.
243 """
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500244 shards_remaining = range(len(task_keys))
maruel@chromium.org0437a732013-08-27 16:05:52 +0000245 number_threads = (
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500246 min(max_threads, len(task_keys)) if max_threads else len(task_keys))
maruel@chromium.org0437a732013-08-27 16:05:52 +0000247 should_stop = threading_utils.Bit()
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500248 results_remaining = len(task_keys)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000249 with threading_utils.ThreadPool(number_threads, number_threads, 0) as pool:
250 try:
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500251 for task_key in task_keys:
maruel@chromium.org0437a732013-08-27 16:05:52 +0000252 pool.add_task(
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500253 0, retrieve_results, swarm_base_url, task_key, timeout, should_stop)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000254 while shards_remaining and results_remaining:
255 result = pool.get_one_result()
256 results_remaining -= 1
257 if not result:
258 # Failed to retrieve one key.
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500259 logging.error('Failed to retrieve the results for a swarming key')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000260 continue
261 shard_index = result['config_instance_index']
262 if shard_index in shards_remaining:
263 shards_remaining.remove(shard_index)
264 yield shard_index, result
265 else:
266 logging.warning('Ignoring duplicate shard index %d', shard_index)
267 # Pop the last entry, there's no such shard.
268 shards_remaining.pop()
269 finally:
270 # Done, kill the remaining threads.
271 should_stop.set()
272
273
274def chromium_setup(manifest):
275 """Sets up the commands to run.
276
277 Highly chromium specific.
278 """
vadimsh@chromium.org6b706212013-08-28 15:03:46 +0000279 # Add uncompressed zip here. It'll be compressed as part of the package sent
280 # to Swarming server.
281 run_test_name = 'run_isolated.zip'
282 manifest.bundle.add_buffer(run_test_name,
283 run_isolated.get_as_zip_package().zip_into_buffer(compress=False))
maruel@chromium.org0437a732013-08-27 16:05:52 +0000284
vadimsh@chromium.org6b706212013-08-28 15:03:46 +0000285 cleanup_script_name = 'swarm_cleanup.py'
286 manifest.bundle.add_file(os.path.join(TOOLS_PATH, cleanup_script_name),
287 cleanup_script_name)
288
maruel@chromium.org0437a732013-08-27 16:05:52 +0000289 run_cmd = [
290 'python', run_test_name,
maruel@chromium.org814d23f2013-10-01 19:08:00 +0000291 '--hash', manifest.isolated_hash,
maruel@chromium.orgb7e79a22013-09-13 01:24:56 +0000292 '--isolate-server', manifest.isolate_server,
maruel@chromium.org0437a732013-08-27 16:05:52 +0000293 ]
294 if manifest.verbose or manifest.profile:
295 # Have it print the profiling section.
296 run_cmd.append('--verbose')
297 manifest.add_task('Run Test', run_cmd)
298
299 # Clean up
300 manifest.add_task('Clean Up', ['python', cleanup_script_name])
301
302
Marc-Antoine Ruelcd629732013-12-20 15:00:42 -0500303def googletest_setup(env, shards):
304 """Sets googletest specific environment variables."""
305 if shards > 1:
306 env = env.copy()
307 env['GTEST_SHARD_INDEX'] = '%(instance_index)s'
308 env['GTEST_TOTAL_SHARDS'] = '%(num_instances)s'
309 return env
310
311
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500312def archive(isolate_server, isolated, algo, verbose):
maruel@chromium.org0437a732013-08-27 16:05:52 +0000313 """Archives a .isolated and all the dependencies on the CAC."""
314 tempdir = None
315 try:
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500316 logging.info('archive(%s, %s)', isolate_server, isolated)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000317 cmd = [
318 sys.executable,
319 os.path.join(ROOT_DIR, 'isolate.py'),
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000320 'archive',
Marc-Antoine Ruel2b13f612014-01-31 13:59:59 -0500321 '--isolate-server', isolate_server,
maruel@chromium.org0437a732013-08-27 16:05:52 +0000322 '--isolated', isolated,
323 ]
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000324 cmd.extend(['--verbose'] * verbose)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000325 logging.info(' '.join(cmd))
326 if subprocess.call(cmd, verbose):
327 return
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000328 return isolateserver.hash_file(isolated, algo)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000329 finally:
330 if tempdir:
331 shutil.rmtree(tempdir)
332
333
334def process_manifest(
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500335 swarming, isolate_server, isolated_hash, task_name, shards,
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -0500336 dimensions, env, working_dir, verbose, profile, priority, algo):
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500337 """Processes the manifest file and send off the swarming task request."""
maruel@chromium.org0437a732013-08-27 16:05:52 +0000338 try:
339 manifest = Manifest(
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500340 isolate_server=isolate_server,
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500341 isolated_hash=isolated_hash,
342 task_name=task_name,
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500343 shards=shards,
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -0500344 dimensions=dimensions,
Marc-Antoine Ruel05dab5e2013-11-06 15:06:47 -0500345 env=env,
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500346 working_dir=working_dir,
347 verbose=verbose,
348 profile=profile,
349 priority=priority,
350 algo=algo)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000351 except ValueError as e:
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500352 tools.report_error('Unable to process %s: %s' % (task_name, e))
maruel@chromium.org0437a732013-08-27 16:05:52 +0000353 return 1
354
355 chromium_setup(manifest)
356
Marc-Antoine Ruelcd629732013-12-20 15:00:42 -0500357 logging.info('Zipping up files...')
358 if not zip_and_upload(manifest):
maruel@chromium.org0437a732013-08-27 16:05:52 +0000359 return 1
360
Marc-Antoine Ruelcd629732013-12-20 15:00:42 -0500361 logging.info('Server: %s', swarming)
362 logging.info('Task name: %s', task_name)
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500363 trigger_url = swarming + '/test'
maruel@chromium.org0437a732013-08-27 16:05:52 +0000364 manifest_text = manifest.to_json()
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500365 result = net.url_read(trigger_url, data={'request': manifest_text})
maruel@chromium.org0437a732013-08-27 16:05:52 +0000366 if not result:
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000367 tools.report_error(
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500368 'Failed to trigger task %s\n%s' % (task_name, trigger_url))
maruel@chromium.org0437a732013-08-27 16:05:52 +0000369 return 1
370 try:
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000371 json.loads(result)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000372 except (ValueError, TypeError) as e:
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000373 msg = '\n'.join((
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500374 'Failed to trigger task %s' % task_name,
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000375 'Manifest: %s' % manifest_text,
376 'Bad response: %s' % result,
377 str(e)))
378 tools.report_error(msg)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000379 return 1
380 return 0
381
382
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500383def isolated_to_hash(isolate_server, arg, algo, verbose):
384 """Archives a .isolated file if needed.
385
386 Returns the file hash to trigger.
387 """
388 if arg.endswith('.isolated'):
389 file_hash = archive(isolate_server, arg, algo, verbose)
390 if not file_hash:
391 tools.report_error('Archival failure %s' % arg)
392 return None
393 return file_hash
394 elif isolateserver.is_valid_hash(arg, algo):
395 return arg
396 else:
397 tools.report_error('Invalid hash %s' % arg)
398 return None
399
400
maruel@chromium.org0437a732013-08-27 16:05:52 +0000401def trigger(
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500402 swarming,
403 isolate_server,
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500404 file_hash_or_isolated,
405 task_name,
406 shards,
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -0500407 dimensions,
408 env,
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500409 working_dir,
maruel@chromium.org0437a732013-08-27 16:05:52 +0000410 verbose,
411 profile,
412 priority):
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500413 """Sends off the hash swarming task requests."""
414 file_hash = isolated_to_hash(
415 isolate_server, file_hash_or_isolated, hashlib.sha1, verbose)
416 if not file_hash:
417 return 1
Marc-Antoine Ruelcd629732013-12-20 15:00:42 -0500418 env = googletest_setup(env, shards)
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500419 # TODO(maruel): It should first create a request manifest object, then pass
420 # it to a function to zip, archive and trigger.
421 return process_manifest(
422 swarming=swarming,
423 isolate_server=isolate_server,
424 isolated_hash=file_hash,
425 task_name=task_name,
426 shards=shards,
427 dimensions=dimensions,
428 env=env,
429 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
435
436def decorate_shard_output(result, shard_exit_code):
437 """Returns wrapped output for swarming task shard."""
438 tag = 'index %s (machine tag: %s, id: %s)' % (
439 result['config_instance_index'],
440 result['machine_id'],
441 result.get('machine_tag', 'unknown'))
442 return (
443 '\n'
444 '================================================================\n'
445 'Begin output from shard %s\n'
446 '================================================================\n'
447 '\n'
448 '%s'
449 '================================================================\n'
450 'End output from shard %s. Return %d\n'
451 '================================================================\n'
452 ) % (tag, result['output'] or NO_OUTPUT_FOUND, tag, shard_exit_code)
453
454
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500455def collect(url, task_name, timeout, decorate):
456 """Retrieves results of a Swarming task."""
457 logging.info('Collecting %s', task_name)
458 task_keys = get_task_keys(url, task_name)
459 if not task_keys:
460 raise Failure('No task keys to get results with.')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000461
maruel@chromium.org9c1c7b52013-08-28 19:04:36 +0000462 exit_code = None
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500463 for _index, output in yield_results(url, task_keys, timeout, None):
maruel@chromium.org0437a732013-08-27 16:05:52 +0000464 shard_exit_codes = (output['exit_codes'] or '1').split(',')
465 shard_exit_code = max(int(i) for i in shard_exit_codes)
466 if decorate:
467 print decorate_shard_output(output, shard_exit_code)
468 else:
469 print(
470 '%s/%s: %s' % (
471 output['machine_id'],
472 output['machine_tag'],
473 output['exit_codes']))
474 print(''.join(' %s\n' % l for l in output['output'].splitlines()))
maruel@chromium.org9c1c7b52013-08-28 19:04:36 +0000475 exit_code = exit_code or shard_exit_code
476 return exit_code if exit_code is not None else 1
maruel@chromium.org0437a732013-08-27 16:05:52 +0000477
478
479def add_trigger_options(parser):
480 """Adds all options to trigger a task on Swarming."""
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500481 parser.server_group.add_option(
maruel@chromium.org0437a732013-08-27 16:05:52 +0000482 '-I', '--isolate-server',
Kevin Graney5346c162014-01-24 12:20:01 -0500483 metavar='URL', default=os.environ.get('ISOLATE_SERVER', ''),
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000484 help='Isolate server to use')
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500485
486 parser.filter_group = tools.optparse.OptionGroup(parser, 'Filtering slaves')
487 parser.filter_group.add_option(
Marc-Antoine Ruelb39e8cf2014-01-20 10:39:31 -0500488 '-d', '--dimension', default=[], action='append', nargs=2,
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -0500489 dest='dimensions', metavar='FOO bar',
490 help='dimension to filter on')
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500491 parser.add_option_group(parser.filter_group)
492
493 parser.task_group = tools.optparse.OptionGroup(parser, 'Task properties')
494 parser.task_group.add_option(
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500495 '-w', '--working-dir', default='swarm_tests',
496 help='Working directory on the swarming slave side. default: %default.')
497 parser.task_group.add_option(
498 '--working_dir', help=tools.optparse.SUPPRESS_HELP)
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500499 parser.task_group.add_option(
500 '-e', '--env', default=[], action='append', nargs=2, metavar='FOO bar',
501 help='environment variables to set')
502 parser.task_group.add_option(
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500503 '--priority', type='int', default=100,
504 help='The lower value, the more important the task is')
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500505 parser.task_group.add_option(
506 '--shards', type='int', default=1, help='number of shards to use')
507 parser.task_group.add_option(
508 '-T', '--task-name', help='display name of the task')
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500509 parser.add_option_group(parser.task_group)
Marc-Antoine Ruelcd629732013-12-20 15:00:42 -0500510 # TODO(maruel): This is currently written in a chromium-specific way.
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500511 parser.group_logging.add_option(
maruel@chromium.org0437a732013-08-27 16:05:52 +0000512 '--profile', action='store_true',
513 default=bool(os.environ.get('ISOLATE_DEBUG')),
514 help='Have run_isolated.py print profiling info')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000515
516
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500517def process_trigger_options(parser, options, args):
maruel@chromium.org0437a732013-08-27 16:05:52 +0000518 options.isolate_server = options.isolate_server.rstrip('/')
519 if not options.isolate_server:
520 parser.error('--isolate-server is required.')
Marc-Antoine Ruel4d8093d2014-01-31 15:07:11 -0500521 if not options.task_name:
522 parser.error(
523 '--task-name is required. It should be <base_name>/<OS>/<isolated>')
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500524 if len(args) != 1:
525 parser.error('Must pass one .isolated file or its hash (sha1).')
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500526 options.dimensions = dict(options.dimensions)
Marc-Antoine Ruelb39e8cf2014-01-20 10:39:31 -0500527 if not options.dimensions.get('os'):
528 parser.error(
529 'Please at least specify the dimension of the swarming bot OS with '
530 '--dimension os <something>.')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000531
532
533def add_collect_options(parser):
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500534 parser.server_group.add_option(
maruel@chromium.org0437a732013-08-27 16:05:52 +0000535 '-t', '--timeout',
536 type='float',
537 default=DEFAULT_SHARD_WAIT_TIME,
538 help='Timeout to wait for result, set to 0 for no timeout; default: '
539 '%default s')
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500540 parser.group_logging.add_option(
541 '--decorate', action='store_true', help='Decorate output')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000542
543
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500544@subcommand.usage('task_name')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000545def CMDcollect(parser, args):
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500546 """Retrieves results of a Swarming task.
maruel@chromium.org0437a732013-08-27 16:05:52 +0000547
548 The result can be in multiple part if the execution was sharded. It can
549 potentially have retries.
550 """
551 add_collect_options(parser)
552 (options, args) = parser.parse_args(args)
553 if not args:
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500554 parser.error('Must specify one task name.')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000555 elif len(args) > 1:
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500556 parser.error('Must specify only one task name.')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000557
558 try:
559 return collect(options.swarming, args[0], options.timeout, options.decorate)
560 except Failure as e:
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000561 tools.report_error(e)
562 return 1
maruel@chromium.org0437a732013-08-27 16:05:52 +0000563
564
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500565@subcommand.usage('[hash|isolated]')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000566def CMDrun(parser, args):
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500567 """Triggers a task and wait for the results.
maruel@chromium.org0437a732013-08-27 16:05:52 +0000568
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500569 Basically, does everything to run a command remotely.
maruel@chromium.org0437a732013-08-27 16:05:52 +0000570 """
571 add_trigger_options(parser)
572 add_collect_options(parser)
573 options, args = parser.parse_args(args)
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500574 process_trigger_options(parser, options, args)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000575
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500576 try:
577 result = trigger(
578 swarming=options.swarming,
579 isolate_server=options.isolate_server,
580 file_hash_or_isolated=args[0],
581 task_name=options.task_name,
582 shards=options.shards,
583 dimensions=options.dimensions,
584 env=dict(options.env),
585 working_dir=options.working_dir,
586 verbose=options.verbose,
587 profile=options.profile,
588 priority=options.priority)
589 except Failure as e:
590 tools.report_error(
591 'Failed to trigger %s(%s): %s' %
592 (options.task_name, args[0], e.args[0]))
593 return 1
594 if result:
595 tools.report_error('Failed to trigger the task.')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000596 return result
597
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500598 try:
599 return collect(
600 options.swarming,
601 options.task_name,
602 options.timeout,
603 options.decorate)
604 except Failure as e:
605 tools.report_error(e)
606 return 1
maruel@chromium.org0437a732013-08-27 16:05:52 +0000607
608
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500609@subcommand.usage("(hash|isolated)")
maruel@chromium.org0437a732013-08-27 16:05:52 +0000610def CMDtrigger(parser, args):
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500611 """Triggers a Swarming task.
maruel@chromium.org0437a732013-08-27 16:05:52 +0000612
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500613 Accepts either the hash (sha1) of a .isolated file already uploaded or the
614 path to an .isolated file to archive, packages it if needed and sends a
615 Swarming manifest file to the Swarming server.
616
617 If an .isolated file is specified instead of an hash, it is first archived.
maruel@chromium.org0437a732013-08-27 16:05:52 +0000618 """
619 add_trigger_options(parser)
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500620 options, args = parser.parse_args(args)
621 process_trigger_options(parser, options, args)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000622
623 try:
624 return trigger(
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500625 swarming=options.swarming,
626 isolate_server=options.isolate_server,
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500627 file_hash_or_isolated=args[0],
628 task_name=options.task_name,
629 dimensions=options.dimensions,
630 shards=options.shards,
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -0500631 env=dict(options.env),
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500632 working_dir=options.working_dir,
633 verbose=options.verbose,
634 profile=options.profile,
635 priority=options.priority)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000636 except Failure as e:
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000637 tools.report_error(e)
638 return 1
maruel@chromium.org0437a732013-08-27 16:05:52 +0000639
640
641class OptionParserSwarming(tools.OptionParserWithLogging):
642 def __init__(self, **kwargs):
643 tools.OptionParserWithLogging.__init__(
644 self, prog='swarming.py', **kwargs)
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500645 self.server_group = tools.optparse.OptionGroup(self, 'Server')
646 self.server_group.add_option(
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000647 '-S', '--swarming',
Kevin Graney5346c162014-01-24 12:20:01 -0500648 metavar='URL', default=os.environ.get('SWARMING_SERVER', ''),
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000649 help='Swarming server to use')
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500650 self.add_option_group(self.server_group)
Vadim Shtayurae34e13a2014-02-02 11:23:26 -0800651 auth.add_auth_options(self)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000652
653 def parse_args(self, *args, **kwargs):
654 options, args = tools.OptionParserWithLogging.parse_args(
655 self, *args, **kwargs)
656 options.swarming = options.swarming.rstrip('/')
657 if not options.swarming:
658 self.error('--swarming is required.')
Vadim Shtayura5d1efce2014-02-04 10:55:43 -0800659 auth.process_auth_options(self, options)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000660 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:]))