blob: 052142d4959717756f35192dbe7d33b919e9be1d [file] [log] [blame]
maruel@chromium.org9c72d4e2012-09-28 19:20:25 +00001#!/usr/bin/env python
maruelea586f32016-04-05 11:11:33 -07002# Copyright 2012 The LUCI Authors. All rights reserved.
maruelf1f5e2a2016-05-25 17:10:39 -07003# Use of this source code is governed under the Apache License, Version 2.0
4# that can be found in the LICENSE file.
maruel@chromium.org9c72d4e2012-09-28 19:20:25 +00005
nodir55be77b2016-05-03 09:39:57 -07006"""Runs a command with optional isolated input/output.
maruel@chromium.org9c72d4e2012-09-28 19:20:25 +00007
nodir55be77b2016-05-03 09:39:57 -07008Despite name "run_isolated", can run a generic non-isolated command specified as
9args.
10
11If input isolated hash is provided, fetches it, creates a tree of hard links,
12appends args to the command in the fetched isolated and runs it.
13To improve performance, keeps a local cache.
14The local cache can safely be deleted.
Marc-Antoine Ruel2283ad12014-02-09 11:14:57 -050015
nodirbe642ff2016-06-09 15:51:51 -070016Any ${EXECUTABLE_SUFFIX} on the command line will be replaced with ".exe" string
17on Windows and "" on other platforms.
18
Marc-Antoine Ruel2283ad12014-02-09 11:14:57 -050019Any ${ISOLATED_OUTDIR} on the command line will be replaced by the location of a
20temporary directory upon execution of the command specified in the .isolated
21file. All content written to this directory will be uploaded upon termination
22and the .isolated file describing this directory will be printed to stdout.
bpastene447c1992016-06-20 15:21:47 -070023
24Any ${SWARMING_BOT_FILE} on the command line will be replaced by the value of
25the --bot-file parameter. This file is used by a swarming bot to communicate
26state of the host to tasks. It is written to by the swarming bot's
27on_before_task() hook in the swarming server's custom bot_config.py.
maruel@chromium.org9c72d4e2012-09-28 19:20:25 +000028"""
29
Marc-Antoine Ruelaf9ea1b2017-11-28 18:33:39 -050030__version__ = '0.10.1'
maruel@chromium.orgdedbf492013-09-12 20:42:11 +000031
aludwin7556e0c2016-10-26 08:46:10 -070032import argparse
maruel064c0a32016-04-05 11:47:15 -070033import base64
iannucci96fcccc2016-08-30 15:52:22 -070034import collections
vadimsh232f5a82017-01-20 19:23:44 -080035import contextlib
aludwin7556e0c2016-10-26 08:46:10 -070036import json
maruel@chromium.org9c72d4e2012-09-28 19:20:25 +000037import logging
38import optparse
39import os
maruel@chromium.org9c72d4e2012-09-28 19:20:25 +000040import sys
41import tempfile
maruel064c0a32016-04-05 11:47:15 -070042import time
maruel@chromium.org9c72d4e2012-09-28 19:20:25 +000043
vadimsh@chromium.orga4326472013-08-24 02:05:41 +000044from third_party.depot_tools import fix_encoding
45
Vadim Shtayura6b555c12014-07-23 16:22:18 -070046from utils import file_path
maruel12e30012015-10-09 11:55:35 -070047from utils import fs
maruel064c0a32016-04-05 11:47:15 -070048from utils import large
Marc-Antoine Ruelf74cffe2015-07-15 15:21:34 -040049from utils import logging_utils
Marc-Antoine Ruelcfb60852014-07-02 15:22:00 -040050from utils import on_error
Marc-Antoine Ruelc44f5722015-01-08 16:10:01 -050051from utils import subprocess42
vadimsh@chromium.orga4326472013-08-24 02:05:41 +000052from utils import tools
vadimsh@chromium.org3e97deb2013-08-24 00:56:44 +000053from utils import zip_package
vadimsh@chromium.org8b9d56b2013-08-21 22:24:35 +000054
vadimsh8ec66822017-07-25 14:08:29 -070055from libs import luci_context
56
Vadim Shtayurae34e13a2014-02-02 11:23:26 -080057import auth
nodirbe642ff2016-06-09 15:51:51 -070058import cipd
maruel@chromium.orgdedbf492013-09-12 20:42:11 +000059import isolateserver
nodirf33b8d62016-10-26 22:34:58 -070060import named_cache
maruel@chromium.orgdedbf492013-09-12 20:42:11 +000061
vadimsh@chromium.orga4326472013-08-24 02:05:41 +000062
vadimsh@chromium.org85071062013-08-21 23:37:45 +000063# Absolute path to this file (can be None if running from zip on Mac).
tansella4949442016-06-23 22:34:32 -070064THIS_FILE_PATH = os.path.abspath(
65 __file__.decode(sys.getfilesystemencoding())) if __file__ else None
vadimsh@chromium.org8b9d56b2013-08-21 22:24:35 +000066
67# Directory that contains this file (might be inside zip package).
tansella4949442016-06-23 22:34:32 -070068BASE_DIR = os.path.dirname(THIS_FILE_PATH) if __file__.decode(
69 sys.getfilesystemencoding()) else None
vadimsh@chromium.org8b9d56b2013-08-21 22:24:35 +000070
71# Directory that contains currently running script file.
maruel@chromium.org814d23f2013-10-01 19:08:00 +000072if zip_package.get_main_script_path():
73 MAIN_DIR = os.path.dirname(
74 os.path.abspath(zip_package.get_main_script_path()))
75else:
76 # This happens when 'import run_isolated' is executed at the python
77 # interactive prompt, in that case __file__ is undefined.
78 MAIN_DIR = None
vadimsh@chromium.org8b9d56b2013-08-21 22:24:35 +000079
maruele2f2cb82016-07-13 14:41:03 -070080
81# Magic variables that can be found in the isolate task command line.
82ISOLATED_OUTDIR_PARAMETER = '${ISOLATED_OUTDIR}'
83EXECUTABLE_SUFFIX_PARAMETER = '${EXECUTABLE_SUFFIX}'
84SWARMING_BOT_FILE_PARAMETER = '${SWARMING_BOT_FILE}'
85
86
csharp@chromium.orgff2a4662012-11-21 20:49:32 +000087# The name of the log file to use.
88RUN_ISOLATED_LOG_FILE = 'run_isolated.log'
89
maruele2f2cb82016-07-13 14:41:03 -070090
csharp@chromium.orge217f302012-11-22 16:51:53 +000091# The name of the log to use for the run_test_cases.py command
vadimsh@chromium.org8b9d56b2013-08-21 22:24:35 +000092RUN_TEST_CASES_LOG = 'run_test_cases.log'
csharp@chromium.orge217f302012-11-22 16:51:53 +000093
vadimsh@chromium.org87d63262013-04-04 19:34:21 +000094
maruele2f2cb82016-07-13 14:41:03 -070095# Use short names for temporary directories. This is driven by Windows, which
96# imposes a relatively short maximum path length of 260 characters, often
97# referred to as MAX_PATH. It is relatively easy to create files with longer
98# path length. A use case is with recursive depedency treesV like npm packages.
99#
100# It is recommended to start the script with a `root_dir` as short as
101# possible.
102# - ir stands for isolated_run
103# - io stands for isolated_out
104# - it stands for isolated_tmp
105ISOLATED_RUN_DIR = u'ir'
106ISOLATED_OUT_DIR = u'io'
107ISOLATED_TMP_DIR = u'it'
108
109
maruel7eb6b562017-06-08 08:20:04 -0700110OUTLIVING_ZOMBIE_MSG = """\
111*** Swarming tried multiple times to delete the %s directory and failed ***
112*** Hard failing the task ***
113
114Swarming detected that your testing script ran an executable, which may have
115started a child executable, and the main script returned early, leaving the
116children executables playing around unguided.
117
118You don't want to leave children processes outliving the task on the Swarming
119bot, do you? The Swarming bot doesn't.
120
121How to fix?
122- For any process that starts children processes, make sure all children
123 processes terminated properly before each parent process exits. This is
124 especially important in very deep process trees.
125 - This must be done properly both in normal successful task and in case of
126 task failure. Cleanup is very important.
127- The Swarming bot sends a SIGTERM in case of timeout.
128 - You have %s seconds to comply after the signal was sent to the process
129 before the process is forcibly killed.
130- To achieve not leaking children processes in case of signals on timeout, you
131 MUST handle signals in each executable / python script and propagate them to
132 children processes.
133 - When your test script (python or binary) receives a signal like SIGTERM or
134 CTRL_BREAK_EVENT on Windows), send it to all children processes and wait for
135 them to terminate before quitting.
136
137See
138https://github.com/luci/luci-py/blob/master/appengine/swarming/doc/Bot.md#graceful-termination-aka-the-sigterm-and-sigkill-dance
139for more information.
140
141*** May the SIGKILL force be with you ***
142"""
143
144
vadimsh@chromium.org8b9d56b2013-08-21 22:24:35 +0000145def get_as_zip_package(executable=True):
146 """Returns ZipPackage with this module and all its dependencies.
147
148 If |executable| is True will store run_isolated.py as __main__.py so that
149 zip package is directly executable be python.
150 """
151 # Building a zip package when running from another zip package is
152 # unsupported and probably unneeded.
153 assert not zip_package.is_zipped_module(sys.modules[__name__])
vadimsh@chromium.org85071062013-08-21 23:37:45 +0000154 assert THIS_FILE_PATH
155 assert BASE_DIR
vadimsh@chromium.org8b9d56b2013-08-21 22:24:35 +0000156 package = zip_package.ZipPackage(root=BASE_DIR)
157 package.add_python_file(THIS_FILE_PATH, '__main__.py' if executable else None)
aludwin81178302016-11-30 17:18:49 -0800158 package.add_python_file(os.path.join(BASE_DIR, 'isolate_storage.py'))
Marc-Antoine Ruel8bee66d2014-08-28 19:02:07 -0400159 package.add_python_file(os.path.join(BASE_DIR, 'isolated_format.py'))
maruel@chromium.orgdedbf492013-09-12 20:42:11 +0000160 package.add_python_file(os.path.join(BASE_DIR, 'isolateserver.py'))
Vadim Shtayurae34e13a2014-02-02 11:23:26 -0800161 package.add_python_file(os.path.join(BASE_DIR, 'auth.py'))
nodirbe642ff2016-06-09 15:51:51 -0700162 package.add_python_file(os.path.join(BASE_DIR, 'cipd.py'))
nodirf33b8d62016-10-26 22:34:58 -0700163 package.add_python_file(os.path.join(BASE_DIR, 'named_cache.py'))
tanselle4288c32016-07-28 09:45:40 -0700164 package.add_directory(os.path.join(BASE_DIR, 'libs'))
vadimsh@chromium.org8b9d56b2013-08-21 22:24:35 +0000165 package.add_directory(os.path.join(BASE_DIR, 'third_party'))
166 package.add_directory(os.path.join(BASE_DIR, 'utils'))
167 return package
168
169
maruel03e11842016-07-14 10:50:16 -0700170def make_temp_dir(prefix, root_dir):
171 """Returns a new unique temporary directory."""
172 return unicode(tempfile.mkdtemp(prefix=prefix, dir=root_dir))
maruel@chromium.org9c72d4e2012-09-28 19:20:25 +0000173
174
Marc-Antoine Ruel7124e392014-01-09 11:49:21 -0500175def change_tree_read_only(rootdir, read_only):
176 """Changes the tree read-only bits according to the read_only specification.
177
178 The flag can be 0, 1 or 2, which will affect the possibility to modify files
179 and create or delete files.
180 """
181 if read_only == 2:
182 # Files and directories (except on Windows) are marked read only. This
183 # inhibits modifying, creating or deleting files in the test directory,
184 # except on Windows where creating and deleting files is still possible.
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -0400185 file_path.make_tree_read_only(rootdir)
Marc-Antoine Ruel7124e392014-01-09 11:49:21 -0500186 elif read_only == 1:
187 # Files are marked read only but not the directories. This inhibits
188 # modifying files but creating or deleting files is still possible.
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -0400189 file_path.make_tree_files_read_only(rootdir)
Marc-Antoine Ruel7124e392014-01-09 11:49:21 -0500190 elif read_only in (0, None):
Marc-Antoine Ruelf1d827c2014-11-24 15:22:25 -0500191 # Anything can be modified.
Marc-Antoine Ruel7124e392014-01-09 11:49:21 -0500192 # TODO(maruel): This is currently dangerous as long as DiskCache.touch()
193 # is not yet changed to verify the hash of the content of the files it is
194 # looking at, so that if a test modifies an input file, the file must be
195 # deleted.
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -0400196 file_path.make_tree_writeable(rootdir)
Marc-Antoine Ruel7124e392014-01-09 11:49:21 -0500197 else:
198 raise ValueError(
199 'change_tree_read_only(%s, %s): Unknown flag %s' %
200 (rootdir, read_only, read_only))
201
202
vadimsh8ec66822017-07-25 14:08:29 -0700203@contextlib.contextmanager
204def set_luci_context_account(account, tmp_dir):
205 """Sets LUCI_CONTEXT account to be used by the task.
206
207 If 'account' is None or '', does nothing at all. This happens when
208 run_isolated.py is called without '--switch-to-account' flag. In this case,
209 if run_isolated.py is running in some LUCI_CONTEXT environment, the task will
210 just inherit whatever account is already set. This may happen is users invoke
211 run_isolated.py explicitly from their code.
212
213 If the requested account is not defined in the context, switches to
214 non-authenticated access. This happens for Swarming tasks that don't use
215 'task' service accounts.
216
217 If not using LUCI_CONTEXT-based auth, does nothing.
218 If already running as requested account, does nothing.
219 """
220 if not account:
221 # Not actually switching.
222 yield
223 return
224
225 local_auth = luci_context.read('local_auth')
226 if not local_auth:
227 # Not using LUCI_CONTEXT auth at all.
228 yield
229 return
230
231 # See LUCI_CONTEXT.md for the format of 'local_auth'.
232 if local_auth.get('default_account_id') == account:
233 # Already set, no need to switch.
234 yield
235 return
236
237 available = {a['id'] for a in local_auth.get('accounts') or []}
238 if account in available:
239 logging.info('Switching default LUCI_CONTEXT account to %r', account)
240 local_auth['default_account_id'] = account
241 else:
242 logging.warning(
243 'Requested LUCI_CONTEXT account %r is not available (have only %r), '
244 'disabling authentication', account, sorted(available))
245 local_auth.pop('default_account_id', None)
246
247 with luci_context.write(_tmpdir=tmp_dir, local_auth=local_auth):
248 yield
249
250
nodir90bc8dc2016-06-15 13:35:21 -0700251def process_command(command, out_dir, bot_file):
nodirbe642ff2016-06-09 15:51:51 -0700252 """Replaces variables in a command line.
253
254 Raises:
255 ValueError if a parameter is requested in |command| but its value is not
256 provided.
257 """
maruela9cfd6f2015-09-15 11:03:15 -0700258 def fix(arg):
nodirbe642ff2016-06-09 15:51:51 -0700259 arg = arg.replace(EXECUTABLE_SUFFIX_PARAMETER, cipd.EXECUTABLE_SUFFIX)
260 replace_slash = False
nodir55be77b2016-05-03 09:39:57 -0700261 if ISOLATED_OUTDIR_PARAMETER in arg:
nodirbe642ff2016-06-09 15:51:51 -0700262 if not out_dir:
maruel7f63a272016-07-12 12:40:36 -0700263 raise ValueError(
264 'output directory is requested in command, but not provided; '
265 'please specify one')
nodir55be77b2016-05-03 09:39:57 -0700266 arg = arg.replace(ISOLATED_OUTDIR_PARAMETER, out_dir)
nodirbe642ff2016-06-09 15:51:51 -0700267 replace_slash = True
nodir90bc8dc2016-06-15 13:35:21 -0700268 if SWARMING_BOT_FILE_PARAMETER in arg:
269 if bot_file:
270 arg = arg.replace(SWARMING_BOT_FILE_PARAMETER, bot_file)
271 replace_slash = True
272 else:
273 logging.warning('SWARMING_BOT_FILE_PARAMETER found in command, but no '
274 'bot_file specified. Leaving parameter unchanged.')
nodirbe642ff2016-06-09 15:51:51 -0700275 if replace_slash:
276 # Replace slashes only if parameters are present
nodir55be77b2016-05-03 09:39:57 -0700277 # because of arguments like '${ISOLATED_OUTDIR}/foo/bar'
278 arg = arg.replace('/', os.sep)
maruela9cfd6f2015-09-15 11:03:15 -0700279 return arg
280
281 return [fix(arg) for arg in command]
282
283
Marc-Antoine Ruelaf9ea1b2017-11-28 18:33:39 -0500284def get_command_env(tmp_dir, cipd_info, cwd, env, env_prefixes):
vadimsh232f5a82017-01-20 19:23:44 -0800285 """Returns full OS environment to run a command in.
286
Robert Iannuccibe66ce72017-11-22 12:56:50 -0800287 Sets up TEMP, puts directory with cipd binary in front of PATH, exposes
288 CIPD_CACHE_DIR env var, and installs all env_prefixes.
vadimsh232f5a82017-01-20 19:23:44 -0800289
290 Args:
291 tmp_dir: temp directory.
292 cipd_info: CipdInfo object is cipd client is used, None if not.
Robert Iannuccibe66ce72017-11-22 12:56:50 -0800293 cwd: The directory the command will run in
Marc-Antoine Ruelaf9ea1b2017-11-28 18:33:39 -0500294 env: environment variables to use
Robert Iannuccibe66ce72017-11-22 12:56:50 -0800295 env_prefixes: {"ENV_KEY": ['cwd', 'relative', 'paths', 'to', 'prepend']}
vadimsh232f5a82017-01-20 19:23:44 -0800296 """
297 def to_fs_enc(s):
298 if isinstance(s, str):
299 return s
300 return s.encode(sys.getfilesystemencoding())
301
Marc-Antoine Ruelaf9ea1b2017-11-28 18:33:39 -0500302 out = os.environ.copy()
303 for k, v in env.iteritems():
304 if not v:
305 del out[k]
306 else:
307 out[k] = v
308
309 if cipd_info:
310 bin_dir = os.path.dirname(cipd_info.client.binary_path)
311 out['PATH'] = '%s%s%s' % (to_fs_enc(bin_dir), os.pathsep, out['PATH'])
312 out['CIPD_CACHE_DIR'] = to_fs_enc(cipd_info.cache_dir)
313
314 for key, paths in env_prefixes.iteritems():
315 paths = [os.path.normpath(os.path.join(cwd, p)) for p in paths]
316 cur = out.get(key)
317 if cur:
318 paths.append(cur)
319 out[key] = os.path.pathsep.join(paths)
vadimsh232f5a82017-01-20 19:23:44 -0800320
iannucciac0342c2017-02-24 05:47:01 -0800321 # TMPDIR is specified as the POSIX standard envvar for the temp directory.
iannucci460def72017-02-24 10:49:48 -0800322 # * mktemp on linux respects $TMPDIR, not $TMP
323 # * mktemp on OS X SOMETIMES respects $TMPDIR
iannucciac0342c2017-02-24 05:47:01 -0800324 # * chromium's base utils respects $TMPDIR on linux, $TEMP on windows.
325 # Unfortunately at the time of writing it completely ignores all envvars
326 # on OS X.
iannucci460def72017-02-24 10:49:48 -0800327 # * python respects TMPDIR, TEMP, and TMP (regardless of platform)
328 # * golang respects TMPDIR on linux+mac, TEMP on windows.
iannucciac0342c2017-02-24 05:47:01 -0800329 key = {'win32': 'TEMP'}.get(sys.platform, 'TMPDIR')
Marc-Antoine Ruelaf9ea1b2017-11-28 18:33:39 -0500330 out[key] = to_fs_enc(tmp_dir)
vadimsh232f5a82017-01-20 19:23:44 -0800331
Marc-Antoine Ruelaf9ea1b2017-11-28 18:33:39 -0500332 return out
vadimsh232f5a82017-01-20 19:23:44 -0800333
334
335def run_command(command, cwd, env, hard_timeout, grace_period):
maruel6be7f9e2015-10-01 12:25:30 -0700336 """Runs the command.
337
338 Returns:
339 tuple(process exit code, bool if had a hard timeout)
340 """
maruela9cfd6f2015-09-15 11:03:15 -0700341 logging.info('run_command(%s, %s)' % (command, cwd))
marueleb5fbee2015-09-17 13:01:36 -0700342
maruel6be7f9e2015-10-01 12:25:30 -0700343 exit_code = None
344 had_hard_timeout = False
maruela9cfd6f2015-09-15 11:03:15 -0700345 with tools.Profiler('RunTest'):
maruel6be7f9e2015-10-01 12:25:30 -0700346 proc = None
347 had_signal = []
maruela9cfd6f2015-09-15 11:03:15 -0700348 try:
maruel6be7f9e2015-10-01 12:25:30 -0700349 # TODO(maruel): This code is imperfect. It doesn't handle well signals
350 # during the download phase and there's short windows were things can go
351 # wrong.
352 def handler(signum, _frame):
353 if proc and not had_signal:
354 logging.info('Received signal %d', signum)
355 had_signal.append(True)
maruel556d9052015-10-05 11:12:44 -0700356 raise subprocess42.TimeoutExpired(command, None)
maruel6be7f9e2015-10-01 12:25:30 -0700357
358 proc = subprocess42.Popen(command, cwd=cwd, env=env, detached=True)
359 with subprocess42.set_signal_handler(subprocess42.STOP_SIGNALS, handler):
360 try:
361 exit_code = proc.wait(hard_timeout or None)
362 except subprocess42.TimeoutExpired:
363 if not had_signal:
364 logging.warning('Hard timeout')
365 had_hard_timeout = True
366 logging.warning('Sending SIGTERM')
367 proc.terminate()
368
369 # Ignore signals in grace period. Forcibly give the grace period to the
370 # child process.
371 if exit_code is None:
372 ignore = lambda *_: None
373 with subprocess42.set_signal_handler(subprocess42.STOP_SIGNALS, ignore):
374 try:
375 exit_code = proc.wait(grace_period or None)
376 except subprocess42.TimeoutExpired:
377 # Now kill for real. The user can distinguish between the
378 # following states:
379 # - signal but process exited within grace period,
380 # hard_timed_out will be set but the process exit code will be
381 # script provided.
382 # - processed exited late, exit code will be -9 on posix.
383 logging.warning('Grace exhausted; sending SIGKILL')
384 proc.kill()
martiniss3343ec02017-08-01 17:09:43 -0700385 logging.info('Waiting for process exit')
maruel6be7f9e2015-10-01 12:25:30 -0700386 exit_code = proc.wait()
maruela9cfd6f2015-09-15 11:03:15 -0700387 except OSError:
388 # This is not considered to be an internal error. The executable simply
389 # does not exit.
maruela72f46e2016-02-24 11:05:45 -0800390 sys.stderr.write(
391 '<The executable does not exist or a dependent library is missing>\n'
392 '<Check for missing .so/.dll in the .isolate or GN file>\n'
393 '<Command: %s>\n' % command)
394 if os.environ.get('SWARMING_TASK_ID'):
395 # Give an additional hint when running as a swarming task.
396 sys.stderr.write(
397 '<See the task\'s page for commands to help diagnose this issue '
398 'by reproducing the task locally>\n')
maruela9cfd6f2015-09-15 11:03:15 -0700399 exit_code = 1
400 logging.info(
401 'Command finished with exit code %d (%s)',
402 exit_code, hex(0xffffffff & exit_code))
maruel6be7f9e2015-10-01 12:25:30 -0700403 return exit_code, had_hard_timeout
maruela9cfd6f2015-09-15 11:03:15 -0700404
405
maruel4409e302016-07-19 14:25:51 -0700406def fetch_and_map(isolated_hash, storage, cache, outdir, use_symlinks):
407 """Fetches an isolated tree, create the tree and returns (bundle, stats)."""
nodir6f801882016-04-29 14:41:50 -0700408 start = time.time()
409 bundle = isolateserver.fetch_isolated(
410 isolated_hash=isolated_hash,
411 storage=storage,
412 cache=cache,
maruel4409e302016-07-19 14:25:51 -0700413 outdir=outdir,
414 use_symlinks=use_symlinks)
nodir6f801882016-04-29 14:41:50 -0700415 return bundle, {
416 'duration': time.time() - start,
417 'initial_number_items': cache.initial_number_items,
418 'initial_size': cache.initial_size,
419 'items_cold': base64.b64encode(large.pack(sorted(cache.added))),
420 'items_hot': base64.b64encode(
tansell9e04a8d2016-07-28 09:31:59 -0700421 large.pack(sorted(set(cache.used) - set(cache.added)))),
nodir6f801882016-04-29 14:41:50 -0700422 }
423
424
aludwin0a8e17d2016-10-27 15:57:39 -0700425def link_outputs_to_outdir(run_dir, out_dir, outputs):
426 """Links any named outputs to out_dir so they can be uploaded.
427
428 Raises an error if the file already exists in that directory.
429 """
430 if not outputs:
431 return
432 isolateserver.create_directories(out_dir, outputs)
433 for o in outputs:
434 try:
aludwinb35146d2017-06-12 06:03:00 -0700435 infile = os.path.join(run_dir, o)
436 outfile = os.path.join(out_dir, o)
437 if fs.islink(infile):
438 # TODO(aludwin): handle directories
439 fs.copy2(infile, outfile)
440 else:
441 file_path.link_file(outfile, infile, file_path.HARDLINK_WITH_FALLBACK)
aludwin0a8e17d2016-10-27 15:57:39 -0700442 except OSError as e:
aludwin81178302016-11-30 17:18:49 -0800443 logging.info("Couldn't collect output file %s: %s", o, e)
aludwin0a8e17d2016-10-27 15:57:39 -0700444
445
maruela9cfd6f2015-09-15 11:03:15 -0700446def delete_and_upload(storage, out_dir, leak_temp_dir):
447 """Deletes the temporary run directory and uploads results back.
448
449 Returns:
nodir6f801882016-04-29 14:41:50 -0700450 tuple(outputs_ref, success, stats)
maruel064c0a32016-04-05 11:47:15 -0700451 - outputs_ref: a dict referring to the results archived back to the isolated
452 server, if applicable.
453 - success: False if something occurred that means that the task must
454 forcibly be considered a failure, e.g. zombie processes were left
455 behind.
nodir6f801882016-04-29 14:41:50 -0700456 - stats: uploading stats.
maruela9cfd6f2015-09-15 11:03:15 -0700457 """
maruela9cfd6f2015-09-15 11:03:15 -0700458 # Upload out_dir and generate a .isolated file out of this directory. It is
459 # only done if files were written in the directory.
460 outputs_ref = None
maruel064c0a32016-04-05 11:47:15 -0700461 cold = []
462 hot = []
nodir6f801882016-04-29 14:41:50 -0700463 start = time.time()
464
maruel12e30012015-10-09 11:55:35 -0700465 if fs.isdir(out_dir) and fs.listdir(out_dir):
maruela9cfd6f2015-09-15 11:03:15 -0700466 with tools.Profiler('ArchiveOutput'):
467 try:
maruel064c0a32016-04-05 11:47:15 -0700468 results, f_cold, f_hot = isolateserver.archive_files_to_storage(
maruela9cfd6f2015-09-15 11:03:15 -0700469 storage, [out_dir], None)
470 outputs_ref = {
471 'isolated': results[0][0],
472 'isolatedserver': storage.location,
473 'namespace': storage.namespace,
474 }
maruel064c0a32016-04-05 11:47:15 -0700475 cold = sorted(i.size for i in f_cold)
476 hot = sorted(i.size for i in f_hot)
maruela9cfd6f2015-09-15 11:03:15 -0700477 except isolateserver.Aborted:
478 # This happens when a signal SIGTERM was received while uploading data.
479 # There is 2 causes:
480 # - The task was too slow and was about to be killed anyway due to
481 # exceeding the hard timeout.
482 # - The amount of data uploaded back is very large and took too much
483 # time to archive.
484 sys.stderr.write('Received SIGTERM while uploading')
485 # Re-raise, so it will be treated as an internal failure.
486 raise
nodir6f801882016-04-29 14:41:50 -0700487
488 success = False
maruela9cfd6f2015-09-15 11:03:15 -0700489 try:
maruel12e30012015-10-09 11:55:35 -0700490 if (not leak_temp_dir and fs.isdir(out_dir) and
maruel6eeea7d2015-09-16 12:17:42 -0700491 not file_path.rmtree(out_dir)):
maruela9cfd6f2015-09-15 11:03:15 -0700492 logging.error('Had difficulties removing out_dir %s', out_dir)
nodir6f801882016-04-29 14:41:50 -0700493 else:
494 success = True
maruela9cfd6f2015-09-15 11:03:15 -0700495 except OSError as e:
496 # When this happens, it means there's a process error.
maruel12e30012015-10-09 11:55:35 -0700497 logging.exception('Had difficulties removing out_dir %s: %s', out_dir, e)
nodir6f801882016-04-29 14:41:50 -0700498 stats = {
499 'duration': time.time() - start,
500 'items_cold': base64.b64encode(large.pack(cold)),
501 'items_hot': base64.b64encode(large.pack(hot)),
502 }
503 return outputs_ref, success, stats
maruela9cfd6f2015-09-15 11:03:15 -0700504
505
marueleb5fbee2015-09-17 13:01:36 -0700506def map_and_run(
nodir26251c42017-05-11 13:21:53 -0700507 command, isolated_hash, storage, isolate_cache, outputs,
508 install_named_caches, leak_temp_dir, root_dir, hard_timeout, grace_period,
Marc-Antoine Ruel7d179af2017-10-24 16:52:02 -0700509 bot_file, switch_to_account, install_packages_fn, use_symlinks, raw_cmd,
Marc-Antoine Ruelaf9ea1b2017-11-28 18:33:39 -0500510 env, env_prefixes, constant_run_path):
nodir55be77b2016-05-03 09:39:57 -0700511 """Runs a command with optional isolated input/output.
512
513 See run_tha_test for argument documentation.
514
515 Returns metadata about the result.
516 """
maruelabec63c2017-04-26 11:53:24 -0700517 assert isinstance(command, list), command
nodir56efa452016-10-12 12:17:39 -0700518 assert root_dir or root_dir is None
maruela9cfd6f2015-09-15 11:03:15 -0700519 result = {
maruel064c0a32016-04-05 11:47:15 -0700520 'duration': None,
maruela9cfd6f2015-09-15 11:03:15 -0700521 'exit_code': None,
maruel6be7f9e2015-10-01 12:25:30 -0700522 'had_hard_timeout': False,
maruela9cfd6f2015-09-15 11:03:15 -0700523 'internal_failure': None,
maruel064c0a32016-04-05 11:47:15 -0700524 'stats': {
nodir55715712016-06-03 12:28:19 -0700525 # 'isolated': {
nodirbe642ff2016-06-09 15:51:51 -0700526 # 'cipd': {
527 # 'duration': 0.,
528 # 'get_client_duration': 0.,
529 # },
nodir55715712016-06-03 12:28:19 -0700530 # 'download': {
531 # 'duration': 0.,
532 # 'initial_number_items': 0,
533 # 'initial_size': 0,
534 # 'items_cold': '<large.pack()>',
535 # 'items_hot': '<large.pack()>',
536 # },
537 # 'upload': {
538 # 'duration': 0.,
539 # 'items_cold': '<large.pack()>',
540 # 'items_hot': '<large.pack()>',
541 # },
maruel064c0a32016-04-05 11:47:15 -0700542 # },
543 },
iannucci96fcccc2016-08-30 15:52:22 -0700544 # 'cipd_pins': {
545 # 'packages': [
546 # {'package_name': ..., 'version': ..., 'path': ...},
547 # ...
548 # ],
549 # 'client_package': {'package_name': ..., 'version': ...},
550 # },
maruela9cfd6f2015-09-15 11:03:15 -0700551 'outputs_ref': None,
nodirbe642ff2016-06-09 15:51:51 -0700552 'version': 5,
maruela9cfd6f2015-09-15 11:03:15 -0700553 }
nodirbe642ff2016-06-09 15:51:51 -0700554
marueleb5fbee2015-09-17 13:01:36 -0700555 if root_dir:
nodire5028a92016-04-29 14:38:21 -0700556 file_path.ensure_tree(root_dir, 0700)
nodir56efa452016-10-12 12:17:39 -0700557 elif isolate_cache.cache_dir:
558 root_dir = os.path.dirname(isolate_cache.cache_dir)
maruele2f2cb82016-07-13 14:41:03 -0700559 # See comment for these constants.
maruelcffa0542017-04-07 08:39:20 -0700560 # If root_dir is not specified, it is not constant.
561 # TODO(maruel): This is not obvious. Change this to become an error once we
562 # make the constant_run_path an exposed flag.
563 if constant_run_path and root_dir:
564 run_dir = os.path.join(root_dir, ISOLATED_RUN_DIR)
maruel13437a72017-05-26 05:33:40 -0700565 if os.path.isdir(run_dir):
566 file_path.rmtree(run_dir)
maruelcffa0542017-04-07 08:39:20 -0700567 os.mkdir(run_dir)
568 else:
569 run_dir = make_temp_dir(ISOLATED_RUN_DIR, root_dir)
maruel03e11842016-07-14 10:50:16 -0700570 # storage should be normally set but don't crash if it is not. This can happen
571 # as Swarming task can run without an isolate server.
maruele2f2cb82016-07-13 14:41:03 -0700572 out_dir = make_temp_dir(ISOLATED_OUT_DIR, root_dir) if storage else None
573 tmp_dir = make_temp_dir(ISOLATED_TMP_DIR, root_dir)
nodir55be77b2016-05-03 09:39:57 -0700574 cwd = run_dir
maruela9cfd6f2015-09-15 11:03:15 -0700575
nodir55be77b2016-05-03 09:39:57 -0700576 try:
vadimsh232f5a82017-01-20 19:23:44 -0800577 with install_packages_fn(run_dir) as cipd_info:
578 if cipd_info:
579 result['stats']['cipd'] = cipd_info.stats
580 result['cipd_pins'] = cipd_info.pins
nodir90bc8dc2016-06-15 13:35:21 -0700581
vadimsh232f5a82017-01-20 19:23:44 -0800582 if isolated_hash:
583 isolated_stats = result['stats'].setdefault('isolated', {})
584 bundle, isolated_stats['download'] = fetch_and_map(
585 isolated_hash=isolated_hash,
586 storage=storage,
587 cache=isolate_cache,
588 outdir=run_dir,
589 use_symlinks=use_symlinks)
vadimsh232f5a82017-01-20 19:23:44 -0800590 change_tree_read_only(run_dir, bundle.read_only)
maruelabec63c2017-04-26 11:53:24 -0700591 # Inject the command
Marc-Antoine Ruel7d179af2017-10-24 16:52:02 -0700592 if not raw_cmd and bundle.command:
maruelabec63c2017-04-26 11:53:24 -0700593 command = bundle.command + command
Marc-Antoine Ruelb2cef0f2017-10-31 10:51:23 -0400594 # Only set the relative directory if the isolated file specified a
595 # command, and no raw command was specified.
596 if bundle.relative_cwd:
597 cwd = os.path.normpath(os.path.join(cwd, bundle.relative_cwd))
maruelabec63c2017-04-26 11:53:24 -0700598
599 if not command:
600 # Handle this as a task failure, not an internal failure.
601 sys.stderr.write(
602 '<No command was specified!>\n'
603 '<Please secify a command when triggering your Swarming task>\n')
604 result['exit_code'] = 1
605 return result
nodirbe642ff2016-06-09 15:51:51 -0700606
vadimsh232f5a82017-01-20 19:23:44 -0800607 # If we have an explicit list of files to return, make sure their
608 # directories exist now.
609 if storage and outputs:
610 isolateserver.create_directories(run_dir, outputs)
aludwin0a8e17d2016-10-27 15:57:39 -0700611
vadimsh232f5a82017-01-20 19:23:44 -0800612 command = tools.fix_python_path(command)
613 command = process_command(command, out_dir, bot_file)
614 file_path.ensure_command_has_abs_path(command, cwd)
nodirbe642ff2016-06-09 15:51:51 -0700615
nodir26251c42017-05-11 13:21:53 -0700616 with install_named_caches(run_dir):
nodird6160682017-02-02 13:03:35 -0800617 sys.stdout.flush()
618 start = time.time()
619 try:
vadimsh8ec66822017-07-25 14:08:29 -0700620 # Need to switch the default account before 'get_command_env' call,
621 # so it can grab correct value of LUCI_CONTEXT env var.
622 with set_luci_context_account(switch_to_account, tmp_dir):
Marc-Antoine Ruelaf9ea1b2017-11-28 18:33:39 -0500623 env = get_command_env(tmp_dir, cipd_info, cwd, env, env_prefixes)
vadimsh8ec66822017-07-25 14:08:29 -0700624 result['exit_code'], result['had_hard_timeout'] = run_command(
Robert Iannuccibe66ce72017-11-22 12:56:50 -0800625 command, cwd, env, hard_timeout, grace_period)
nodird6160682017-02-02 13:03:35 -0800626 finally:
627 result['duration'] = max(time.time() - start, 0)
maruela9cfd6f2015-09-15 11:03:15 -0700628 except Exception as e:
nodir90bc8dc2016-06-15 13:35:21 -0700629 # An internal error occurred. Report accordingly so the swarming task will
630 # be retried automatically.
maruel12e30012015-10-09 11:55:35 -0700631 logging.exception('internal failure: %s', e)
maruela9cfd6f2015-09-15 11:03:15 -0700632 result['internal_failure'] = str(e)
633 on_error.report(None)
aludwin0a8e17d2016-10-27 15:57:39 -0700634
635 # Clean up
maruela9cfd6f2015-09-15 11:03:15 -0700636 finally:
637 try:
aludwin0a8e17d2016-10-27 15:57:39 -0700638 # Try to link files to the output directory, if specified.
639 if out_dir:
640 link_outputs_to_outdir(run_dir, out_dir, outputs)
641
nodir32a1ec12016-10-26 18:34:07 -0700642 success = False
maruela9cfd6f2015-09-15 11:03:15 -0700643 if leak_temp_dir:
nodir32a1ec12016-10-26 18:34:07 -0700644 success = True
maruela9cfd6f2015-09-15 11:03:15 -0700645 logging.warning(
646 'Deliberately leaking %s for later examination', run_dir)
marueleb5fbee2015-09-17 13:01:36 -0700647 else:
maruel84537cb2015-10-16 14:21:28 -0700648 # On Windows rmtree(run_dir) call above has a synchronization effect: it
649 # finishes only when all task child processes terminate (since a running
650 # process locks *.exe file). Examine out_dir only after that call
651 # completes (since child processes may write to out_dir too and we need
652 # to wait for them to finish).
653 if fs.isdir(run_dir):
654 try:
655 success = file_path.rmtree(run_dir)
656 except OSError as e:
657 logging.error('Failure with %s', e)
658 success = False
659 if not success:
maruel7eb6b562017-06-08 08:20:04 -0700660 sys.stderr.write(OUTLIVING_ZOMBIE_MSG % ('run', grace_period))
maruel84537cb2015-10-16 14:21:28 -0700661 if result['exit_code'] == 0:
662 result['exit_code'] = 1
663 if fs.isdir(tmp_dir):
664 try:
665 success = file_path.rmtree(tmp_dir)
666 except OSError as e:
667 logging.error('Failure with %s', e)
668 success = False
669 if not success:
maruel9832b052017-06-08 13:06:40 -0700670 sys.stderr.write(OUTLIVING_ZOMBIE_MSG % ('temp', grace_period))
maruel84537cb2015-10-16 14:21:28 -0700671 if result['exit_code'] == 0:
672 result['exit_code'] = 1
maruela9cfd6f2015-09-15 11:03:15 -0700673
marueleb5fbee2015-09-17 13:01:36 -0700674 # This deletes out_dir if leak_temp_dir is not set.
nodir9130f072016-05-27 13:59:08 -0700675 if out_dir:
nodir55715712016-06-03 12:28:19 -0700676 isolated_stats = result['stats'].setdefault('isolated', {})
677 result['outputs_ref'], success, isolated_stats['upload'] = (
nodir9130f072016-05-27 13:59:08 -0700678 delete_and_upload(storage, out_dir, leak_temp_dir))
maruela9cfd6f2015-09-15 11:03:15 -0700679 if not success and result['exit_code'] == 0:
680 result['exit_code'] = 1
681 except Exception as e:
682 # Swallow any exception in the main finally clause.
nodir9130f072016-05-27 13:59:08 -0700683 if out_dir:
684 logging.exception('Leaking out_dir %s: %s', out_dir, e)
maruela9cfd6f2015-09-15 11:03:15 -0700685 result['internal_failure'] = str(e)
686 return result
Marc-Antoine Ruel2283ad12014-02-09 11:14:57 -0500687
688
Marc-Antoine Ruel0ec868b2015-08-12 14:12:46 -0400689def run_tha_test(
nodir26251c42017-05-11 13:21:53 -0700690 command, isolated_hash, storage, isolate_cache, outputs,
691 install_named_caches, leak_temp_dir, result_json, root_dir, hard_timeout,
vadimsh8ec66822017-07-25 14:08:29 -0700692 grace_period, bot_file, switch_to_account, install_packages_fn,
Marc-Antoine Ruelaf9ea1b2017-11-28 18:33:39 -0500693 use_symlinks, raw_cmd, env, env_prefixes):
nodir55be77b2016-05-03 09:39:57 -0700694 """Runs an executable and records execution metadata.
695
696 Either command or isolated_hash must be specified.
697
698 If isolated_hash is specified, downloads the dependencies in the cache,
699 hardlinks them into a temporary directory and runs the command specified in
700 the .isolated.
Marc-Antoine Ruel2283ad12014-02-09 11:14:57 -0500701
702 A temporary directory is created to hold the output files. The content inside
703 this directory will be uploaded back to |storage| packaged as a .isolated
704 file.
705
706 Arguments:
maruelabec63c2017-04-26 11:53:24 -0700707 command: a list of string; the command to run OR optional arguments to add
708 to the command stated in the .isolated file if a command was
709 specified.
Marc-Antoine Ruel35b58432014-12-08 17:40:40 -0500710 isolated_hash: the SHA-1 of the .isolated file that must be retrieved to
Marc-Antoine Ruel2283ad12014-02-09 11:14:57 -0500711 recreate the tree of files to run the target executable.
nodir55be77b2016-05-03 09:39:57 -0700712 The command specified in the .isolated is executed.
713 Mutually exclusive with command argument.
Marc-Antoine Ruel2283ad12014-02-09 11:14:57 -0500714 storage: an isolateserver.Storage object to retrieve remote objects. This
715 object has a reference to an isolateserver.StorageApi, which does
716 the actual I/O.
nodir6b945692016-10-19 19:09:06 -0700717 isolate_cache: an isolateserver.LocalCache to keep from retrieving the
718 same objects constantly by caching the objects retrieved.
719 Can be on-disk or in-memory.
vadimsh8ec66822017-07-25 14:08:29 -0700720 outputs: list of paths relative to root_dir to put into the output isolated
721 bundle upon task completion (see link_outputs_to_outdir).
nodir26251c42017-05-11 13:21:53 -0700722 install_named_caches: a function (run_dir) => context manager that installs
vadimsh8ec66822017-07-25 14:08:29 -0700723 named caches into |run_dir|.
Kenneth Russell61d42352014-09-15 11:41:16 -0700724 leak_temp_dir: if true, the temporary directory will be deliberately leaked
725 for later examination.
maruela9cfd6f2015-09-15 11:03:15 -0700726 result_json: file path to dump result metadata into. If set, the process
nodirbe642ff2016-06-09 15:51:51 -0700727 exit code is always 0 unless an internal error occurred.
nodir90bc8dc2016-06-15 13:35:21 -0700728 root_dir: path to the directory to use to create the temporary directory. If
marueleb5fbee2015-09-17 13:01:36 -0700729 not specified, a random temporary directory is created.
maruel6be7f9e2015-10-01 12:25:30 -0700730 hard_timeout: kills the process if it lasts more than this amount of
731 seconds.
732 grace_period: number of seconds to wait between SIGTERM and SIGKILL.
vadimsh8ec66822017-07-25 14:08:29 -0700733 bot_file: path to a file with bot state, used in place of
734 ${SWARMING_BOT_FILE} task command line argument.
735 switch_to_account: a logical account to switch LUCI_CONTEXT into.
iannuccib58d10d2017-03-18 02:00:25 -0700736 install_packages_fn: context manager dir => CipdInfo, see
vadimsh8ec66822017-07-25 14:08:29 -0700737 install_client_and_packages.
maruel4409e302016-07-19 14:25:51 -0700738 use_symlinks: create tree with symlinks instead of hardlinks.
Marc-Antoine Ruel7d179af2017-10-24 16:52:02 -0700739 raw_cmd: ignore the command in the isolated file.
Marc-Antoine Ruelaf9ea1b2017-11-28 18:33:39 -0500740 env: environment variables to set
Robert Iannuccibe66ce72017-11-22 12:56:50 -0800741 env_prefixes: {"ENV_KEY": ['relative', 'paths', 'to', 'prepend']}
maruela9cfd6f2015-09-15 11:03:15 -0700742
743 Returns:
744 Process exit code that should be used.
maruel@chromium.org9c72d4e2012-09-28 19:20:25 +0000745 """
maruela76b9ee2015-12-15 06:18:08 -0800746 if result_json:
747 # Write a json output file right away in case we get killed.
748 result = {
749 'exit_code': None,
750 'had_hard_timeout': False,
751 'internal_failure': 'Was terminated before completion',
752 'outputs_ref': None,
nodirbe642ff2016-06-09 15:51:51 -0700753 'version': 5,
maruela76b9ee2015-12-15 06:18:08 -0800754 }
755 tools.write_json(result_json, result, dense=True)
756
maruela9cfd6f2015-09-15 11:03:15 -0700757 # run_isolated exit code. Depends on if result_json is used or not.
758 result = map_and_run(
nodir220308c2017-02-01 19:32:53 -0800759 command, isolated_hash, storage, isolate_cache, outputs,
nodir26251c42017-05-11 13:21:53 -0700760 install_named_caches, leak_temp_dir, root_dir, hard_timeout, grace_period,
Marc-Antoine Ruel7d179af2017-10-24 16:52:02 -0700761 bot_file, switch_to_account, install_packages_fn, use_symlinks, raw_cmd,
Marc-Antoine Ruelaf9ea1b2017-11-28 18:33:39 -0500762 env, env_prefixes, True)
maruela9cfd6f2015-09-15 11:03:15 -0700763 logging.info('Result:\n%s', tools.format_json(result, dense=True))
bpastene3ae09522016-06-10 17:12:59 -0700764
maruela9cfd6f2015-09-15 11:03:15 -0700765 if result_json:
maruel05d5a882015-09-21 13:59:02 -0700766 # We've found tests to delete 'work' when quitting, causing an exception
767 # here. Try to recreate the directory if necessary.
nodire5028a92016-04-29 14:38:21 -0700768 file_path.ensure_tree(os.path.dirname(result_json))
maruela9cfd6f2015-09-15 11:03:15 -0700769 tools.write_json(result_json, result, dense=True)
770 # Only return 1 if there was an internal error.
771 return int(bool(result['internal_failure']))
maruel@chromium.org781ccf62013-09-17 19:39:47 +0000772
maruela9cfd6f2015-09-15 11:03:15 -0700773 # Marshall into old-style inline output.
774 if result['outputs_ref']:
775 data = {
776 'hash': result['outputs_ref']['isolated'],
777 'namespace': result['outputs_ref']['namespace'],
778 'storage': result['outputs_ref']['isolatedserver'],
779 }
Marc-Antoine Ruelc44f5722015-01-08 16:10:01 -0500780 sys.stdout.flush()
maruela9cfd6f2015-09-15 11:03:15 -0700781 print(
782 '[run_isolated_out_hack]%s[/run_isolated_out_hack]' %
783 tools.format_json(data, dense=True))
maruelb76604c2015-11-11 11:53:44 -0800784 sys.stdout.flush()
maruela9cfd6f2015-09-15 11:03:15 -0700785 return result['exit_code'] or int(bool(result['internal_failure']))
maruel@chromium.org9c72d4e2012-09-28 19:20:25 +0000786
787
iannuccib58d10d2017-03-18 02:00:25 -0700788# Yielded by 'install_client_and_packages'.
vadimsh232f5a82017-01-20 19:23:44 -0800789CipdInfo = collections.namedtuple('CipdInfo', [
790 'client', # cipd.CipdClient object
791 'cache_dir', # absolute path to bot-global cipd tag and instance cache
792 'stats', # dict with stats to return to the server
793 'pins', # dict with installed cipd pins to return to the server
794])
795
796
797@contextlib.contextmanager
798def noop_install_packages(_run_dir):
iannuccib58d10d2017-03-18 02:00:25 -0700799 """Placeholder for 'install_client_and_packages' if cipd is disabled."""
vadimsh232f5a82017-01-20 19:23:44 -0800800 yield None
801
802
iannuccib58d10d2017-03-18 02:00:25 -0700803def _install_packages(run_dir, cipd_cache_dir, client, packages, timeout):
804 """Calls 'cipd ensure' for packages.
805
806 Args:
807 run_dir (str): root of installation.
808 cipd_cache_dir (str): the directory to use for the cipd package cache.
809 client (CipdClient): the cipd client to use
810 packages: packages to install, list [(path, package_name, version), ...].
811 timeout: max duration in seconds that this function can take.
812
813 Returns: list of pinned packages. Looks like [
814 {
815 'path': 'subdirectory',
816 'package_name': 'resolved/package/name',
817 'version': 'deadbeef...',
818 },
819 ...
820 ]
821 """
822 package_pins = [None]*len(packages)
823 def insert_pin(path, name, version, idx):
824 package_pins[idx] = {
825 'package_name': name,
826 # swarming deals with 'root' as '.'
827 'path': path or '.',
828 'version': version,
829 }
830
831 by_path = collections.defaultdict(list)
832 for i, (path, name, version) in enumerate(packages):
833 # cipd deals with 'root' as ''
834 if path == '.':
835 path = ''
836 by_path[path].append((name, version, i))
837
838 pins = client.ensure(
839 run_dir,
840 {
841 subdir: [(name, vers) for name, vers, _ in pkgs]
842 for subdir, pkgs in by_path.iteritems()
843 },
844 cache_dir=cipd_cache_dir,
845 timeout=timeout,
846 )
847
848 for subdir, pin_list in sorted(pins.iteritems()):
849 this_subdir = by_path[subdir]
850 for i, (name, version) in enumerate(pin_list):
851 insert_pin(subdir, name, version, this_subdir[i][2])
852
853 assert None not in package_pins
854
855 return package_pins
856
857
vadimsh232f5a82017-01-20 19:23:44 -0800858@contextlib.contextmanager
iannuccib58d10d2017-03-18 02:00:25 -0700859def install_client_and_packages(
nodirff531b42016-06-23 13:05:06 -0700860 run_dir, packages, service_url, client_package_name,
vadimsh232f5a82017-01-20 19:23:44 -0800861 client_version, cache_dir, timeout=None):
vadimsh902948e2017-01-20 15:57:32 -0800862 """Bootstraps CIPD client and installs CIPD packages.
iannucci96fcccc2016-08-30 15:52:22 -0700863
vadimsh232f5a82017-01-20 19:23:44 -0800864 Yields CipdClient, stats, client info and pins (as single CipdInfo object).
865
866 Pins and the CIPD client info are in the form of:
iannucci96fcccc2016-08-30 15:52:22 -0700867 [
868 {
869 "path": path, "package_name": package_name, "version": version,
870 },
871 ...
872 ]
vadimsh902948e2017-01-20 15:57:32 -0800873 (the CIPD client info is a single dictionary instead of a list)
iannucci96fcccc2016-08-30 15:52:22 -0700874
875 such that they correspond 1:1 to all input package arguments from the command
876 line. These dictionaries make their all the way back to swarming, where they
877 become the arguments of CipdPackage.
nodirbe642ff2016-06-09 15:51:51 -0700878
vadimsh902948e2017-01-20 15:57:32 -0800879 If 'packages' list is empty, will bootstrap CIPD client, but won't install
880 any packages.
881
882 The bootstrapped client (regardless whether 'packages' list is empty or not),
vadimsh232f5a82017-01-20 19:23:44 -0800883 will be made available to the task via $PATH.
vadimsh902948e2017-01-20 15:57:32 -0800884
nodirbe642ff2016-06-09 15:51:51 -0700885 Args:
nodir90bc8dc2016-06-15 13:35:21 -0700886 run_dir (str): root of installation.
vadimsh902948e2017-01-20 15:57:32 -0800887 packages: packages to install, list [(path, package_name, version), ...].
nodirbe642ff2016-06-09 15:51:51 -0700888 service_url (str): CIPD server url, e.g.
889 "https://chrome-infra-packages.appspot.com."
nodir90bc8dc2016-06-15 13:35:21 -0700890 client_package_name (str): CIPD package name of CIPD client.
891 client_version (str): Version of CIPD client.
nodirbe642ff2016-06-09 15:51:51 -0700892 cache_dir (str): where to keep cache of cipd clients, packages and tags.
893 timeout: max duration in seconds that this function can take.
nodirbe642ff2016-06-09 15:51:51 -0700894 """
895 assert cache_dir
nodir90bc8dc2016-06-15 13:35:21 -0700896
nodirbe642ff2016-06-09 15:51:51 -0700897 timeoutfn = tools.sliding_timeout(timeout)
nodirbe642ff2016-06-09 15:51:51 -0700898 start = time.time()
nodirbe642ff2016-06-09 15:51:51 -0700899
vadimsh902948e2017-01-20 15:57:32 -0800900 cache_dir = os.path.abspath(cache_dir)
vadimsh232f5a82017-01-20 19:23:44 -0800901 cipd_cache_dir = os.path.join(cache_dir, 'cache') # tag and instance caches
nodir90bc8dc2016-06-15 13:35:21 -0700902 run_dir = os.path.abspath(run_dir)
vadimsh902948e2017-01-20 15:57:32 -0800903 packages = packages or []
nodir90bc8dc2016-06-15 13:35:21 -0700904
nodirbe642ff2016-06-09 15:51:51 -0700905 get_client_start = time.time()
906 client_manager = cipd.get_client(
907 service_url, client_package_name, client_version, cache_dir,
908 timeout=timeoutfn())
iannucci96fcccc2016-08-30 15:52:22 -0700909
nodirbe642ff2016-06-09 15:51:51 -0700910 with client_manager as client:
911 get_client_duration = time.time() - get_client_start
nodir90bc8dc2016-06-15 13:35:21 -0700912
iannuccib58d10d2017-03-18 02:00:25 -0700913 package_pins = []
914 if packages:
915 package_pins = _install_packages(
916 run_dir, cipd_cache_dir, client, packages, timeoutfn())
917
918 file_path.make_tree_files_read_only(run_dir)
nodir90bc8dc2016-06-15 13:35:21 -0700919
vadimsh232f5a82017-01-20 19:23:44 -0800920 total_duration = time.time() - start
921 logging.info(
922 'Installing CIPD client and packages took %d seconds', total_duration)
nodir90bc8dc2016-06-15 13:35:21 -0700923
vadimsh232f5a82017-01-20 19:23:44 -0800924 yield CipdInfo(
925 client=client,
926 cache_dir=cipd_cache_dir,
927 stats={
928 'duration': total_duration,
929 'get_client_duration': get_client_duration,
930 },
931 pins={
iannuccib58d10d2017-03-18 02:00:25 -0700932 'client_package': {
933 'package_name': client.package_name,
934 'version': client.instance_id,
935 },
vadimsh232f5a82017-01-20 19:23:44 -0800936 'packages': package_pins,
937 })
nodirbe642ff2016-06-09 15:51:51 -0700938
939
nodirf33b8d62016-10-26 22:34:58 -0700940def clean_caches(options, isolate_cache, named_cache_manager):
maruele6fc9382017-05-04 09:03:48 -0700941 """Trims isolated and named caches.
942
943 The goal here is to coherently trim both caches, deleting older items
944 independent of which container they belong to.
945 """
946 # TODO(maruel): Trim CIPD cache the same way.
947 total = 0
nodirf33b8d62016-10-26 22:34:58 -0700948 with named_cache_manager.open():
949 oldest_isolated = isolate_cache.get_oldest()
950 oldest_named = named_cache_manager.get_oldest()
951 trimmers = [
952 (
953 isolate_cache.trim,
954 isolate_cache.get_timestamp(oldest_isolated) if oldest_isolated else 0,
955 ),
956 (
957 lambda: named_cache_manager.trim(options.min_free_space),
958 named_cache_manager.get_timestamp(oldest_named) if oldest_named else 0,
959 ),
960 ]
961 trimmers.sort(key=lambda (_, ts): ts)
maruele6fc9382017-05-04 09:03:48 -0700962 # TODO(maruel): This is incorrect, we want to trim 'items' that are strictly
963 # the oldest independent of in which cache they live in. Right now, the
964 # cache with the oldest item pays the price.
nodirf33b8d62016-10-26 22:34:58 -0700965 for trim, _ in trimmers:
maruele6fc9382017-05-04 09:03:48 -0700966 total += trim()
nodirf33b8d62016-10-26 22:34:58 -0700967 isolate_cache.cleanup()
maruele6fc9382017-05-04 09:03:48 -0700968 return total
nodirf33b8d62016-10-26 22:34:58 -0700969
970
nodirbe642ff2016-06-09 15:51:51 -0700971def create_option_parser():
Marc-Antoine Ruelf74cffe2015-07-15 15:21:34 -0400972 parser = logging_utils.OptionParserWithLogging(
nodir55be77b2016-05-03 09:39:57 -0700973 usage='%prog <options> [command to run or extra args]',
maruel@chromium.orgdedbf492013-09-12 20:42:11 +0000974 version=__version__,
975 log_file=RUN_ISOLATED_LOG_FILE)
maruela9cfd6f2015-09-15 11:03:15 -0700976 parser.add_option(
maruel36a963d2016-04-08 17:15:49 -0700977 '--clean', action='store_true',
978 help='Cleans the cache, trimming it necessary and remove corrupted items '
979 'and returns without executing anything; use with -v to know what '
980 'was done')
981 parser.add_option(
maruel2e8d0f52016-07-16 07:51:29 -0700982 '--no-clean', action='store_true',
983 help='Do not clean the cache automatically on startup. This is meant for '
984 'bots where a separate execution with --clean was done earlier so '
985 'doing it again is redundant')
986 parser.add_option(
maruel4409e302016-07-19 14:25:51 -0700987 '--use-symlinks', action='store_true',
988 help='Use symlinks instead of hardlinks')
989 parser.add_option(
maruela9cfd6f2015-09-15 11:03:15 -0700990 '--json',
991 help='dump output metadata to json file. When used, run_isolated returns '
992 'non-zero only on internal failure')
maruel6be7f9e2015-10-01 12:25:30 -0700993 parser.add_option(
maruel5c9e47b2015-12-18 13:02:30 -0800994 '--hard-timeout', type='float', help='Enforce hard timeout in execution')
maruel6be7f9e2015-10-01 12:25:30 -0700995 parser.add_option(
maruel5c9e47b2015-12-18 13:02:30 -0800996 '--grace-period', type='float',
maruel6be7f9e2015-10-01 12:25:30 -0700997 help='Grace period between SIGTERM and SIGKILL')
bpastene3ae09522016-06-10 17:12:59 -0700998 parser.add_option(
Marc-Antoine Ruel7d179af2017-10-24 16:52:02 -0700999 '--raw-cmd', action='store_true',
1000 help='Ignore the isolated command, use the one supplied at the command '
1001 'line')
1002 parser.add_option(
Marc-Antoine Ruelaf9ea1b2017-11-28 18:33:39 -05001003 '--env', default=[], action='append',
1004 help='Environment variables to set for the child process')
1005 parser.add_option(
1006 '--env-prefix', default=[], action='append',
Robert Iannuccibe66ce72017-11-22 12:56:50 -08001007 help='Specify a VAR=./path/fragment to put in the environment variable '
1008 'before executing the command. The path fragment must be relative '
1009 'to the isolated run directory, and must not contain a `..` token. '
1010 'The path will be made absolute and prepended to the indicated '
1011 '$VAR using the OS\'s path separator. Multiple items for the same '
1012 '$VAR will be prepended in order.')
1013 parser.add_option(
bpastene3ae09522016-06-10 17:12:59 -07001014 '--bot-file',
1015 help='Path to a file describing the state of the host. The content is '
1016 'defined by on_before_task() in bot_config.')
aludwin7556e0c2016-10-26 08:46:10 -07001017 parser.add_option(
vadimsh8ec66822017-07-25 14:08:29 -07001018 '--switch-to-account',
1019 help='If given, switches LUCI_CONTEXT to given logical service account '
1020 '(e.g. "task" or "system") before launching the isolated process.')
1021 parser.add_option(
aludwin0a8e17d2016-10-27 15:57:39 -07001022 '--output', action='append',
1023 help='Specifies an output to return. If no outputs are specified, all '
1024 'files located in $(ISOLATED_OUTDIR) will be returned; '
1025 'otherwise, outputs in both $(ISOLATED_OUTDIR) and those '
1026 'specified by --output option (there can be multiple) will be '
1027 'returned. Note that if a file in OUT_DIR has the same path '
1028 'as an --output option, the --output version will be returned.')
1029 parser.add_option(
aludwin7556e0c2016-10-26 08:46:10 -07001030 '-a', '--argsfile',
1031 # This is actually handled in parse_args; it's included here purely so it
1032 # can make it into the help text.
1033 help='Specify a file containing a JSON array of arguments to this '
1034 'script. If --argsfile is provided, no other argument may be '
1035 'provided on the command line.')
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -05001036 data_group = optparse.OptionGroup(parser, 'Data source')
1037 data_group.add_option(
Marc-Antoine Ruel185ded42015-01-28 20:49:18 -05001038 '-s', '--isolated',
nodir55be77b2016-05-03 09:39:57 -07001039 help='Hash of the .isolated to grab from the isolate server.')
Marc-Antoine Ruelf7d737d2014-12-10 15:36:29 -05001040 isolateserver.add_isolate_server_options(data_group)
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -05001041 parser.add_option_group(data_group)
maruel@chromium.org9c72d4e2012-09-28 19:20:25 +00001042
Marc-Antoine Ruela57d7db2014-10-15 20:31:19 -04001043 isolateserver.add_cache_options(parser)
nodirbe642ff2016-06-09 15:51:51 -07001044
1045 cipd.add_cipd_options(parser)
nodirf33b8d62016-10-26 22:34:58 -07001046 named_cache.add_named_cache_options(parser)
maruel@chromium.org9c72d4e2012-09-28 19:20:25 +00001047
Kenneth Russell61d42352014-09-15 11:41:16 -07001048 debug_group = optparse.OptionGroup(parser, 'Debugging')
1049 debug_group.add_option(
1050 '--leak-temp-dir',
1051 action='store_true',
nodirbe642ff2016-06-09 15:51:51 -07001052 help='Deliberately leak isolate\'s temp dir for later examination. '
1053 'Default: %default')
marueleb5fbee2015-09-17 13:01:36 -07001054 debug_group.add_option(
1055 '--root-dir', help='Use a directory instead of a random one')
Kenneth Russell61d42352014-09-15 11:41:16 -07001056 parser.add_option_group(debug_group)
1057
Vadim Shtayurae34e13a2014-02-02 11:23:26 -08001058 auth.add_auth_options(parser)
nodirbe642ff2016-06-09 15:51:51 -07001059
nodirf33b8d62016-10-26 22:34:58 -07001060 parser.set_defaults(
1061 cache='cache',
1062 cipd_cache='cipd_cache',
1063 named_cache_root='named_caches')
nodirbe642ff2016-06-09 15:51:51 -07001064 return parser
1065
1066
aludwin7556e0c2016-10-26 08:46:10 -07001067def parse_args(args):
1068 # Create a fake mini-parser just to get out the "-a" command. Note that
1069 # it's not documented here; instead, it's documented in create_option_parser
1070 # even though that parser will never actually get to parse it. This is
1071 # because --argsfile is exclusive with all other options and arguments.
1072 file_argparse = argparse.ArgumentParser(add_help=False)
1073 file_argparse.add_argument('-a', '--argsfile')
1074 (file_args, nonfile_args) = file_argparse.parse_known_args(args)
1075 if file_args.argsfile:
1076 if nonfile_args:
1077 file_argparse.error('Can\'t specify --argsfile with'
1078 'any other arguments (%s)' % nonfile_args)
1079 try:
1080 with open(file_args.argsfile, 'r') as f:
1081 args = json.load(f)
1082 except (IOError, OSError, ValueError) as e:
1083 # We don't need to error out here - "args" is now empty,
1084 # so the call below to parser.parse_args(args) will fail
1085 # and print the full help text.
1086 print >> sys.stderr, 'Couldn\'t read arguments: %s' % e
1087
1088 # Even if we failed to read the args, just call the normal parser now since it
1089 # will print the correct help message.
nodirbe642ff2016-06-09 15:51:51 -07001090 parser = create_option_parser()
Marc-Antoine Ruel90c98162013-12-18 15:11:57 -05001091 options, args = parser.parse_args(args)
aludwin7556e0c2016-10-26 08:46:10 -07001092 return (parser, options, args)
1093
1094
1095def main(args):
1096 (parser, options, args) = parse_args(args)
maruel36a963d2016-04-08 17:15:49 -07001097
Marc-Antoine Ruelc7a332f2017-08-25 17:37:51 -04001098 if not file_path.enable_symlink():
1099 logging.error('Symlink support is not enabled')
1100
nodirf33b8d62016-10-26 22:34:58 -07001101 isolate_cache = isolateserver.process_cache_options(options, trim=False)
1102 named_cache_manager = named_cache.process_named_cache_options(parser, options)
maruel36a963d2016-04-08 17:15:49 -07001103 if options.clean:
1104 if options.isolated:
1105 parser.error('Can\'t use --isolated with --clean.')
1106 if options.isolate_server:
1107 parser.error('Can\'t use --isolate-server with --clean.')
1108 if options.json:
1109 parser.error('Can\'t use --json with --clean.')
nodirf33b8d62016-10-26 22:34:58 -07001110 if options.named_caches:
1111 parser.error('Can\t use --named-cache with --clean.')
1112 clean_caches(options, isolate_cache, named_cache_manager)
maruel36a963d2016-04-08 17:15:49 -07001113 return 0
nodirf33b8d62016-10-26 22:34:58 -07001114
maruel2e8d0f52016-07-16 07:51:29 -07001115 if not options.no_clean:
nodirf33b8d62016-10-26 22:34:58 -07001116 clean_caches(options, isolate_cache, named_cache_manager)
maruel36a963d2016-04-08 17:15:49 -07001117
nodir55be77b2016-05-03 09:39:57 -07001118 if not options.isolated and not args:
1119 parser.error('--isolated or command to run is required.')
1120
Vadim Shtayura5d1efce2014-02-04 10:55:43 -08001121 auth.process_auth_options(parser, options)
nodir55be77b2016-05-03 09:39:57 -07001122
1123 isolateserver.process_isolate_server_options(
Marc-Antoine Ruelc7a332f2017-08-25 17:37:51 -04001124 parser, options, True, False)
nodir55be77b2016-05-03 09:39:57 -07001125 if not options.isolate_server:
1126 if options.isolated:
1127 parser.error('--isolated requires --isolate-server')
1128 if ISOLATED_OUTDIR_PARAMETER in args:
1129 parser.error(
1130 '%s in args requires --isolate-server' % ISOLATED_OUTDIR_PARAMETER)
maruel@chromium.org9c72d4e2012-09-28 19:20:25 +00001131
nodir90bc8dc2016-06-15 13:35:21 -07001132 if options.root_dir:
1133 options.root_dir = unicode(os.path.abspath(options.root_dir))
maruel12e30012015-10-09 11:55:35 -07001134 if options.json:
1135 options.json = unicode(os.path.abspath(options.json))
nodir55be77b2016-05-03 09:39:57 -07001136
Marc-Antoine Ruelaf9ea1b2017-11-28 18:33:39 -05001137 if any('=' not in i for i in options.env):
1138 parser.error(
1139 '--env required key=value form. value can be skipped to delete '
1140 'the variable')
1141 options.env = {k: v for k, v in (i.split('=', 1) for i in options.env)}
1142
1143 prefixes = {}
1144 cwd = os.path.realpath(os.getcwd())
1145 for item in options.env_prefix:
1146 if '=' not in item:
1147 parser.error(
1148 '--env-prefix %r is malformed, must be in the form `VAR=./path`'
1149 % item)
1150 key, opath = item.split('=', 1)
1151 if os.path.isabs(opath):
1152 parser.error('--env-prefix %r path is bad, must be relative.' % opath)
1153 opath = os.path.normpath(opath)
1154 if not os.path.realpath(os.path.join(cwd, opath)).startswith(cwd):
1155 parser.error(
1156 '--env-prefix %r path is bad, must be relative and not contain `..`.'
1157 % opath)
1158 prefixes.setdefault(key, []).append(opath)
1159 options.env_prefix = prefixes
Robert Iannuccibe66ce72017-11-22 12:56:50 -08001160
nodirbe642ff2016-06-09 15:51:51 -07001161 cipd.validate_cipd_options(parser, options)
1162
vadimsh232f5a82017-01-20 19:23:44 -08001163 install_packages_fn = noop_install_packages
vadimsh902948e2017-01-20 15:57:32 -08001164 if options.cipd_enabled:
iannuccib58d10d2017-03-18 02:00:25 -07001165 install_packages_fn = lambda run_dir: install_client_and_packages(
vadimsh902948e2017-01-20 15:57:32 -08001166 run_dir, cipd.parse_package_args(options.cipd_packages),
1167 options.cipd_server, options.cipd_client_package,
1168 options.cipd_client_version, cache_dir=options.cipd_cache)
nodirbe642ff2016-06-09 15:51:51 -07001169
nodird6160682017-02-02 13:03:35 -08001170 @contextlib.contextmanager
nodir26251c42017-05-11 13:21:53 -07001171 def install_named_caches(run_dir):
nodird6160682017-02-02 13:03:35 -08001172 # WARNING: this function depends on "options" variable defined in the outer
1173 # function.
nodir26251c42017-05-11 13:21:53 -07001174 caches = [
1175 (os.path.join(run_dir, unicode(relpath)), name)
1176 for name, relpath in options.named_caches
1177 ]
nodirf33b8d62016-10-26 22:34:58 -07001178 with named_cache_manager.open():
nodir26251c42017-05-11 13:21:53 -07001179 for path, name in caches:
1180 named_cache_manager.install(path, name)
nodird6160682017-02-02 13:03:35 -08001181 try:
1182 yield
1183 finally:
dnjd5e4ecc2017-07-07 11:16:44 -07001184 # Uninstall each named cache, returning it to the cache pool. If an
1185 # uninstall fails for a given cache, it will remain in the task's
1186 # temporary space, get cleaned up by the Swarming bot, and be lost.
1187 #
1188 # If the Swarming bot cannot clean up the cache, it will handle it like
1189 # any other bot file that could not be removed.
nodir26251c42017-05-11 13:21:53 -07001190 with named_cache_manager.open():
1191 for path, name in caches:
dnjd5e4ecc2017-07-07 11:16:44 -07001192 try:
1193 named_cache_manager.uninstall(path, name)
1194 except named_cache.Error:
1195 logging.exception('Error while removing named cache %r at %r. '
1196 'The cache will be lost.', path, name)
nodirf33b8d62016-10-26 22:34:58 -07001197
nodirbe642ff2016-06-09 15:51:51 -07001198 try:
nodir90bc8dc2016-06-15 13:35:21 -07001199 if options.isolate_server:
1200 storage = isolateserver.get_storage(
1201 options.isolate_server, options.namespace)
1202 with storage:
nodirf33b8d62016-10-26 22:34:58 -07001203 # Hashing schemes used by |storage| and |isolate_cache| MUST match.
1204 assert storage.hash_algo == isolate_cache.hash_algo
nodirbe642ff2016-06-09 15:51:51 -07001205 return run_tha_test(
maruelabec63c2017-04-26 11:53:24 -07001206 args,
nodirf33b8d62016-10-26 22:34:58 -07001207 options.isolated,
1208 storage,
1209 isolate_cache,
aludwin0a8e17d2016-10-27 15:57:39 -07001210 options.output,
nodir26251c42017-05-11 13:21:53 -07001211 install_named_caches,
nodirf33b8d62016-10-26 22:34:58 -07001212 options.leak_temp_dir,
1213 options.json, options.root_dir,
1214 options.hard_timeout,
1215 options.grace_period,
maruelabec63c2017-04-26 11:53:24 -07001216 options.bot_file,
vadimsh8ec66822017-07-25 14:08:29 -07001217 options.switch_to_account,
nodirf33b8d62016-10-26 22:34:58 -07001218 install_packages_fn,
Marc-Antoine Ruel7d179af2017-10-24 16:52:02 -07001219 options.use_symlinks,
Robert Iannuccibe66ce72017-11-22 12:56:50 -08001220 options.raw_cmd,
Marc-Antoine Ruelaf9ea1b2017-11-28 18:33:39 -05001221 options.env,
Robert Iannuccibe66ce72017-11-22 12:56:50 -08001222 options.env_prefix)
maruel4409e302016-07-19 14:25:51 -07001223 return run_tha_test(
maruelabec63c2017-04-26 11:53:24 -07001224 args,
nodirf33b8d62016-10-26 22:34:58 -07001225 options.isolated,
1226 None,
1227 isolate_cache,
aludwin0a8e17d2016-10-27 15:57:39 -07001228 options.output,
nodir26251c42017-05-11 13:21:53 -07001229 install_named_caches,
nodirf33b8d62016-10-26 22:34:58 -07001230 options.leak_temp_dir,
1231 options.json,
1232 options.root_dir,
1233 options.hard_timeout,
1234 options.grace_period,
maruelabec63c2017-04-26 11:53:24 -07001235 options.bot_file,
vadimsh8ec66822017-07-25 14:08:29 -07001236 options.switch_to_account,
nodirf33b8d62016-10-26 22:34:58 -07001237 install_packages_fn,
Marc-Antoine Ruel7d179af2017-10-24 16:52:02 -07001238 options.use_symlinks,
Robert Iannuccibe66ce72017-11-22 12:56:50 -08001239 options.raw_cmd,
Marc-Antoine Ruelaf9ea1b2017-11-28 18:33:39 -05001240 options.env,
Robert Iannuccibe66ce72017-11-22 12:56:50 -08001241 options.env_prefix)
nodirf33b8d62016-10-26 22:34:58 -07001242 except (cipd.Error, named_cache.Error) as ex:
nodirbe642ff2016-06-09 15:51:51 -07001243 print >> sys.stderr, ex.message
1244 return 1
maruel@chromium.org9c72d4e2012-09-28 19:20:25 +00001245
1246
1247if __name__ == '__main__':
maruel8e4e40c2016-05-30 06:21:07 -07001248 subprocess42.inhibit_os_error_reporting()
csharp@chromium.orgbfb98742013-03-26 20:28:36 +00001249 # Ensure that we are always running with the correct encoding.
vadimsh@chromium.orga4326472013-08-24 02:05:41 +00001250 fix_encoding.fix_encoding()
Marc-Antoine Ruel90c98162013-12-18 15:11:57 -05001251 sys.exit(main(sys.argv[1:]))