blob: 4c65e8945da36b2574a064919e2dde239cba0a08 [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 Ruel7c543272013-11-26 13:26:15 -05008__version__ = '0.3'
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 = (
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -050042 'No output produced by the task, it may have failed to run.\n'
maruel@chromium.org0437a732013-08-27 16:05:52 +000043 '\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 Ruel7c543272013-11-26 13:26:15 -050073 self, isolate_server, isolated_hash, task_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.
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -050079 task_name - The name to give the task request.
80 shards - The number of swarming 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
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -050095 self._task_name = task_name
maruel@chromium.org0437a732013-08-27 16:05:52 +000096 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):
Marc-Antoine Ruelcd629732013-12-20 15:00:42 -0500110 """Appends a new task to the swarming manifest file.
111
112 Tasks cannot be added once the manifest was uploaded.
113 """
114 assert not self._isolate_item
maruel@chromium.org0437a732013-08-27 16:05:52 +0000115 # See swarming/src/common/test_request_message.py TestObject constructor for
116 # the valid flags.
117 self._tasks.append(
118 {
119 'action': actions,
120 'decorate_output': self.verbose,
121 'test_name': task_name,
122 'time_out': time_out,
123 })
124
maruel@chromium.org0437a732013-08-27 16:05:52 +0000125 def to_json(self):
126 """Exports the current configuration into a swarm-readable manifest file.
127
128 This function doesn't mutate the object.
129 """
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500130 request = {
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500131 'cleanup': 'root',
maruel@chromium.org0437a732013-08-27 16:05:52 +0000132 'configurations': [
133 {
Marc-Antoine Ruel5d799192013-11-06 15:20:39 -0500134 'config_name': 'isolated',
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -0500135 'dimensions': self._dimensions,
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500136 'min_instances': self._shards,
137 'priority': self.priority,
maruel@chromium.org0437a732013-08-27 16:05:52 +0000138 },
139 ],
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500140 'data': [],
141 # TODO: Let the encoding get set from the command line.
142 'encoding': 'UTF-8',
Marc-Antoine Ruel05dab5e2013-11-06 15:06:47 -0500143 'env_vars': self._env,
maruel@chromium.org0437a732013-08-27 16:05:52 +0000144 'restart_on_failure': True,
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500145 'test_case_name': self._task_name,
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500146 'tests': self._tasks,
147 'working_dir': self._working_dir,
maruel@chromium.org0437a732013-08-27 16:05:52 +0000148 }
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000149 if self._isolate_item:
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500150 request['data'].append(
maruel@chromium.org814d23f2013-10-01 19:08:00 +0000151 [
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000152 self.storage.get_fetch_url(self._isolate_item.digest),
maruel@chromium.org814d23f2013-10-01 19:08:00 +0000153 'swarm_data.zip',
154 ])
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500155 return json.dumps(request, sort_keys=True, separators=(',',':'))
maruel@chromium.org0437a732013-08-27 16:05:52 +0000156
Marc-Antoine Ruelcd629732013-12-20 15:00:42 -0500157 @property
158 def isolate_item(self):
159 """Calling this property 'closes' the manifest and it can't be modified
160 afterward.
161 """
162 if self._isolate_item is None:
163 self._isolate_item = isolateserver.BufferItem(
164 self.bundle.zip_into_buffer(), self._algo, is_isolated=True)
165 return self._isolate_item
166
167
168def zip_and_upload(manifest):
169 """Zips up all the files necessary to run a manifest and uploads to Swarming
170 master.
171 """
172 try:
173 start_time = time.time()
174 with manifest.storage:
175 uploaded = manifest.storage.upload_items([manifest.isolate_item])
176 elapsed = time.time() - start_time
177 except (IOError, OSError) as exc:
178 tools.report_error('Failed to upload the zip file: %s' % exc)
179 return False
180
181 if manifest.isolate_item in uploaded:
182 logging.info('Upload complete, time elapsed: %f', elapsed)
183 else:
184 logging.info('Zip file already on server, time elapsed: %f', elapsed)
185 return True
186
maruel@chromium.org0437a732013-08-27 16:05:52 +0000187
188def now():
189 """Exists so it can be mocked easily."""
190 return time.time()
191
192
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500193def get_task_keys(swarm_base_url, task_name):
194 """Returns the Swarming task key for each shards of task_name."""
195 key_data = urllib.urlencode([('name', task_name)])
maruel@chromium.org0437a732013-08-27 16:05:52 +0000196 url = '%s/get_matching_test_cases?%s' % (swarm_base_url, key_data)
197
vadimsh@chromium.org043b76d2013-09-12 16:15:13 +0000198 for _ in net.retry_loop(max_attempts=net.URL_OPEN_MAX_ATTEMPTS):
199 result = net.url_read(url, retry_404=True)
200 if result is None:
maruel@chromium.org0437a732013-08-27 16:05:52 +0000201 raise Failure(
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500202 'Error: Unable to find any task with the name, %s, on swarming server'
203 % task_name)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000204
maruel@chromium.org0437a732013-08-27 16:05:52 +0000205 # TODO(maruel): Compare exact string.
206 if 'No matching' in result:
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500207 logging.warning('Unable to find any task with the name, %s, on swarming '
208 'server' % task_name)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000209 continue
210 return json.loads(result)
211
212 raise Failure(
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500213 'Error: Unable to find any task with the name, %s, on swarming server'
214 % task_name)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000215
216
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500217def retrieve_results(base_url, task_key, timeout, should_stop):
218 """Retrieves results for a single task_key."""
maruel@chromium.org814d23f2013-10-01 19:08:00 +0000219 assert isinstance(timeout, float), timeout
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500220 params = [('r', task_key)]
maruel@chromium.org0437a732013-08-27 16:05:52 +0000221 result_url = '%s/get_result?%s' % (base_url, urllib.urlencode(params))
222 start = now()
223 while True:
224 if timeout and (now() - start) >= timeout:
225 logging.error('retrieve_results(%s) timed out', base_url)
226 return {}
227 # Do retries ourselves.
vadimsh@chromium.org043b76d2013-09-12 16:15:13 +0000228 response = net.url_read(result_url, retry_404=False, retry_50x=False)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000229 if response is None:
230 # Aggressively poll for results. Do not use retry_404 so
231 # should_stop is polled more often.
232 remaining = min(5, timeout - (now() - start)) if timeout else 5
233 if remaining > 0:
maruel@chromium.org814d23f2013-10-01 19:08:00 +0000234 if should_stop.get():
235 return {}
vadimsh@chromium.org043b76d2013-09-12 16:15:13 +0000236 net.sleep_before_retry(1, remaining)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000237 else:
238 try:
vadimsh@chromium.org043b76d2013-09-12 16:15:13 +0000239 data = json.loads(response) or {}
maruel@chromium.org0437a732013-08-27 16:05:52 +0000240 except (ValueError, TypeError):
241 logging.warning(
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500242 'Received corrupted data for task_key %s. Retrying.', task_key)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000243 else:
244 if data['output']:
245 return data
246 if should_stop.get():
247 return {}
248
249
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500250def yield_results(swarm_base_url, task_keys, timeout, max_threads):
251 """Yields swarming task results from the swarming server as (index, result).
maruel@chromium.org0437a732013-08-27 16:05:52 +0000252
253 Duplicate shards are ignored, the first one to complete is returned.
254
255 max_threads is optional and is used to limit the number of parallel fetches
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500256 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 +0000257 worth normally to limit the number threads. Mostly used for testing purposes.
258 """
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500259 shards_remaining = range(len(task_keys))
maruel@chromium.org0437a732013-08-27 16:05:52 +0000260 number_threads = (
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500261 min(max_threads, len(task_keys)) if max_threads else len(task_keys))
maruel@chromium.org0437a732013-08-27 16:05:52 +0000262 should_stop = threading_utils.Bit()
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500263 results_remaining = len(task_keys)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000264 with threading_utils.ThreadPool(number_threads, number_threads, 0) as pool:
265 try:
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500266 for task_key in task_keys:
maruel@chromium.org0437a732013-08-27 16:05:52 +0000267 pool.add_task(
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500268 0, retrieve_results, swarm_base_url, task_key, timeout, should_stop)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000269 while shards_remaining and results_remaining:
270 result = pool.get_one_result()
271 results_remaining -= 1
272 if not result:
273 # Failed to retrieve one key.
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500274 logging.error('Failed to retrieve the results for a swarming key')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000275 continue
276 shard_index = result['config_instance_index']
277 if shard_index in shards_remaining:
278 shards_remaining.remove(shard_index)
279 yield shard_index, result
280 else:
281 logging.warning('Ignoring duplicate shard index %d', shard_index)
282 # Pop the last entry, there's no such shard.
283 shards_remaining.pop()
284 finally:
285 # Done, kill the remaining threads.
286 should_stop.set()
287
288
289def chromium_setup(manifest):
290 """Sets up the commands to run.
291
292 Highly chromium specific.
293 """
vadimsh@chromium.org6b706212013-08-28 15:03:46 +0000294 # Add uncompressed zip here. It'll be compressed as part of the package sent
295 # to Swarming server.
296 run_test_name = 'run_isolated.zip'
297 manifest.bundle.add_buffer(run_test_name,
298 run_isolated.get_as_zip_package().zip_into_buffer(compress=False))
maruel@chromium.org0437a732013-08-27 16:05:52 +0000299
vadimsh@chromium.org6b706212013-08-28 15:03:46 +0000300 cleanup_script_name = 'swarm_cleanup.py'
301 manifest.bundle.add_file(os.path.join(TOOLS_PATH, cleanup_script_name),
302 cleanup_script_name)
303
maruel@chromium.org0437a732013-08-27 16:05:52 +0000304 run_cmd = [
305 'python', run_test_name,
maruel@chromium.org814d23f2013-10-01 19:08:00 +0000306 '--hash', manifest.isolated_hash,
maruel@chromium.orgb7e79a22013-09-13 01:24:56 +0000307 '--isolate-server', manifest.isolate_server,
maruel@chromium.org0437a732013-08-27 16:05:52 +0000308 ]
309 if manifest.verbose or manifest.profile:
310 # Have it print the profiling section.
311 run_cmd.append('--verbose')
312 manifest.add_task('Run Test', run_cmd)
313
314 # Clean up
315 manifest.add_task('Clean Up', ['python', cleanup_script_name])
316
317
Marc-Antoine Ruelcd629732013-12-20 15:00:42 -0500318def googletest_setup(env, shards):
319 """Sets googletest specific environment variables."""
320 if shards > 1:
321 env = env.copy()
322 env['GTEST_SHARD_INDEX'] = '%(instance_index)s'
323 env['GTEST_TOTAL_SHARDS'] = '%(num_instances)s'
324 return env
325
326
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500327def archive(isolate_server, isolated, algo, verbose):
maruel@chromium.org0437a732013-08-27 16:05:52 +0000328 """Archives a .isolated and all the dependencies on the CAC."""
329 tempdir = None
330 try:
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500331 logging.info('archive(%s, %s)', isolate_server, isolated)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000332 cmd = [
333 sys.executable,
334 os.path.join(ROOT_DIR, 'isolate.py'),
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000335 'archive',
maruel@chromium.org0437a732013-08-27 16:05:52 +0000336 '--outdir', isolate_server,
337 '--isolated', isolated,
338 ]
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000339 cmd.extend(['--verbose'] * verbose)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000340 logging.info(' '.join(cmd))
341 if subprocess.call(cmd, verbose):
342 return
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000343 return isolateserver.hash_file(isolated, algo)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000344 finally:
345 if tempdir:
346 shutil.rmtree(tempdir)
347
348
349def process_manifest(
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500350 swarming, isolate_server, isolated_hash, task_name, shards,
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -0500351 dimensions, env, working_dir, verbose, profile, priority, algo):
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500352 """Processes the manifest file and send off the swarming task request."""
maruel@chromium.org0437a732013-08-27 16:05:52 +0000353 try:
354 manifest = Manifest(
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500355 isolate_server=isolate_server,
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500356 isolated_hash=isolated_hash,
357 task_name=task_name,
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500358 shards=shards,
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -0500359 dimensions=dimensions,
Marc-Antoine Ruel05dab5e2013-11-06 15:06:47 -0500360 env=env,
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500361 working_dir=working_dir,
362 verbose=verbose,
363 profile=profile,
364 priority=priority,
365 algo=algo)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000366 except ValueError as e:
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500367 tools.report_error('Unable to process %s: %s' % (task_name, e))
maruel@chromium.org0437a732013-08-27 16:05:52 +0000368 return 1
369
370 chromium_setup(manifest)
371
Marc-Antoine Ruelcd629732013-12-20 15:00:42 -0500372 logging.info('Zipping up files...')
373 if not zip_and_upload(manifest):
maruel@chromium.org0437a732013-08-27 16:05:52 +0000374 return 1
375
Marc-Antoine Ruelcd629732013-12-20 15:00:42 -0500376 logging.info('Server: %s', swarming)
377 logging.info('Task name: %s', task_name)
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500378 trigger_url = swarming + '/test'
maruel@chromium.org0437a732013-08-27 16:05:52 +0000379 manifest_text = manifest.to_json()
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500380 result = net.url_read(trigger_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(
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500383 'Failed to trigger task %s\n%s' % (task_name, trigger_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((
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500389 'Failed to trigger task %s' % task_name,
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000390 '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
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500398def isolated_to_hash(isolate_server, arg, algo, verbose):
399 """Archives a .isolated file if needed.
400
401 Returns the file hash to trigger.
402 """
403 if arg.endswith('.isolated'):
404 file_hash = archive(isolate_server, arg, algo, verbose)
405 if not file_hash:
406 tools.report_error('Archival failure %s' % arg)
407 return None
408 return file_hash
409 elif isolateserver.is_valid_hash(arg, algo):
410 return arg
411 else:
412 tools.report_error('Invalid hash %s' % arg)
413 return None
414
415
maruel@chromium.org0437a732013-08-27 16:05:52 +0000416def trigger(
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500417 swarming,
418 isolate_server,
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500419 file_hash_or_isolated,
420 task_name,
421 shards,
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -0500422 dimensions,
423 env,
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500424 working_dir,
maruel@chromium.org0437a732013-08-27 16:05:52 +0000425 verbose,
426 profile,
427 priority):
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500428 """Sends off the hash swarming task requests."""
429 file_hash = isolated_to_hash(
430 isolate_server, file_hash_or_isolated, hashlib.sha1, verbose)
431 if not file_hash:
432 return 1
Marc-Antoine Ruelcd629732013-12-20 15:00:42 -0500433 env = googletest_setup(env, shards)
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500434 # TODO(maruel): It should first create a request manifest object, then pass
435 # it to a function to zip, archive and trigger.
436 return process_manifest(
437 swarming=swarming,
438 isolate_server=isolate_server,
439 isolated_hash=file_hash,
440 task_name=task_name,
441 shards=shards,
442 dimensions=dimensions,
443 env=env,
444 working_dir=working_dir,
445 verbose=verbose,
446 profile=profile,
447 priority=priority,
448 algo=hashlib.sha1)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000449
450
451def decorate_shard_output(result, shard_exit_code):
452 """Returns wrapped output for swarming task shard."""
453 tag = 'index %s (machine tag: %s, id: %s)' % (
454 result['config_instance_index'],
455 result['machine_id'],
456 result.get('machine_tag', 'unknown'))
457 return (
458 '\n'
459 '================================================================\n'
460 'Begin output from shard %s\n'
461 '================================================================\n'
462 '\n'
463 '%s'
464 '================================================================\n'
465 'End output from shard %s. Return %d\n'
466 '================================================================\n'
467 ) % (tag, result['output'] or NO_OUTPUT_FOUND, tag, shard_exit_code)
468
469
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500470def collect(url, task_name, timeout, decorate):
471 """Retrieves results of a Swarming task."""
472 logging.info('Collecting %s', task_name)
473 task_keys = get_task_keys(url, task_name)
474 if not task_keys:
475 raise Failure('No task keys to get results with.')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000476
maruel@chromium.org9c1c7b52013-08-28 19:04:36 +0000477 exit_code = None
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500478 for _index, output in yield_results(url, task_keys, timeout, None):
maruel@chromium.org0437a732013-08-27 16:05:52 +0000479 shard_exit_codes = (output['exit_codes'] or '1').split(',')
480 shard_exit_code = max(int(i) for i in shard_exit_codes)
481 if decorate:
482 print decorate_shard_output(output, shard_exit_code)
483 else:
484 print(
485 '%s/%s: %s' % (
486 output['machine_id'],
487 output['machine_tag'],
488 output['exit_codes']))
489 print(''.join(' %s\n' % l for l in output['output'].splitlines()))
maruel@chromium.org9c1c7b52013-08-28 19:04:36 +0000490 exit_code = exit_code or shard_exit_code
491 return exit_code if exit_code is not None else 1
maruel@chromium.org0437a732013-08-27 16:05:52 +0000492
493
494def add_trigger_options(parser):
495 """Adds all options to trigger a task on Swarming."""
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500496 parser.server_group.add_option(
maruel@chromium.org0437a732013-08-27 16:05:52 +0000497 '-I', '--isolate-server',
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000498 metavar='URL', default='',
499 help='Isolate server to use')
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500500
501 parser.filter_group = tools.optparse.OptionGroup(parser, 'Filtering slaves')
Marc-Antoine Ruelcd629732013-12-20 15:00:42 -0500502 # TODO(maruel): Remove, 'os' is like any other dimension.
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500503 parser.filter_group.add_option(
maruel@chromium.org0437a732013-08-27 16:05:52 +0000504 '-o', '--os', default=sys.platform,
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500505 help='Slave OS to request. Should be one of the valid sys.platform '
maruel@chromium.org0437a732013-08-27 16:05:52 +0000506 'values like darwin, linux2 or win32 default: %default.')
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500507 parser.filter_group.add_option(
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -0500508 '-d', '--dimensions', default=[], action='append', nargs=2,
509 dest='dimensions', metavar='FOO bar',
510 help='dimension to filter on')
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500511 parser.add_option_group(parser.filter_group)
512
513 parser.task_group = tools.optparse.OptionGroup(parser, 'Task properties')
514 parser.task_group.add_option(
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500515 '-w', '--working-dir', default='swarm_tests',
516 help='Working directory on the swarming slave side. default: %default.')
517 parser.task_group.add_option(
518 '--working_dir', help=tools.optparse.SUPPRESS_HELP)
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500519 parser.task_group.add_option(
520 '-e', '--env', default=[], action='append', nargs=2, metavar='FOO bar',
521 help='environment variables to set')
522 parser.task_group.add_option(
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500523 '--priority', type='int', default=100,
524 help='The lower value, the more important the task is')
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500525 parser.task_group.add_option(
526 '--shards', type='int', default=1, help='number of shards to use')
527 parser.task_group.add_option(
528 '-T', '--task-name', help='display name of the task')
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500529 parser.add_option_group(parser.task_group)
Marc-Antoine Ruelcd629732013-12-20 15:00:42 -0500530 # TODO(maruel): This is currently written in a chromium-specific way.
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500531 parser.group_logging.add_option(
maruel@chromium.org0437a732013-08-27 16:05:52 +0000532 '--profile', action='store_true',
533 default=bool(os.environ.get('ISOLATE_DEBUG')),
534 help='Have run_isolated.py print profiling info')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000535
536
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500537def process_trigger_options(parser, options, args):
maruel@chromium.org0437a732013-08-27 16:05:52 +0000538 options.isolate_server = options.isolate_server.rstrip('/')
539 if not options.isolate_server:
540 parser.error('--isolate-server is required.')
541 if options.os in ('', 'None'):
542 # Use the current OS.
543 options.os = sys.platform
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000544 if not options.os in PLATFORM_MAPPING_SWARMING:
maruel@chromium.org0437a732013-08-27 16:05:52 +0000545 parser.error('Invalid --os option.')
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500546 if len(args) != 1:
547 parser.error('Must pass one .isolated file or its hash (sha1).')
548 options.dimensions.append(('os', PLATFORM_MAPPING_SWARMING[options.os]))
549 options.dimensions = dict(options.dimensions)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000550
551
552def add_collect_options(parser):
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500553 parser.server_group.add_option(
maruel@chromium.org0437a732013-08-27 16:05:52 +0000554 '-t', '--timeout',
555 type='float',
556 default=DEFAULT_SHARD_WAIT_TIME,
557 help='Timeout to wait for result, set to 0 for no timeout; default: '
558 '%default s')
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500559 parser.group_logging.add_option(
560 '--decorate', action='store_true', help='Decorate output')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000561
562
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500563@subcommand.usage('task_name')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000564def CMDcollect(parser, args):
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500565 """Retrieves results of a Swarming task.
maruel@chromium.org0437a732013-08-27 16:05:52 +0000566
567 The result can be in multiple part if the execution was sharded. It can
568 potentially have retries.
569 """
570 add_collect_options(parser)
571 (options, args) = parser.parse_args(args)
572 if not args:
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500573 parser.error('Must specify one task name.')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000574 elif len(args) > 1:
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500575 parser.error('Must specify only one task name.')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000576
577 try:
578 return collect(options.swarming, args[0], options.timeout, options.decorate)
579 except Failure as e:
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000580 tools.report_error(e)
581 return 1
maruel@chromium.org0437a732013-08-27 16:05:52 +0000582
583
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500584@subcommand.usage('[hash|isolated]')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000585def CMDrun(parser, args):
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500586 """Triggers a task and wait for the results.
maruel@chromium.org0437a732013-08-27 16:05:52 +0000587
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500588 Basically, does everything to run a command remotely.
maruel@chromium.org0437a732013-08-27 16:05:52 +0000589 """
590 add_trigger_options(parser)
591 add_collect_options(parser)
592 options, args = parser.parse_args(args)
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500593 process_trigger_options(parser, options, args)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000594
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500595 try:
596 result = trigger(
597 swarming=options.swarming,
598 isolate_server=options.isolate_server,
599 file_hash_or_isolated=args[0],
600 task_name=options.task_name,
601 shards=options.shards,
602 dimensions=options.dimensions,
603 env=dict(options.env),
604 working_dir=options.working_dir,
605 verbose=options.verbose,
606 profile=options.profile,
607 priority=options.priority)
608 except Failure as e:
609 tools.report_error(
610 'Failed to trigger %s(%s): %s' %
611 (options.task_name, args[0], e.args[0]))
612 return 1
613 if result:
614 tools.report_error('Failed to trigger the task.')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000615 return result
616
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500617 try:
618 return collect(
619 options.swarming,
620 options.task_name,
621 options.timeout,
622 options.decorate)
623 except Failure as e:
624 tools.report_error(e)
625 return 1
maruel@chromium.org0437a732013-08-27 16:05:52 +0000626
627
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500628@subcommand.usage("(hash|isolated)")
maruel@chromium.org0437a732013-08-27 16:05:52 +0000629def CMDtrigger(parser, args):
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500630 """Triggers a Swarming task.
maruel@chromium.org0437a732013-08-27 16:05:52 +0000631
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500632 Accepts either the hash (sha1) of a .isolated file already uploaded or the
633 path to an .isolated file to archive, packages it if needed and sends a
634 Swarming manifest file to the Swarming server.
635
636 If an .isolated file is specified instead of an hash, it is first archived.
maruel@chromium.org0437a732013-08-27 16:05:52 +0000637 """
638 add_trigger_options(parser)
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500639 options, args = parser.parse_args(args)
640 process_trigger_options(parser, options, args)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000641
642 try:
643 return trigger(
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500644 swarming=options.swarming,
645 isolate_server=options.isolate_server,
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500646 file_hash_or_isolated=args[0],
647 task_name=options.task_name,
648 dimensions=options.dimensions,
649 shards=options.shards,
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -0500650 env=dict(options.env),
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500651 working_dir=options.working_dir,
652 verbose=options.verbose,
653 profile=options.profile,
654 priority=options.priority)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000655 except Failure as e:
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000656 tools.report_error(e)
657 return 1
maruel@chromium.org0437a732013-08-27 16:05:52 +0000658
659
660class OptionParserSwarming(tools.OptionParserWithLogging):
661 def __init__(self, **kwargs):
662 tools.OptionParserWithLogging.__init__(
663 self, prog='swarming.py', **kwargs)
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500664 self.server_group = tools.optparse.OptionGroup(self, 'Server')
665 self.server_group.add_option(
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000666 '-S', '--swarming',
667 metavar='URL', default='',
668 help='Swarming server to use')
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500669 self.add_option_group(self.server_group)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000670
671 def parse_args(self, *args, **kwargs):
672 options, args = tools.OptionParserWithLogging.parse_args(
673 self, *args, **kwargs)
674 options.swarming = options.swarming.rstrip('/')
675 if not options.swarming:
676 self.error('--swarming is required.')
677 return options, args
678
679
680def main(args):
681 dispatcher = subcommand.CommandDispatcher(__name__)
682 try:
683 return dispatcher.execute(OptionParserSwarming(version=__version__), args)
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000684 except Exception as e:
685 tools.report_error(e)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000686 return 1
687
688
689if __name__ == '__main__':
690 fix_encoding.fix_encoding()
691 tools.disable_buffering()
692 colorama.init()
693 sys.exit(main(sys.argv[1:]))