blob: 28a6ef357a2750343c2649b31d3b1345372c5ba6 [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,
Vadim Shtayurabcff74f2014-02-27 16:19:34 -080061 dimensions, working_dir, verbose, profile, priority):
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.
maruel@chromium.org0437a732013-08-27 16:05:52 +000075 """
Marc-Antoine Ruela7049872013-11-05 19:28:35 -050076 self.isolate_server = isolate_server
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -050077 self.namespace = namespace
78 # The reason is that swarm_bot doesn't understand compressed data yet. So
79 # the data to be downloaded by swarm_bot is in 'default', independent of
80 # what run_isolated.py is going to fetch.
Marc-Antoine Ruela7049872013-11-05 19:28:35 -050081 self.storage = isolateserver.get_storage(isolate_server, 'default')
82
maruel@chromium.org814d23f2013-10-01 19:08:00 +000083 self.isolated_hash = isolated_hash
vadimsh@chromium.org6b706212013-08-28 15:03:46 +000084 self.bundle = zip_package.ZipPackage(ROOT_DIR)
85
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -050086 self._task_name = task_name
maruel@chromium.org0437a732013-08-27 16:05:52 +000087 self._shards = shards
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -050088 self._env = env.copy()
89 self._dimensions = dimensions.copy()
maruel@chromium.org0437a732013-08-27 16:05:52 +000090 self._working_dir = working_dir
91
maruel@chromium.org0437a732013-08-27 16:05:52 +000092 self.verbose = bool(verbose)
93 self.profile = bool(profile)
94 self.priority = priority
95
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +000096 self._isolate_item = None
maruel@chromium.org0437a732013-08-27 16:05:52 +000097 self._tasks = []
maruel@chromium.org0437a732013-08-27 16:05:52 +000098
99 def add_task(self, task_name, actions, time_out=600):
Marc-Antoine Ruel5c720342014-02-21 14:46:14 -0500100 """Appends a new task as a TestObject to the swarming manifest file.
Marc-Antoine Ruelcd629732013-12-20 15:00:42 -0500101
102 Tasks cannot be added once the manifest was uploaded.
Marc-Antoine Ruel5c720342014-02-21 14:46:14 -0500103
104 See TestObject in services/swarming/src/common/test_request_message.py for
105 the valid format.
Marc-Antoine Ruelcd629732013-12-20 15:00:42 -0500106 """
107 assert not self._isolate_item
maruel@chromium.org0437a732013-08-27 16:05:52 +0000108 self._tasks.append(
109 {
110 'action': actions,
111 'decorate_output': self.verbose,
112 'test_name': task_name,
113 'time_out': time_out,
114 })
115
maruel@chromium.org0437a732013-08-27 16:05:52 +0000116 def to_json(self):
117 """Exports the current configuration into a swarm-readable manifest file.
118
Marc-Antoine Ruel5c720342014-02-21 14:46:14 -0500119 The actual serialization format is defined as a TestCase object as described
120 in services/swarming/src/common/test_request_message.py
121
maruel@chromium.org0437a732013-08-27 16:05:52 +0000122 This function doesn't mutate the object.
123 """
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500124 request = {
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500125 'cleanup': 'root',
maruel@chromium.org0437a732013-08-27 16:05:52 +0000126 'configurations': [
Marc-Antoine Ruel5c720342014-02-21 14:46:14 -0500127 # Is a TestConfiguration.
maruel@chromium.org0437a732013-08-27 16:05:52 +0000128 {
Marc-Antoine Ruel5d799192013-11-06 15:20:39 -0500129 'config_name': 'isolated',
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -0500130 'dimensions': self._dimensions,
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500131 'min_instances': self._shards,
132 'priority': self.priority,
maruel@chromium.org0437a732013-08-27 16:05:52 +0000133 },
134 ],
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500135 'data': [],
136 # TODO: Let the encoding get set from the command line.
137 'encoding': 'UTF-8',
Marc-Antoine Ruel05dab5e2013-11-06 15:06:47 -0500138 'env_vars': self._env,
maruel@chromium.org0437a732013-08-27 16:05:52 +0000139 'restart_on_failure': True,
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500140 'test_case_name': self._task_name,
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500141 'tests': self._tasks,
142 'working_dir': self._working_dir,
maruel@chromium.org0437a732013-08-27 16:05:52 +0000143 }
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000144 if self._isolate_item:
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500145 request['data'].append(
maruel@chromium.org814d23f2013-10-01 19:08:00 +0000146 [
Vadim Shtayurabcff74f2014-02-27 16:19:34 -0800147 self.storage.get_fetch_url(self._isolate_item),
maruel@chromium.org814d23f2013-10-01 19:08:00 +0000148 'swarm_data.zip',
149 ])
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500150 return json.dumps(request, sort_keys=True, separators=(',',':'))
maruel@chromium.org0437a732013-08-27 16:05:52 +0000151
Marc-Antoine Ruelcd629732013-12-20 15:00:42 -0500152 @property
153 def isolate_item(self):
154 """Calling this property 'closes' the manifest and it can't be modified
155 afterward.
156 """
157 if self._isolate_item is None:
158 self._isolate_item = isolateserver.BufferItem(
Vadim Shtayurabcff74f2014-02-27 16:19:34 -0800159 self.bundle.zip_into_buffer(), high_priority=True)
Marc-Antoine Ruelcd629732013-12-20 15:00:42 -0500160 return self._isolate_item
161
162
163def zip_and_upload(manifest):
164 """Zips up all the files necessary to run a manifest and uploads to Swarming
165 master.
166 """
167 try:
168 start_time = time.time()
169 with manifest.storage:
170 uploaded = manifest.storage.upload_items([manifest.isolate_item])
171 elapsed = time.time() - start_time
172 except (IOError, OSError) as exc:
173 tools.report_error('Failed to upload the zip file: %s' % exc)
174 return False
175
176 if manifest.isolate_item in uploaded:
177 logging.info('Upload complete, time elapsed: %f', elapsed)
178 else:
179 logging.info('Zip file already on server, time elapsed: %f', elapsed)
180 return True
181
maruel@chromium.org0437a732013-08-27 16:05:52 +0000182
183def now():
184 """Exists so it can be mocked easily."""
185 return time.time()
186
187
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500188def get_task_keys(swarm_base_url, task_name):
189 """Returns the Swarming task key for each shards of task_name."""
190 key_data = urllib.urlencode([('name', task_name)])
maruel@chromium.org0437a732013-08-27 16:05:52 +0000191 url = '%s/get_matching_test_cases?%s' % (swarm_base_url, key_data)
192
vadimsh@chromium.org043b76d2013-09-12 16:15:13 +0000193 for _ in net.retry_loop(max_attempts=net.URL_OPEN_MAX_ATTEMPTS):
194 result = net.url_read(url, retry_404=True)
195 if result is None:
maruel@chromium.org0437a732013-08-27 16:05:52 +0000196 raise Failure(
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500197 'Error: Unable to find any task with the name, %s, on swarming server'
198 % task_name)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000199
maruel@chromium.org0437a732013-08-27 16:05:52 +0000200 # TODO(maruel): Compare exact string.
201 if 'No matching' in result:
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500202 logging.warning('Unable to find any task with the name, %s, on swarming '
203 'server' % task_name)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000204 continue
205 return json.loads(result)
206
207 raise Failure(
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500208 'Error: Unable to find any task with the name, %s, on swarming server'
209 % task_name)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000210
211
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500212def retrieve_results(base_url, task_key, timeout, should_stop):
213 """Retrieves results for a single task_key."""
maruel@chromium.org814d23f2013-10-01 19:08:00 +0000214 assert isinstance(timeout, float), timeout
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500215 params = [('r', task_key)]
maruel@chromium.org0437a732013-08-27 16:05:52 +0000216 result_url = '%s/get_result?%s' % (base_url, urllib.urlencode(params))
217 start = now()
218 while True:
219 if timeout and (now() - start) >= timeout:
220 logging.error('retrieve_results(%s) timed out', base_url)
221 return {}
222 # Do retries ourselves.
vadimsh@chromium.org043b76d2013-09-12 16:15:13 +0000223 response = net.url_read(result_url, retry_404=False, retry_50x=False)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000224 if response is None:
225 # Aggressively poll for results. Do not use retry_404 so
226 # should_stop is polled more often.
227 remaining = min(5, timeout - (now() - start)) if timeout else 5
228 if remaining > 0:
maruel@chromium.org814d23f2013-10-01 19:08:00 +0000229 if should_stop.get():
230 return {}
vadimsh@chromium.org043b76d2013-09-12 16:15:13 +0000231 net.sleep_before_retry(1, remaining)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000232 else:
233 try:
vadimsh@chromium.org043b76d2013-09-12 16:15:13 +0000234 data = json.loads(response) or {}
maruel@chromium.org0437a732013-08-27 16:05:52 +0000235 except (ValueError, TypeError):
236 logging.warning(
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500237 'Received corrupted data for task_key %s. Retrying.', task_key)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000238 else:
239 if data['output']:
240 return data
241 if should_stop.get():
242 return {}
243
244
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500245def yield_results(swarm_base_url, task_keys, timeout, max_threads):
246 """Yields swarming task results from the swarming server as (index, result).
maruel@chromium.org0437a732013-08-27 16:05:52 +0000247
248 Duplicate shards are ignored, the first one to complete is returned.
249
250 max_threads is optional and is used to limit the number of parallel fetches
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500251 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 +0000252 worth normally to limit the number threads. Mostly used for testing purposes.
Marc-Antoine Ruel5c720342014-02-21 14:46:14 -0500253
254 Yields:
255 (index, result). In particular, 'result' is defined as the
256 GetRunnerResults() function in services/swarming/server/test_runner.py.
maruel@chromium.org0437a732013-08-27 16:05:52 +0000257 """
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500258 shards_remaining = range(len(task_keys))
maruel@chromium.org0437a732013-08-27 16:05:52 +0000259 number_threads = (
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500260 min(max_threads, len(task_keys)) if max_threads else len(task_keys))
maruel@chromium.org0437a732013-08-27 16:05:52 +0000261 should_stop = threading_utils.Bit()
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500262 results_remaining = len(task_keys)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000263 with threading_utils.ThreadPool(number_threads, number_threads, 0) as pool:
264 try:
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500265 for task_key in task_keys:
maruel@chromium.org0437a732013-08-27 16:05:52 +0000266 pool.add_task(
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500267 0, retrieve_results, swarm_base_url, task_key, timeout, should_stop)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000268 while shards_remaining and results_remaining:
269 result = pool.get_one_result()
270 results_remaining -= 1
271 if not result:
272 # Failed to retrieve one key.
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500273 logging.error('Failed to retrieve the results for a swarming key')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000274 continue
275 shard_index = result['config_instance_index']
276 if shard_index in shards_remaining:
277 shards_remaining.remove(shard_index)
278 yield shard_index, result
279 else:
280 logging.warning('Ignoring duplicate shard index %d', shard_index)
281 # Pop the last entry, there's no such shard.
282 shards_remaining.pop()
283 finally:
284 # Done, kill the remaining threads.
285 should_stop.set()
286
287
288def chromium_setup(manifest):
289 """Sets up the commands to run.
290
291 Highly chromium specific.
292 """
vadimsh@chromium.org6b706212013-08-28 15:03:46 +0000293 # Add uncompressed zip here. It'll be compressed as part of the package sent
294 # to Swarming server.
295 run_test_name = 'run_isolated.zip'
296 manifest.bundle.add_buffer(run_test_name,
297 run_isolated.get_as_zip_package().zip_into_buffer(compress=False))
maruel@chromium.org0437a732013-08-27 16:05:52 +0000298
vadimsh@chromium.org6b706212013-08-28 15:03:46 +0000299 cleanup_script_name = 'swarm_cleanup.py'
300 manifest.bundle.add_file(os.path.join(TOOLS_PATH, cleanup_script_name),
301 cleanup_script_name)
302
maruel@chromium.org0437a732013-08-27 16:05:52 +0000303 run_cmd = [
304 'python', run_test_name,
maruel@chromium.org814d23f2013-10-01 19:08:00 +0000305 '--hash', manifest.isolated_hash,
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500306 '--namespace', manifest.namespace,
maruel@chromium.org0437a732013-08-27 16:05:52 +0000307 ]
Marc-Antoine Ruel8806e622014-02-12 14:15:53 -0500308 if file_path.is_url(manifest.isolate_server):
309 run_cmd.extend(('--isolate-server', manifest.isolate_server))
310 else:
311 run_cmd.extend(('--indir', manifest.isolate_server))
312
maruel@chromium.org0437a732013-08-27 16:05:52 +0000313 if manifest.verbose or manifest.profile:
314 # Have it print the profiling section.
315 run_cmd.append('--verbose')
316 manifest.add_task('Run Test', run_cmd)
317
318 # Clean up
319 manifest.add_task('Clean Up', ['python', cleanup_script_name])
320
321
Marc-Antoine Ruelcd629732013-12-20 15:00:42 -0500322def googletest_setup(env, shards):
323 """Sets googletest specific environment variables."""
324 if shards > 1:
325 env = env.copy()
326 env['GTEST_SHARD_INDEX'] = '%(instance_index)s'
327 env['GTEST_TOTAL_SHARDS'] = '%(num_instances)s'
328 return env
329
330
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500331def archive(isolate_server, namespace, isolated, algo, verbose):
maruel@chromium.org0437a732013-08-27 16:05:52 +0000332 """Archives a .isolated and all the dependencies on the CAC."""
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500333 logging.info('archive(%s, %s, %s)', isolate_server, namespace, isolated)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000334 tempdir = None
Marc-Antoine Ruel8806e622014-02-12 14:15:53 -0500335 if file_path.is_url(isolate_server):
336 command = 'archive'
337 flag = '--isolate-server'
338 else:
339 command = 'hashtable'
340 flag = '--outdir'
341
Marc-Antoine Ruel5b475782014-02-14 20:57:59 -0500342 print('Archiving: %s' % isolated)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000343 try:
maruel@chromium.org0437a732013-08-27 16:05:52 +0000344 cmd = [
345 sys.executable,
346 os.path.join(ROOT_DIR, 'isolate.py'),
Marc-Antoine Ruel8806e622014-02-12 14:15:53 -0500347 command,
348 flag, isolate_server,
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500349 '--namespace', namespace,
maruel@chromium.org0437a732013-08-27 16:05:52 +0000350 '--isolated', isolated,
351 ]
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000352 cmd.extend(['--verbose'] * verbose)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000353 logging.info(' '.join(cmd))
354 if subprocess.call(cmd, verbose):
355 return
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000356 return isolateserver.hash_file(isolated, algo)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000357 finally:
358 if tempdir:
359 shutil.rmtree(tempdir)
360
361
362def process_manifest(
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500363 swarming, isolate_server, namespace, isolated_hash, task_name, shards,
Vadim Shtayurabcff74f2014-02-27 16:19:34 -0800364 dimensions, env, working_dir, verbose, profile, priority):
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500365 """Processes the manifest file and send off the swarming task request."""
maruel@chromium.org0437a732013-08-27 16:05:52 +0000366 try:
367 manifest = Manifest(
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500368 isolate_server=isolate_server,
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500369 namespace=namespace,
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500370 isolated_hash=isolated_hash,
371 task_name=task_name,
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500372 shards=shards,
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -0500373 dimensions=dimensions,
Marc-Antoine Ruel05dab5e2013-11-06 15:06:47 -0500374 env=env,
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500375 working_dir=working_dir,
376 verbose=verbose,
377 profile=profile,
Vadim Shtayurabcff74f2014-02-27 16:19:34 -0800378 priority=priority)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000379 except ValueError as e:
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500380 tools.report_error('Unable to process %s: %s' % (task_name, e))
maruel@chromium.org0437a732013-08-27 16:05:52 +0000381 return 1
382
383 chromium_setup(manifest)
384
Marc-Antoine Ruelcd629732013-12-20 15:00:42 -0500385 logging.info('Zipping up files...')
386 if not zip_and_upload(manifest):
maruel@chromium.org0437a732013-08-27 16:05:52 +0000387 return 1
388
Marc-Antoine Ruelcd629732013-12-20 15:00:42 -0500389 logging.info('Server: %s', swarming)
390 logging.info('Task name: %s', task_name)
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500391 trigger_url = swarming + '/test'
maruel@chromium.org0437a732013-08-27 16:05:52 +0000392 manifest_text = manifest.to_json()
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500393 result = net.url_read(trigger_url, data={'request': manifest_text})
maruel@chromium.org0437a732013-08-27 16:05:52 +0000394 if not result:
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000395 tools.report_error(
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500396 'Failed to trigger task %s\n%s' % (task_name, trigger_url))
maruel@chromium.org0437a732013-08-27 16:05:52 +0000397 return 1
398 try:
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000399 json.loads(result)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000400 except (ValueError, TypeError) as e:
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000401 msg = '\n'.join((
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500402 'Failed to trigger task %s' % task_name,
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000403 'Manifest: %s' % manifest_text,
404 'Bad response: %s' % result,
405 str(e)))
406 tools.report_error(msg)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000407 return 1
408 return 0
409
410
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500411def isolated_to_hash(isolate_server, namespace, arg, algo, verbose):
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500412 """Archives a .isolated file if needed.
413
Marc-Antoine Ruel5b475782014-02-14 20:57:59 -0500414 Returns the file hash to trigger and a bool specifying if it was a file (True)
415 or a hash (False).
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500416 """
417 if arg.endswith('.isolated'):
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500418 file_hash = archive(isolate_server, namespace, arg, algo, verbose)
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500419 if not file_hash:
420 tools.report_error('Archival failure %s' % arg)
Marc-Antoine Ruel5b475782014-02-14 20:57:59 -0500421 return None, True
422 return file_hash, True
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500423 elif isolateserver.is_valid_hash(arg, algo):
Marc-Antoine Ruel5b475782014-02-14 20:57:59 -0500424 return arg, False
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500425 else:
426 tools.report_error('Invalid hash %s' % arg)
Marc-Antoine Ruel5b475782014-02-14 20:57:59 -0500427 return None, False
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500428
429
maruel@chromium.org0437a732013-08-27 16:05:52 +0000430def trigger(
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500431 swarming,
432 isolate_server,
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500433 namespace,
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500434 file_hash_or_isolated,
435 task_name,
436 shards,
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -0500437 dimensions,
438 env,
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500439 working_dir,
maruel@chromium.org0437a732013-08-27 16:05:52 +0000440 verbose,
441 profile,
442 priority):
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500443 """Sends off the hash swarming task requests."""
Marc-Antoine Ruel5b475782014-02-14 20:57:59 -0500444 file_hash, is_file = isolated_to_hash(
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500445 isolate_server, namespace, file_hash_or_isolated, hashlib.sha1, verbose)
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500446 if not file_hash:
Marc-Antoine Ruel5b475782014-02-14 20:57:59 -0500447 return 1, ''
448 if not task_name:
449 # If a file name was passed, use its base name of the isolated hash.
450 # Otherwise, use user name as an approximation of a task name.
451 if is_file:
452 key = os.path.splitext(os.path.basename(file_hash_or_isolated))[0]
453 else:
454 key = getpass.getuser()
455 task_name = '%s/%s/%s' % (
456 key,
457 '_'.join('%s=%s' % (k, v) for k, v in sorted(dimensions.iteritems())),
458 file_hash)
459
Marc-Antoine Ruelcd629732013-12-20 15:00:42 -0500460 env = googletest_setup(env, shards)
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500461 # TODO(maruel): It should first create a request manifest object, then pass
462 # it to a function to zip, archive and trigger.
Marc-Antoine Ruel5b475782014-02-14 20:57:59 -0500463 result = process_manifest(
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500464 swarming=swarming,
465 isolate_server=isolate_server,
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500466 namespace=namespace,
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500467 isolated_hash=file_hash,
468 task_name=task_name,
469 shards=shards,
470 dimensions=dimensions,
471 env=env,
472 working_dir=working_dir,
473 verbose=verbose,
474 profile=profile,
Vadim Shtayurabcff74f2014-02-27 16:19:34 -0800475 priority=priority)
Marc-Antoine Ruel5b475782014-02-14 20:57:59 -0500476 return result, task_name
maruel@chromium.org0437a732013-08-27 16:05:52 +0000477
478
479def decorate_shard_output(result, shard_exit_code):
480 """Returns wrapped output for swarming task shard."""
481 tag = 'index %s (machine tag: %s, id: %s)' % (
482 result['config_instance_index'],
483 result['machine_id'],
484 result.get('machine_tag', 'unknown'))
485 return (
486 '\n'
487 '================================================================\n'
488 'Begin output from shard %s\n'
489 '================================================================\n'
490 '\n'
491 '%s'
492 '================================================================\n'
493 'End output from shard %s. Return %d\n'
494 '================================================================\n'
495 ) % (tag, result['output'] or NO_OUTPUT_FOUND, tag, shard_exit_code)
496
497
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500498def collect(url, task_name, timeout, decorate):
499 """Retrieves results of a Swarming task."""
500 logging.info('Collecting %s', task_name)
501 task_keys = get_task_keys(url, task_name)
502 if not task_keys:
503 raise Failure('No task keys to get results with.')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000504
maruel@chromium.org9c1c7b52013-08-28 19:04:36 +0000505 exit_code = None
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500506 for _index, output in yield_results(url, task_keys, timeout, None):
maruel@chromium.org0437a732013-08-27 16:05:52 +0000507 shard_exit_codes = (output['exit_codes'] or '1').split(',')
508 shard_exit_code = max(int(i) for i in shard_exit_codes)
509 if decorate:
510 print decorate_shard_output(output, shard_exit_code)
511 else:
512 print(
513 '%s/%s: %s' % (
514 output['machine_id'],
515 output['machine_tag'],
516 output['exit_codes']))
517 print(''.join(' %s\n' % l for l in output['output'].splitlines()))
maruel@chromium.org9c1c7b52013-08-28 19:04:36 +0000518 exit_code = exit_code or shard_exit_code
519 return exit_code if exit_code is not None else 1
maruel@chromium.org0437a732013-08-27 16:05:52 +0000520
521
522def add_trigger_options(parser):
523 """Adds all options to trigger a task on Swarming."""
Marc-Antoine Ruel8806e622014-02-12 14:15:53 -0500524 isolateserver.add_isolate_server_options(parser, True)
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500525
526 parser.filter_group = tools.optparse.OptionGroup(parser, 'Filtering slaves')
527 parser.filter_group.add_option(
Marc-Antoine Ruelb39e8cf2014-01-20 10:39:31 -0500528 '-d', '--dimension', default=[], action='append', nargs=2,
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -0500529 dest='dimensions', metavar='FOO bar',
530 help='dimension to filter on')
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500531 parser.add_option_group(parser.filter_group)
532
533 parser.task_group = tools.optparse.OptionGroup(parser, 'Task properties')
534 parser.task_group.add_option(
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500535 '-w', '--working-dir', default='swarm_tests',
536 help='Working directory on the swarming slave side. default: %default.')
537 parser.task_group.add_option(
538 '--working_dir', help=tools.optparse.SUPPRESS_HELP)
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500539 parser.task_group.add_option(
540 '-e', '--env', default=[], action='append', nargs=2, metavar='FOO bar',
541 help='environment variables to set')
542 parser.task_group.add_option(
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500543 '--priority', type='int', default=100,
544 help='The lower value, the more important the task is')
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500545 parser.task_group.add_option(
546 '--shards', type='int', default=1, help='number of shards to use')
547 parser.task_group.add_option(
Marc-Antoine Ruel5b475782014-02-14 20:57:59 -0500548 '-T', '--task-name',
549 help='Display name of the task. It uniquely identifies the task. '
550 'Defaults to <base_name>/<dimensions>/<isolated hash> if an '
551 'isolated file is provided, if a hash is provided, it defaults to '
552 '<user>/<dimensions>/<isolated hash>')
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500553 parser.add_option_group(parser.task_group)
Marc-Antoine Ruelcd629732013-12-20 15:00:42 -0500554 # TODO(maruel): This is currently written in a chromium-specific way.
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500555 parser.group_logging.add_option(
maruel@chromium.org0437a732013-08-27 16:05:52 +0000556 '--profile', action='store_true',
557 default=bool(os.environ.get('ISOLATE_DEBUG')),
558 help='Have run_isolated.py print profiling info')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000559
560
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500561def process_trigger_options(parser, options, args):
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500562 isolateserver.process_isolate_server_options(parser, options)
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500563 if len(args) != 1:
564 parser.error('Must pass one .isolated file or its hash (sha1).')
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500565 options.dimensions = dict(options.dimensions)
Marc-Antoine Ruelb39e8cf2014-01-20 10:39:31 -0500566 if not options.dimensions.get('os'):
567 parser.error(
568 'Please at least specify the dimension of the swarming bot OS with '
569 '--dimension os <something>.')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000570
571
572def add_collect_options(parser):
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500573 parser.server_group.add_option(
maruel@chromium.org0437a732013-08-27 16:05:52 +0000574 '-t', '--timeout',
575 type='float',
576 default=DEFAULT_SHARD_WAIT_TIME,
577 help='Timeout to wait for result, set to 0 for no timeout; default: '
578 '%default s')
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500579 parser.group_logging.add_option(
580 '--decorate', action='store_true', help='Decorate output')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000581
582
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500583@subcommand.usage('task_name')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000584def CMDcollect(parser, args):
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500585 """Retrieves results of a Swarming task.
maruel@chromium.org0437a732013-08-27 16:05:52 +0000586
587 The result can be in multiple part if the execution was sharded. It can
588 potentially have retries.
589 """
590 add_collect_options(parser)
591 (options, args) = parser.parse_args(args)
592 if not args:
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500593 parser.error('Must specify one task name.')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000594 elif len(args) > 1:
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500595 parser.error('Must specify only one task name.')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000596
597 try:
598 return collect(options.swarming, args[0], options.timeout, options.decorate)
599 except Failure as e:
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000600 tools.report_error(e)
601 return 1
maruel@chromium.org0437a732013-08-27 16:05:52 +0000602
603
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500604@subcommand.usage('[hash|isolated]')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000605def CMDrun(parser, args):
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500606 """Triggers a task and wait for the results.
maruel@chromium.org0437a732013-08-27 16:05:52 +0000607
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500608 Basically, does everything to run a command remotely.
maruel@chromium.org0437a732013-08-27 16:05:52 +0000609 """
610 add_trigger_options(parser)
611 add_collect_options(parser)
612 options, args = parser.parse_args(args)
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500613 process_trigger_options(parser, options, args)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000614
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500615 try:
Marc-Antoine Ruel5b475782014-02-14 20:57:59 -0500616 result, task_name = trigger(
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500617 swarming=options.swarming,
Marc-Antoine Ruel8806e622014-02-12 14:15:53 -0500618 isolate_server=options.isolate_server or options.indir,
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500619 namespace=options.namespace,
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500620 file_hash_or_isolated=args[0],
621 task_name=options.task_name,
622 shards=options.shards,
623 dimensions=options.dimensions,
624 env=dict(options.env),
625 working_dir=options.working_dir,
626 verbose=options.verbose,
627 profile=options.profile,
628 priority=options.priority)
629 except Failure as e:
630 tools.report_error(
631 'Failed to trigger %s(%s): %s' %
632 (options.task_name, args[0], e.args[0]))
633 return 1
634 if result:
635 tools.report_error('Failed to trigger the task.')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000636 return result
Marc-Antoine Ruel5b475782014-02-14 20:57:59 -0500637 if task_name != options.task_name:
638 print('Triggered task: %s' % task_name)
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500639 try:
640 return collect(
641 options.swarming,
Marc-Antoine Ruel5b475782014-02-14 20:57:59 -0500642 task_name,
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500643 options.timeout,
644 options.decorate)
645 except Failure as e:
646 tools.report_error(e)
647 return 1
maruel@chromium.org0437a732013-08-27 16:05:52 +0000648
649
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500650@subcommand.usage("(hash|isolated)")
maruel@chromium.org0437a732013-08-27 16:05:52 +0000651def CMDtrigger(parser, args):
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500652 """Triggers a Swarming task.
maruel@chromium.org0437a732013-08-27 16:05:52 +0000653
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500654 Accepts either the hash (sha1) of a .isolated file already uploaded or the
655 path to an .isolated file to archive, packages it if needed and sends a
656 Swarming manifest file to the Swarming server.
657
658 If an .isolated file is specified instead of an hash, it is first archived.
maruel@chromium.org0437a732013-08-27 16:05:52 +0000659 """
660 add_trigger_options(parser)
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500661 options, args = parser.parse_args(args)
662 process_trigger_options(parser, options, args)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000663
664 try:
Marc-Antoine Ruel5b475782014-02-14 20:57:59 -0500665 result, task_name = trigger(
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500666 swarming=options.swarming,
Marc-Antoine Ruel8806e622014-02-12 14:15:53 -0500667 isolate_server=options.isolate_server or options.indir,
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500668 namespace=options.namespace,
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500669 file_hash_or_isolated=args[0],
670 task_name=options.task_name,
671 dimensions=options.dimensions,
672 shards=options.shards,
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -0500673 env=dict(options.env),
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500674 working_dir=options.working_dir,
675 verbose=options.verbose,
676 profile=options.profile,
677 priority=options.priority)
Marc-Antoine Ruel5b475782014-02-14 20:57:59 -0500678 if task_name != options.task_name and not result:
679 print('Triggered task: %s' % task_name)
680 return result
maruel@chromium.org0437a732013-08-27 16:05:52 +0000681 except Failure as e:
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000682 tools.report_error(e)
683 return 1
maruel@chromium.org0437a732013-08-27 16:05:52 +0000684
685
686class OptionParserSwarming(tools.OptionParserWithLogging):
687 def __init__(self, **kwargs):
688 tools.OptionParserWithLogging.__init__(
689 self, prog='swarming.py', **kwargs)
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500690 self.server_group = tools.optparse.OptionGroup(self, 'Server')
691 self.server_group.add_option(
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000692 '-S', '--swarming',
Kevin Graney5346c162014-01-24 12:20:01 -0500693 metavar='URL', default=os.environ.get('SWARMING_SERVER', ''),
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000694 help='Swarming server to use')
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500695 self.add_option_group(self.server_group)
Vadim Shtayurae34e13a2014-02-02 11:23:26 -0800696 auth.add_auth_options(self)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000697
698 def parse_args(self, *args, **kwargs):
699 options, args = tools.OptionParserWithLogging.parse_args(
700 self, *args, **kwargs)
701 options.swarming = options.swarming.rstrip('/')
702 if not options.swarming:
703 self.error('--swarming is required.')
Vadim Shtayura5d1efce2014-02-04 10:55:43 -0800704 auth.process_auth_options(self, options)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000705 return options, args
706
707
708def main(args):
709 dispatcher = subcommand.CommandDispatcher(__name__)
710 try:
711 return dispatcher.execute(OptionParserSwarming(version=__version__), args)
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000712 except Exception as e:
713 tools.report_error(e)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000714 return 1
715
716
717if __name__ == '__main__':
718 fix_encoding.fix_encoding()
719 tools.disable_buffering()
720 colorama.init()
721 sys.exit(main(sys.argv[1:]))