blob: b93fbfcd833dc66db278dc1534d57ef5985baf56 [file] [log] [blame]
maruel@chromium.org0437a732013-08-27 16:05:52 +00001#!/usr/bin/env python
Marc-Antoine Ruel8add1242013-11-05 17:28:27 -05002# Copyright 2013 The Swarming Authors. All rights reserved.
Marc-Antoine Ruele98b1122013-11-05 20:27:57 -05003# Use of this source code is governed under the Apache License, Version 2.0 that
4# can be found in the LICENSE file.
maruel@chromium.org0437a732013-08-27 16:05:52 +00005
6"""Client tool to trigger tasks or retrieve results from a Swarming server."""
7
Marc-Antoine Ruelb39e8cf2014-01-20 10:39:31 -05008__version__ = '0.4'
maruel@chromium.org0437a732013-08-27 16:05:52 +00009
10import hashlib
11import json
12import logging
13import os
maruel@chromium.org0437a732013-08-27 16:05:52 +000014import shutil
maruel@chromium.org0437a732013-08-27 16:05:52 +000015import subprocess
16import sys
17import time
18import urllib
maruel@chromium.org0437a732013-08-27 16:05:52 +000019
20from third_party import colorama
21from third_party.depot_tools import fix_encoding
22from third_party.depot_tools import subcommand
vadimsh@chromium.org6b706212013-08-28 15:03:46 +000023
24from utils import net
maruel@chromium.org0437a732013-08-27 16:05:52 +000025from utils import threading_utils
vadimsh@chromium.org6b706212013-08-28 15:03:46 +000026from utils import tools
27from utils import zip_package
maruel@chromium.org0437a732013-08-27 16:05:52 +000028
Vadim Shtayurae34e13a2014-02-02 11:23:26 -080029import auth
maruel@chromium.org7b844a62013-09-17 13:04:59 +000030import isolateserver
maruel@chromium.org0437a732013-08-27 16:05:52 +000031import run_isolated
32
33
34ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
35TOOLS_PATH = os.path.join(ROOT_DIR, 'tools')
36
37
maruel@chromium.org0437a732013-08-27 16:05:52 +000038# The default time to wait for a shard to finish running.
csharp@chromium.org24758492013-08-28 19:10:54 +000039DEFAULT_SHARD_WAIT_TIME = 80 * 60.
maruel@chromium.org0437a732013-08-27 16:05:52 +000040
41
42NO_OUTPUT_FOUND = (
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -050043 'No output produced by the task, it may have failed to run.\n'
maruel@chromium.org0437a732013-08-27 16:05:52 +000044 '\n')
45
46
maruel@chromium.org0437a732013-08-27 16:05:52 +000047class Failure(Exception):
48 """Generic failure."""
49 pass
50
51
52class Manifest(object):
53 """Represents a Swarming task manifest.
54
55 Also includes code to zip code and upload itself.
56 """
57 def __init__(
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -050058 self, isolate_server, namespace, isolated_hash, task_name, shards, env,
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -050059 dimensions, working_dir, verbose, profile, priority, algo):
maruel@chromium.org0437a732013-08-27 16:05:52 +000060 """Populates a manifest object.
61 Args:
Marc-Antoine Ruela7049872013-11-05 19:28:35 -050062 isolate_server - isolate server url.
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -050063 namespace - isolate server namespace to use.
maruel@chromium.org814d23f2013-10-01 19:08:00 +000064 isolated_hash - The manifest's sha-1 that the slave is going to fetch.
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -050065 task_name - The name to give the task request.
66 shards - The number of swarming shards to request.
Marc-Antoine Ruel05dab5e2013-11-06 15:06:47 -050067 env - environment variables to set.
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -050068 dimensions - dimensions to filter the task on.
maruel@chromium.org0437a732013-08-27 16:05:52 +000069 working_dir - Relative working directory to start the script.
maruel@chromium.org0437a732013-08-27 16:05:52 +000070 verbose - if True, have the slave print more details.
71 profile - if True, have the slave print more timing data.
maruel@chromium.org7b844a62013-09-17 13:04:59 +000072 priority - int between 0 and 1000, lower the higher priority.
73 algo - hashing algorithm used.
maruel@chromium.org0437a732013-08-27 16:05:52 +000074 """
Marc-Antoine Ruela7049872013-11-05 19:28:35 -050075 self.isolate_server = isolate_server
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -050076 self.namespace = namespace
77 # The reason is that swarm_bot doesn't understand compressed data yet. So
78 # the data to be downloaded by swarm_bot is in 'default', independent of
79 # what run_isolated.py is going to fetch.
Marc-Antoine Ruela7049872013-11-05 19:28:35 -050080 self.storage = isolateserver.get_storage(isolate_server, 'default')
81
maruel@chromium.org814d23f2013-10-01 19:08:00 +000082 self.isolated_hash = isolated_hash
vadimsh@chromium.org6b706212013-08-28 15:03:46 +000083 self.bundle = zip_package.ZipPackage(ROOT_DIR)
84
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -050085 self._task_name = task_name
maruel@chromium.org0437a732013-08-27 16:05:52 +000086 self._shards = shards
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -050087 self._env = env.copy()
88 self._dimensions = dimensions.copy()
maruel@chromium.org0437a732013-08-27 16:05:52 +000089 self._working_dir = working_dir
90
maruel@chromium.org0437a732013-08-27 16:05:52 +000091 self.verbose = bool(verbose)
92 self.profile = bool(profile)
93 self.priority = priority
maruel@chromium.org7b844a62013-09-17 13:04:59 +000094 self._algo = algo
maruel@chromium.org0437a732013-08-27 16:05:52 +000095
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 Ruelcd629732013-12-20 15:00:42 -0500100 """Appends a new task to the swarming manifest file.
101
102 Tasks cannot be added once the manifest was uploaded.
103 """
104 assert not self._isolate_item
maruel@chromium.org0437a732013-08-27 16:05:52 +0000105 # See swarming/src/common/test_request_message.py TestObject constructor for
106 # the valid flags.
107 self._tasks.append(
108 {
109 'action': actions,
110 'decorate_output': self.verbose,
111 'test_name': task_name,
112 'time_out': time_out,
113 })
114
maruel@chromium.org0437a732013-08-27 16:05:52 +0000115 def to_json(self):
116 """Exports the current configuration into a swarm-readable manifest file.
117
118 This function doesn't mutate the object.
119 """
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500120 request = {
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500121 'cleanup': 'root',
maruel@chromium.org0437a732013-08-27 16:05:52 +0000122 'configurations': [
123 {
Marc-Antoine Ruel5d799192013-11-06 15:20:39 -0500124 'config_name': 'isolated',
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -0500125 'dimensions': self._dimensions,
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500126 'min_instances': self._shards,
127 'priority': self.priority,
maruel@chromium.org0437a732013-08-27 16:05:52 +0000128 },
129 ],
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500130 'data': [],
131 # TODO: Let the encoding get set from the command line.
132 'encoding': 'UTF-8',
Marc-Antoine Ruel05dab5e2013-11-06 15:06:47 -0500133 'env_vars': self._env,
maruel@chromium.org0437a732013-08-27 16:05:52 +0000134 'restart_on_failure': True,
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500135 'test_case_name': self._task_name,
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500136 'tests': self._tasks,
137 'working_dir': self._working_dir,
maruel@chromium.org0437a732013-08-27 16:05:52 +0000138 }
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000139 if self._isolate_item:
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500140 request['data'].append(
maruel@chromium.org814d23f2013-10-01 19:08:00 +0000141 [
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000142 self.storage.get_fetch_url(self._isolate_item.digest),
maruel@chromium.org814d23f2013-10-01 19:08:00 +0000143 'swarm_data.zip',
144 ])
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500145 return json.dumps(request, sort_keys=True, separators=(',',':'))
maruel@chromium.org0437a732013-08-27 16:05:52 +0000146
Marc-Antoine Ruelcd629732013-12-20 15:00:42 -0500147 @property
148 def isolate_item(self):
149 """Calling this property 'closes' the manifest and it can't be modified
150 afterward.
151 """
152 if self._isolate_item is None:
153 self._isolate_item = isolateserver.BufferItem(
154 self.bundle.zip_into_buffer(), self._algo, is_isolated=True)
155 return self._isolate_item
156
157
158def zip_and_upload(manifest):
159 """Zips up all the files necessary to run a manifest and uploads to Swarming
160 master.
161 """
162 try:
163 start_time = time.time()
164 with manifest.storage:
165 uploaded = manifest.storage.upload_items([manifest.isolate_item])
166 elapsed = time.time() - start_time
167 except (IOError, OSError) as exc:
168 tools.report_error('Failed to upload the zip file: %s' % exc)
169 return False
170
171 if manifest.isolate_item in uploaded:
172 logging.info('Upload complete, time elapsed: %f', elapsed)
173 else:
174 logging.info('Zip file already on server, time elapsed: %f', elapsed)
175 return True
176
maruel@chromium.org0437a732013-08-27 16:05:52 +0000177
178def now():
179 """Exists so it can be mocked easily."""
180 return time.time()
181
182
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500183def get_task_keys(swarm_base_url, task_name):
184 """Returns the Swarming task key for each shards of task_name."""
185 key_data = urllib.urlencode([('name', task_name)])
maruel@chromium.org0437a732013-08-27 16:05:52 +0000186 url = '%s/get_matching_test_cases?%s' % (swarm_base_url, key_data)
187
vadimsh@chromium.org043b76d2013-09-12 16:15:13 +0000188 for _ in net.retry_loop(max_attempts=net.URL_OPEN_MAX_ATTEMPTS):
189 result = net.url_read(url, retry_404=True)
190 if result is None:
maruel@chromium.org0437a732013-08-27 16:05:52 +0000191 raise Failure(
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500192 'Error: Unable to find any task with the name, %s, on swarming server'
193 % task_name)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000194
maruel@chromium.org0437a732013-08-27 16:05:52 +0000195 # TODO(maruel): Compare exact string.
196 if 'No matching' in result:
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500197 logging.warning('Unable to find any task with the name, %s, on swarming '
198 'server' % task_name)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000199 continue
200 return json.loads(result)
201
202 raise Failure(
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500203 'Error: Unable to find any task with the name, %s, on swarming server'
204 % task_name)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000205
206
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500207def retrieve_results(base_url, task_key, timeout, should_stop):
208 """Retrieves results for a single task_key."""
maruel@chromium.org814d23f2013-10-01 19:08:00 +0000209 assert isinstance(timeout, float), timeout
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500210 params = [('r', task_key)]
maruel@chromium.org0437a732013-08-27 16:05:52 +0000211 result_url = '%s/get_result?%s' % (base_url, urllib.urlencode(params))
212 start = now()
213 while True:
214 if timeout and (now() - start) >= timeout:
215 logging.error('retrieve_results(%s) timed out', base_url)
216 return {}
217 # Do retries ourselves.
vadimsh@chromium.org043b76d2013-09-12 16:15:13 +0000218 response = net.url_read(result_url, retry_404=False, retry_50x=False)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000219 if response is None:
220 # Aggressively poll for results. Do not use retry_404 so
221 # should_stop is polled more often.
222 remaining = min(5, timeout - (now() - start)) if timeout else 5
223 if remaining > 0:
maruel@chromium.org814d23f2013-10-01 19:08:00 +0000224 if should_stop.get():
225 return {}
vadimsh@chromium.org043b76d2013-09-12 16:15:13 +0000226 net.sleep_before_retry(1, remaining)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000227 else:
228 try:
vadimsh@chromium.org043b76d2013-09-12 16:15:13 +0000229 data = json.loads(response) or {}
maruel@chromium.org0437a732013-08-27 16:05:52 +0000230 except (ValueError, TypeError):
231 logging.warning(
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500232 'Received corrupted data for task_key %s. Retrying.', task_key)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000233 else:
234 if data['output']:
235 return data
236 if should_stop.get():
237 return {}
238
239
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500240def yield_results(swarm_base_url, task_keys, timeout, max_threads):
241 """Yields swarming task results from the swarming server as (index, result).
maruel@chromium.org0437a732013-08-27 16:05:52 +0000242
243 Duplicate shards are ignored, the first one to complete is returned.
244
245 max_threads is optional and is used to limit the number of parallel fetches
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500246 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 +0000247 worth normally to limit the number threads. Mostly used for testing purposes.
248 """
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500249 shards_remaining = range(len(task_keys))
maruel@chromium.org0437a732013-08-27 16:05:52 +0000250 number_threads = (
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500251 min(max_threads, len(task_keys)) if max_threads else len(task_keys))
maruel@chromium.org0437a732013-08-27 16:05:52 +0000252 should_stop = threading_utils.Bit()
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500253 results_remaining = len(task_keys)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000254 with threading_utils.ThreadPool(number_threads, number_threads, 0) as pool:
255 try:
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500256 for task_key in task_keys:
maruel@chromium.org0437a732013-08-27 16:05:52 +0000257 pool.add_task(
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500258 0, retrieve_results, swarm_base_url, task_key, timeout, should_stop)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000259 while shards_remaining and results_remaining:
260 result = pool.get_one_result()
261 results_remaining -= 1
262 if not result:
263 # Failed to retrieve one key.
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500264 logging.error('Failed to retrieve the results for a swarming key')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000265 continue
266 shard_index = result['config_instance_index']
267 if shard_index in shards_remaining:
268 shards_remaining.remove(shard_index)
269 yield shard_index, result
270 else:
271 logging.warning('Ignoring duplicate shard index %d', shard_index)
272 # Pop the last entry, there's no such shard.
273 shards_remaining.pop()
274 finally:
275 # Done, kill the remaining threads.
276 should_stop.set()
277
278
279def chromium_setup(manifest):
280 """Sets up the commands to run.
281
282 Highly chromium specific.
283 """
vadimsh@chromium.org6b706212013-08-28 15:03:46 +0000284 # Add uncompressed zip here. It'll be compressed as part of the package sent
285 # to Swarming server.
286 run_test_name = 'run_isolated.zip'
287 manifest.bundle.add_buffer(run_test_name,
288 run_isolated.get_as_zip_package().zip_into_buffer(compress=False))
maruel@chromium.org0437a732013-08-27 16:05:52 +0000289
vadimsh@chromium.org6b706212013-08-28 15:03:46 +0000290 cleanup_script_name = 'swarm_cleanup.py'
291 manifest.bundle.add_file(os.path.join(TOOLS_PATH, cleanup_script_name),
292 cleanup_script_name)
293
maruel@chromium.org0437a732013-08-27 16:05:52 +0000294 run_cmd = [
295 'python', run_test_name,
maruel@chromium.org814d23f2013-10-01 19:08:00 +0000296 '--hash', manifest.isolated_hash,
maruel@chromium.orgb7e79a22013-09-13 01:24:56 +0000297 '--isolate-server', manifest.isolate_server,
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500298 '--namespace', manifest.namespace,
maruel@chromium.org0437a732013-08-27 16:05:52 +0000299 ]
300 if manifest.verbose or manifest.profile:
301 # Have it print the profiling section.
302 run_cmd.append('--verbose')
303 manifest.add_task('Run Test', run_cmd)
304
305 # Clean up
306 manifest.add_task('Clean Up', ['python', cleanup_script_name])
307
308
Marc-Antoine Ruelcd629732013-12-20 15:00:42 -0500309def googletest_setup(env, shards):
310 """Sets googletest specific environment variables."""
311 if shards > 1:
312 env = env.copy()
313 env['GTEST_SHARD_INDEX'] = '%(instance_index)s'
314 env['GTEST_TOTAL_SHARDS'] = '%(num_instances)s'
315 return env
316
317
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500318def archive(isolate_server, namespace, isolated, algo, verbose):
maruel@chromium.org0437a732013-08-27 16:05:52 +0000319 """Archives a .isolated and all the dependencies on the CAC."""
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500320 logging.info('archive(%s, %s, %s)', isolate_server, namespace, isolated)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000321 tempdir = None
322 try:
maruel@chromium.org0437a732013-08-27 16:05:52 +0000323 cmd = [
324 sys.executable,
325 os.path.join(ROOT_DIR, 'isolate.py'),
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000326 'archive',
Marc-Antoine Ruel2b13f612014-01-31 13:59:59 -0500327 '--isolate-server', isolate_server,
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500328 '--namespace', namespace,
maruel@chromium.org0437a732013-08-27 16:05:52 +0000329 '--isolated', isolated,
330 ]
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000331 cmd.extend(['--verbose'] * verbose)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000332 logging.info(' '.join(cmd))
333 if subprocess.call(cmd, verbose):
334 return
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000335 return isolateserver.hash_file(isolated, algo)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000336 finally:
337 if tempdir:
338 shutil.rmtree(tempdir)
339
340
341def process_manifest(
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500342 swarming, isolate_server, namespace, isolated_hash, task_name, shards,
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -0500343 dimensions, env, working_dir, verbose, profile, priority, algo):
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500344 """Processes the manifest file and send off the swarming task request."""
maruel@chromium.org0437a732013-08-27 16:05:52 +0000345 try:
346 manifest = Manifest(
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500347 isolate_server=isolate_server,
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500348 namespace=namespace,
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500349 isolated_hash=isolated_hash,
350 task_name=task_name,
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500351 shards=shards,
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -0500352 dimensions=dimensions,
Marc-Antoine Ruel05dab5e2013-11-06 15:06:47 -0500353 env=env,
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500354 working_dir=working_dir,
355 verbose=verbose,
356 profile=profile,
357 priority=priority,
358 algo=algo)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000359 except ValueError as e:
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500360 tools.report_error('Unable to process %s: %s' % (task_name, e))
maruel@chromium.org0437a732013-08-27 16:05:52 +0000361 return 1
362
363 chromium_setup(manifest)
364
Marc-Antoine Ruelcd629732013-12-20 15:00:42 -0500365 logging.info('Zipping up files...')
366 if not zip_and_upload(manifest):
maruel@chromium.org0437a732013-08-27 16:05:52 +0000367 return 1
368
Marc-Antoine Ruelcd629732013-12-20 15:00:42 -0500369 logging.info('Server: %s', swarming)
370 logging.info('Task name: %s', task_name)
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500371 trigger_url = swarming + '/test'
maruel@chromium.org0437a732013-08-27 16:05:52 +0000372 manifest_text = manifest.to_json()
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500373 result = net.url_read(trigger_url, data={'request': manifest_text})
maruel@chromium.org0437a732013-08-27 16:05:52 +0000374 if not result:
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000375 tools.report_error(
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500376 'Failed to trigger task %s\n%s' % (task_name, trigger_url))
maruel@chromium.org0437a732013-08-27 16:05:52 +0000377 return 1
378 try:
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000379 json.loads(result)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000380 except (ValueError, TypeError) as e:
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000381 msg = '\n'.join((
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500382 'Failed to trigger task %s' % task_name,
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000383 'Manifest: %s' % manifest_text,
384 'Bad response: %s' % result,
385 str(e)))
386 tools.report_error(msg)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000387 return 1
388 return 0
389
390
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500391def isolated_to_hash(isolate_server, namespace, arg, algo, verbose):
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500392 """Archives a .isolated file if needed.
393
394 Returns the file hash to trigger.
395 """
396 if arg.endswith('.isolated'):
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500397 file_hash = archive(isolate_server, namespace, arg, algo, verbose)
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500398 if not file_hash:
399 tools.report_error('Archival failure %s' % arg)
400 return None
401 return file_hash
402 elif isolateserver.is_valid_hash(arg, algo):
403 return arg
404 else:
405 tools.report_error('Invalid hash %s' % arg)
406 return None
407
408
maruel@chromium.org0437a732013-08-27 16:05:52 +0000409def trigger(
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500410 swarming,
411 isolate_server,
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500412 namespace,
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500413 file_hash_or_isolated,
414 task_name,
415 shards,
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -0500416 dimensions,
417 env,
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500418 working_dir,
maruel@chromium.org0437a732013-08-27 16:05:52 +0000419 verbose,
420 profile,
421 priority):
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500422 """Sends off the hash swarming task requests."""
423 file_hash = isolated_to_hash(
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500424 isolate_server, namespace, file_hash_or_isolated, hashlib.sha1, verbose)
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500425 if not file_hash:
426 return 1
Marc-Antoine Ruelcd629732013-12-20 15:00:42 -0500427 env = googletest_setup(env, shards)
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500428 # TODO(maruel): It should first create a request manifest object, then pass
429 # it to a function to zip, archive and trigger.
430 return process_manifest(
431 swarming=swarming,
432 isolate_server=isolate_server,
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500433 namespace=namespace,
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500434 isolated_hash=file_hash,
435 task_name=task_name,
436 shards=shards,
437 dimensions=dimensions,
438 env=env,
439 working_dir=working_dir,
440 verbose=verbose,
441 profile=profile,
442 priority=priority,
443 algo=hashlib.sha1)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000444
445
446def decorate_shard_output(result, shard_exit_code):
447 """Returns wrapped output for swarming task shard."""
448 tag = 'index %s (machine tag: %s, id: %s)' % (
449 result['config_instance_index'],
450 result['machine_id'],
451 result.get('machine_tag', 'unknown'))
452 return (
453 '\n'
454 '================================================================\n'
455 'Begin output from shard %s\n'
456 '================================================================\n'
457 '\n'
458 '%s'
459 '================================================================\n'
460 'End output from shard %s. Return %d\n'
461 '================================================================\n'
462 ) % (tag, result['output'] or NO_OUTPUT_FOUND, tag, shard_exit_code)
463
464
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500465def collect(url, task_name, timeout, decorate):
466 """Retrieves results of a Swarming task."""
467 logging.info('Collecting %s', task_name)
468 task_keys = get_task_keys(url, task_name)
469 if not task_keys:
470 raise Failure('No task keys to get results with.')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000471
maruel@chromium.org9c1c7b52013-08-28 19:04:36 +0000472 exit_code = None
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500473 for _index, output in yield_results(url, task_keys, timeout, None):
maruel@chromium.org0437a732013-08-27 16:05:52 +0000474 shard_exit_codes = (output['exit_codes'] or '1').split(',')
475 shard_exit_code = max(int(i) for i in shard_exit_codes)
476 if decorate:
477 print decorate_shard_output(output, shard_exit_code)
478 else:
479 print(
480 '%s/%s: %s' % (
481 output['machine_id'],
482 output['machine_tag'],
483 output['exit_codes']))
484 print(''.join(' %s\n' % l for l in output['output'].splitlines()))
maruel@chromium.org9c1c7b52013-08-28 19:04:36 +0000485 exit_code = exit_code or shard_exit_code
486 return exit_code if exit_code is not None else 1
maruel@chromium.org0437a732013-08-27 16:05:52 +0000487
488
489def add_trigger_options(parser):
490 """Adds all options to trigger a task on Swarming."""
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500491 isolateserver.add_isolate_server_options(parser)
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500492
493 parser.filter_group = tools.optparse.OptionGroup(parser, 'Filtering slaves')
494 parser.filter_group.add_option(
Marc-Antoine Ruelb39e8cf2014-01-20 10:39:31 -0500495 '-d', '--dimension', default=[], action='append', nargs=2,
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -0500496 dest='dimensions', metavar='FOO bar',
497 help='dimension to filter on')
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500498 parser.add_option_group(parser.filter_group)
499
500 parser.task_group = tools.optparse.OptionGroup(parser, 'Task properties')
501 parser.task_group.add_option(
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500502 '-w', '--working-dir', default='swarm_tests',
503 help='Working directory on the swarming slave side. default: %default.')
504 parser.task_group.add_option(
505 '--working_dir', help=tools.optparse.SUPPRESS_HELP)
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500506 parser.task_group.add_option(
507 '-e', '--env', default=[], action='append', nargs=2, metavar='FOO bar',
508 help='environment variables to set')
509 parser.task_group.add_option(
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500510 '--priority', type='int', default=100,
511 help='The lower value, the more important the task is')
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500512 parser.task_group.add_option(
513 '--shards', type='int', default=1, help='number of shards to use')
514 parser.task_group.add_option(
515 '-T', '--task-name', help='display name of the task')
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500516 parser.add_option_group(parser.task_group)
Marc-Antoine Ruelcd629732013-12-20 15:00:42 -0500517 # TODO(maruel): This is currently written in a chromium-specific way.
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500518 parser.group_logging.add_option(
maruel@chromium.org0437a732013-08-27 16:05:52 +0000519 '--profile', action='store_true',
520 default=bool(os.environ.get('ISOLATE_DEBUG')),
521 help='Have run_isolated.py print profiling info')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000522
523
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500524def process_trigger_options(parser, options, args):
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500525 isolateserver.process_isolate_server_options(parser, options)
Marc-Antoine Ruel4d8093d2014-01-31 15:07:11 -0500526 if not options.task_name:
527 parser.error(
528 '--task-name is required. It should be <base_name>/<OS>/<isolated>')
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500529 if len(args) != 1:
530 parser.error('Must pass one .isolated file or its hash (sha1).')
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500531 options.dimensions = dict(options.dimensions)
Marc-Antoine Ruelb39e8cf2014-01-20 10:39:31 -0500532 if not options.dimensions.get('os'):
533 parser.error(
534 'Please at least specify the dimension of the swarming bot OS with '
535 '--dimension os <something>.')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000536
537
538def add_collect_options(parser):
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500539 parser.server_group.add_option(
maruel@chromium.org0437a732013-08-27 16:05:52 +0000540 '-t', '--timeout',
541 type='float',
542 default=DEFAULT_SHARD_WAIT_TIME,
543 help='Timeout to wait for result, set to 0 for no timeout; default: '
544 '%default s')
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500545 parser.group_logging.add_option(
546 '--decorate', action='store_true', help='Decorate output')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000547
548
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500549@subcommand.usage('task_name')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000550def CMDcollect(parser, args):
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500551 """Retrieves results of a Swarming task.
maruel@chromium.org0437a732013-08-27 16:05:52 +0000552
553 The result can be in multiple part if the execution was sharded. It can
554 potentially have retries.
555 """
556 add_collect_options(parser)
557 (options, args) = parser.parse_args(args)
558 if not args:
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500559 parser.error('Must specify one task name.')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000560 elif len(args) > 1:
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500561 parser.error('Must specify only one task name.')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000562
563 try:
564 return collect(options.swarming, args[0], options.timeout, options.decorate)
565 except Failure as e:
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000566 tools.report_error(e)
567 return 1
maruel@chromium.org0437a732013-08-27 16:05:52 +0000568
569
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500570@subcommand.usage('[hash|isolated]')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000571def CMDrun(parser, args):
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500572 """Triggers a task and wait for the results.
maruel@chromium.org0437a732013-08-27 16:05:52 +0000573
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500574 Basically, does everything to run a command remotely.
maruel@chromium.org0437a732013-08-27 16:05:52 +0000575 """
576 add_trigger_options(parser)
577 add_collect_options(parser)
578 options, args = parser.parse_args(args)
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500579 process_trigger_options(parser, options, args)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000580
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500581 try:
582 result = trigger(
583 swarming=options.swarming,
584 isolate_server=options.isolate_server,
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500585 namespace=options.namespace,
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500586 file_hash_or_isolated=args[0],
587 task_name=options.task_name,
588 shards=options.shards,
589 dimensions=options.dimensions,
590 env=dict(options.env),
591 working_dir=options.working_dir,
592 verbose=options.verbose,
593 profile=options.profile,
594 priority=options.priority)
595 except Failure as e:
596 tools.report_error(
597 'Failed to trigger %s(%s): %s' %
598 (options.task_name, args[0], e.args[0]))
599 return 1
600 if result:
601 tools.report_error('Failed to trigger the task.')
maruel@chromium.org0437a732013-08-27 16:05:52 +0000602 return result
603
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500604 try:
605 return collect(
606 options.swarming,
607 options.task_name,
608 options.timeout,
609 options.decorate)
610 except Failure as e:
611 tools.report_error(e)
612 return 1
maruel@chromium.org0437a732013-08-27 16:05:52 +0000613
614
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500615@subcommand.usage("(hash|isolated)")
maruel@chromium.org0437a732013-08-27 16:05:52 +0000616def CMDtrigger(parser, args):
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500617 """Triggers a Swarming task.
maruel@chromium.org0437a732013-08-27 16:05:52 +0000618
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500619 Accepts either the hash (sha1) of a .isolated file already uploaded or the
620 path to an .isolated file to archive, packages it if needed and sends a
621 Swarming manifest file to the Swarming server.
622
623 If an .isolated file is specified instead of an hash, it is first archived.
maruel@chromium.org0437a732013-08-27 16:05:52 +0000624 """
625 add_trigger_options(parser)
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500626 options, args = parser.parse_args(args)
627 process_trigger_options(parser, options, args)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000628
629 try:
630 return trigger(
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500631 swarming=options.swarming,
632 isolate_server=options.isolate_server,
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500633 namespace=options.namespace,
Marc-Antoine Ruel7c543272013-11-26 13:26:15 -0500634 file_hash_or_isolated=args[0],
635 task_name=options.task_name,
636 dimensions=options.dimensions,
637 shards=options.shards,
Marc-Antoine Ruel92f32422013-11-06 18:12:13 -0500638 env=dict(options.env),
Marc-Antoine Ruela7049872013-11-05 19:28:35 -0500639 working_dir=options.working_dir,
640 verbose=options.verbose,
641 profile=options.profile,
642 priority=options.priority)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000643 except Failure as e:
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000644 tools.report_error(e)
645 return 1
maruel@chromium.org0437a732013-08-27 16:05:52 +0000646
647
648class OptionParserSwarming(tools.OptionParserWithLogging):
649 def __init__(self, **kwargs):
650 tools.OptionParserWithLogging.__init__(
651 self, prog='swarming.py', **kwargs)
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500652 self.server_group = tools.optparse.OptionGroup(self, 'Server')
653 self.server_group.add_option(
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000654 '-S', '--swarming',
Kevin Graney5346c162014-01-24 12:20:01 -0500655 metavar='URL', default=os.environ.get('SWARMING_SERVER', ''),
maruel@chromium.orge9403ab2013-09-20 18:03:49 +0000656 help='Swarming server to use')
Marc-Antoine Ruel5471e3d2013-11-11 19:10:32 -0500657 self.add_option_group(self.server_group)
Vadim Shtayurae34e13a2014-02-02 11:23:26 -0800658 auth.add_auth_options(self)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000659
660 def parse_args(self, *args, **kwargs):
661 options, args = tools.OptionParserWithLogging.parse_args(
662 self, *args, **kwargs)
663 options.swarming = options.swarming.rstrip('/')
664 if not options.swarming:
665 self.error('--swarming is required.')
Vadim Shtayura5d1efce2014-02-04 10:55:43 -0800666 auth.process_auth_options(self, options)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000667 return options, args
668
669
670def main(args):
671 dispatcher = subcommand.CommandDispatcher(__name__)
672 try:
673 return dispatcher.execute(OptionParserSwarming(version=__version__), args)
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +0000674 except Exception as e:
675 tools.report_error(e)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000676 return 1
677
678
679if __name__ == '__main__':
680 fix_encoding.fix_encoding()
681 tools.disable_buffering()
682 colorama.init()
683 sys.exit(main(sys.argv[1:]))