mirrored from https://chromium.googlesource.com/infra/luci/luci-py
-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathrun_isolated.py
executable file
·1771 lines (1547 loc) · 62.8 KB
/
run_isolated.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 2012 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.
"""Runs a command with optional isolated input/output.
run_isolated takes cares of setting up a temporary environment, running a
command, and tearing it down.
It handles downloading and uploading isolated files, mapping CIPD packages and
reusing stateful named caches.
The isolated files, CIPD packages and named caches are kept as a global LRU
cache.
Any ${EXECUTABLE_SUFFIX} on the command line or the environment variables passed
with the --env option will be replaced with ".exe" string on Windows and "" on
other platforms.
Any ${ISOLATED_OUTDIR} on the command line or the environment variables passed
with the --env option will be replaced by the location of a temporary directory
upon execution of the command specified in the .isolated file. All content
written to this directory will be uploaded upon termination and the .isolated
file describing this directory will be printed to stdout.
Any ${SWARMING_BOT_FILE} on the command line or the environment variables passed
with the --env option will be replaced by the value of the --bot-file parameter.
This file is used by a swarming bot to communicate state of the host to tasks.
It is written to by the swarming bot's on_before_task() hook in the swarming
server's custom bot_config.py.
Any ${SWARMING_TASK_ID} on the command line will be replaced by the
SWARMING_TASK_ID value passed with the --env option.
See
https://chromium.googlesource.com/infra/luci/luci-py.git/+/main/appengine/swarming/doc/Magic-Values.md
for all the variables.
See
https://chromium.googlesource.com/infra/luci/luci-py.git/+/main/appengine/swarming/swarming_bot/config/bot_config.py
for more information about bot_config.py.
"""
from __future__ import print_function
__version__ = '1.0.1'
import argparse
import base64
import collections
import contextlib
import distutils
import errno
import json
import logging
import optparse
import os
import platform
import re
import shutil
import sys
import tempfile
import time
from utils import tools
tools.force_local_third_party()
# third_party/
from depot_tools import fix_encoding
# pylint: disable=ungrouped-imports
import auth
import cipd
import errors
import local_caching
from libs import luci_context
from utils import file_path
from utils import fs
from utils import logging_utils
from utils import net
from utils import on_error
from utils import subprocess42
# Magic variables that can be found in the isolate task command line.
ISOLATED_OUTDIR_PARAMETER = '${ISOLATED_OUTDIR}'
EXECUTABLE_SUFFIX_PARAMETER = '${EXECUTABLE_SUFFIX}'
SWARMING_BOT_FILE_PARAMETER = '${SWARMING_BOT_FILE}'
SWARMING_TASK_ID_PARAMETER = '${SWARMING_TASK_ID}'
# The name of the log file to use.
RUN_ISOLATED_LOG_FILE = 'run_isolated.log'
# Use short names for temporary directories. This is driven by Windows, which
# imposes a relatively short maximum path length of 260 characters, often
# referred to as MAX_PATH. It is relatively easy to create files with longer
# path length. A use case is with recursive dependency trees like npm packages.
#
# It is recommended to start the script with a `root_dir` as short as
# possible.
# - ir stands for isolated_run
# - io stands for isolated_out
# - it stands for isolated_tmp
ISOLATED_RUN_DIR = 'ir'
ISOLATED_OUT_DIR = 'io'
ISOLATED_TMP_DIR = 'it'
_CAS_CLIENT_DIR = 'cc'
# TODO(tikuta): take these parameter from luci-config?
_CAS_PACKAGE = 'infra/tools/luci/cas/${platform}'
_LUCI_GO_REVISION = 'git_revision:d290e92048ea30ad4f74232430604cbf7053557c'
# Keep synced with task_request.py
CACHE_NAME_RE = re.compile(r'^[a-z0-9_]{1,4096}$')
_FREE_SPACE_BUFFER_FOR_CIPD_PACKAGES = 2 * 1024 * 1024 * 1024
OUTLIVING_ZOMBIE_MSG = """\
*** Swarming tried multiple times to delete the %s directory and failed ***
*** Hard failing the task ***
Swarming detected that your testing script ran an executable, which may have
started a child executable, and the main script returned early, leaving the
children executables playing around unguided.
You don't want to leave children processes outliving the task on the Swarming
bot, do you? The Swarming bot doesn't.
How to fix?
- For any process that starts children processes, make sure all children
processes terminated properly before each parent process exits. This is
especially important in very deep process trees.
- This must be done properly both in normal successful task and in case of
task failure. Cleanup is very important.
- The Swarming bot sends a SIGTERM in case of timeout.
- You have %s seconds to comply after the signal was sent to the process
before the process is forcibly killed.
- To achieve not leaking children processes in case of signals on timeout, you
MUST handle signals in each executable / python script and propagate them to
children processes.
- When your test script (python or binary) receives a signal like SIGTERM or
CTRL_BREAK_EVENT on Windows), send it to all children processes and wait for
them to terminate before quitting.
See
https://chromium.googlesource.com/infra/luci/luci-py.git/+/main/appengine/swarming/doc/Bot.md#Graceful-termination_aka-the-SIGTERM-and-SIGKILL-dance
for more information.
*** May the SIGKILL force be with you ***
"""
# Currently hardcoded. Eventually could be exposed as a flag once there's value.
# 3 weeks
MAX_AGE_SECS = 21*24*60*60
_CAS_KVS_CACHE_THRESHOLD = 5 * 1024 * 1024 * 1024 # 5 GiB
TaskData = collections.namedtuple(
'TaskData',
[
# List of strings; the command line to use, independent of what was
# specified in the isolated file.
'command',
# Relative directory to start command into.
'relative_cwd',
# Digest of the input root on RBE-CAS.
'cas_digest',
# Full CAS instance name.
'cas_instance',
# List of paths relative to root_dir to put into the output isolated
# bundle upon task completion (see link_outputs_to_outdir).
'outputs',
# Function (run_dir) => context manager that installs named caches into
# |run_dir|.
'install_named_caches',
# If True, the temporary directory will be deliberately leaked for later
# examination.
'leak_temp_dir',
# Path to the directory to use to create the temporary directory. If not
# specified, a random temporary directory is created.
'root_dir',
# Kills the process if it lasts more than this amount of seconds.
'hard_timeout',
# Number of seconds to wait between SIGTERM and SIGKILL.
'grace_period',
# Path to a file with bot state, used in place of ${SWARMING_BOT_FILE}
# task command line argument.
'bot_file',
# Logical account to switch LUCI_CONTEXT into.
'switch_to_account',
# Context manager dir => CipdInfo, see install_client_and_packages.
'install_packages_fn',
# Cache directory for `cas` client.
'cas_cache_dir',
# Parameters passed to `cas` client.
'cas_cache_policies',
# Parameters for kvs file used by `cas` client.
'cas_kvs',
# Environment variables to set.
'env',
# Environment variables to mutate with relative directories.
# Example: {"ENV_KEY": ['relative', 'paths', 'to', 'prepend']}
'env_prefix',
# Lowers the task process priority.
'lower_priority',
# subprocess42.Containment instance. Can be None.
'containment',
# Function to trim caches before installing cipd packages and
# downloading isolated files.
'trim_caches_fn',
])
def make_temp_dir(prefix, root_dir):
"""Returns a new unique temporary directory."""
return tempfile.mkdtemp(prefix=prefix, dir=root_dir)
@contextlib.contextmanager
def set_luci_context_account(account, tmp_dir):
"""Sets LUCI_CONTEXT account to be used by the task.
If 'account' is None or '', does nothing at all. This happens when
run_isolated.py is called without '--switch-to-account' flag. In this case,
if run_isolated.py is running in some LUCI_CONTEXT environment, the task will
just inherit whatever account is already set. This may happen if users invoke
run_isolated.py explicitly from their code.
If the requested account is not defined in the context, switches to
non-authenticated access. This happens for Swarming tasks that don't use
'task' service accounts.
If not using LUCI_CONTEXT-based auth, does nothing.
If already running as requested account, does nothing.
"""
if not account:
# Not actually switching.
yield
return
local_auth = luci_context.read('local_auth')
if not local_auth:
# Not using LUCI_CONTEXT auth at all.
yield
return
# See LUCI_CONTEXT.md for the format of 'local_auth'.
if local_auth.get('default_account_id') == account:
# Already set, no need to switch.
yield
return
available = {a['id'] for a in local_auth.get('accounts') or []}
if account in available:
logging.info('Switching default LUCI_CONTEXT account to %r', account)
local_auth['default_account_id'] = account
else:
logging.warning(
'Requested LUCI_CONTEXT account %r is not available (have only %r), '
'disabling authentication', account, sorted(available))
local_auth.pop('default_account_id', None)
with luci_context.write(_tmpdir=tmp_dir, local_auth=local_auth):
yield
def process_command(command, out_dir, bot_file):
"""Replaces parameters in a command line.
Raises:
ValueError if a parameter is requested in |command| but its value is not
provided.
"""
return [replace_parameters(arg, out_dir, bot_file) for arg in command]
def replace_parameters(arg, out_dir, bot_file):
"""Replaces parameter tokens with appropriate values in a string.
Raises:
ValueError if a parameter is requested in |arg| but its value is not
provided.
"""
arg = arg.replace(EXECUTABLE_SUFFIX_PARAMETER, cipd.EXECUTABLE_SUFFIX)
replace_slash = False
if ISOLATED_OUTDIR_PARAMETER in arg:
if not out_dir:
raise ValueError(
'output directory is requested in command or env var, but not '
'provided; please specify one')
arg = arg.replace(ISOLATED_OUTDIR_PARAMETER, out_dir)
replace_slash = True
if SWARMING_BOT_FILE_PARAMETER in arg:
if bot_file:
arg = arg.replace(SWARMING_BOT_FILE_PARAMETER, bot_file)
replace_slash = True
else:
logging.warning('SWARMING_BOT_FILE_PARAMETER found in command or env '
'var, but no bot_file specified. Leaving parameter '
'unchanged.')
if SWARMING_TASK_ID_PARAMETER in arg:
task_id = os.environ.get('SWARMING_TASK_ID')
if task_id:
arg = arg.replace(SWARMING_TASK_ID_PARAMETER, task_id)
if replace_slash:
# Replace slashes only if parameters are present
# because of arguments like '${ISOLATED_OUTDIR}/foo/bar'
arg = arg.replace('/', os.sep)
return arg
def set_temp_dir(env, tmp_dir):
"""Set temp dir to given env var dictionary"""
# pylint: disable=line-too-long
# * python respects $TMPDIR, $TEMP, and $TMP in this order, regardless of
# platform. So $TMPDIR must be set on all platforms.
# https://github.com/python/cpython/blob/2.7/Lib/tempfile.py#L155
env['TMPDIR'] = tmp_dir
if sys.platform == 'win32':
# * chromium's base utils uses GetTempPath().
# https://cs.chromium.org/chromium/src/base/files/file_util_win.cc?q=GetTempPath
# * Go uses GetTempPath().
# * GetTempDir() uses %TMP%, then %TEMP%, then other stuff. So %TMP% must be
# set.
# https://docs.microsoft.com/en-us/windows/desktop/api/fileapi/nf-fileapi-gettemppathw
env['TMP'] = tmp_dir
# https://blogs.msdn.microsoft.com/oldnewthing/20150417-00/?p=44213
env['TEMP'] = tmp_dir
elif sys.platform == 'darwin':
# * Chromium uses an hack on macOS before calling into
# NSTemporaryDirectory().
# https://cs.chromium.org/chromium/src/base/files/file_util_mac.mm?q=GetTempDir
# https://developer.apple.com/documentation/foundation/1409211-nstemporarydirectory
env['MAC_CHROMIUM_TMPDIR'] = tmp_dir
else:
# TMPDIR is specified as the POSIX standard envvar for the temp directory.
# http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html
# * mktemp on linux respects $TMPDIR.
# * Chromium respects $TMPDIR on linux.
# https://cs.chromium.org/chromium/src/base/files/file_util_posix.cc?q=GetTempDir
# * Go uses $TMPDIR.
# https://go.googlesource.com/go/+/go1.10.3/src/os/file_unix.go#307
pass
def get_command_env(tmp_dir, cipd_info, run_dir, env, env_prefixes, out_dir,
bot_file):
"""Returns full OS environment to run a command in.
Sets up TEMP, puts directory with cipd binary in front of PATH, exposes
CIPD_CACHE_DIR env var, and installs all env_prefixes.
Args:
tmp_dir: temp directory.
cipd_info: CipdInfo object is cipd client is used, None if not.
run_dir: The root directory the isolated tree is mapped in.
env: environment variables to use
env_prefixes: {"ENV_KEY": ['cwd', 'relative', 'paths', 'to', 'prepend']}
out_dir: Isolated output directory. Required to be != None if any of the
env vars contain ISOLATED_OUTDIR_PARAMETER.
bot_file: Required to be != None if any of the env vars contain
SWARMING_BOT_FILE_PARAMETER.
"""
out = os.environ.copy()
for k, v in env.items():
if not v:
out.pop(k, None)
else:
out[k] = replace_parameters(v, out_dir, bot_file)
if cipd_info:
bin_dir = os.path.dirname(cipd_info.client.binary_path)
out['PATH'] = '%s%s%s' % (bin_dir, os.pathsep, out['PATH'])
out['CIPD_CACHE_DIR'] = cipd_info.cache_dir
cipd_info_path = os.path.join(tmp_dir, 'cipd_info.json')
with open(cipd_info_path, 'w') as f:
json.dump(cipd_info.pins, f)
out['ISOLATED_RESOLVED_PACKAGE_VERSIONS_FILE'] = cipd_info_path
for key, paths in env_prefixes.items():
assert isinstance(paths, list), paths
paths = [os.path.normpath(os.path.join(run_dir, p)) for p in paths]
cur = out.get(key)
if cur:
paths.append(cur)
out[key] = os.path.pathsep.join(paths)
set_temp_dir(out, tmp_dir)
return out
def run_command(
command, cwd, env, hard_timeout, grace_period, lower_priority, containment):
"""Runs the command.
Returns:
tuple(process exit code, bool if had a hard timeout)
"""
logging_utils.user_logs('run_command(%s, %s, %s, %s, %s, %s)', command, cwd,
hard_timeout, grace_period, lower_priority,
containment)
exit_code = None
had_hard_timeout = False
with tools.Profiler('RunTest'):
proc = None
had_signal = []
try:
# TODO(maruel): This code is imperfect. It doesn't handle well signals
# during the download phase and there's short windows were things can go
# wrong.
def handler(signum, _frame):
if proc and not had_signal:
logging.info('Received signal %d', signum)
had_signal.append(True)
raise subprocess42.TimeoutExpired(command, None)
proc = subprocess42.Popen(
command, cwd=cwd, env=env, detached=True, close_fds=True,
lower_priority=lower_priority, containment=containment)
logging.info('Subprocess for command started')
with subprocess42.set_signal_handler(subprocess42.STOP_SIGNALS, handler):
try:
exit_code = proc.wait(hard_timeout or None)
logging.info("finished with exit code %d after hard_timeout %s",
exit_code, hard_timeout)
except subprocess42.TimeoutExpired:
if not had_signal:
logging.warning('Hard timeout')
had_hard_timeout = True
logging.warning('Sending SIGTERM')
proc.terminate()
kill_sent = False
# Ignore signals in grace period. Forcibly give the grace period to the
# child process.
if exit_code is None:
ignore = lambda *_: None
with subprocess42.set_signal_handler(subprocess42.STOP_SIGNALS, ignore):
try:
exit_code = proc.wait(grace_period or None)
logging.info("finished with exit code %d after grace_period %s",
exit_code, grace_period)
except subprocess42.TimeoutExpired:
# Now kill for real. The user can distinguish between the
# following states:
# - signal but process exited within grace period,
# hard_timed_out will be set but the process exit code will be
# script provided.
# - processed exited late, exit code will be -9 on posix.
logging.warning('Grace exhausted; sending SIGKILL')
proc.kill()
kill_sent = True
logging.info('Waiting for process exit')
exit_code = proc.wait()
# the process group / job object may be dangling so if we didn't kill
# it already, give it a poke now.
if not kill_sent:
proc.kill()
except OSError as e:
# This is not considered to be an internal error. The executable simply
# does not exit.
sys.stderr.write(
'<The executable does not exist, a dependent library is missing or '
'the command line is too long>\n'
'<Check for missing .so/.dll in the .isolate or GN file or length of '
'command line args>\n'
'<Command: %s>\n'
'<Exception: %s>\n' % (command, e))
if os.environ.get('SWARMING_TASK_ID'):
# Give an additional hint when running as a swarming task.
sys.stderr.write(
'<See the task\'s page for commands to help diagnose this issue '
'by reproducing the task locally>\n')
exit_code = 1
logging.info(
'Command finished with exit code %d (%s)',
exit_code, hex(0xffffffff & exit_code))
return exit_code, had_hard_timeout
def _run_go_cmd_and_wait(cmd, tmp_dir):
"""
Runs an external Go command, `isolated` or `cas`, and wait for its completion.
While this is a generic function to launch a subprocess, it has logic that
is specific to Go `isolated` and `cas` for waiting and logging.
Returns:
The subprocess object
"""
cmd_str = ' '.join(cmd)
try:
env = os.environ.copy()
set_temp_dir(env, tmp_dir)
proc = subprocess42.Popen(cmd, env=env)
exceeded_max_timeout = True
check_period_sec = 30
max_checks = 100
# max timeout = max_checks * check_period_sec = 50 minutes
for i in range(max_checks):
# This is to prevent I/O timeout error during setup.
try:
retcode = proc.wait(check_period_sec)
if retcode != 0:
raise subprocess42.CalledProcessError(retcode, cmd=cmd_str)
exceeded_max_timeout = False
break
except subprocess42.TimeoutExpired:
print('still running (after %d seconds)' % ((i + 1) * check_period_sec))
if exceeded_max_timeout:
proc.terminate()
try:
proc.wait(check_period_sec)
except subprocess42.TimeoutExpired:
logging.exception(
"failed to terminate? timeout happened after %d seconds",
check_period_sec)
proc.kill()
proc.wait()
# Raise unconditionally, because |proc| was forcefully terminated.
raise ValueError("timedout after %d seconds (cmd=%s)" %
(check_period_sec * max_checks, cmd_str))
return proc
except Exception:
logging.exception('Failed to run Go cmd %s', cmd_str)
raise
def _fetch_and_map(cas_client, digest, instance, output_dir, cache_dir,
policies, kvs_dir, tmp_dir):
"""
Fetches a CAS tree using cas client, create the tree and returns download
stats.
"""
start = time.time()
result_json_handle, result_json_path = tempfile.mkstemp(
prefix='fetch-and-map-result-', suffix='.json')
os.close(result_json_handle)
profile_dir = tempfile.mkdtemp(dir=tmp_dir)
try:
cmd = [
cas_client,
'download',
'-digest',
digest,
# flags for cache.
'-cache-dir',
cache_dir,
'-cache-max-size',
str(policies.max_cache_size),
'-cache-min-free-space',
str(policies.min_free_space),
# flags for output.
'-dir',
output_dir,
'-dump-json',
result_json_path,
'-log-level',
'info',
]
# When RUN_ISOLATED_CAS_ADDRESS is set in test mode,
# Use it and ignore CAS instance option.
cas_addr = os.environ.get('RUN_ISOLATED_CAS_ADDRESS')
if cas_addr:
cmd.extend([
'-cas-addr',
cas_addr,
])
else:
cmd.extend([
'-cas-instance',
instance
])
if kvs_dir:
cmd.extend(['-kvs-dir', kvs_dir])
def open_json_and_check(result_json_path, cleanup_dirs):
cas_error = False
result_json = {}
error_digest = digest
try:
with open(result_json_path) as json_file:
result_json = json.load(json_file)
cas_error = result_json.get('result') in ('digest_invalid',
'authentication_error',
'arguments_invalid')
if cas_error and result_json.get('error_details'):
error_digest = result_json['error_details'].get('digest', digest)
except (IOError, ValueError):
logging.error('Failed to read json file: %s', result_json_path)
raise
finally:
if cleanup_dirs:
file_path.rmtree(kvs_dir)
file_path.rmtree(output_dir)
if cas_error:
raise errors.NonRecoverableCasException(result_json['result'],
error_digest, instance)
return result_json
try:
_run_go_cmd_and_wait(cmd, tmp_dir)
except subprocess42.CalledProcessError as ex:
if not kvs_dir:
open_json_and_check(result_json_path, False)
raise
open_json_and_check(result_json_path, True)
logging.exception('Failed to run cas, removing kvs cache dir and retry.')
on_error.report("Failed to run cas %s" % ex)
_run_go_cmd_and_wait(cmd, tmp_dir)
result_json = open_json_and_check(result_json_path, False)
return {
'duration': time.time() - start,
'items_cold': result_json['items_cold'],
'items_hot': result_json['items_hot'],
}
finally:
fs.remove(result_json_path)
file_path.rmtree(profile_dir)
def link_outputs_to_outdir(run_dir, out_dir, outputs):
"""Links any named outputs to out_dir so they can be uploaded.
Raises an error if the file already exists in that directory.
"""
if not outputs:
return
file_path.create_directories(out_dir, outputs)
for o in outputs:
copy_recursively(os.path.join(run_dir, o), os.path.join(out_dir, o))
def copy_recursively(src, dst):
"""Efficiently copies a file or directory from src_dir to dst_dir.
`item` may be a file, directory, or a symlink to a file or directory.
All symlinks are replaced with their targets, so the resulting
directory structure in dst_dir will never have any symlinks.
To increase speed, copy_recursively hardlinks individual files into the
(newly created) directory structure if possible, unlike Python's
shutil.copytree().
"""
orig_src = src
try:
# Replace symlinks with their final target.
while fs.islink(src):
res = fs.readlink(src)
src = os.path.realpath(os.path.join(os.path.dirname(src), res))
# TODO(sadafm): Explicitly handle cyclic symlinks.
if not fs.exists(src):
logging.warning('Path %s does not exist or %s is a broken symlink', src,
orig_src)
return
if fs.isfile(src):
file_path.link_file(dst, src, file_path.HARDLINK_WITH_FALLBACK)
return
if not fs.exists(dst):
os.makedirs(dst)
for child in fs.listdir(src):
copy_recursively(os.path.join(src, child), os.path.join(dst, child))
except OSError as e:
if e.errno == errno.ENOENT:
logging.warning('Path %s does not exist or %s is a broken symlink',
src, orig_src)
else:
logging.info("Couldn't collect output file %s: %s", src, e)
def upload_outdir(cas_client, cas_instance, outdir, tmp_dir):
"""Uploads the results in |outdir|, if there is any.
Returns:
tuple(root_digest, stats)
- root_digest: a digest of the output directory.
- stats: uploading stats.
"""
if not fs.listdir(outdir):
return None, None
digest_file_handle, digest_path = tempfile.mkstemp(prefix='cas-digest',
suffix='.txt')
os.close(digest_file_handle)
stats_json_handle, stats_json_path = tempfile.mkstemp(prefix='upload-stats',
suffix='.json')
os.close(stats_json_handle)
try:
cmd = [
cas_client,
'archive',
'-log-level',
'debug',
'-paths',
# Format: <working directory>:<relative path to dir>
outdir + ':',
# output
'-dump-digest',
digest_path,
'-dump-json',
stats_json_path,
]
# When RUN_ISOLATED_CAS_ADDRESS is set in test mode,
# Use it and ignore CAS instance option.
cas_addr = os.environ.get('RUN_ISOLATED_CAS_ADDRESS')
if cas_addr:
cmd.extend([
'-cas-addr',
cas_addr,
])
elif cas_instance:
cmd.extend([
'-cas-instance',
cas_instance
])
else:
return None, None
start = time.time()
_run_go_cmd_and_wait(cmd, tmp_dir)
with open(digest_path) as digest_file:
digest = digest_file.read()
h, s = digest.split('/')
cas_output_root = {
'cas_instance': cas_instance,
'digest': {
'hash': h,
'size_bytes': int(s)
}
}
with open(stats_json_path) as stats_file:
stats = json.load(stats_file)
stats['duration'] = time.time() - start
return cas_output_root, stats
finally:
fs.remove(digest_path)
fs.remove(stats_json_path)
def map_and_run(data, constant_run_path):
"""Runs a command with optional isolated input/output.
Arguments:
- data: TaskData instance.
- constant_run_path: TODO
Returns metadata about the result.
"""
# TODO(tikuta): take stats from state.json in this case too.
download_stats = {
# 'duration': 0.,
# 'initial_number_items': len(data.cas_cache),
# 'initial_size': data.cas_cache.total_size,
# 'items_cold': '<large.pack()>',
# 'items_hot': '<large.pack()>',
}
result = {
'duration': None,
'exit_code': None,
'had_hard_timeout': False,
'internal_failure': 'run_isolated did not complete properly',
'stats': {
'trim_caches': {
'duration': 0,
},
#'cipd': {
# 'duration': 0.,
# 'get_client_duration': 0.,
#},
'isolated': {
'download': download_stats,
#'upload': {
# 'duration': 0.,
# 'items_cold': '<large.pack()>',
# 'items_hot': '<large.pack()>',
#},
},
'named_caches': {
'install': {
'duration': 0,
},
'uninstall': {
'duration': 0,
},
},
'cleanup': {
'duration': 0,
}
},
#'cipd_pins': {
# 'packages': [
# {'package_name': ..., 'version': ..., 'path': ...},
# ...
# ],
# 'client_package': {'package_name': ..., 'version': ...},
#},
'outputs_ref': None,
'cas_output_root': None,
'version': 5,
}
assert os.path.isabs(data.root_dir), ("data.root_dir is not abs path: %s" %
data.root_dir)
file_path.ensure_tree(data.root_dir, 0o700)
# See comment for these constants.
# TODO(maruel): This is not obvious. Change this to become an error once we
# make the constant_run_path an exposed flag.
if constant_run_path and data.root_dir:
run_dir = os.path.join(data.root_dir, ISOLATED_RUN_DIR)
if os.path.isdir(run_dir):
file_path.rmtree(run_dir)
os.mkdir(run_dir, 0o700)
else:
run_dir = make_temp_dir(ISOLATED_RUN_DIR, data.root_dir)
# storage should be normally set but don't crash if it is not. This can happen
# as Swarming task can run without an isolate server.
out_dir = make_temp_dir(ISOLATED_OUT_DIR, data.root_dir)
tmp_dir = make_temp_dir(ISOLATED_TMP_DIR, data.root_dir)
cwd = run_dir
if data.relative_cwd:
cwd = os.path.normpath(os.path.join(cwd, data.relative_cwd))
command = data.command
cas_client_dir = make_temp_dir(_CAS_CLIENT_DIR, data.root_dir)
cas_client = os.path.join(cas_client_dir, 'cas' + cipd.EXECUTABLE_SUFFIX)
data.trim_caches_fn(result['stats']['trim_caches'])
try:
with data.install_packages_fn(run_dir, cas_client_dir) as cipd_info:
if cipd_info:
result['stats']['cipd'] = cipd_info.stats
result['cipd_pins'] = cipd_info.pins
isolated_stats = result['stats'].setdefault('isolated', {})
if data.cas_digest:
stats = _fetch_and_map(
cas_client=cas_client,
digest=data.cas_digest,
instance=data.cas_instance,
output_dir=run_dir,
cache_dir=data.cas_cache_dir,
policies=data.cas_cache_policies,
kvs_dir=data.cas_kvs,
tmp_dir=tmp_dir)
isolated_stats['download'].update(stats)
logging_utils.user_logs('Fetched CAS inputs')
if not command:
# Handle this as a task failure, not an internal failure.
sys.stderr.write(
'<No command was specified!>\n'
'<Please secify a command when triggering your Swarming task>\n')
result['exit_code'] = 1
return result
if not cwd.startswith(run_dir):
# Handle this as a task failure, not an internal failure. This is a
# 'last chance' way to gate against directory escape.
sys.stderr.write('<Relative CWD is outside of run directory!>\n')
result['exit_code'] = 1
return result
if not os.path.isdir(cwd):
# Accepts relative_cwd that does not exist.
os.makedirs(cwd, 0o700)
# If we have an explicit list of files to return, make sure their
# directories exist now.
if data.outputs:
file_path.create_directories(run_dir, data.outputs)
with data.install_named_caches(run_dir, result['stats']['named_caches']):
logging_utils.user_logs('Installed named caches')
sys.stdout.flush()
start = time.time()
try:
# Need to switch the default account before 'get_command_env' call,
# so it can grab correct value of LUCI_CONTEXT env var.
with set_luci_context_account(data.switch_to_account, tmp_dir):
env = get_command_env(
tmp_dir, cipd_info, run_dir, data.env, data.env_prefix, out_dir,
data.bot_file)
command = tools.find_executable(command, env)
command = process_command(command, out_dir, data.bot_file)
file_path.ensure_command_has_abs_path(command, cwd)
result['exit_code'], result['had_hard_timeout'] = run_command(
command, cwd, env, data.hard_timeout, data.grace_period,
data.lower_priority, data.containment)
finally:
result['duration'] = max(time.time() - start, 0)
# Try to link files to the output directory, if specified.
link_outputs_to_outdir(run_dir, out_dir, data.outputs)
isolated_stats = result['stats'].setdefault('isolated', {})
result['cas_output_root'], upload_stats = upload_outdir(
cas_client, data.cas_instance, out_dir, tmp_dir)
if upload_stats:
isolated_stats['upload'] = upload_stats
# We successfully ran the command, set internal_failure back to
# None (even if the command failed, it's not an internal error).
result['internal_failure'] = None
except errors.NonRecoverableCasException as e:
# We could not find the CAS package. The swarming task should not
# be retried automatically
result['missing_cas'] = [e.to_dict()]
logging.exception('internal failure: %s', e)
result['internal_failure'] = str(e)
on_error.report(None)
except errors.NonRecoverableCipdException as e:
# We could not find the CIPD package. The swarming task should not
# be retried automatically
result['missing_cipd'] = [e.to_dict()]
logging.exception('internal failure: %s', e)
result['internal_failure'] = str(e)
on_error.report(None)
except Exception as e:
# An internal error occurred. Report accordingly so the swarming task will
# be retried automatically.
logging.exception('internal failure: %s', e)
result['internal_failure'] = str(e)
on_error.report(None)
# Clean up
finally:
try:
cleanup_start = time.time()
success = True
if data.leak_temp_dir:
success = True
logging.warning(
'Deliberately leaking %s for later examination', run_dir)
else:
# On Windows rmtree(run_dir) call above has a synchronization effect: it
# finishes only when all task child processes terminate (since a running
# process locks *.exe file). Examine out_dir only after that call
# completes (since child processes may write to out_dir too and we need
# to wait for them to finish).
dirs_to_remove = [run_dir, tmp_dir, cas_client_dir]
if out_dir:
dirs_to_remove.append(out_dir)
for directory in dirs_to_remove:
if not fs.isdir(directory):
continue
start = time.time()
try:
file_path.rmtree(directory)
except OSError as e:
logging.error('rmtree(%r) failed: %s', directory, e)
success = False
finally:
logging.info('Cleanup: rmtree(%r) took %d seconds', directory,
time.time() - start)
if not success:
sys.stderr.write(
OUTLIVING_ZOMBIE_MSG % (directory, data.grace_period))
if sys.platform == 'win32':
subprocess42.check_call(['tasklist.exe', '/V'], stdout=sys.stderr)
else:
subprocess42.check_call(['ps', 'axu'], stdout=sys.stderr)
if result['exit_code'] == 0:
result['exit_code'] = 1
if not success and result['exit_code'] == 0:
result['exit_code'] = 1
except Exception as e:
# Swallow any exception in the main finally clause.
if out_dir: