blob: 2955de715ecdc7f358a8442d3f848d5e04b6c8f0 [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 Ruel5c720342014-02-21 14:46:14 -0500102 """Appends a new task as a TestObject to the swarming manifest file.
Marc-Antoine Ruelcd629732013-12-20 15:00:42 -0500103
104 Tasks cannot be added once the manifest was uploaded.
Marc-Antoine Ruel5c720342014-02-21 14:46:14 -0500105
106 See TestObject in services/swarming/src/common/test_request_message.py for
107 the valid format.
Marc-Antoine Ruelcd629732013-12-20 15:00:42 -0500108 """
109 assert not self._isolate_item
maruel@chromium.org0437a732013-08-27 16:05:52 +0000110 self._tasks.append(
111 {
112 'action': actions,
113 'decorate_output': self.verbose,
114 'test_name': task_name,
115 'time_out': time_out,
116 })
117
maruel@chromium.org0437a732013-08-27 16:05:52 +0000118 def to_json(self):
119 """Exports the current configuration into a swarm-readable manifest file.
120
Marc-Antoine Ruel5c720342014-02-21 14:46:14 -0500121 The actual serialization format is defined as a TestCase object as described
122 in services/swarming/src/common/test_request_message.py
123
maruel@chromium.org0437a732013-08-27 16:05:52 +0000124 This function doesn't mutate the object.
125 """
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500126 request = {
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500127 'cleanup': 'root',
maruel@chromium.org0437a732013-08-27 16:05:52 +0000128 'configurations': [
Marc-Antoine Ruel5c720342014-02-21 14:46:14 -0500129 # Is a TestConfiguration.
maruel@chromium.org0437a732013-08-27 16:05:52 +0000130 {
Marc-Antoine Ruel5d799192013-11-06 15:20:39 -0500131 'config_name': 'isolated',
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -0500132 'dimensions': self._dimensions,
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500133 'min_instances': self._shards,
134 'priority': self.priority,
maruel@chromium.org0437a732013-08-27 16:05:52 +0000135 },
136 ],
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500137 'data': [],
138 # TODO: Let the encoding get set from the command line.
139 'encoding': 'UTF-8',
Marc-Antoine Ruel05dab5e2013-11-06 15:06:47 -0500140 'env_vars': self._env,
maruel@chromium.org0437a732013-08-27 16:05:52 +0000141 'restart_on_failure': True,
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500142 'test_case_name': self._task_name,
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500143 'tests': self._tasks,
144 'working_dir': self._working_dir,
maruel@chromium.org0437a732013-08-27 16:05:52 +0000145 }
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000146 if self._isolate_item:
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500147 request['data'].append(
maruel@chromium.org814d23f2013-10-01 19:08:00 +0000148 [
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000149 self.storage.get_fetch_url(self._isolate_item.digest),
maruel@chromium.org814d23f2013-10-01 19:08:00 +0000150 'swarm_data.zip',
151 ])
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500152 return json.dumps(request, sort_keys=True, separators=(',',':'))
maruel@chromium.org0437a732013-08-27 16:05:52 +0000153
Marc-Antoine Ruelcd629732013-12-20 15:00:42 -0500154 @property
155 def isolate_item(self):
156 """Calling this property 'closes' the manifest and it can't be modified
157 afterward.
158 """
159 if self._isolate_item is None:
160 self._isolate_item = isolateserver.BufferItem(
161 self.bundle.zip_into_buffer(), self._algo, is_isolated=True)
162 return self._isolate_item
163
164
165def zip_and_upload(manifest):
166 """Zips up all the files necessary to run a manifest and uploads to Swarming
167 master.
168 """
169 try:
170 start_time = time.time()
171 with manifest.storage:
172 uploaded = manifest.storage.upload_items([manifest.isolate_item])
173 elapsed = time.time() - start_time
174 except (IOError, OSError) as exc:
175 tools.report_error('Failed to upload the zip file: %s' % exc)
176 return False
177
178 if manifest.isolate_item in uploaded:
179 logging.info('Upload complete, time elapsed: %f', elapsed)
180 else:
181 logging.info('Zip file already on server, time elapsed: %f', elapsed)
182 return True
183
maruel@chromium.org0437a732013-08-27 16:05:52 +0000184
185def now():
186 """Exists so it can be mocked easily."""
187 return time.time()
188
189
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500190def get_task_keys(swarm_base_url, task_name):
191 """Returns the Swarming task key for each shards of task_name."""
192 key_data = urllib.urlencode([('name', task_name)])
maruel@chromium.org0437a732013-08-27 16:05:52 +0000193 url = '%s/get_matching_test_cases?%s' % (swarm_base_url, key_data)
194
vadimsh@chromium.org043b76d2013-09-12 16:15:13 +0000195 for _ in net.retry_loop(max_attempts=net.URL_OPEN_MAX_ATTEMPTS):
196 result = net.url_read(url, retry_404=True)
197 if result is None:
maruel@chromium.org0437a732013-08-27 16:05:52 +0000198 raise Failure(
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500199 'Error: Unable to find any task with the name, %s, on swarming server'
200 % task_name)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000201
maruel@chromium.org0437a732013-08-27 16:05:52 +0000202 # TODO(maruel): Compare exact string.
203 if 'No matching' in result:
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500204 logging.warning('Unable to find any task with the name, %s, on swarming '
205 'server' % task_name)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000206 continue
207 return json.loads(result)
208
209 raise Failure(
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500210 'Error: Unable to find any task with the name, %s, on swarming server'
211 % task_name)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000212
213
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500214def retrieve_results(base_url, task_key, timeout, should_stop):
215 """Retrieves results for a single task_key."""
maruel@chromium.org814d23f2013-10-01 19:08:00 +0000216 assert isinstance(timeout, float), timeout
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500217 params = [('r', task_key)]
maruel@chromium.org0437a732013-08-27 16:05:52 +0000218 result_url = '%s/get_result?%s' % (base_url, urllib.urlencode(params))
219 start = now()
220 while True:
221 if timeout and (now() - start) >= timeout:
222 logging.error('retrieve_results(%s) timed out', base_url)
223 return {}
224 # Do retries ourselves.
vadimsh@chromium.org043b76d2013-09-12 16:15:13 +0000225 response = net.url_read(result_url, retry_404=False, retry_50x=False)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000226 if response is None:
227 # Aggressively poll for results. Do not use retry_404 so
228 # should_stop is polled more often.
229 remaining = min(5, timeout - (now() - start)) if timeout else 5
230 if remaining > 0:
maruel@chromium.org814d23f2013-10-01 19:08:00 +0000231 if should_stop.get():
232 return {}
vadimsh@chromium.org043b76d2013-09-12 16:15:13 +0000233 net.sleep_before_retry(1, remaining)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000234 else:
235 try:
vadimsh@chromium.org043b76d2013-09-12 16:15:13 +0000236 data = json.loads(response) or {}
maruel@chromium.org0437a732013-08-27 16:05:52 +0000237 except (ValueError, TypeError):
238 logging.warning(
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500239 'Received corrupted data for task_key %s. Retrying.', task_key)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000240 else:
241 if data['output']:
242 return data
243 if should_stop.get():
244 return {}
245
246
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500247def yield_results(swarm_base_url, task_keys, timeout, max_threads):
248 """Yields swarming task results from the swarming server as (index, result).
maruel@chromium.org0437a732013-08-27 16:05:52 +0000249
250 Duplicate shards are ignored, the first one to complete is returned.
251
252 max_threads is optional and is used to limit the number of parallel fetches
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500253 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 +0000254 worth normally to limit the number threads. Mostly used for testing purposes.
Marc-Antoine Ruel5c720342014-02-21 14:46:14 -0500255
256 Yields:
257 (index, result). In particular, 'result' is defined as the
258 GetRunnerResults() function in services/swarming/server/test_runner.py.
maruel@chromium.org0437a732013-08-27 16:05:52 +0000259 """
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500260 shards_remaining = range(len(task_keys))
maruel@chromium.org0437a732013-08-27 16:05:52 +0000261 number_threads = (
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500262 min(max_threads, len(task_keys)) if max_threads else len(task_keys))
maruel@chromium.org0437a732013-08-27 16:05:52 +0000263 should_stop = threading_utils.Bit()
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500264 results_remaining = len(task_keys)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000265 with threading_utils.ThreadPool(number_threads, number_threads, 0) as pool:
266 try:
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500267 for task_key in task_keys:
maruel@chromium.org0437a732013-08-27 16:05:52 +0000268 pool.add_task(
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500269 0, retrieve_results, swarm_base_url, task_key, timeout, should_stop)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000270 while shards_remaining and results_remaining:
271 result = pool.get_one_result()
272 results_remaining -= 1
273 if not result:
274 # Failed to retrieve one key.
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500275 logging.error('Failed to retrieve the results for a swarming key')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000276 continue
277 shard_index = result['config_instance_index']
278 if shard_index in shards_remaining:
279 shards_remaining.remove(shard_index)
280 yield shard_index, result
281 else:
282 logging.warning('Ignoring duplicate shard index %d', shard_index)
283 # Pop the last entry, there's no such shard.
284 shards_remaining.pop()
285 finally:
286 # Done, kill the remaining threads.
287 should_stop.set()
288
289
290def chromium_setup(manifest):
291 """Sets up the commands to run.
292
293 Highly chromium specific.
294 """
vadimsh@chromium.org6b706212013-08-28 15:03:46 +0000295 # Add uncompressed zip here. It'll be compressed as part of the package sent
296 # to Swarming server.
297 run_test_name = 'run_isolated.zip'
298 manifest.bundle.add_buffer(run_test_name,
299 run_isolated.get_as_zip_package().zip_into_buffer(compress=False))
maruel@chromium.org0437a732013-08-27 16:05:52 +0000300
vadimsh@chromium.org6b706212013-08-28 15:03:46 +0000301 cleanup_script_name = 'swarm_cleanup.py'
302 manifest.bundle.add_file(os.path.join(TOOLS_PATH, cleanup_script_name),
303 cleanup_script_name)
304
maruel@chromium.org0437a732013-08-27 16:05:52 +0000305 run_cmd = [
306 'python', run_test_name,
maruel@chromium.org814d23f2013-10-01 19:08:00 +0000307 '--hash', manifest.isolated_hash,
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500308 '--namespace', manifest.namespace,
maruel@chromium.org0437a732013-08-27 16:05:52 +0000309 ]
Marc-Antoine Ruel8806e622014-02-12 14:15:53 -0500310 if file_path.is_url(manifest.isolate_server):
311 run_cmd.extend(('--isolate-server', manifest.isolate_server))
312 else:
313 run_cmd.extend(('--indir', manifest.isolate_server))
314
maruel@chromium.org0437a732013-08-27 16:05:52 +0000315 if manifest.verbose or manifest.profile:
316 # Have it print the profiling section.
317 run_cmd.append('--verbose')
318 manifest.add_task('Run Test', run_cmd)
319
320 # Clean up
321 manifest.add_task('Clean Up', ['python', cleanup_script_name])
322
323
Marc-Antoine Ruelcd629732013-12-20 15:00:42 -0500324def googletest_setup(env, shards):
325 """Sets googletest specific environment variables."""
326 if shards > 1:
327 env = env.copy()
328 env['GTEST_SHARD_INDEX'] = '%(instance_index)s'
329 env['GTEST_TOTAL_SHARDS'] = '%(num_instances)s'
330 return env
331
332
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500333def archive(isolate_server, namespace, isolated, algo, verbose):
maruel@chromium.org0437a732013-08-27 16:05:52 +0000334 """Archives a .isolated and all the dependencies on the CAC."""
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500335 logging.info('archive(%s, %s, %s)', isolate_server, namespace, isolated)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000336 tempdir = None
Marc-Antoine Ruel8806e622014-02-12 14:15:53 -0500337 if file_path.is_url(isolate_server):
338 command = 'archive'
339 flag = '--isolate-server'
340 else:
341 command = 'hashtable'
342 flag = '--outdir'
343
Marc-Antoine Ruel5b475782014-02-14 20:57:59 -0500344 print('Archiving: %s' % isolated)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000345 try:
maruel@chromium.org0437a732013-08-27 16:05:52 +0000346 cmd = [
347 sys.executable,
348 os.path.join(ROOT_DIR, 'isolate.py'),
Marc-Antoine Ruel8806e622014-02-12 14:15:53 -0500349 command,
350 flag, isolate_server,
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500351 '--namespace', namespace,
maruel@chromium.org0437a732013-08-27 16:05:52 +0000352 '--isolated', isolated,
353 ]
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000354 cmd.extend(['--verbose'] * verbose)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000355 logging.info(' '.join(cmd))
356 if subprocess.call(cmd, verbose):
357 return
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000358 return isolateserver.hash_file(isolated, algo)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000359 finally:
360 if tempdir:
361 shutil.rmtree(tempdir)
362
363
364def process_manifest(
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500365 swarming, isolate_server, namespace, isolated_hash, task_name, shards,
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -0500366 dimensions, env, working_dir, verbose, profile, priority, algo):
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500367 """Processes the manifest file and send off the swarming task request."""
maruel@chromium.org0437a732013-08-27 16:05:52 +0000368 try:
369 manifest = Manifest(
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500370 isolate_server=isolate_server,
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500371 namespace=namespace,
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500372 isolated_hash=isolated_hash,
373 task_name=task_name,
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500374 shards=shards,
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -0500375 dimensions=dimensions,
Marc-Antoine Ruel05dab5e2013-11-06 15:06:47 -0500376 env=env,
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500377 working_dir=working_dir,
378 verbose=verbose,
379 profile=profile,
380 priority=priority,
381 algo=algo)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000382 except ValueError as e:
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500383 tools.report_error('Unable to process %s: %s' % (task_name, e))
maruel@chromium.org0437a732013-08-27 16:05:52 +0000384 return 1
385
386 chromium_setup(manifest)
387
Marc-Antoine Ruelcd629732013-12-20 15:00:42 -0500388 logging.info('Zipping up files...')
389 if not zip_and_upload(manifest):
maruel@chromium.org0437a732013-08-27 16:05:52 +0000390 return 1
391
Marc-Antoine Ruelcd629732013-12-20 15:00:42 -0500392 logging.info('Server: %s', swarming)
393 logging.info('Task name: %s', task_name)
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500394 trigger_url = swarming + '/test'
maruel@chromium.org0437a732013-08-27 16:05:52 +0000395 manifest_text = manifest.to_json()
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500396 result = net.url_read(trigger_url, data={'request': manifest_text})
maruel@chromium.org0437a732013-08-27 16:05:52 +0000397 if not result:
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000398 tools.report_error(
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500399 'Failed to trigger task %s\n%s' % (task_name, trigger_url))
maruel@chromium.org0437a732013-08-27 16:05:52 +0000400 return 1
401 try:
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000402 json.loads(result)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000403 except (ValueError, TypeError) as e:
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000404 msg = '\n'.join((
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500405 'Failed to trigger task %s' % task_name,
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000406 'Manifest: %s' % manifest_text,
407 'Bad response: %s' % result,
408 str(e)))
409 tools.report_error(msg)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000410 return 1
411 return 0
412
413
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500414def isolated_to_hash(isolate_server, namespace, arg, algo, verbose):
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500415 """Archives a .isolated file if needed.
416
Marc-Antoine Ruel5b475782014-02-14 20:57:59 -0500417 Returns the file hash to trigger and a bool specifying if it was a file (True)
418 or a hash (False).
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500419 """
420 if arg.endswith('.isolated'):
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500421 file_hash = archive(isolate_server, namespace, arg, algo, verbose)
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500422 if not file_hash:
423 tools.report_error('Archival failure %s' % arg)
Marc-Antoine Ruel5b475782014-02-14 20:57:59 -0500424 return None, True
425 return file_hash, True
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500426 elif isolateserver.is_valid_hash(arg, algo):
Marc-Antoine Ruel5b475782014-02-14 20:57:59 -0500427 return arg, False
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500428 else:
429 tools.report_error('Invalid hash %s' % arg)
Marc-Antoine Ruel5b475782014-02-14 20:57:59 -0500430 return None, False
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500431
432
maruel@chromium.org0437a732013-08-27 16:05:52 +0000433def trigger(
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500434 swarming,
435 isolate_server,
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500436 namespace,
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500437 file_hash_or_isolated,
438 task_name,
439 shards,
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -0500440 dimensions,
441 env,
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500442 working_dir,
maruel@chromium.org0437a732013-08-27 16:05:52 +0000443 verbose,
444 profile,
445 priority):
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500446 """Sends off the hash swarming task requests."""
Marc-Antoine Ruel5b475782014-02-14 20:57:59 -0500447 file_hash, is_file = isolated_to_hash(
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500448 isolate_server, namespace, file_hash_or_isolated, hashlib.sha1, verbose)
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500449 if not file_hash:
Marc-Antoine Ruel5b475782014-02-14 20:57:59 -0500450 return 1, ''
451 if not task_name:
452 # If a file name was passed, use its base name of the isolated hash.
453 # Otherwise, use user name as an approximation of a task name.
454 if is_file:
455 key = os.path.splitext(os.path.basename(file_hash_or_isolated))[0]
456 else:
457 key = getpass.getuser()
458 task_name = '%s/%s/%s' % (
459 key,
460 '_'.join('%s=%s' % (k, v) for k, v in sorted(dimensions.iteritems())),
461 file_hash)
462
Marc-Antoine Ruelcd629732013-12-20 15:00:42 -0500463 env = googletest_setup(env, shards)
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500464 # TODO(maruel): It should first create a request manifest object, then pass
465 # it to a function to zip, archive and trigger.
Marc-Antoine Ruel5b475782014-02-14 20:57:59 -0500466 result = process_manifest(
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500467 swarming=swarming,
468 isolate_server=isolate_server,
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500469 namespace=namespace,
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500470 isolated_hash=file_hash,
471 task_name=task_name,
472 shards=shards,
473 dimensions=dimensions,
474 env=env,
475 working_dir=working_dir,
476 verbose=verbose,
477 profile=profile,
478 priority=priority,
479 algo=hashlib.sha1)
Marc-Antoine Ruel5b475782014-02-14 20:57:59 -0500480 return result, task_name
maruel@chromium.org0437a732013-08-27 16:05:52 +0000481
482
483def decorate_shard_output(result, shard_exit_code):
484 """Returns wrapped output for swarming task shard."""
485 tag = 'index %s (machine tag: %s, id: %s)' % (
486 result['config_instance_index'],
487 result['machine_id'],
488 result.get('machine_tag', 'unknown'))
489 return (
490 '\n'
491 '================================================================\n'
492 'Begin output from shard %s\n'
493 '================================================================\n'
494 '\n'
495 '%s'
496 '================================================================\n'
497 'End output from shard %s. Return %d\n'
498 '================================================================\n'
499 ) % (tag, result['output'] or NO_OUTPUT_FOUND, tag, shard_exit_code)
500
501
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500502def collect(url, task_name, timeout, decorate):
503 """Retrieves results of a Swarming task."""
504 logging.info('Collecting %s', task_name)
505 task_keys = get_task_keys(url, task_name)
506 if not task_keys:
507 raise Failure('No task keys to get results with.')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000508
maruel@chromium.org9c1c7b52013-08-28 19:04:36 +0000509 exit_code = None
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500510 for _index, output in yield_results(url, task_keys, timeout, None):
maruel@chromium.org0437a732013-08-27 16:05:52 +0000511 shard_exit_codes = (output['exit_codes'] or '1').split(',')
512 shard_exit_code = max(int(i) for i in shard_exit_codes)
513 if decorate:
514 print decorate_shard_output(output, shard_exit_code)
515 else:
516 print(
517 '%s/%s: %s' % (
518 output['machine_id'],
519 output['machine_tag'],
520 output['exit_codes']))
521 print(''.join(' %s\n' % l for l in output['output'].splitlines()))
maruel@chromium.org9c1c7b52013-08-28 19:04:36 +0000522 exit_code = exit_code or shard_exit_code
523 return exit_code if exit_code is not None else 1
maruel@chromium.org0437a732013-08-27 16:05:52 +0000524
525
526def add_trigger_options(parser):
527 """Adds all options to trigger a task on Swarming."""
Marc-Antoine Ruel8806e622014-02-12 14:15:53 -0500528 isolateserver.add_isolate_server_options(parser, True)
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500529
530 parser.filter_group = tools.optparse.OptionGroup(parser, 'Filtering slaves')
531 parser.filter_group.add_option(
Marc-Antoine Ruelb39e8cf2014-01-20 10:39:31 -0500532 '-d', '--dimension', default=[], action='append', nargs=2,
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -0500533 dest='dimensions', metavar='FOO bar',
534 help='dimension to filter on')
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500535 parser.add_option_group(parser.filter_group)
536
537 parser.task_group = tools.optparse.OptionGroup(parser, 'Task properties')
538 parser.task_group.add_option(
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500539 '-w', '--working-dir', default='swarm_tests',
540 help='Working directory on the swarming slave side. default: %default.')
541 parser.task_group.add_option(
542 '--working_dir', help=tools.optparse.SUPPRESS_HELP)
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500543 parser.task_group.add_option(
544 '-e', '--env', default=[], action='append', nargs=2, metavar='FOO bar',
545 help='environment variables to set')
546 parser.task_group.add_option(
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500547 '--priority', type='int', default=100,
548 help='The lower value, the more important the task is')
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500549 parser.task_group.add_option(
550 '--shards', type='int', default=1, help='number of shards to use')
551 parser.task_group.add_option(
Marc-Antoine Ruel5b475782014-02-14 20:57:59 -0500552 '-T', '--task-name',
553 help='Display name of the task. It uniquely identifies the task. '
554 'Defaults to <base_name>/<dimensions>/<isolated hash> if an '
555 'isolated file is provided, if a hash is provided, it defaults to '
556 '<user>/<dimensions>/<isolated hash>')
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500557 parser.add_option_group(parser.task_group)
Marc-Antoine Ruelcd629732013-12-20 15:00:42 -0500558 # TODO(maruel): This is currently written in a chromium-specific way.
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500559 parser.group_logging.add_option(
maruel@chromium.org0437a732013-08-27 16:05:52 +0000560 '--profile', action='store_true',
561 default=bool(os.environ.get('ISOLATE_DEBUG')),
562 help='Have run_isolated.py print profiling info')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000563
564
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500565def process_trigger_options(parser, options, args):
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500566 isolateserver.process_isolate_server_options(parser, options)
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500567 if len(args) != 1:
568 parser.error('Must pass one .isolated file or its hash (sha1).')
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500569 options.dimensions = dict(options.dimensions)
Marc-Antoine Ruelb39e8cf2014-01-20 10:39:31 -0500570 if not options.dimensions.get('os'):
571 parser.error(
572 'Please at least specify the dimension of the swarming bot OS with '
573 '--dimension os <something>.')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000574
575
576def add_collect_options(parser):
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500577 parser.server_group.add_option(
maruel@chromium.org0437a732013-08-27 16:05:52 +0000578 '-t', '--timeout',
579 type='float',
580 default=DEFAULT_SHARD_WAIT_TIME,
581 help='Timeout to wait for result, set to 0 for no timeout; default: '
582 '%default s')
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500583 parser.group_logging.add_option(
584 '--decorate', action='store_true', help='Decorate output')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000585
586
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500587@subcommand.usage('task_name')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000588def CMDcollect(parser, args):
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500589 """Retrieves results of a Swarming task.
maruel@chromium.org0437a732013-08-27 16:05:52 +0000590
591 The result can be in multiple part if the execution was sharded. It can
592 potentially have retries.
593 """
594 add_collect_options(parser)
595 (options, args) = parser.parse_args(args)
596 if not args:
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500597 parser.error('Must specify one task name.')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000598 elif len(args) > 1:
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500599 parser.error('Must specify only one task name.')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000600
601 try:
602 return collect(options.swarming, args[0], options.timeout, options.decorate)
603 except Failure as e:
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000604 tools.report_error(e)
605 return 1
maruel@chromium.org0437a732013-08-27 16:05:52 +0000606
607
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500608@subcommand.usage('[hash|isolated]')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000609def CMDrun(parser, args):
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500610 """Triggers a task and wait for the results.
maruel@chromium.org0437a732013-08-27 16:05:52 +0000611
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500612 Basically, does everything to run a command remotely.
maruel@chromium.org0437a732013-08-27 16:05:52 +0000613 """
614 add_trigger_options(parser)
615 add_collect_options(parser)
616 options, args = parser.parse_args(args)
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500617 process_trigger_options(parser, options, args)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000618
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500619 try:
Marc-Antoine Ruel5b475782014-02-14 20:57:59 -0500620 result, task_name = trigger(
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500621 swarming=options.swarming,
Marc-Antoine Ruel8806e622014-02-12 14:15:53 -0500622 isolate_server=options.isolate_server or options.indir,
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500623 namespace=options.namespace,
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500624 file_hash_or_isolated=args[0],
625 task_name=options.task_name,
626 shards=options.shards,
627 dimensions=options.dimensions,
628 env=dict(options.env),
629 working_dir=options.working_dir,
630 verbose=options.verbose,
631 profile=options.profile,
632 priority=options.priority)
633 except Failure as e:
634 tools.report_error(
635 'Failed to trigger %s(%s): %s' %
636 (options.task_name, args[0], e.args[0]))
637 return 1
638 if result:
639 tools.report_error('Failed to trigger the task.')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000640 return result
Marc-Antoine Ruel5b475782014-02-14 20:57:59 -0500641 if task_name != options.task_name:
642 print('Triggered task: %s' % task_name)
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500643 try:
644 return collect(
645 options.swarming,
Marc-Antoine Ruel5b475782014-02-14 20:57:59 -0500646 task_name,
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500647 options.timeout,
648 options.decorate)
649 except Failure as e:
650 tools.report_error(e)
651 return 1
maruel@chromium.org0437a732013-08-27 16:05:52 +0000652
653
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500654@subcommand.usage("(hash|isolated)")
maruel@chromium.org0437a732013-08-27 16:05:52 +0000655def CMDtrigger(parser, args):
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500656 """Triggers a Swarming task.
maruel@chromium.org0437a732013-08-27 16:05:52 +0000657
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500658 Accepts either the hash (sha1) of a .isolated file already uploaded or the
659 path to an .isolated file to archive, packages it if needed and sends a
660 Swarming manifest file to the Swarming server.
661
662 If an .isolated file is specified instead of an hash, it is first archived.
maruel@chromium.org0437a732013-08-27 16:05:52 +0000663 """
664 add_trigger_options(parser)
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500665 options, args = parser.parse_args(args)
666 process_trigger_options(parser, options, args)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000667
668 try:
Marc-Antoine Ruel5b475782014-02-14 20:57:59 -0500669 result, task_name = trigger(
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500670 swarming=options.swarming,
Marc-Antoine Ruel8806e622014-02-12 14:15:53 -0500671 isolate_server=options.isolate_server or options.indir,
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500672 namespace=options.namespace,
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500673 file_hash_or_isolated=args[0],
674 task_name=options.task_name,
675 dimensions=options.dimensions,
676 shards=options.shards,
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -0500677 env=dict(options.env),
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500678 working_dir=options.working_dir,
679 verbose=options.verbose,
680 profile=options.profile,
681 priority=options.priority)
Marc-Antoine Ruel5b475782014-02-14 20:57:59 -0500682 if task_name != options.task_name and not result:
683 print('Triggered task: %s' % task_name)
684 return result
maruel@chromium.org0437a732013-08-27 16:05:52 +0000685 except Failure as e:
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000686 tools.report_error(e)
687 return 1
maruel@chromium.org0437a732013-08-27 16:05:52 +0000688
689
690class OptionParserSwarming(tools.OptionParserWithLogging):
691 def __init__(self, **kwargs):
692 tools.OptionParserWithLogging.__init__(
693 self, prog='swarming.py', **kwargs)
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500694 self.server_group = tools.optparse.OptionGroup(self, 'Server')
695 self.server_group.add_option(
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000696 '-S', '--swarming',
Kevin Graney5346c162014-01-24 12:20:01 -0500697 metavar='URL', default=os.environ.get('SWARMING_SERVER', ''),
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000698 help='Swarming server to use')
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500699 self.add_option_group(self.server_group)
Vadim Shtayurae34e13a2014-02-02 11:23:26 -0800700 auth.add_auth_options(self)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000701
702 def parse_args(self, *args, **kwargs):
703 options, args = tools.OptionParserWithLogging.parse_args(
704 self, *args, **kwargs)
705 options.swarming = options.swarming.rstrip('/')
706 if not options.swarming:
707 self.error('--swarming is required.')
Vadim Shtayura5d1efce2014-02-04 10:55:43 -0800708 auth.process_auth_options(self, options)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000709 return options, args
710
711
712def main(args):
713 dispatcher = subcommand.CommandDispatcher(__name__)
714 try:
715 return dispatcher.execute(OptionParserSwarming(version=__version__), args)
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000716 except Exception as e:
717 tools.report_error(e)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000718 return 1
719
720
721if __name__ == '__main__':
722 fix_encoding.fix_encoding()
723 tools.disable_buffering()
724 colorama.init()
725 sys.exit(main(sys.argv[1:]))