forked from luci/luci-py
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathswarming.py
executable file
·1704 lines (1479 loc) · 55.7 KB
/
swarming.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# Copyright 2013 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
"""Client tool to trigger tasks or retrieve results from a Swarming server."""
__version__ = '0.9.1'
import collections
import datetime
import json
import logging
import optparse
import os
import subprocess
import sys
import textwrap
import threading
import time
import urllib
from third_party import colorama
from third_party.depot_tools import fix_encoding
from third_party.depot_tools import subcommand
from utils import file_path
from utils import fs
from utils import logging_utils
from third_party.chromium import natsort
from utils import net
from utils import on_error
from utils import subprocess42
from utils import threading_utils
from utils import tools
import auth
import cipd
import isolated_format
import isolateserver
import run_isolated
ROOT_DIR = os.path.dirname(os.path.abspath(
__file__.decode(sys.getfilesystemencoding())))
class Failure(Exception):
"""Generic failure."""
pass
def default_task_name(options):
"""Returns a default task name if not specified."""
if not options.task_name:
task_name = u'%s/%s' % (
options.user,
'_'.join('%s=%s' % (k, v) for k, v in options.dimensions))
if options.isolated:
task_name += u'/' + options.isolated
return task_name
return options.task_name
### Triggering.
# See ../appengine/swarming/swarming_rpcs.py.
CipdPackage = collections.namedtuple(
'CipdPackage',
[
'package_name',
'path',
'version',
])
# See ../appengine/swarming/swarming_rpcs.py.
CipdInput = collections.namedtuple(
'CipdInput',
[
'client_package',
'packages',
'server',
])
# See ../appengine/swarming/swarming_rpcs.py.
FilesRef = collections.namedtuple(
'FilesRef',
[
'isolated',
'isolatedserver',
'namespace',
])
# See ../appengine/swarming/swarming_rpcs.py.
TaskProperties = collections.namedtuple(
'TaskProperties',
[
'caches',
'cipd_input',
'command',
'dimensions',
'env',
'execution_timeout_secs',
'extra_args',
'grace_period_secs',
'idempotent',
'inputs_ref',
'io_timeout_secs',
'outputs',
'secret_bytes',
])
# See ../appengine/swarming/swarming_rpcs.py.
NewTaskRequest = collections.namedtuple(
'NewTaskRequest',
[
'expiration_secs',
'name',
'parent_task_id',
'priority',
'properties',
'service_account_token',
'tags',
'user',
])
def namedtuple_to_dict(value):
"""Recursively converts a namedtuple to a dict."""
out = dict(value._asdict())
for k, v in out.iteritems():
if hasattr(v, '_asdict'):
out[k] = namedtuple_to_dict(v)
elif isinstance(v, (list, tuple)):
l = []
for elem in v:
if hasattr(elem, '_asdict'):
l.append(namedtuple_to_dict(elem))
else:
l.append(elem)
out[k] = l
return out
def task_request_to_raw_request(task_request, hide_token):
"""Returns the json-compatible dict expected by the server for new request.
This is for the v1 client Swarming API.
"""
out = namedtuple_to_dict(task_request)
if hide_token:
if out['service_account_token'] not in (None, 'bot', 'none'):
out['service_account_token'] = '<hidden>'
# Don't send 'service_account_token' if it is None to avoid confusing older
# version of the server that doesn't know about 'service_account_token'.
if out['service_account_token'] in (None, 'none'):
out.pop('service_account_token')
out['properties']['dimensions'] = [
{'key': k, 'value': v}
for k, v in out['properties']['dimensions']
]
out['properties']['env'] = [
{'key': k, 'value': v}
for k, v in out['properties']['env'].iteritems()
]
out['properties']['env'].sort(key=lambda x: x['key'])
return out
def swarming_trigger(swarming, raw_request):
"""Triggers a request on the Swarming server and returns the json data.
It's the low-level function.
Returns:
{
'request': {
'created_ts': u'2010-01-02 03:04:05',
'name': ..
},
'task_id': '12300',
}
"""
logging.info('Triggering: %s', raw_request['name'])
result = net.url_read_json(
swarming + '/api/swarming/v1/tasks/new', data=raw_request)
if not result:
on_error.report('Failed to trigger task %s' % raw_request['name'])
return None
if result.get('error'):
# The reply is an error.
msg = 'Failed to trigger task %s' % raw_request['name']
if result['error'].get('errors'):
for err in result['error']['errors']:
if err.get('message'):
msg += '\nMessage: %s' % err['message']
if err.get('debugInfo'):
msg += '\nDebug info:\n%s' % err['debugInfo']
elif result['error'].get('message'):
msg += '\nMessage: %s' % result['error']['message']
on_error.report(msg)
return None
return result
def setup_googletest(env, shards, index):
"""Sets googletest specific environment variables."""
if shards > 1:
assert not any(i['key'] == 'GTEST_SHARD_INDEX' for i in env), env
assert not any(i['key'] == 'GTEST_TOTAL_SHARDS' for i in env), env
env = env[:]
env.append({'key': 'GTEST_SHARD_INDEX', 'value': str(index)})
env.append({'key': 'GTEST_TOTAL_SHARDS', 'value': str(shards)})
return env
def trigger_task_shards(swarming, task_request, shards):
"""Triggers one or many subtasks of a sharded task.
Returns:
Dict with task details, returned to caller as part of --dump-json output.
None in case of failure.
"""
def convert(index):
req = task_request_to_raw_request(task_request, False)
if shards > 1:
req['properties']['env'] = setup_googletest(
req['properties']['env'], shards, index)
req['name'] += ':%s:%s' % (index, shards)
return req
requests = [convert(index) for index in xrange(shards)]
tasks = {}
priority_warning = False
for index, request in enumerate(requests):
task = swarming_trigger(swarming, request)
if not task:
break
logging.info('Request result: %s', task)
if (not priority_warning and
task['request']['priority'] != task_request.priority):
priority_warning = True
print >> sys.stderr, (
'Priority was reset to %s' % task['request']['priority'])
tasks[request['name']] = {
'shard_index': index,
'task_id': task['task_id'],
'view_url': '%s/user/task/%s' % (swarming, task['task_id']),
}
# Some shards weren't triggered. Abort everything.
if len(tasks) != len(requests):
if tasks:
print >> sys.stderr, 'Only %d shard(s) out of %d were triggered' % (
len(tasks), len(requests))
for task_dict in tasks.itervalues():
abort_task(swarming, task_dict['task_id'])
return None
return tasks
def mint_service_account_token(service_account):
"""Given a service account name returns a delegation token for this account.
The token is generated based on triggering user's credentials. It is passed
to Swarming, that uses it when running tasks.
"""
logging.info(
'Generating delegation token for service account "%s"', service_account)
raise NotImplementedError('Custom service accounts are not implemented yet')
### Collection.
# How often to print status updates to stdout in 'collect'.
STATUS_UPDATE_INTERVAL = 15 * 60.
class State(object):
"""States in which a task can be.
WARNING: Copy-pasted from appengine/swarming/server/task_result.py. These
values are part of the API so if they change, the API changed.
It's in fact an enum. Values should be in decreasing order of importance.
"""
RUNNING = 0x10
PENDING = 0x20
EXPIRED = 0x30
TIMED_OUT = 0x40
BOT_DIED = 0x50
CANCELED = 0x60
COMPLETED = 0x70
STATES = (
'RUNNING', 'PENDING', 'EXPIRED', 'TIMED_OUT', 'BOT_DIED', 'CANCELED',
'COMPLETED')
STATES_RUNNING = ('RUNNING', 'PENDING')
STATES_NOT_RUNNING = (
'EXPIRED', 'TIMED_OUT', 'BOT_DIED', 'CANCELED', 'COMPLETED')
STATES_DONE = ('TIMED_OUT', 'COMPLETED')
STATES_ABANDONED = ('EXPIRED', 'BOT_DIED', 'CANCELED')
_NAMES = {
RUNNING: 'Running',
PENDING: 'Pending',
EXPIRED: 'Expired',
TIMED_OUT: 'Execution timed out',
BOT_DIED: 'Bot died',
CANCELED: 'User canceled',
COMPLETED: 'Completed',
}
_ENUMS = {
'RUNNING': RUNNING,
'PENDING': PENDING,
'EXPIRED': EXPIRED,
'TIMED_OUT': TIMED_OUT,
'BOT_DIED': BOT_DIED,
'CANCELED': CANCELED,
'COMPLETED': COMPLETED,
}
@classmethod
def to_string(cls, state):
"""Returns a user-readable string representing a State."""
if state not in cls._NAMES:
raise ValueError('Invalid state %s' % state)
return cls._NAMES[state]
@classmethod
def from_enum(cls, state):
"""Returns int value based on the string."""
if state not in cls._ENUMS:
raise ValueError('Invalid state %s' % state)
return cls._ENUMS[state]
class TaskOutputCollector(object):
"""Assembles task execution summary (for --task-summary-json output).
Optionally fetches task outputs from isolate server to local disk (used when
--task-output-dir is passed).
This object is shared among multiple threads running 'retrieve_results'
function, in particular they call 'process_shard_result' method in parallel.
"""
def __init__(self, task_output_dir, shard_count):
"""Initializes TaskOutputCollector, ensures |task_output_dir| exists.
Args:
task_output_dir: (optional) local directory to put fetched files to.
shard_count: expected number of task shards.
"""
self.task_output_dir = (
unicode(os.path.abspath(task_output_dir))
if task_output_dir else task_output_dir)
self.shard_count = shard_count
self._lock = threading.Lock()
self._per_shard_results = {}
self._storage = None
if self.task_output_dir:
file_path.ensure_tree(self.task_output_dir)
def process_shard_result(self, shard_index, result):
"""Stores results of a single task shard, fetches output files if necessary.
Modifies |result| in place.
shard_index is 0-based.
Called concurrently from multiple threads.
"""
# Sanity check index is in expected range.
assert isinstance(shard_index, int)
if shard_index < 0 or shard_index >= self.shard_count:
logging.warning(
'Shard index %d is outside of expected range: [0; %d]',
shard_index, self.shard_count - 1)
return
if result.get('outputs_ref'):
ref = result['outputs_ref']
result['outputs_ref']['view_url'] = '%s/browse?%s' % (
ref['isolatedserver'],
urllib.urlencode(
[('namespace', ref['namespace']), ('hash', ref['isolated'])]))
# Store result dict of that shard, ignore results we've already seen.
with self._lock:
if shard_index in self._per_shard_results:
logging.warning('Ignoring duplicate shard index %d', shard_index)
return
self._per_shard_results[shard_index] = result
# Fetch output files if necessary.
if self.task_output_dir and result.get('outputs_ref'):
storage = self._get_storage(
result['outputs_ref']['isolatedserver'],
result['outputs_ref']['namespace'])
if storage:
# Output files are supposed to be small and they are not reused across
# tasks. So use MemoryCache for them instead of on-disk cache. Make
# files writable, so that calling script can delete them.
isolateserver.fetch_isolated(
result['outputs_ref']['isolated'],
storage,
isolateserver.MemoryCache(file_mode_mask=0700),
os.path.join(self.task_output_dir, str(shard_index)),
False)
def finalize(self):
"""Assembles and returns task summary JSON, shutdowns underlying Storage."""
with self._lock:
# Write an array of shard results with None for missing shards.
summary = {
'shards': [
self._per_shard_results.get(i) for i in xrange(self.shard_count)
],
}
# Write summary.json to task_output_dir as well.
if self.task_output_dir:
tools.write_json(
os.path.join(self.task_output_dir, u'summary.json'),
summary,
False)
if self._storage:
self._storage.close()
self._storage = None
return summary
def _get_storage(self, isolate_server, namespace):
"""Returns isolateserver.Storage to use to fetch files."""
assert self.task_output_dir
with self._lock:
if not self._storage:
self._storage = isolateserver.get_storage(isolate_server, namespace)
else:
# Shards must all use exact same isolate server and namespace.
if self._storage.location != isolate_server:
logging.error(
'Task shards are using multiple isolate servers: %s and %s',
self._storage.location, isolate_server)
return None
if self._storage.namespace != namespace:
logging.error(
'Task shards are using multiple namespaces: %s and %s',
self._storage.namespace, namespace)
return None
return self._storage
def now():
"""Exists so it can be mocked easily."""
return time.time()
def parse_time(value):
"""Converts serialized time from the API to datetime.datetime."""
# When microseconds are 0, the '.123456' suffix is elided. This means the
# serialized format is not consistent, which confuses the hell out of python.
for fmt in ('%Y-%m-%dT%H:%M:%S.%f', '%Y-%m-%dT%H:%M:%S'):
try:
return datetime.datetime.strptime(value, fmt)
except ValueError:
pass
raise ValueError('Failed to parse %s' % value)
def retrieve_results(
base_url, shard_index, task_id, timeout, should_stop, output_collector,
include_perf):
"""Retrieves results for a single task ID.
Returns:
<result dict> on success.
None on failure.
"""
assert timeout is None or isinstance(timeout, float), timeout
result_url = '%s/api/swarming/v1/task/%s/result' % (base_url, task_id)
if include_perf:
result_url += '?include_performance_stats=true'
output_url = '%s/api/swarming/v1/task/%s/stdout' % (base_url, task_id)
started = now()
deadline = started + timeout if timeout else None
attempt = 0
while not should_stop.is_set():
attempt += 1
# Waiting for too long -> give up.
current_time = now()
if deadline and current_time >= deadline:
logging.error('retrieve_results(%s) timed out on attempt %d',
base_url, attempt)
return None
# Do not spin too fast. Spin faster at the beginning though.
# Start with 1 sec delay and for each 30 sec of waiting add another second
# of delay, until hitting 15 sec ceiling.
if attempt > 1:
max_delay = min(15, 1 + (current_time - started) / 30.0)
delay = min(max_delay, deadline - current_time) if deadline else max_delay
if delay > 0:
logging.debug('Waiting %.1f sec before retrying', delay)
should_stop.wait(delay)
if should_stop.is_set():
return None
# Disable internal retries in net.url_read_json, since we are doing retries
# ourselves.
# TODO(maruel): We'd need to know if it's a 404 and not retry at all.
# TODO(maruel): Sadly, we currently have to poll here. Use hanging HTTP
# request on GAE v2.
result = net.url_read_json(result_url, retry_50x=False)
if not result:
continue
if result.get('error'):
# An error occurred.
if result['error'].get('errors'):
for err in result['error']['errors']:
logging.warning(
'Error while reading task: %s; %s',
err.get('message'), err.get('debugInfo'))
elif result['error'].get('message'):
logging.warning(
'Error while reading task: %s', result['error']['message'])
continue
if result['state'] in State.STATES_NOT_RUNNING:
# TODO(maruel): Not always fetch stdout?
out = net.url_read_json(output_url)
result['output'] = out.get('output') if out else out
# Record the result, try to fetch attached output files (if any).
if output_collector:
# TODO(vadimsh): Respect |should_stop| and |deadline| when fetching.
output_collector.process_shard_result(shard_index, result)
if result.get('internal_failure'):
logging.error('Internal error!')
elif result['state'] == 'BOT_DIED':
logging.error('Bot died!')
return result
def convert_to_old_format(result):
"""Converts the task result data from Endpoints API format to old API format
for compatibility.
This goes into the file generated as --task-summary-json.
"""
# Sets default.
result.setdefault('abandoned_ts', None)
result.setdefault('bot_id', None)
result.setdefault('bot_version', None)
result.setdefault('children_task_ids', [])
result.setdefault('completed_ts', None)
result.setdefault('cost_saved_usd', None)
result.setdefault('costs_usd', None)
result.setdefault('deduped_from', None)
result.setdefault('name', None)
result.setdefault('outputs_ref', None)
result.setdefault('properties_hash', None)
result.setdefault('server_versions', None)
result.setdefault('started_ts', None)
result.setdefault('tags', None)
result.setdefault('user', None)
# Convertion back to old API.
duration = result.pop('duration', None)
result['durations'] = [duration] if duration else []
exit_code = result.pop('exit_code', None)
result['exit_codes'] = [int(exit_code)] if exit_code else []
result['id'] = result.pop('task_id')
result['isolated_out'] = result.get('outputs_ref', None)
output = result.pop('output', None)
result['outputs'] = [output] if output else []
# properties_hash
# server_version
# Endpoints result 'state' as string. For compatibility with old code, convert
# to int.
result['state'] = State.from_enum(result['state'])
result['try_number'] = (
int(result['try_number']) if result.get('try_number') else None)
if 'bot_dimensions' in result:
result['bot_dimensions'] = {
i['key']: i.get('value', []) for i in result['bot_dimensions']
}
else:
result['bot_dimensions'] = None
def yield_results(
swarm_base_url, task_ids, timeout, max_threads, print_status_updates,
output_collector, include_perf):
"""Yields swarming task results from the swarming server as (index, result).
Duplicate shards are ignored. Shards are yielded in order of completion.
Timed out shards are NOT yielded at all. Caller can compare number of yielded
shards with len(task_keys) to verify all shards completed.
max_threads is optional and is used to limit the number of parallel fetches
done. Since in general the number of task_keys is in the range <=10, it's not
worth normally to limit the number threads. Mostly used for testing purposes.
output_collector is an optional instance of TaskOutputCollector that will be
used to fetch files produced by a task from isolate server to the local disk.
Yields:
(index, result). In particular, 'result' is defined as the
GetRunnerResults() function in services/swarming/server/test_runner.py.
"""
number_threads = (
min(max_threads, len(task_ids)) if max_threads else len(task_ids))
should_stop = threading.Event()
results_channel = threading_utils.TaskChannel()
with threading_utils.ThreadPool(number_threads, number_threads, 0) as pool:
try:
# Adds a task to the thread pool to call 'retrieve_results' and return
# the results together with shard_index that produced them (as a tuple).
def enqueue_retrieve_results(shard_index, task_id):
task_fn = lambda *args: (shard_index, retrieve_results(*args))
pool.add_task(
0, results_channel.wrap_task(task_fn), swarm_base_url, shard_index,
task_id, timeout, should_stop, output_collector, include_perf)
# Enqueue 'retrieve_results' calls for each shard key to run in parallel.
for shard_index, task_id in enumerate(task_ids):
enqueue_retrieve_results(shard_index, task_id)
# Wait for all of them to finish.
shards_remaining = range(len(task_ids))
active_task_count = len(task_ids)
while active_task_count:
shard_index, result = None, None
try:
shard_index, result = results_channel.pull(
timeout=STATUS_UPDATE_INTERVAL)
except threading_utils.TaskChannel.Timeout:
if print_status_updates:
print(
'Waiting for results from the following shards: %s' %
', '.join(map(str, shards_remaining)))
sys.stdout.flush()
continue
except Exception:
logging.exception('Unexpected exception in retrieve_results')
# A call to 'retrieve_results' finished (successfully or not).
active_task_count -= 1
if not result:
logging.error('Failed to retrieve the results for a swarming key')
continue
# Yield back results to the caller.
assert shard_index in shards_remaining
shards_remaining.remove(shard_index)
yield shard_index, result
finally:
# Done or aborted with Ctrl+C, kill the remaining threads.
should_stop.set()
def decorate_shard_output(swarming, shard_index, metadata):
"""Returns wrapped output for swarming task shard."""
if metadata.get('started_ts') and not metadata.get('deduped_from'):
pending = '%.1fs' % (
parse_time(metadata['started_ts']) - parse_time(metadata['created_ts'])
).total_seconds()
else:
pending = 'N/A'
if metadata.get('duration') is not None:
duration = '%.1fs' % metadata['duration']
else:
duration = 'N/A'
if metadata.get('exit_code') is not None:
# Integers are encoded as string to not loose precision.
exit_code = '%s' % metadata['exit_code']
else:
exit_code = 'N/A'
bot_id = metadata.get('bot_id') or 'N/A'
url = '%s/user/task/%s' % (swarming, metadata['task_id'])
tag_header = 'Shard %d %s' % (shard_index, url)
tag_footer = (
'End of shard %d Pending: %s Duration: %s Bot: %s Exit: %s' % (
shard_index, pending, duration, bot_id, exit_code))
tag_len = max(len(tag_header), len(tag_footer))
dash_pad = '+-%s-+\n' % ('-' * tag_len)
tag_header = '| %s |\n' % tag_header.ljust(tag_len)
tag_footer = '| %s |\n' % tag_footer.ljust(tag_len)
header = dash_pad + tag_header + dash_pad
footer = dash_pad + tag_footer + dash_pad[:-1]
output = (metadata.get('output') or '').rstrip() + '\n'
return header + output + footer
def collect(
swarming, task_ids, timeout, decorate, print_status_updates,
task_summary_json, task_output_dir, include_perf):
"""Retrieves results of a Swarming task.
Returns:
process exit code that should be returned to the user.
"""
# Collect summary JSON and output files (if task_output_dir is not None).
output_collector = TaskOutputCollector(task_output_dir, len(task_ids))
seen_shards = set()
exit_code = None
total_duration = 0
try:
for index, metadata in yield_results(
swarming, task_ids, timeout, None, print_status_updates,
output_collector, include_perf):
seen_shards.add(index)
# Default to failure if there was no process that even started.
shard_exit_code = metadata.get('exit_code')
if shard_exit_code:
# It's encoded as a string, so bool('0') is True.
shard_exit_code = int(shard_exit_code)
if shard_exit_code or exit_code is None:
exit_code = shard_exit_code
total_duration += metadata.get('duration', 0)
if decorate:
s = decorate_shard_output(swarming, index, metadata).encode(
'utf-8', 'replace')
print(s)
if len(seen_shards) < len(task_ids):
print('')
else:
print('%s: %s %s' % (
metadata.get('bot_id', 'N/A'),
metadata['task_id'],
shard_exit_code))
if metadata['output']:
output = metadata['output'].rstrip()
if output:
print(''.join(' %s\n' % l for l in output.splitlines()))
finally:
summary = output_collector.finalize()
if task_summary_json:
# TODO(maruel): Make this optional.
for i in summary['shards']:
if i:
convert_to_old_format(i)
tools.write_json(task_summary_json, summary, False)
if decorate and total_duration:
print('Total duration: %.1fs' % total_duration)
if len(seen_shards) != len(task_ids):
missing_shards = [x for x in range(len(task_ids)) if x not in seen_shards]
print >> sys.stderr, ('Results from some shards are missing: %s' %
', '.join(map(str, missing_shards)))
return 1
return exit_code if exit_code is not None else 1
### API management.
class APIError(Exception):
pass
def endpoints_api_discovery_apis(host):
"""Uses Cloud Endpoints' API Discovery Service to returns metadata about all
the APIs exposed by a host.
https://developers.google.com/discovery/v1/reference/apis/list
"""
# Uses the real Cloud Endpoints. This needs to be fixed once the Cloud
# Endpoints version is turned down.
data = net.url_read_json(host + '/_ah/api/discovery/v1/apis')
if data is None:
raise APIError('Failed to discover APIs on %s' % host)
out = {}
for api in data['items']:
if api['id'] == 'discovery:v1':
continue
# URL is of the following form:
# url = host + (
# '/_ah/api/discovery/v1/apis/%s/%s/rest' % (api['id'], api['version'])
api_data = net.url_read_json(api['discoveryRestUrl'])
if api_data is None:
raise APIError('Failed to discover %s on %s' % (api['id'], host))
out[api['id']] = api_data
return out
def get_yielder(base_url, limit):
"""Returns the first query and a function that yields following items."""
CHUNK_SIZE = 250
url = base_url
if limit:
url += '%slimit=%d' % ('&' if '?' in url else '?', min(CHUNK_SIZE, limit))
data = net.url_read_json(url)
if data is None:
# TODO(maruel): Do basic diagnostic.
raise Failure('Failed to access %s' % url)
org_cursor = data.pop('cursor', None)
org_total = len(data.get('items') or [])
logging.info('get_yielder(%s) returning %d items', base_url, org_total)
if not org_cursor or not org_total:
# This is not an iterable resource.
return data, lambda: []
def yielder():
cursor = org_cursor
total = org_total
# Some items support cursors. Try to get automatically if cursors are needed
# by looking at the 'cursor' items.
while cursor and (not limit or total < limit):
merge_char = '&' if '?' in base_url else '?'
url = base_url + '%scursor=%s' % (merge_char, urllib.quote(cursor))
if limit:
url += '&limit=%d' % min(CHUNK_SIZE, limit - total)
new = net.url_read_json(url)
if new is None:
raise Failure('Failed to access %s' % url)
cursor = new.get('cursor')
new_items = new.get('items')
nb_items = len(new_items or [])
total += nb_items
logging.info('get_yielder(%s) yielding %d items', base_url, nb_items)
yield new_items
return data, yielder
### Commands.
def abort_task(_swarming, _manifest):
"""Given a task manifest that was triggered, aborts its execution."""
# TODO(vadimsh): No supported by the server yet.
def add_filter_options(parser):
parser.filter_group = optparse.OptionGroup(parser, 'Bot selection')
parser.filter_group.add_option(
'-d', '--dimension', default=[], action='append', nargs=2,
dest='dimensions', metavar='FOO bar',
help='dimension to filter on')
parser.add_option_group(parser.filter_group)
def process_filter_options(parser, options):
for key, value in options.dimensions:
if ':' in key:
parser.error('--dimension key cannot contain ":"')
if key.strip() != key:
parser.error('--dimension key has whitespace')
if not key:
parser.error('--dimension key is empty')
if value.strip() != value:
parser.error('--dimension value has whitespace')
if not value:
parser.error('--dimension value is empty')
options.dimensions.sort()
def add_sharding_options(parser):
parser.sharding_group = optparse.OptionGroup(parser, 'Sharding options')
parser.sharding_group.add_option(
'--shards', type='int', default=1, metavar='NUMBER',
help='Number of shards to trigger and collect.')
parser.add_option_group(parser.sharding_group)
def add_trigger_options(parser):
"""Adds all options to trigger a task on Swarming."""
isolateserver.add_isolate_server_options(parser)
add_filter_options(parser)
group = optparse.OptionGroup(parser, 'Task properties')
group.add_option(
'-s', '--isolated', metavar='HASH',
help='Hash of the .isolated to grab from the isolate server')
group.add_option(
'-e', '--env', default=[], action='append', nargs=2, metavar='FOO bar',
help='Environment variables to set')
group.add_option(
'--idempotent', action='store_true', default=False,
help='When set, the server will actively try to find a previous task '
'with the same parameter and return this result instead if possible')
group.add_option(
'--secret-bytes-path', metavar='FILE',
help='The optional path to a file containing the secret_bytes to use with'
'this task.')
group.add_option(
'--hard-timeout', type='int', default=60*60, metavar='SECS',
help='Seconds to allow the task to complete.')
group.add_option(
'--io-timeout', type='int', default=20*60, metavar='SECS',
help='Seconds to allow the task to be silent.')
group.add_option(
'--raw-cmd', action='store_true', default=False,
help='When set, the command after -- is used as-is without run_isolated. '
'In this case, the .isolated file is expected to not have a command')
group.add_option(
'--cipd-package', action='append', default=[], metavar='PKG',
help='CIPD packages to install on the Swarming bot. Uses the format: '
'path:package_name:version')
group.add_option(
'--named-cache', action='append', nargs=2, default=[],
metavar='NAME RELPATH',
help='"<name> <relpath>" items to keep a persistent bot managed cache')
group.add_option(
'--service-account',
help='Name of a service account to run the task as. Only literal "bot" '
'string can be specified currently (to run the task under bot\'s '
'account). Don\'t use task service accounts if not given '
'(default).')
group.add_option(
'-o', '--output', action='append', default=[], metavar='PATH',
help='A list of files to return in addition to those written to '
'${ISOLATED_OUTDIR}. An error will occur if a file specified by'
'this option is also written directly to ${ISOLATED_OUTDIR}.')
parser.add_option_group(group)
group = optparse.OptionGroup(parser, 'Task request')
group.add_option(
'--priority', type='int', default=100,
help='The lower value, the more important the task is')
group.add_option(
'-T', '--task-name', metavar='NAME',
help='Display name of the task. Defaults to '
'<base_name>/<dimensions>/<isolated hash>/<timestamp> if an '
'isolated file is provided, if a hash is provided, it defaults to '
'<user>/<dimensions>/<isolated hash>/<timestamp>')
group.add_option(
'--tags', action='append', default=[], metavar='FOO:BAR',
help='Tags to assign to the task.')
group.add_option(
'--user', default='',
help='User associated with the task. Defaults to authenticated user on '
'the server.')
group.add_option(
'--expiration', type='int', default=6*60*60, metavar='SECS',
help='Seconds to allow the task to be pending for a bot to run before '
'this task request expires.')
group.add_option(
'--deadline', type='int', dest='expiration',
help=optparse.SUPPRESS_HELP)
parser.add_option_group(group)
def process_trigger_options(parser, options, args):
"""Processes trigger options and does preparatory steps.
Generates service account tokens if necessary.
"""
process_filter_options(parser, options)
options.env = dict(options.env)
if args and args[0] == '--':
args = args[1:]
if not options.dimensions:
parser.error('Please at least specify one --dimension')
if not all(len(t.split(':', 1)) == 2 for t in options.tags):
parser.error('--tags must be in the format key:value')
if options.raw_cmd and not args:
parser.error(
'Arguments with --raw-cmd should be passed after -- as command '
'delimiter.')
if options.isolate_server and not options.namespace:
parser.error(
'--namespace must be a valid value when --isolate-server is used')
if not options.isolated and not options.raw_cmd:
parser.error('Specify at least one of --raw-cmd or --isolated or both')
# Isolated
# --isolated is required only if --raw-cmd wasn't provided.
# TODO(maruel): --isolate-server may be optional as Swarming may have its own