blob: 5588cdafe7605f528f1c5d1e559a0ef1084fe166 [file] [log] [blame]
maruel@chromium.org0437a732013-08-27 16:05:52 +00001#!/usr/bin/env python
2# Copyright 2013 The Chromium Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6"""Client tool to trigger tasks or retrieve results from a Swarming server."""
7
8__version__ = '0.1'
9
vadimsh@chromium.org6b706212013-08-28 15:03:46 +000010import binascii
maruel@chromium.org0437a732013-08-27 16:05:52 +000011import hashlib
12import json
13import logging
14import os
15import re
16import shutil
maruel@chromium.org0437a732013-08-27 16:05:52 +000017import subprocess
18import sys
19import time
20import urllib
maruel@chromium.org0437a732013-08-27 16:05:52 +000021
22from third_party import colorama
23from third_party.depot_tools import fix_encoding
24from third_party.depot_tools import subcommand
vadimsh@chromium.org6b706212013-08-28 15:03:46 +000025
26from 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
31import run_isolated
32
33
34ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
35TOOLS_PATH = os.path.join(ROOT_DIR, 'tools')
36
37
38# Default servers.
39# TODO(maruel): Chromium-specific.
40ISOLATE_SERVER = 'https://isolateserver-dev.appspot.com/'
41SWARM_SERVER = 'https://chromium-swarm-dev.appspot.com'
42
43
44# The default time to wait for a shard to finish running.
csharp@chromium.org24758492013-08-28 19:10:54 +000045DEFAULT_SHARD_WAIT_TIME = 80 * 60.
maruel@chromium.org0437a732013-08-27 16:05:52 +000046
47
48NO_OUTPUT_FOUND = (
49 'No output produced by the test, it may have failed to run.\n'
50 '\n')
51
52
53PLATFORM_MAPPING = {
54 'cygwin': 'Windows',
55 'darwin': 'Mac',
56 'linux2': 'Linux',
57 'win32': 'Windows',
58}
59
60
61class Failure(Exception):
62 """Generic failure."""
63 pass
64
65
66class Manifest(object):
67 """Represents a Swarming task manifest.
68
69 Also includes code to zip code and upload itself.
70 """
71 def __init__(
72 self, manifest_hash, test_name, shards, test_filter, slave_os,
73 working_dir, isolate_server, verbose, profile, priority):
74 """Populates a manifest object.
75 Args:
76 manifest_hash - The manifest's sha-1 that the slave is going to fetch.
77 test_name - The name to give the test request.
78 shards - The number of swarm shards to request.
79 test_filter - The gtest filter to apply when running the test.
80 slave_os - OS to run on.
81 working_dir - Relative working directory to start the script.
82 isolate_server - isolate server url.
83 verbose - if True, have the slave print more details.
84 profile - if True, have the slave print more timing data.
85 priority - int between 0 and 1000, lower the higher priority
86 """
87 self.manifest_hash = manifest_hash
vadimsh@chromium.org6b706212013-08-28 15:03:46 +000088 self.bundle = zip_package.ZipPackage(ROOT_DIR)
89
maruel@chromium.org0437a732013-08-27 16:05:52 +000090 self._test_name = test_name
91 self._shards = shards
92 self._test_filter = test_filter
93 self._target_platform = PLATFORM_MAPPING[slave_os]
94 self._working_dir = working_dir
95
96 self.data_server_retrieval = isolate_server + '/content/retrieve/default/'
97 self._data_server_storage = isolate_server + '/content/store/default/'
98 self._data_server_has = isolate_server + '/content/contains/default'
99 self._data_server_get_token = isolate_server + '/content/get_token'
100
101 self.verbose = bool(verbose)
102 self.profile = bool(profile)
103 self.priority = priority
104
105 self._zip_file_hash = ''
106 self._tasks = []
107 self._files = {}
108 self._token_cache = None
109
110 def _token(self):
111 if not self._token_cache:
vadimsh@chromium.org6b706212013-08-28 15:03:46 +0000112 result = net.url_open(self._data_server_get_token)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000113 if not result:
114 # TODO(maruel): Implement authentication.
115 raise Failure('Failed to get token, need authentication')
116 # Quote it right away, so creating the urls is simpler.
117 self._token_cache = urllib.quote(result.read())
118 return self._token_cache
119
120 def add_task(self, task_name, actions, time_out=600):
121 """Appends a new task to the swarm manifest file."""
122 # See swarming/src/common/test_request_message.py TestObject constructor for
123 # the valid flags.
124 self._tasks.append(
125 {
126 'action': actions,
127 'decorate_output': self.verbose,
128 'test_name': task_name,
129 'time_out': time_out,
130 })
131
maruel@chromium.org0437a732013-08-27 16:05:52 +0000132 def zip_and_upload(self):
133 """Zips up all the files necessary to run a shard and uploads to Swarming
134 master.
135 """
136 assert not self._zip_file_hash
vadimsh@chromium.org6b706212013-08-28 15:03:46 +0000137
maruel@chromium.org0437a732013-08-27 16:05:52 +0000138 start_time = time.time()
vadimsh@chromium.org6b706212013-08-28 15:03:46 +0000139 zip_contents = self.bundle.zip_into_buffer()
140 self._zip_file_hash = hashlib.sha1(zip_contents).hexdigest()
maruel@chromium.org0437a732013-08-27 16:05:52 +0000141 print 'Zipping completed, time elapsed: %f' % (time.time() - start_time)
142
vadimsh@chromium.org6b706212013-08-28 15:03:46 +0000143 response = net.url_open(
maruel@chromium.org0437a732013-08-27 16:05:52 +0000144 self._data_server_has + '?token=%s' % self._token(),
vadimsh@chromium.org6b706212013-08-28 15:03:46 +0000145 data=binascii.unhexlify(self._zip_file_hash),
maruel@chromium.org0437a732013-08-27 16:05:52 +0000146 content_type='application/octet-stream')
147 if response is None:
148 print >> sys.stderr, (
149 'Unable to query server for zip file presence, aborting.')
150 return False
151
152 if response.read(1) == chr(1):
153 print 'Zip file already on server, no need to reupload.'
154 return True
155
156 print 'Zip file not on server, starting uploading.'
157
158 url = '%s%s?priority=0&token=%s' % (
159 self._data_server_storage, self._zip_file_hash, self._token())
vadimsh@chromium.org6b706212013-08-28 15:03:46 +0000160 response = net.url_open(
maruel@chromium.org0437a732013-08-27 16:05:52 +0000161 url, data=zip_contents, content_type='application/octet-stream')
162 if response is None:
163 print >> sys.stderr, 'Failed to upload the zip file: %s' % url
164 return False
165
166 return True
167
168 def to_json(self):
169 """Exports the current configuration into a swarm-readable manifest file.
170
171 This function doesn't mutate the object.
172 """
173 test_case = {
174 'test_case_name': self._test_name,
175 'data': [
176 [self.data_server_retrieval + urllib.quote(self._zip_file_hash),
177 'swarm_data.zip'],
178 ],
179 'tests': self._tasks,
180 'env_vars': {},
181 'configurations': [
182 {
183 'min_instances': self._shards,
184 'config_name': self._target_platform,
185 'dimensions': {
186 'os': self._target_platform,
187 },
188 },
189 ],
190 'working_dir': self._working_dir,
191 'restart_on_failure': True,
192 'cleanup': 'root',
193 'priority': self.priority,
194 }
195
196 # These flags are googletest specific.
197 if self._test_filter and self._test_filter != '*':
198 test_case['env_vars']['GTEST_FILTER'] = self._test_filter
199 if self._shards > 1:
200 test_case['env_vars']['GTEST_SHARD_INDEX'] = '%(instance_index)s'
201 test_case['env_vars']['GTEST_TOTAL_SHARDS'] = '%(num_instances)s'
202
203 return json.dumps(test_case, separators=(',',':'))
204
205
206def now():
207 """Exists so it can be mocked easily."""
208 return time.time()
209
210
211def get_test_keys(swarm_base_url, test_name):
212 """Returns the Swarm test key for each shards of test_name."""
213 key_data = urllib.urlencode([('name', test_name)])
214 url = '%s/get_matching_test_cases?%s' % (swarm_base_url, key_data)
215
vadimsh@chromium.org043b76d2013-09-12 16:15:13 +0000216 for _ in net.retry_loop(max_attempts=net.URL_OPEN_MAX_ATTEMPTS):
217 result = net.url_read(url, retry_404=True)
218 if result is None:
maruel@chromium.org0437a732013-08-27 16:05:52 +0000219 raise Failure(
220 'Error: Unable to find any tests with the name, %s, on swarm server'
221 % test_name)
222
maruel@chromium.org0437a732013-08-27 16:05:52 +0000223 # TODO(maruel): Compare exact string.
224 if 'No matching' in result:
225 logging.warning('Unable to find any tests with the name, %s, on swarm '
226 'server' % test_name)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000227 continue
228 return json.loads(result)
229
230 raise Failure(
231 'Error: Unable to find any tests with the name, %s, on swarm server'
232 % test_name)
233
234
235def retrieve_results(base_url, test_key, timeout, should_stop):
236 """Retrieves results for a single test_key."""
237 assert isinstance(timeout, float)
238 params = [('r', test_key)]
239 result_url = '%s/get_result?%s' % (base_url, urllib.urlencode(params))
240 start = now()
241 while True:
242 if timeout and (now() - start) >= timeout:
243 logging.error('retrieve_results(%s) timed out', base_url)
244 return {}
245 # Do retries ourselves.
vadimsh@chromium.org043b76d2013-09-12 16:15:13 +0000246 response = net.url_read(result_url, retry_404=False, retry_50x=False)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000247 if response is None:
248 # Aggressively poll for results. Do not use retry_404 so
249 # should_stop is polled more often.
250 remaining = min(5, timeout - (now() - start)) if timeout else 5
251 if remaining > 0:
vadimsh@chromium.org043b76d2013-09-12 16:15:13 +0000252 net.sleep_before_retry(1, remaining)
maruel@chromium.org0437a732013-08-27 16:05:52 +0000253 else:
254 try:
vadimsh@chromium.org043b76d2013-09-12 16:15:13 +0000255 data = json.loads(response) or {}
maruel@chromium.org0437a732013-08-27 16:05:52 +0000256 except (ValueError, TypeError):
257 logging.warning(
258 'Received corrupted data for test_key %s. Retrying.', test_key)
259 else:
260 if data['output']:
261 return data
262 if should_stop.get():
263 return {}
264
265
266def yield_results(swarm_base_url, test_keys, timeout, max_threads):
267 """Yields swarm test results from the swarm server as (index, result).
268
269 Duplicate shards are ignored, the first one to complete is returned.
270
271 max_threads is optional and is used to limit the number of parallel fetches
272 done. Since in general the number of test_keys is in the range <=10, it's not
273 worth normally to limit the number threads. Mostly used for testing purposes.
274 """
275 shards_remaining = range(len(test_keys))
276 number_threads = (
277 min(max_threads, len(test_keys)) if max_threads else len(test_keys))
278 should_stop = threading_utils.Bit()
279 results_remaining = len(test_keys)
280 with threading_utils.ThreadPool(number_threads, number_threads, 0) as pool:
281 try:
282 for test_key in test_keys:
283 pool.add_task(
284 0, retrieve_results, swarm_base_url, test_key, timeout, should_stop)
285 while shards_remaining and results_remaining:
286 result = pool.get_one_result()
287 results_remaining -= 1
288 if not result:
289 # Failed to retrieve one key.
290 logging.error('Failed to retrieve the results for a swarm key')
291 continue
292 shard_index = result['config_instance_index']
293 if shard_index in shards_remaining:
294 shards_remaining.remove(shard_index)
295 yield shard_index, result
296 else:
297 logging.warning('Ignoring duplicate shard index %d', shard_index)
298 # Pop the last entry, there's no such shard.
299 shards_remaining.pop()
300 finally:
301 # Done, kill the remaining threads.
302 should_stop.set()
303
304
305def chromium_setup(manifest):
306 """Sets up the commands to run.
307
308 Highly chromium specific.
309 """
vadimsh@chromium.org6b706212013-08-28 15:03:46 +0000310 # Add uncompressed zip here. It'll be compressed as part of the package sent
311 # to Swarming server.
312 run_test_name = 'run_isolated.zip'
313 manifest.bundle.add_buffer(run_test_name,
314 run_isolated.get_as_zip_package().zip_into_buffer(compress=False))
maruel@chromium.org0437a732013-08-27 16:05:52 +0000315
vadimsh@chromium.org6b706212013-08-28 15:03:46 +0000316 cleanup_script_name = 'swarm_cleanup.py'
317 manifest.bundle.add_file(os.path.join(TOOLS_PATH, cleanup_script_name),
318 cleanup_script_name)
319
maruel@chromium.org0437a732013-08-27 16:05:52 +0000320 run_cmd = [
321 'python', run_test_name,
322 '--hash', manifest.manifest_hash,
323 '--remote', manifest.data_server_retrieval.rstrip('/') + '-gzip/',
324 ]
325 if manifest.verbose or manifest.profile:
326 # Have it print the profiling section.
327 run_cmd.append('--verbose')
328 manifest.add_task('Run Test', run_cmd)
329
330 # Clean up
331 manifest.add_task('Clean Up', ['python', cleanup_script_name])
332
333
334def archive(isolated, isolate_server, verbose):
335 """Archives a .isolated and all the dependencies on the CAC."""
336 tempdir = None
337 try:
338 logging.info('Archiving')
339 cmd = [
340 sys.executable,
341 os.path.join(ROOT_DIR, 'isolate.py'),
342 'hashtable',
343 '--outdir', isolate_server,
344 '--isolated', isolated,
345 ]
346 if verbose:
347 cmd.append('--verbose')
348 logging.info(' '.join(cmd))
349 if subprocess.call(cmd, verbose):
350 return
351 return hashlib.sha1(open(isolated, 'rb').read()).hexdigest()
352 finally:
353 if tempdir:
354 shutil.rmtree(tempdir)
355
356
357def process_manifest(
358 file_sha1_or_isolated, test_name, shards, test_filter, slave_os,
359 working_dir, isolate_server, swarming, verbose, profile, priority):
360 """Process the manifest file and send off the swarm test request.
361
362 Optionally archives an .isolated file.
363 """
364 if file_sha1_or_isolated.endswith('.isolated'):
365 file_sha1 = archive(file_sha1_or_isolated, isolate_server, verbose)
366 if not file_sha1:
367 print >> sys.stderr, 'Archival failure %s' % file_sha1_or_isolated
368 return 1
369 elif re.match(r'^[a-f0-9]{40}$', file_sha1_or_isolated):
370 file_sha1 = file_sha1_or_isolated
371 else:
372 print >> sys.stderr, 'Invalid hash %s' % file_sha1_or_isolated
373 return 1
374
375 try:
376 manifest = Manifest(
377 file_sha1, test_name, shards, test_filter, slave_os,
378 working_dir, isolate_server, verbose, profile, priority)
379 except ValueError as e:
380 print >> sys.stderr, 'Unable to process %s: %s' % (test_name, e)
381 return 1
382
383 chromium_setup(manifest)
384
385 # Zip up relevant files.
386 print('Zipping up files...')
387 if not manifest.zip_and_upload():
388 return 1
389
390 # Send test requests off to swarm.
391 print('Sending test requests to swarm.')
392 print('Server: %s' % swarming)
393 print('Job name: %s' % test_name)
394 test_url = swarming + '/test'
395 manifest_text = manifest.to_json()
vadimsh@chromium.org6b706212013-08-28 15:03:46 +0000396 result = net.url_open(test_url, data={'request': manifest_text})
maruel@chromium.org0437a732013-08-27 16:05:52 +0000397 if not result:
398 print >> sys.stderr, 'Failed to send test for %s\n%s' % (
399 test_name, test_url)
400 return 1
401 try:
402 json.load(result)
403 except (ValueError, TypeError) as e:
404 print >> sys.stderr, 'Failed to send test for %s' % test_name
405 print >> sys.stderr, 'Manifest: %s' % manifest_text
406 print >> sys.stderr, str(e)
407 return 1
408 return 0
409
410
411def trigger(
412 slave_os,
413 tasks,
414 task_prefix,
415 working_dir,
416 isolate_server,
417 swarming,
418 verbose,
419 profile,
420 priority):
421 """Sends off the hash swarming test requests."""
422 highest_exit_code = 0
423 for (file_sha1, test_name, shards, testfilter) in tasks:
424 # TODO(maruel): It should first create a request manifest object, then pass
425 # it to a function to zip, archive and trigger.
426 exit_code = process_manifest(
427 file_sha1,
428 task_prefix + test_name,
429 int(shards),
430 testfilter,
431 slave_os,
432 working_dir,
433 isolate_server,
434 swarming,
435 verbose,
436 profile,
437 priority)
438 highest_exit_code = max(highest_exit_code, exit_code)
439 return highest_exit_code
440
441
442def decorate_shard_output(result, shard_exit_code):
443 """Returns wrapped output for swarming task shard."""
444 tag = 'index %s (machine tag: %s, id: %s)' % (
445 result['config_instance_index'],
446 result['machine_id'],
447 result.get('machine_tag', 'unknown'))
448 return (
449 '\n'
450 '================================================================\n'
451 'Begin output from shard %s\n'
452 '================================================================\n'
453 '\n'
454 '%s'
455 '================================================================\n'
456 'End output from shard %s. Return %d\n'
457 '================================================================\n'
458 ) % (tag, result['output'] or NO_OUTPUT_FOUND, tag, shard_exit_code)
459
460
461def collect(url, test_name, timeout, decorate):
462 """Retrieves results of a Swarming job."""
463 test_keys = get_test_keys(url, test_name)
464 if not test_keys:
465 raise Failure('No test keys to get results with.')
466
maruel@chromium.org9c1c7b52013-08-28 19:04:36 +0000467 exit_code = None
maruel@chromium.org0437a732013-08-27 16:05:52 +0000468 for _index, output in yield_results(url, test_keys, timeout, None):
469 shard_exit_codes = (output['exit_codes'] or '1').split(',')
470 shard_exit_code = max(int(i) for i in shard_exit_codes)
471 if decorate:
472 print decorate_shard_output(output, shard_exit_code)
473 else:
474 print(
475 '%s/%s: %s' % (
476 output['machine_id'],
477 output['machine_tag'],
478 output['exit_codes']))
479 print(''.join(' %s\n' % l for l in output['output'].splitlines()))
maruel@chromium.org9c1c7b52013-08-28 19:04:36 +0000480 exit_code = exit_code or shard_exit_code
481 return exit_code if exit_code is not None else 1
maruel@chromium.org0437a732013-08-27 16:05:52 +0000482
483
484def add_trigger_options(parser):
485 """Adds all options to trigger a task on Swarming."""
486 parser.add_option(
487 '-I', '--isolate-server',
488 default=ISOLATE_SERVER,
489 metavar='URL',
490 help='Isolate server where data is stored. default: %default')
491 parser.add_option(
492 '-w', '--working_dir', default='swarm_tests',
493 help='Working directory on the swarm slave side. default: %default.')
494 parser.add_option(
495 '-o', '--os', default=sys.platform,
496 help='Swarm OS image to request. Should be one of the valid sys.platform '
497 'values like darwin, linux2 or win32 default: %default.')
498 parser.add_option(
499 '-T', '--task-prefix', default='',
500 help='Prefix to give the swarm test request. default: %default')
501 parser.add_option(
502 '--profile', action='store_true',
503 default=bool(os.environ.get('ISOLATE_DEBUG')),
504 help='Have run_isolated.py print profiling info')
505 parser.add_option(
506 '--priority', type='int', default=100,
507 help='The lower value, the more important the task is')
508
509
510def process_trigger_options(parser, options):
511 options.isolate_server = options.isolate_server.rstrip('/')
512 if not options.isolate_server:
513 parser.error('--isolate-server is required.')
514 if options.os in ('', 'None'):
515 # Use the current OS.
516 options.os = sys.platform
517 if not options.os in PLATFORM_MAPPING:
518 parser.error('Invalid --os option.')
519
520
521def add_collect_options(parser):
522 parser.add_option(
523 '-t', '--timeout',
524 type='float',
525 default=DEFAULT_SHARD_WAIT_TIME,
526 help='Timeout to wait for result, set to 0 for no timeout; default: '
527 '%default s')
528 parser.add_option('--decorate', action='store_true', help='Decorate output')
529
530
531@subcommand.usage('test_name')
532def CMDcollect(parser, args):
533 """Retrieves results of a Swarming job.
534
535 The result can be in multiple part if the execution was sharded. It can
536 potentially have retries.
537 """
538 add_collect_options(parser)
539 (options, args) = parser.parse_args(args)
540 if not args:
541 parser.error('Must specify one test name.')
542 elif len(args) > 1:
543 parser.error('Must specify only one test name.')
544
545 try:
546 return collect(options.swarming, args[0], options.timeout, options.decorate)
547 except Failure as e:
548 parser.error(e.args[0])
549
550
551@subcommand.usage('[sha1|isolated ...]')
552def CMDrun(parser, args):
553 """Triggers a job and wait for the results.
554
555 Basically, does everything to run command(s) remotely.
556 """
557 add_trigger_options(parser)
558 add_collect_options(parser)
559 options, args = parser.parse_args(args)
560
561 if not args:
562 parser.error('Must pass at least one .isolated file or its sha1.')
563 process_trigger_options(parser, options)
564
565 success = []
566 for arg in args:
567 logging.info('Triggering %s', arg)
568 try:
569 result = trigger(
570 options.os,
571 [(arg, os.path.basename(arg), '1', '')],
572 options.task_prefix,
573 options.working_dir,
574 options.isolate_server,
575 options.swarming,
576 options.verbose,
577 options.profile,
578 options.priority)
579 except Failure as e:
580 result = e.args[0]
581 if result:
582 print >> sys.stderr, 'Failed to trigger %s: %s' % (arg, result)
583 else:
584 success.append(os.path.basename(arg))
585
586 if not success:
587 print >> sys.stderr, 'Failed to trigger any job.'
588 return result
589
590 code = 0
591 for arg in success:
592 logging.info('Collecting %s', arg)
593 try:
594 new_code = collect(
595 options.swarming,
596 options.task_prefix + arg,
597 options.timeout,
598 options.decorate)
599 code = max(code, new_code)
600 except Failure as e:
601 code = max(code, 1)
602 print >> sys.stderr, e.args[0]
603 return code
604
605
606def CMDtrigger(parser, args):
607 """Triggers Swarm request(s).
608
609 Accepts one or multiple --task requests, with either the sha1 of a .isolated
610 file already uploaded or the path to an .isolated file to archive, packages it
611 if needed and sends a Swarm manifest file to the Swarm server.
612 """
613 add_trigger_options(parser)
614 parser.add_option(
615 '--task', nargs=4, action='append', default=[], dest='tasks',
616 help='Task to trigger. The format is '
617 '(hash|isolated, test_name, shards, test_filter). This may be '
618 'used multiple times to send multiple hashes jobs. If an isolated '
619 'file is specified instead of an hash, it is first archived.')
620 (options, args) = parser.parse_args(args)
621
622 if args:
623 parser.error('Unknown args: %s' % args)
624 process_trigger_options(parser, options)
625 if not options.tasks:
626 parser.error('At least one --task is required.')
627
628 try:
629 return trigger(
630 options.os,
631 options.tasks,
632 options.task_prefix,
633 options.working_dir,
634 options.isolate_server,
635 options.swarming,
636 options.verbose,
637 options.profile,
638 options.priority)
639 except Failure as e:
640 parser.error(e.args[0])
641
642
643class OptionParserSwarming(tools.OptionParserWithLogging):
644 def __init__(self, **kwargs):
645 tools.OptionParserWithLogging.__init__(
646 self, prog='swarming.py', **kwargs)
647 self.add_option(
648 '-S', '--swarming', default=SWARM_SERVER,
649 help='Specify the url of the Swarming server, default: %default')
650
651 def parse_args(self, *args, **kwargs):
652 options, args = tools.OptionParserWithLogging.parse_args(
653 self, *args, **kwargs)
654 options.swarming = options.swarming.rstrip('/')
655 if not options.swarming:
656 self.error('--swarming is required.')
657 return options, args
658
659
660def main(args):
661 dispatcher = subcommand.CommandDispatcher(__name__)
662 try:
663 return dispatcher.execute(OptionParserSwarming(version=__version__), args)
664 except (
665 Failure,
666 run_isolated.MappingError,
667 run_isolated.ConfigError) as e:
668 sys.stderr.write('\nError: ')
669 sys.stderr.write(str(e))
670 sys.stderr.write('\n')
671 return 1
672
673
674if __name__ == '__main__':
675 fix_encoding.fix_encoding()
676 tools.disable_buffering()
677 colorama.init()
678 sys.exit(main(sys.argv[1:]))