blob: 26312417eb90caa1e6123e755b400f839e2a6802 [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 Ruel8806e622014-02-12 14:15:53 -05008__version__ = '0.4.1'
maruel@chromium.org0437a732013-08-27 16:05:52 +00009
Marc-Antoine Ruel5b475782014-02-14 20:57:59 -050010import getpass
maruel@chromium.org0437a732013-08-27 16:05:52 +000011import hashlib
12import json
13import logging
14import os
maruel@chromium.org0437a732013-08-27 16:05:52 +000015import shutil
maruel@chromium.org0437a732013-08-27 16:05:52 +000016import subprocess
17import sys
18import time
19import urllib
maruel@chromium.org0437a732013-08-27 16:05:52 +000020
21from third_party import colorama
22from third_party.depot_tools import fix_encoding
23from third_party.depot_tools import subcommand
vadimsh@chromium.org6b706212013-08-28 15:03:46 +000024
Marc-Antoine Ruel8806e622014-02-12 14:15:53 -050025from utils import file_path
vadimsh@chromium.org6b706212013-08-28 15:03:46 +000026from utils import net
maruel@chromium.org0437a732013-08-27 16:05:52 +000027from utils import threading_utils
vadimsh@chromium.org6b706212013-08-28 15:03:46 +000028from utils import tools
29from utils import zip_package
maruel@chromium.org0437a732013-08-27 16:05:52 +000030
Vadim Shtayurae34e13a2014-02-02 11:23:26 -080031import auth
maruel@chromium.org7b844a62013-09-17 13:04:59 +000032import isolateserver
maruel@chromium.org0437a732013-08-27 16:05:52 +000033import run_isolated
34
35
36ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
37TOOLS_PATH = os.path.join(ROOT_DIR, 'tools')
38
39
maruel@chromium.org0437a732013-08-27 16:05:52 +000040# The default time to wait for a shard to finish running.
csharp@chromium.org24758492013-08-28 19:10:54 +000041DEFAULT_SHARD_WAIT_TIME = 80 * 60.
maruel@chromium.org0437a732013-08-27 16:05:52 +000042
43
44NO_OUTPUT_FOUND = (
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -050045 'No output produced by the task, it may have failed to run.\n'
maruel@chromium.org0437a732013-08-27 16:05:52 +000046 '\n')
47
48
maruel@chromium.org0437a732013-08-27 16:05:52 +000049class Failure(Exception):
50 """Generic failure."""
51 pass
52
53
54class Manifest(object):
55 """Represents a Swarming task manifest.
56
57 Also includes code to zip code and upload itself.
58 """
59 def __init__(
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -050060 self, isolate_server, namespace, isolated_hash, task_name, shards, env,
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -050061 dimensions, working_dir, verbose, profile, priority, algo):
maruel@chromium.org0437a732013-08-27 16:05:52 +000062 """Populates a manifest object.
63 Args:
Marc-Antoine Ruela7049872013-11-05 19:28:35 -050064 isolate_server - isolate server url.
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -050065 namespace - isolate server namespace to use.
maruel@chromium.org814d23f2013-10-01 19:08:00 +000066 isolated_hash - The manifest's sha-1 that the slave is going to fetch.
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -050067 task_name - The name to give the task request.
68 shards - The number of swarming shards to request.
Marc-Antoine Ruel05dab5e2013-11-06 15:06:47 -050069 env - environment variables to set.
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -050070 dimensions - dimensions to filter the task on.
maruel@chromium.org0437a732013-08-27 16:05:52 +000071 working_dir - Relative working directory to start the script.
maruel@chromium.org0437a732013-08-27 16:05:52 +000072 verbose - if True, have the slave print more details.
73 profile - if True, have the slave print more timing data.
maruel@chromium.org7b844a62013-09-17 13:04:59 +000074 priority - int between 0 and 1000, lower the higher priority.
75 algo - hashing algorithm used.
maruel@chromium.org0437a732013-08-27 16:05:52 +000076 """
Marc-Antoine Ruela7049872013-11-05 19:28:35 -050077 self.isolate_server = isolate_server
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -050078 self.namespace = namespace
79 # The reason is that swarm_bot doesn't understand compressed data yet. So
80 # the data to be downloaded by swarm_bot is in 'default', independent of
81 # what run_isolated.py is going to fetch.
Marc-Antoine Ruela7049872013-11-05 19:28:35 -050082 self.storage = isolateserver.get_storage(isolate_server, 'default')
83
maruel@chromium.org814d23f2013-10-01 19:08:00 +000084 self.isolated_hash = isolated_hash
vadimsh@chromium.org6b706212013-08-28 15:03:46 +000085 self.bundle = zip_package.ZipPackage(ROOT_DIR)
86
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -050087 self._task_name = task_name
maruel@chromium.org0437a732013-08-27 16:05:52 +000088 self._shards = shards
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -050089 self._env = env.copy()
90 self._dimensions = dimensions.copy()
maruel@chromium.org0437a732013-08-27 16:05:52 +000091 self._working_dir = working_dir
92
maruel@chromium.org0437a732013-08-27 16:05:52 +000093 self.verbose = bool(verbose)
94 self.profile = bool(profile)
95 self.priority = priority
maruel@chromium.org7b844a62013-09-17 13:04:59 +000096 self._algo = algo
maruel@chromium.org0437a732013-08-27 16:05:52 +000097
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +000098 self._isolate_item = None
maruel@chromium.org0437a732013-08-27 16:05:52 +000099 self._tasks = []
maruel@chromium.org0437a732013-08-27 16:05:52 +0000100
101 def add_task(self, task_name, actions, time_out=600):
Marc-Antoine Ruelcd629732013-12-20 15:00:42 -0500102 """Appends a new task to the swarming manifest file.
103
104 Tasks cannot be added once the manifest was uploaded.
105 """
106 assert not self._isolate_item
maruel@chromium.org0437a732013-08-27 16:05:52 +0000107 # See swarming/src/common/test_request_message.py TestObject constructor for
108 # the valid flags.
109 self._tasks.append(
110 {
111 'action': actions,
112 'decorate_output': self.verbose,
113 'test_name': task_name,
114 'time_out': time_out,
115 })
116
maruel@chromium.org0437a732013-08-27 16:05:52 +0000117 def to_json(self):
118 """Exports the current configuration into a swarm-readable manifest file.
119
120 This function doesn't mutate the object.
121 """
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500122 request = {
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500123 'cleanup': 'root',
maruel@chromium.org0437a732013-08-27 16:05:52 +0000124 'configurations': [
125 {
Marc-Antoine Ruel5d799192013-11-06 15:20:39 -0500126 'config_name': 'isolated',
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -0500127 'dimensions': self._dimensions,
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500128 'min_instances': self._shards,
129 'priority': self.priority,
maruel@chromium.org0437a732013-08-27 16:05:52 +0000130 },
131 ],
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500132 'data': [],
133 # TODO: Let the encoding get set from the command line.
134 'encoding': 'UTF-8',
Marc-Antoine Ruel05dab5e2013-11-06 15:06:47 -0500135 'env_vars': self._env,
maruel@chromium.org0437a732013-08-27 16:05:52 +0000136 'restart_on_failure': True,
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500137 'test_case_name': self._task_name,
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500138 'tests': self._tasks,
139 'working_dir': self._working_dir,
maruel@chromium.org0437a732013-08-27 16:05:52 +0000140 }
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000141 if self._isolate_item:
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500142 request['data'].append(
maruel@chromium.org814d23f2013-10-01 19:08:00 +0000143 [
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000144 self.storage.get_fetch_url(self._isolate_item.digest),
maruel@chromium.org814d23f2013-10-01 19:08:00 +0000145 'swarm_data.zip',
146 ])
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500147 return json.dumps(request, sort_keys=True, separators=(',',':'))
maruel@chromium.org0437a732013-08-27 16:05:52 +0000148
Marc-Antoine Ruelcd629732013-12-20 15:00:42 -0500149 @property
150 def isolate_item(self):
151 """Calling this property 'closes' the manifest and it can't be modified
152 afterward.
153 """
154 if self._isolate_item is None:
155 self._isolate_item = isolateserver.BufferItem(
156 self.bundle.zip_into_buffer(), self._algo, is_isolated=True)
157 return self._isolate_item
158
159
160def zip_and_upload(manifest):
161 """Zips up all the files necessary to run a manifest and uploads to Swarming
162 master.
163 """
164 try:
165 start_time = time.time()
166 with manifest.storage:
167 uploaded = manifest.storage.upload_items([manifest.isolate_item])
168 elapsed = time.time() - start_time
169 except (IOError, OSError) as exc:
170 tools.report_error('Failed to upload the zip file: %s' % exc)
171 return False
172
173 if manifest.isolate_item in uploaded:
174 logging.info('Upload complete, time elapsed: %f', elapsed)
175 else:
176 logging.info('Zip file already on server, time elapsed: %f', elapsed)
177 return True
178
maruel@chromium.org0437a732013-08-27 16:05:52 +0000179
180def now():
181 """Exists so it can be mocked easily."""
182 return time.time()
183
184
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500185def get_task_keys(swarm_base_url, task_name):
186 """Returns the Swarming task key for each shards of task_name."""
187 key_data = urllib.urlencode([('name', task_name)])
maruel@chromium.org0437a732013-08-27 16:05:52 +0000188 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(
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500194 'Error: Unable to find any task with the name, %s, on swarming server'
195 % task_name)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000196
maruel@chromium.org0437a732013-08-27 16:05:52 +0000197 # TODO(maruel): Compare exact string.
198 if 'No matching' in result:
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500199 logging.warning('Unable to find any task with the name, %s, on swarming '
200 'server' % task_name)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000201 continue
202 return json.loads(result)
203
204 raise Failure(
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500205 'Error: Unable to find any task with the name, %s, on swarming server'
206 % task_name)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000207
208
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500209def retrieve_results(base_url, task_key, timeout, should_stop):
210 """Retrieves results for a single task_key."""
maruel@chromium.org814d23f2013-10-01 19:08:00 +0000211 assert isinstance(timeout, float), timeout
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500212 params = [('r', task_key)]
maruel@chromium.org0437a732013-08-27 16:05:52 +0000213 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(
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500234 'Received corrupted data for task_key %s. Retrying.', task_key)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000235 else:
236 if data['output']:
237 return data
238 if should_stop.get():
239 return {}
240
241
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500242def yield_results(swarm_base_url, task_keys, timeout, max_threads):
243 """Yields swarming task results from the swarming server as (index, result).
maruel@chromium.org0437a732013-08-27 16:05:52 +0000244
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
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500248 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 +0000249 worth normally to limit the number threads. Mostly used for testing purposes.
250 """
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500251 shards_remaining = range(len(task_keys))
maruel@chromium.org0437a732013-08-27 16:05:52 +0000252 number_threads = (
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500253 min(max_threads, len(task_keys)) if max_threads else len(task_keys))
maruel@chromium.org0437a732013-08-27 16:05:52 +0000254 should_stop = threading_utils.Bit()
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500255 results_remaining = len(task_keys)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000256 with threading_utils.ThreadPool(number_threads, number_threads, 0) as pool:
257 try:
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500258 for task_key in task_keys:
maruel@chromium.org0437a732013-08-27 16:05:52 +0000259 pool.add_task(
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500260 0, retrieve_results, swarm_base_url, task_key, timeout, should_stop)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000261 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.
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500266 logging.error('Failed to retrieve the results for a swarming key')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000267 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,
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500299 '--namespace', manifest.namespace,
maruel@chromium.org0437a732013-08-27 16:05:52 +0000300 ]
Marc-Antoine Ruel8806e622014-02-12 14:15:53 -0500301 if file_path.is_url(manifest.isolate_server):
302 run_cmd.extend(('--isolate-server', manifest.isolate_server))
303 else:
304 run_cmd.extend(('--indir', manifest.isolate_server))
305
maruel@chromium.org0437a732013-08-27 16:05:52 +0000306 if manifest.verbose or manifest.profile:
307 # Have it print the profiling section.
308 run_cmd.append('--verbose')
309 manifest.add_task('Run Test', run_cmd)
310
311 # Clean up
312 manifest.add_task('Clean Up', ['python', cleanup_script_name])
313
314
Marc-Antoine Ruelcd629732013-12-20 15:00:42 -0500315def googletest_setup(env, shards):
316 """Sets googletest specific environment variables."""
317 if shards > 1:
318 env = env.copy()
319 env['GTEST_SHARD_INDEX'] = '%(instance_index)s'
320 env['GTEST_TOTAL_SHARDS'] = '%(num_instances)s'
321 return env
322
323
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500324def archive(isolate_server, namespace, isolated, algo, verbose):
maruel@chromium.org0437a732013-08-27 16:05:52 +0000325 """Archives a .isolated and all the dependencies on the CAC."""
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500326 logging.info('archive(%s, %s, %s)', isolate_server, namespace, isolated)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000327 tempdir = None
Marc-Antoine Ruel8806e622014-02-12 14:15:53 -0500328 if file_path.is_url(isolate_server):
329 command = 'archive'
330 flag = '--isolate-server'
331 else:
332 command = 'hashtable'
333 flag = '--outdir'
334
Marc-Antoine Ruel5b475782014-02-14 20:57:59 -0500335 print('Archiving: %s' % isolated)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000336 try:
maruel@chromium.org0437a732013-08-27 16:05:52 +0000337 cmd = [
338 sys.executable,
339 os.path.join(ROOT_DIR, 'isolate.py'),
Marc-Antoine Ruel8806e622014-02-12 14:15:53 -0500340 command,
341 flag, isolate_server,
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500342 '--namespace', namespace,
maruel@chromium.org0437a732013-08-27 16:05:52 +0000343 '--isolated', isolated,
344 ]
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000345 cmd.extend(['--verbose'] * verbose)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000346 logging.info(' '.join(cmd))
347 if subprocess.call(cmd, verbose):
348 return
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000349 return isolateserver.hash_file(isolated, algo)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000350 finally:
351 if tempdir:
352 shutil.rmtree(tempdir)
353
354
355def process_manifest(
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500356 swarming, isolate_server, namespace, isolated_hash, task_name, shards,
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -0500357 dimensions, env, working_dir, verbose, profile, priority, algo):
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500358 """Processes the manifest file and send off the swarming task request."""
maruel@chromium.org0437a732013-08-27 16:05:52 +0000359 try:
360 manifest = Manifest(
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500361 isolate_server=isolate_server,
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500362 namespace=namespace,
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500363 isolated_hash=isolated_hash,
364 task_name=task_name,
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500365 shards=shards,
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -0500366 dimensions=dimensions,
Marc-Antoine Ruel05dab5e2013-11-06 15:06:47 -0500367 env=env,
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500368 working_dir=working_dir,
369 verbose=verbose,
370 profile=profile,
371 priority=priority,
372 algo=algo)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000373 except ValueError as e:
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500374 tools.report_error('Unable to process %s: %s' % (task_name, e))
maruel@chromium.org0437a732013-08-27 16:05:52 +0000375 return 1
376
377 chromium_setup(manifest)
378
Marc-Antoine Ruelcd629732013-12-20 15:00:42 -0500379 logging.info('Zipping up files...')
380 if not zip_and_upload(manifest):
maruel@chromium.org0437a732013-08-27 16:05:52 +0000381 return 1
382
Marc-Antoine Ruelcd629732013-12-20 15:00:42 -0500383 logging.info('Server: %s', swarming)
384 logging.info('Task name: %s', task_name)
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500385 trigger_url = swarming + '/test'
maruel@chromium.org0437a732013-08-27 16:05:52 +0000386 manifest_text = manifest.to_json()
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500387 result = net.url_read(trigger_url, data={'request': manifest_text})
maruel@chromium.org0437a732013-08-27 16:05:52 +0000388 if not result:
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000389 tools.report_error(
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500390 'Failed to trigger task %s\n%s' % (task_name, trigger_url))
maruel@chromium.org0437a732013-08-27 16:05:52 +0000391 return 1
392 try:
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000393 json.loads(result)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000394 except (ValueError, TypeError) as e:
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000395 msg = '\n'.join((
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500396 'Failed to trigger task %s' % task_name,
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000397 'Manifest: %s' % manifest_text,
398 'Bad response: %s' % result,
399 str(e)))
400 tools.report_error(msg)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000401 return 1
402 return 0
403
404
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500405def isolated_to_hash(isolate_server, namespace, arg, algo, verbose):
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500406 """Archives a .isolated file if needed.
407
Marc-Antoine Ruel5b475782014-02-14 20:57:59 -0500408 Returns the file hash to trigger and a bool specifying if it was a file (True)
409 or a hash (False).
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500410 """
411 if arg.endswith('.isolated'):
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500412 file_hash = archive(isolate_server, namespace, arg, algo, verbose)
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500413 if not file_hash:
414 tools.report_error('Archival failure %s' % arg)
Marc-Antoine Ruel5b475782014-02-14 20:57:59 -0500415 return None, True
416 return file_hash, True
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500417 elif isolateserver.is_valid_hash(arg, algo):
Marc-Antoine Ruel5b475782014-02-14 20:57:59 -0500418 return arg, False
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500419 else:
420 tools.report_error('Invalid hash %s' % arg)
Marc-Antoine Ruel5b475782014-02-14 20:57:59 -0500421 return None, False
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500422
423
maruel@chromium.org0437a732013-08-27 16:05:52 +0000424def trigger(
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500425 swarming,
426 isolate_server,
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500427 namespace,
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500428 file_hash_or_isolated,
429 task_name,
430 shards,
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -0500431 dimensions,
432 env,
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500433 working_dir,
maruel@chromium.org0437a732013-08-27 16:05:52 +0000434 verbose,
435 profile,
436 priority):
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500437 """Sends off the hash swarming task requests."""
Marc-Antoine Ruel5b475782014-02-14 20:57:59 -0500438 file_hash, is_file = isolated_to_hash(
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500439 isolate_server, namespace, file_hash_or_isolated, hashlib.sha1, verbose)
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500440 if not file_hash:
Marc-Antoine Ruel5b475782014-02-14 20:57:59 -0500441 return 1, ''
442 if not task_name:
443 # If a file name was passed, use its base name of the isolated hash.
444 # Otherwise, use user name as an approximation of a task name.
445 if is_file:
446 key = os.path.splitext(os.path.basename(file_hash_or_isolated))[0]
447 else:
448 key = getpass.getuser()
449 task_name = '%s/%s/%s' % (
450 key,
451 '_'.join('%s=%s' % (k, v) for k, v in sorted(dimensions.iteritems())),
452 file_hash)
453
Marc-Antoine Ruelcd629732013-12-20 15:00:42 -0500454 env = googletest_setup(env, shards)
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500455 # TODO(maruel): It should first create a request manifest object, then pass
456 # it to a function to zip, archive and trigger.
Marc-Antoine Ruel5b475782014-02-14 20:57:59 -0500457 result = process_manifest(
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500458 swarming=swarming,
459 isolate_server=isolate_server,
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500460 namespace=namespace,
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500461 isolated_hash=file_hash,
462 task_name=task_name,
463 shards=shards,
464 dimensions=dimensions,
465 env=env,
466 working_dir=working_dir,
467 verbose=verbose,
468 profile=profile,
469 priority=priority,
470 algo=hashlib.sha1)
Marc-Antoine Ruel5b475782014-02-14 20:57:59 -0500471 return result, task_name
maruel@chromium.org0437a732013-08-27 16:05:52 +0000472
473
474def decorate_shard_output(result, shard_exit_code):
475 """Returns wrapped output for swarming task shard."""
476 tag = 'index %s (machine tag: %s, id: %s)' % (
477 result['config_instance_index'],
478 result['machine_id'],
479 result.get('machine_tag', 'unknown'))
480 return (
481 '\n'
482 '================================================================\n'
483 'Begin output from shard %s\n'
484 '================================================================\n'
485 '\n'
486 '%s'
487 '================================================================\n'
488 'End output from shard %s. Return %d\n'
489 '================================================================\n'
490 ) % (tag, result['output'] or NO_OUTPUT_FOUND, tag, shard_exit_code)
491
492
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500493def collect(url, task_name, timeout, decorate):
494 """Retrieves results of a Swarming task."""
495 logging.info('Collecting %s', task_name)
496 task_keys = get_task_keys(url, task_name)
497 if not task_keys:
498 raise Failure('No task keys to get results with.')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000499
maruel@chromium.org9c1c7b52013-08-28 19:04:36 +0000500 exit_code = None
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500501 for _index, output in yield_results(url, task_keys, timeout, None):
maruel@chromium.org0437a732013-08-27 16:05:52 +0000502 shard_exit_codes = (output['exit_codes'] or '1').split(',')
503 shard_exit_code = max(int(i) for i in shard_exit_codes)
504 if decorate:
505 print decorate_shard_output(output, shard_exit_code)
506 else:
507 print(
508 '%s/%s: %s' % (
509 output['machine_id'],
510 output['machine_tag'],
511 output['exit_codes']))
512 print(''.join(' %s\n' % l for l in output['output'].splitlines()))
maruel@chromium.org9c1c7b52013-08-28 19:04:36 +0000513 exit_code = exit_code or shard_exit_code
514 return exit_code if exit_code is not None else 1
maruel@chromium.org0437a732013-08-27 16:05:52 +0000515
516
517def add_trigger_options(parser):
518 """Adds all options to trigger a task on Swarming."""
Marc-Antoine Ruel8806e622014-02-12 14:15:53 -0500519 isolateserver.add_isolate_server_options(parser, True)
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500520
521 parser.filter_group = tools.optparse.OptionGroup(parser, 'Filtering slaves')
522 parser.filter_group.add_option(
Marc-Antoine Ruelb39e8cf2014-01-20 10:39:31 -0500523 '-d', '--dimension', default=[], action='append', nargs=2,
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -0500524 dest='dimensions', metavar='FOO bar',
525 help='dimension to filter on')
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500526 parser.add_option_group(parser.filter_group)
527
528 parser.task_group = tools.optparse.OptionGroup(parser, 'Task properties')
529 parser.task_group.add_option(
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500530 '-w', '--working-dir', default='swarm_tests',
531 help='Working directory on the swarming slave side. default: %default.')
532 parser.task_group.add_option(
533 '--working_dir', help=tools.optparse.SUPPRESS_HELP)
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500534 parser.task_group.add_option(
535 '-e', '--env', default=[], action='append', nargs=2, metavar='FOO bar',
536 help='environment variables to set')
537 parser.task_group.add_option(
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500538 '--priority', type='int', default=100,
539 help='The lower value, the more important the task is')
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500540 parser.task_group.add_option(
541 '--shards', type='int', default=1, help='number of shards to use')
542 parser.task_group.add_option(
Marc-Antoine Ruel5b475782014-02-14 20:57:59 -0500543 '-T', '--task-name',
544 help='Display name of the task. It uniquely identifies the task. '
545 'Defaults to <base_name>/<dimensions>/<isolated hash> if an '
546 'isolated file is provided, if a hash is provided, it defaults to '
547 '<user>/<dimensions>/<isolated hash>')
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500548 parser.add_option_group(parser.task_group)
Marc-Antoine Ruelcd629732013-12-20 15:00:42 -0500549 # TODO(maruel): This is currently written in a chromium-specific way.
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500550 parser.group_logging.add_option(
maruel@chromium.org0437a732013-08-27 16:05:52 +0000551 '--profile', action='store_true',
552 default=bool(os.environ.get('ISOLATE_DEBUG')),
553 help='Have run_isolated.py print profiling info')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000554
555
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500556def process_trigger_options(parser, options, args):
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500557 isolateserver.process_isolate_server_options(parser, options)
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500558 if len(args) != 1:
559 parser.error('Must pass one .isolated file or its hash (sha1).')
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500560 options.dimensions = dict(options.dimensions)
Marc-Antoine Ruelb39e8cf2014-01-20 10:39:31 -0500561 if not options.dimensions.get('os'):
562 parser.error(
563 'Please at least specify the dimension of the swarming bot OS with '
564 '--dimension os <something>.')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000565
566
567def add_collect_options(parser):
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500568 parser.server_group.add_option(
maruel@chromium.org0437a732013-08-27 16:05:52 +0000569 '-t', '--timeout',
570 type='float',
571 default=DEFAULT_SHARD_WAIT_TIME,
572 help='Timeout to wait for result, set to 0 for no timeout; default: '
573 '%default s')
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500574 parser.group_logging.add_option(
575 '--decorate', action='store_true', help='Decorate output')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000576
577
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500578@subcommand.usage('task_name')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000579def CMDcollect(parser, args):
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500580 """Retrieves results of a Swarming task.
maruel@chromium.org0437a732013-08-27 16:05:52 +0000581
582 The result can be in multiple part if the execution was sharded. It can
583 potentially have retries.
584 """
585 add_collect_options(parser)
586 (options, args) = parser.parse_args(args)
587 if not args:
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500588 parser.error('Must specify one task name.')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000589 elif len(args) > 1:
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500590 parser.error('Must specify only one task name.')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000591
592 try:
593 return collect(options.swarming, args[0], options.timeout, options.decorate)
594 except Failure as e:
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000595 tools.report_error(e)
596 return 1
maruel@chromium.org0437a732013-08-27 16:05:52 +0000597
598
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500599@subcommand.usage('[hash|isolated]')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000600def CMDrun(parser, args):
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500601 """Triggers a task and wait for the results.
maruel@chromium.org0437a732013-08-27 16:05:52 +0000602
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500603 Basically, does everything to run a command remotely.
maruel@chromium.org0437a732013-08-27 16:05:52 +0000604 """
605 add_trigger_options(parser)
606 add_collect_options(parser)
607 options, args = parser.parse_args(args)
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500608 process_trigger_options(parser, options, args)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000609
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500610 try:
Marc-Antoine Ruel5b475782014-02-14 20:57:59 -0500611 result, task_name = trigger(
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500612 swarming=options.swarming,
Marc-Antoine Ruel8806e622014-02-12 14:15:53 -0500613 isolate_server=options.isolate_server or options.indir,
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500614 namespace=options.namespace,
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500615 file_hash_or_isolated=args[0],
616 task_name=options.task_name,
617 shards=options.shards,
618 dimensions=options.dimensions,
619 env=dict(options.env),
620 working_dir=options.working_dir,
621 verbose=options.verbose,
622 profile=options.profile,
623 priority=options.priority)
624 except Failure as e:
625 tools.report_error(
626 'Failed to trigger %s(%s): %s' %
627 (options.task_name, args[0], e.args[0]))
628 return 1
629 if result:
630 tools.report_error('Failed to trigger the task.')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000631 return result
Marc-Antoine Ruel5b475782014-02-14 20:57:59 -0500632 if task_name != options.task_name:
633 print('Triggered task: %s' % task_name)
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500634 try:
635 return collect(
636 options.swarming,
Marc-Antoine Ruel5b475782014-02-14 20:57:59 -0500637 task_name,
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500638 options.timeout,
639 options.decorate)
640 except Failure as e:
641 tools.report_error(e)
642 return 1
maruel@chromium.org0437a732013-08-27 16:05:52 +0000643
644
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500645@subcommand.usage("(hash|isolated)")
maruel@chromium.org0437a732013-08-27 16:05:52 +0000646def CMDtrigger(parser, args):
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500647 """Triggers a Swarming task.
maruel@chromium.org0437a732013-08-27 16:05:52 +0000648
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500649 Accepts either the hash (sha1) of a .isolated file already uploaded or the
650 path to an .isolated file to archive, packages it if needed and sends a
651 Swarming manifest file to the Swarming server.
652
653 If an .isolated file is specified instead of an hash, it is first archived.
maruel@chromium.org0437a732013-08-27 16:05:52 +0000654 """
655 add_trigger_options(parser)
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500656 options, args = parser.parse_args(args)
657 process_trigger_options(parser, options, args)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000658
659 try:
Marc-Antoine Ruel5b475782014-02-14 20:57:59 -0500660 result, task_name = trigger(
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500661 swarming=options.swarming,
Marc-Antoine Ruel8806e622014-02-12 14:15:53 -0500662 isolate_server=options.isolate_server or options.indir,
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500663 namespace=options.namespace,
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500664 file_hash_or_isolated=args[0],
665 task_name=options.task_name,
666 dimensions=options.dimensions,
667 shards=options.shards,
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -0500668 env=dict(options.env),
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500669 working_dir=options.working_dir,
670 verbose=options.verbose,
671 profile=options.profile,
672 priority=options.priority)
Marc-Antoine Ruel5b475782014-02-14 20:57:59 -0500673 if task_name != options.task_name and not result:
674 print('Triggered task: %s' % task_name)
675 return result
maruel@chromium.org0437a732013-08-27 16:05:52 +0000676 except Failure as e:
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000677 tools.report_error(e)
678 return 1
maruel@chromium.org0437a732013-08-27 16:05:52 +0000679
680
681class OptionParserSwarming(tools.OptionParserWithLogging):
682 def __init__(self, **kwargs):
683 tools.OptionParserWithLogging.__init__(
684 self, prog='swarming.py', **kwargs)
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500685 self.server_group = tools.optparse.OptionGroup(self, 'Server')
686 self.server_group.add_option(
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000687 '-S', '--swarming',
Kevin Graney5346c162014-01-24 12:20:01 -0500688 metavar='URL', default=os.environ.get('SWARMING_SERVER', ''),
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000689 help='Swarming server to use')
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500690 self.add_option_group(self.server_group)
Vadim Shtayurae34e13a2014-02-02 11:23:26 -0800691 auth.add_auth_options(self)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000692
693 def parse_args(self, *args, **kwargs):
694 options, args = tools.OptionParserWithLogging.parse_args(
695 self, *args, **kwargs)
696 options.swarming = options.swarming.rstrip('/')
697 if not options.swarming:
698 self.error('--swarming is required.')
Vadim Shtayura5d1efce2014-02-04 10:55:43 -0800699 auth.process_auth_options(self, options)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000700 return options, args
701
702
703def main(args):
704 dispatcher = subcommand.CommandDispatcher(__name__)
705 try:
706 return dispatcher.execute(OptionParserSwarming(version=__version__), args)
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000707 except Exception as e:
708 tools.report_error(e)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000709 return 1
710
711
712if __name__ == '__main__':
713 fix_encoding.fix_encoding()
714 tools.disable_buffering()
715 colorama.init()
716 sys.exit(main(sys.argv[1:]))