maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1 | #!/usr/bin/env python |
maruel | ea586f3 | 2016-04-05 11:11:33 -0700 | [diff] [blame] | 2 | # Copyright 2012 The LUCI Authors. All rights reserved. |
maruel | f1f5e2a | 2016-05-25 17:10:39 -0700 | [diff] [blame] | 3 | # 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.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 5 | |
nodir | 55be77b | 2016-05-03 09:39:57 -0700 | [diff] [blame] | 6 | """Runs a command with optional isolated input/output. |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 7 | |
nodir | 55be77b | 2016-05-03 09:39:57 -0700 | [diff] [blame] | 8 | Despite name "run_isolated", can run a generic non-isolated command specified as |
| 9 | args. |
| 10 | |
| 11 | If input isolated hash is provided, fetches it, creates a tree of hard links, |
| 12 | appends args to the command in the fetched isolated and runs it. |
| 13 | To improve performance, keeps a local cache. |
| 14 | The local cache can safely be deleted. |
Marc-Antoine Ruel | 2283ad1 | 2014-02-09 11:14:57 -0500 | [diff] [blame] | 15 | |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 16 | Any ${EXECUTABLE_SUFFIX} on the command line will be replaced with ".exe" string |
| 17 | on Windows and "" on other platforms. |
| 18 | |
Marc-Antoine Ruel | 2283ad1 | 2014-02-09 11:14:57 -0500 | [diff] [blame] | 19 | Any ${ISOLATED_OUTDIR} on the command line will be replaced by the location of a |
| 20 | temporary directory upon execution of the command specified in the .isolated |
| 21 | file. All content written to this directory will be uploaded upon termination |
| 22 | and the .isolated file describing this directory will be printed to stdout. |
bpastene | 447c199 | 2016-06-20 15:21:47 -0700 | [diff] [blame] | 23 | |
| 24 | Any ${SWARMING_BOT_FILE} on the command line will be replaced by the value of |
| 25 | the --bot-file parameter. This file is used by a swarming bot to communicate |
| 26 | state of the host to tasks. It is written to by the swarming bot's |
| 27 | on_before_task() hook in the swarming server's custom bot_config.py. |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 28 | """ |
| 29 | |
vadimsh | 8ec6682 | 2017-07-25 14:08:29 -0700 | [diff] [blame] | 30 | __version__ = '0.9.2' |
maruel@chromium.org | dedbf49 | 2013-09-12 20:42:11 +0000 | [diff] [blame] | 31 | |
aludwin | 7556e0c | 2016-10-26 08:46:10 -0700 | [diff] [blame] | 32 | import argparse |
maruel | 064c0a3 | 2016-04-05 11:47:15 -0700 | [diff] [blame] | 33 | import base64 |
iannucci | 96fcccc | 2016-08-30 15:52:22 -0700 | [diff] [blame] | 34 | import collections |
vadimsh | 232f5a8 | 2017-01-20 19:23:44 -0800 | [diff] [blame] | 35 | import contextlib |
aludwin | 7556e0c | 2016-10-26 08:46:10 -0700 | [diff] [blame] | 36 | import json |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 37 | import logging |
| 38 | import optparse |
| 39 | import os |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 40 | import sys |
| 41 | import tempfile |
maruel | 064c0a3 | 2016-04-05 11:47:15 -0700 | [diff] [blame] | 42 | import time |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 43 | |
vadimsh@chromium.org | a432647 | 2013-08-24 02:05:41 +0000 | [diff] [blame] | 44 | from third_party.depot_tools import fix_encoding |
| 45 | |
Vadim Shtayura | 6b555c1 | 2014-07-23 16:22:18 -0700 | [diff] [blame] | 46 | from utils import file_path |
maruel | 12e3001 | 2015-10-09 11:55:35 -0700 | [diff] [blame] | 47 | from utils import fs |
maruel | 064c0a3 | 2016-04-05 11:47:15 -0700 | [diff] [blame] | 48 | from utils import large |
Marc-Antoine Ruel | f74cffe | 2015-07-15 15:21:34 -0400 | [diff] [blame] | 49 | from utils import logging_utils |
Marc-Antoine Ruel | cfb6085 | 2014-07-02 15:22:00 -0400 | [diff] [blame] | 50 | from utils import on_error |
Marc-Antoine Ruel | c44f572 | 2015-01-08 16:10:01 -0500 | [diff] [blame] | 51 | from utils import subprocess42 |
vadimsh@chromium.org | a432647 | 2013-08-24 02:05:41 +0000 | [diff] [blame] | 52 | from utils import tools |
vadimsh@chromium.org | 3e97deb | 2013-08-24 00:56:44 +0000 | [diff] [blame] | 53 | from utils import zip_package |
vadimsh@chromium.org | 8b9d56b | 2013-08-21 22:24:35 +0000 | [diff] [blame] | 54 | |
vadimsh | 8ec6682 | 2017-07-25 14:08:29 -0700 | [diff] [blame] | 55 | from libs import luci_context |
| 56 | |
Vadim Shtayura | e34e13a | 2014-02-02 11:23:26 -0800 | [diff] [blame] | 57 | import auth |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 58 | import cipd |
maruel@chromium.org | dedbf49 | 2013-09-12 20:42:11 +0000 | [diff] [blame] | 59 | import isolateserver |
nodir | f33b8d6 | 2016-10-26 22:34:58 -0700 | [diff] [blame] | 60 | import named_cache |
maruel@chromium.org | dedbf49 | 2013-09-12 20:42:11 +0000 | [diff] [blame] | 61 | |
vadimsh@chromium.org | a432647 | 2013-08-24 02:05:41 +0000 | [diff] [blame] | 62 | |
vadimsh@chromium.org | 8507106 | 2013-08-21 23:37:45 +0000 | [diff] [blame] | 63 | # Absolute path to this file (can be None if running from zip on Mac). |
tansell | a494944 | 2016-06-23 22:34:32 -0700 | [diff] [blame] | 64 | THIS_FILE_PATH = os.path.abspath( |
| 65 | __file__.decode(sys.getfilesystemencoding())) if __file__ else None |
vadimsh@chromium.org | 8b9d56b | 2013-08-21 22:24:35 +0000 | [diff] [blame] | 66 | |
| 67 | # Directory that contains this file (might be inside zip package). |
tansell | a494944 | 2016-06-23 22:34:32 -0700 | [diff] [blame] | 68 | BASE_DIR = os.path.dirname(THIS_FILE_PATH) if __file__.decode( |
| 69 | sys.getfilesystemencoding()) else None |
vadimsh@chromium.org | 8b9d56b | 2013-08-21 22:24:35 +0000 | [diff] [blame] | 70 | |
| 71 | # Directory that contains currently running script file. |
maruel@chromium.org | 814d23f | 2013-10-01 19:08:00 +0000 | [diff] [blame] | 72 | if zip_package.get_main_script_path(): |
| 73 | MAIN_DIR = os.path.dirname( |
| 74 | os.path.abspath(zip_package.get_main_script_path())) |
| 75 | else: |
| 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.org | 8b9d56b | 2013-08-21 22:24:35 +0000 | [diff] [blame] | 79 | |
maruel | e2f2cb8 | 2016-07-13 14:41:03 -0700 | [diff] [blame] | 80 | |
| 81 | # Magic variables that can be found in the isolate task command line. |
| 82 | ISOLATED_OUTDIR_PARAMETER = '${ISOLATED_OUTDIR}' |
| 83 | EXECUTABLE_SUFFIX_PARAMETER = '${EXECUTABLE_SUFFIX}' |
| 84 | SWARMING_BOT_FILE_PARAMETER = '${SWARMING_BOT_FILE}' |
| 85 | |
| 86 | |
csharp@chromium.org | ff2a466 | 2012-11-21 20:49:32 +0000 | [diff] [blame] | 87 | # The name of the log file to use. |
| 88 | RUN_ISOLATED_LOG_FILE = 'run_isolated.log' |
| 89 | |
maruel | e2f2cb8 | 2016-07-13 14:41:03 -0700 | [diff] [blame] | 90 | |
csharp@chromium.org | e217f30 | 2012-11-22 16:51:53 +0000 | [diff] [blame] | 91 | # The name of the log to use for the run_test_cases.py command |
vadimsh@chromium.org | 8b9d56b | 2013-08-21 22:24:35 +0000 | [diff] [blame] | 92 | RUN_TEST_CASES_LOG = 'run_test_cases.log' |
csharp@chromium.org | e217f30 | 2012-11-22 16:51:53 +0000 | [diff] [blame] | 93 | |
vadimsh@chromium.org | 87d6326 | 2013-04-04 19:34:21 +0000 | [diff] [blame] | 94 | |
maruel | e2f2cb8 | 2016-07-13 14:41:03 -0700 | [diff] [blame] | 95 | # 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 |
| 105 | ISOLATED_RUN_DIR = u'ir' |
| 106 | ISOLATED_OUT_DIR = u'io' |
| 107 | ISOLATED_TMP_DIR = u'it' |
| 108 | |
| 109 | |
maruel | 7eb6b56 | 2017-06-08 08:20:04 -0700 | [diff] [blame] | 110 | OUTLIVING_ZOMBIE_MSG = """\ |
| 111 | *** Swarming tried multiple times to delete the %s directory and failed *** |
| 112 | *** Hard failing the task *** |
| 113 | |
| 114 | Swarming detected that your testing script ran an executable, which may have |
| 115 | started a child executable, and the main script returned early, leaving the |
| 116 | children executables playing around unguided. |
| 117 | |
| 118 | You don't want to leave children processes outliving the task on the Swarming |
| 119 | bot, do you? The Swarming bot doesn't. |
| 120 | |
| 121 | How 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 | |
| 137 | See |
| 138 | https://github.com/luci/luci-py/blob/master/appengine/swarming/doc/Bot.md#graceful-termination-aka-the-sigterm-and-sigkill-dance |
| 139 | for more information. |
| 140 | |
| 141 | *** May the SIGKILL force be with you *** |
| 142 | """ |
| 143 | |
| 144 | |
vadimsh@chromium.org | 8b9d56b | 2013-08-21 22:24:35 +0000 | [diff] [blame] | 145 | def 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.org | 8507106 | 2013-08-21 23:37:45 +0000 | [diff] [blame] | 154 | assert THIS_FILE_PATH |
| 155 | assert BASE_DIR |
vadimsh@chromium.org | 8b9d56b | 2013-08-21 22:24:35 +0000 | [diff] [blame] | 156 | package = zip_package.ZipPackage(root=BASE_DIR) |
| 157 | package.add_python_file(THIS_FILE_PATH, '__main__.py' if executable else None) |
aludwin | 8117830 | 2016-11-30 17:18:49 -0800 | [diff] [blame] | 158 | package.add_python_file(os.path.join(BASE_DIR, 'isolate_storage.py')) |
Marc-Antoine Ruel | 8bee66d | 2014-08-28 19:02:07 -0400 | [diff] [blame] | 159 | package.add_python_file(os.path.join(BASE_DIR, 'isolated_format.py')) |
maruel@chromium.org | dedbf49 | 2013-09-12 20:42:11 +0000 | [diff] [blame] | 160 | package.add_python_file(os.path.join(BASE_DIR, 'isolateserver.py')) |
Vadim Shtayura | e34e13a | 2014-02-02 11:23:26 -0800 | [diff] [blame] | 161 | package.add_python_file(os.path.join(BASE_DIR, 'auth.py')) |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 162 | package.add_python_file(os.path.join(BASE_DIR, 'cipd.py')) |
nodir | f33b8d6 | 2016-10-26 22:34:58 -0700 | [diff] [blame] | 163 | package.add_python_file(os.path.join(BASE_DIR, 'named_cache.py')) |
tansell | e4288c3 | 2016-07-28 09:45:40 -0700 | [diff] [blame] | 164 | package.add_directory(os.path.join(BASE_DIR, 'libs')) |
vadimsh@chromium.org | 8b9d56b | 2013-08-21 22:24:35 +0000 | [diff] [blame] | 165 | 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 | |
maruel | 03e1184 | 2016-07-14 10:50:16 -0700 | [diff] [blame] | 170 | def 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.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 173 | |
| 174 | |
Marc-Antoine Ruel | 7124e39 | 2014-01-09 11:49:21 -0500 | [diff] [blame] | 175 | def 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 Ruel | e4ad07e | 2014-10-15 20:22:29 -0400 | [diff] [blame] | 185 | file_path.make_tree_read_only(rootdir) |
Marc-Antoine Ruel | 7124e39 | 2014-01-09 11:49:21 -0500 | [diff] [blame] | 186 | 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 Ruel | e4ad07e | 2014-10-15 20:22:29 -0400 | [diff] [blame] | 189 | file_path.make_tree_files_read_only(rootdir) |
Marc-Antoine Ruel | 7124e39 | 2014-01-09 11:49:21 -0500 | [diff] [blame] | 190 | elif read_only in (0, None): |
Marc-Antoine Ruel | f1d827c | 2014-11-24 15:22:25 -0500 | [diff] [blame] | 191 | # Anything can be modified. |
Marc-Antoine Ruel | 7124e39 | 2014-01-09 11:49:21 -0500 | [diff] [blame] | 192 | # 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 Ruel | e4ad07e | 2014-10-15 20:22:29 -0400 | [diff] [blame] | 196 | file_path.make_tree_writeable(rootdir) |
Marc-Antoine Ruel | 7124e39 | 2014-01-09 11:49:21 -0500 | [diff] [blame] | 197 | else: |
| 198 | raise ValueError( |
| 199 | 'change_tree_read_only(%s, %s): Unknown flag %s' % |
| 200 | (rootdir, read_only, read_only)) |
| 201 | |
| 202 | |
vadimsh | 8ec6682 | 2017-07-25 14:08:29 -0700 | [diff] [blame] | 203 | @contextlib.contextmanager |
| 204 | def 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 | |
nodir | 90bc8dc | 2016-06-15 13:35:21 -0700 | [diff] [blame] | 251 | def process_command(command, out_dir, bot_file): |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 252 | """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 | """ |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 258 | def fix(arg): |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 259 | arg = arg.replace(EXECUTABLE_SUFFIX_PARAMETER, cipd.EXECUTABLE_SUFFIX) |
| 260 | replace_slash = False |
nodir | 55be77b | 2016-05-03 09:39:57 -0700 | [diff] [blame] | 261 | if ISOLATED_OUTDIR_PARAMETER in arg: |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 262 | if not out_dir: |
maruel | 7f63a27 | 2016-07-12 12:40:36 -0700 | [diff] [blame] | 263 | raise ValueError( |
| 264 | 'output directory is requested in command, but not provided; ' |
| 265 | 'please specify one') |
nodir | 55be77b | 2016-05-03 09:39:57 -0700 | [diff] [blame] | 266 | arg = arg.replace(ISOLATED_OUTDIR_PARAMETER, out_dir) |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 267 | replace_slash = True |
nodir | 90bc8dc | 2016-06-15 13:35:21 -0700 | [diff] [blame] | 268 | 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.') |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 275 | if replace_slash: |
| 276 | # Replace slashes only if parameters are present |
nodir | 55be77b | 2016-05-03 09:39:57 -0700 | [diff] [blame] | 277 | # because of arguments like '${ISOLATED_OUTDIR}/foo/bar' |
| 278 | arg = arg.replace('/', os.sep) |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 279 | return arg |
| 280 | |
| 281 | return [fix(arg) for arg in command] |
| 282 | |
| 283 | |
vadimsh | 232f5a8 | 2017-01-20 19:23:44 -0800 | [diff] [blame] | 284 | def get_command_env(tmp_dir, cipd_info): |
| 285 | """Returns full OS environment to run a command in. |
| 286 | |
| 287 | Sets up TEMP, puts directory with cipd binary in front of PATH, and exposes |
| 288 | CIPD_CACHE_DIR env var. |
| 289 | |
| 290 | Args: |
| 291 | tmp_dir: temp directory. |
| 292 | cipd_info: CipdInfo object is cipd client is used, None if not. |
| 293 | """ |
| 294 | def to_fs_enc(s): |
| 295 | if isinstance(s, str): |
| 296 | return s |
| 297 | return s.encode(sys.getfilesystemencoding()) |
| 298 | |
| 299 | env = os.environ.copy() |
| 300 | |
iannucci | ac0342c | 2017-02-24 05:47:01 -0800 | [diff] [blame] | 301 | # TMPDIR is specified as the POSIX standard envvar for the temp directory. |
iannucci | 460def7 | 2017-02-24 10:49:48 -0800 | [diff] [blame] | 302 | # * mktemp on linux respects $TMPDIR, not $TMP |
| 303 | # * mktemp on OS X SOMETIMES respects $TMPDIR |
iannucci | ac0342c | 2017-02-24 05:47:01 -0800 | [diff] [blame] | 304 | # * chromium's base utils respects $TMPDIR on linux, $TEMP on windows. |
| 305 | # Unfortunately at the time of writing it completely ignores all envvars |
| 306 | # on OS X. |
iannucci | 460def7 | 2017-02-24 10:49:48 -0800 | [diff] [blame] | 307 | # * python respects TMPDIR, TEMP, and TMP (regardless of platform) |
| 308 | # * golang respects TMPDIR on linux+mac, TEMP on windows. |
iannucci | ac0342c | 2017-02-24 05:47:01 -0800 | [diff] [blame] | 309 | key = {'win32': 'TEMP'}.get(sys.platform, 'TMPDIR') |
vadimsh | 232f5a8 | 2017-01-20 19:23:44 -0800 | [diff] [blame] | 310 | env[key] = to_fs_enc(tmp_dir) |
| 311 | |
| 312 | if cipd_info: |
| 313 | bin_dir = os.path.dirname(cipd_info.client.binary_path) |
| 314 | env['PATH'] = '%s%s%s' % (to_fs_enc(bin_dir), os.pathsep, env['PATH']) |
| 315 | env['CIPD_CACHE_DIR'] = to_fs_enc(cipd_info.cache_dir) |
| 316 | |
| 317 | return env |
| 318 | |
| 319 | |
| 320 | def run_command(command, cwd, env, hard_timeout, grace_period): |
maruel | 6be7f9e | 2015-10-01 12:25:30 -0700 | [diff] [blame] | 321 | """Runs the command. |
| 322 | |
| 323 | Returns: |
| 324 | tuple(process exit code, bool if had a hard timeout) |
| 325 | """ |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 326 | logging.info('run_command(%s, %s)' % (command, cwd)) |
maruel | eb5fbee | 2015-09-17 13:01:36 -0700 | [diff] [blame] | 327 | |
maruel | 6be7f9e | 2015-10-01 12:25:30 -0700 | [diff] [blame] | 328 | exit_code = None |
| 329 | had_hard_timeout = False |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 330 | with tools.Profiler('RunTest'): |
maruel | 6be7f9e | 2015-10-01 12:25:30 -0700 | [diff] [blame] | 331 | proc = None |
| 332 | had_signal = [] |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 333 | try: |
maruel | 6be7f9e | 2015-10-01 12:25:30 -0700 | [diff] [blame] | 334 | # TODO(maruel): This code is imperfect. It doesn't handle well signals |
| 335 | # during the download phase and there's short windows were things can go |
| 336 | # wrong. |
| 337 | def handler(signum, _frame): |
| 338 | if proc and not had_signal: |
| 339 | logging.info('Received signal %d', signum) |
| 340 | had_signal.append(True) |
maruel | 556d905 | 2015-10-05 11:12:44 -0700 | [diff] [blame] | 341 | raise subprocess42.TimeoutExpired(command, None) |
maruel | 6be7f9e | 2015-10-01 12:25:30 -0700 | [diff] [blame] | 342 | |
| 343 | proc = subprocess42.Popen(command, cwd=cwd, env=env, detached=True) |
| 344 | with subprocess42.set_signal_handler(subprocess42.STOP_SIGNALS, handler): |
| 345 | try: |
| 346 | exit_code = proc.wait(hard_timeout or None) |
| 347 | except subprocess42.TimeoutExpired: |
| 348 | if not had_signal: |
| 349 | logging.warning('Hard timeout') |
| 350 | had_hard_timeout = True |
| 351 | logging.warning('Sending SIGTERM') |
| 352 | proc.terminate() |
| 353 | |
| 354 | # Ignore signals in grace period. Forcibly give the grace period to the |
| 355 | # child process. |
| 356 | if exit_code is None: |
| 357 | ignore = lambda *_: None |
| 358 | with subprocess42.set_signal_handler(subprocess42.STOP_SIGNALS, ignore): |
| 359 | try: |
| 360 | exit_code = proc.wait(grace_period or None) |
| 361 | except subprocess42.TimeoutExpired: |
| 362 | # Now kill for real. The user can distinguish between the |
| 363 | # following states: |
| 364 | # - signal but process exited within grace period, |
| 365 | # hard_timed_out will be set but the process exit code will be |
| 366 | # script provided. |
| 367 | # - processed exited late, exit code will be -9 on posix. |
| 368 | logging.warning('Grace exhausted; sending SIGKILL') |
| 369 | proc.kill() |
martiniss | 3343ec0 | 2017-08-01 17:09:43 -0700 | [diff] [blame] | 370 | logging.info('Waiting for process exit') |
maruel | 6be7f9e | 2015-10-01 12:25:30 -0700 | [diff] [blame] | 371 | exit_code = proc.wait() |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 372 | except OSError: |
| 373 | # This is not considered to be an internal error. The executable simply |
| 374 | # does not exit. |
maruel | a72f46e | 2016-02-24 11:05:45 -0800 | [diff] [blame] | 375 | sys.stderr.write( |
| 376 | '<The executable does not exist or a dependent library is missing>\n' |
| 377 | '<Check for missing .so/.dll in the .isolate or GN file>\n' |
| 378 | '<Command: %s>\n' % command) |
| 379 | if os.environ.get('SWARMING_TASK_ID'): |
| 380 | # Give an additional hint when running as a swarming task. |
| 381 | sys.stderr.write( |
| 382 | '<See the task\'s page for commands to help diagnose this issue ' |
| 383 | 'by reproducing the task locally>\n') |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 384 | exit_code = 1 |
| 385 | logging.info( |
| 386 | 'Command finished with exit code %d (%s)', |
| 387 | exit_code, hex(0xffffffff & exit_code)) |
maruel | 6be7f9e | 2015-10-01 12:25:30 -0700 | [diff] [blame] | 388 | return exit_code, had_hard_timeout |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 389 | |
| 390 | |
maruel | 4409e30 | 2016-07-19 14:25:51 -0700 | [diff] [blame] | 391 | def fetch_and_map(isolated_hash, storage, cache, outdir, use_symlinks): |
| 392 | """Fetches an isolated tree, create the tree and returns (bundle, stats).""" |
nodir | 6f80188 | 2016-04-29 14:41:50 -0700 | [diff] [blame] | 393 | start = time.time() |
| 394 | bundle = isolateserver.fetch_isolated( |
| 395 | isolated_hash=isolated_hash, |
| 396 | storage=storage, |
| 397 | cache=cache, |
maruel | 4409e30 | 2016-07-19 14:25:51 -0700 | [diff] [blame] | 398 | outdir=outdir, |
| 399 | use_symlinks=use_symlinks) |
nodir | 6f80188 | 2016-04-29 14:41:50 -0700 | [diff] [blame] | 400 | return bundle, { |
| 401 | 'duration': time.time() - start, |
| 402 | 'initial_number_items': cache.initial_number_items, |
| 403 | 'initial_size': cache.initial_size, |
| 404 | 'items_cold': base64.b64encode(large.pack(sorted(cache.added))), |
| 405 | 'items_hot': base64.b64encode( |
tansell | 9e04a8d | 2016-07-28 09:31:59 -0700 | [diff] [blame] | 406 | large.pack(sorted(set(cache.used) - set(cache.added)))), |
nodir | 6f80188 | 2016-04-29 14:41:50 -0700 | [diff] [blame] | 407 | } |
| 408 | |
| 409 | |
aludwin | 0a8e17d | 2016-10-27 15:57:39 -0700 | [diff] [blame] | 410 | def link_outputs_to_outdir(run_dir, out_dir, outputs): |
| 411 | """Links any named outputs to out_dir so they can be uploaded. |
| 412 | |
| 413 | Raises an error if the file already exists in that directory. |
| 414 | """ |
| 415 | if not outputs: |
| 416 | return |
| 417 | isolateserver.create_directories(out_dir, outputs) |
| 418 | for o in outputs: |
| 419 | try: |
aludwin | b35146d | 2017-06-12 06:03:00 -0700 | [diff] [blame] | 420 | infile = os.path.join(run_dir, o) |
| 421 | outfile = os.path.join(out_dir, o) |
| 422 | if fs.islink(infile): |
| 423 | # TODO(aludwin): handle directories |
| 424 | fs.copy2(infile, outfile) |
| 425 | else: |
| 426 | file_path.link_file(outfile, infile, file_path.HARDLINK_WITH_FALLBACK) |
aludwin | 0a8e17d | 2016-10-27 15:57:39 -0700 | [diff] [blame] | 427 | except OSError as e: |
aludwin | 8117830 | 2016-11-30 17:18:49 -0800 | [diff] [blame] | 428 | logging.info("Couldn't collect output file %s: %s", o, e) |
aludwin | 0a8e17d | 2016-10-27 15:57:39 -0700 | [diff] [blame] | 429 | |
| 430 | |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 431 | def delete_and_upload(storage, out_dir, leak_temp_dir): |
| 432 | """Deletes the temporary run directory and uploads results back. |
| 433 | |
| 434 | Returns: |
nodir | 6f80188 | 2016-04-29 14:41:50 -0700 | [diff] [blame] | 435 | tuple(outputs_ref, success, stats) |
maruel | 064c0a3 | 2016-04-05 11:47:15 -0700 | [diff] [blame] | 436 | - outputs_ref: a dict referring to the results archived back to the isolated |
| 437 | server, if applicable. |
| 438 | - success: False if something occurred that means that the task must |
| 439 | forcibly be considered a failure, e.g. zombie processes were left |
| 440 | behind. |
nodir | 6f80188 | 2016-04-29 14:41:50 -0700 | [diff] [blame] | 441 | - stats: uploading stats. |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 442 | """ |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 443 | # Upload out_dir and generate a .isolated file out of this directory. It is |
| 444 | # only done if files were written in the directory. |
| 445 | outputs_ref = None |
maruel | 064c0a3 | 2016-04-05 11:47:15 -0700 | [diff] [blame] | 446 | cold = [] |
| 447 | hot = [] |
nodir | 6f80188 | 2016-04-29 14:41:50 -0700 | [diff] [blame] | 448 | start = time.time() |
| 449 | |
maruel | 12e3001 | 2015-10-09 11:55:35 -0700 | [diff] [blame] | 450 | if fs.isdir(out_dir) and fs.listdir(out_dir): |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 451 | with tools.Profiler('ArchiveOutput'): |
| 452 | try: |
maruel | 064c0a3 | 2016-04-05 11:47:15 -0700 | [diff] [blame] | 453 | results, f_cold, f_hot = isolateserver.archive_files_to_storage( |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 454 | storage, [out_dir], None) |
| 455 | outputs_ref = { |
| 456 | 'isolated': results[0][0], |
| 457 | 'isolatedserver': storage.location, |
| 458 | 'namespace': storage.namespace, |
| 459 | } |
maruel | 064c0a3 | 2016-04-05 11:47:15 -0700 | [diff] [blame] | 460 | cold = sorted(i.size for i in f_cold) |
| 461 | hot = sorted(i.size for i in f_hot) |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 462 | except isolateserver.Aborted: |
| 463 | # This happens when a signal SIGTERM was received while uploading data. |
| 464 | # There is 2 causes: |
| 465 | # - The task was too slow and was about to be killed anyway due to |
| 466 | # exceeding the hard timeout. |
| 467 | # - The amount of data uploaded back is very large and took too much |
| 468 | # time to archive. |
| 469 | sys.stderr.write('Received SIGTERM while uploading') |
| 470 | # Re-raise, so it will be treated as an internal failure. |
| 471 | raise |
nodir | 6f80188 | 2016-04-29 14:41:50 -0700 | [diff] [blame] | 472 | |
| 473 | success = False |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 474 | try: |
maruel | 12e3001 | 2015-10-09 11:55:35 -0700 | [diff] [blame] | 475 | if (not leak_temp_dir and fs.isdir(out_dir) and |
maruel | 6eeea7d | 2015-09-16 12:17:42 -0700 | [diff] [blame] | 476 | not file_path.rmtree(out_dir)): |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 477 | logging.error('Had difficulties removing out_dir %s', out_dir) |
nodir | 6f80188 | 2016-04-29 14:41:50 -0700 | [diff] [blame] | 478 | else: |
| 479 | success = True |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 480 | except OSError as e: |
| 481 | # When this happens, it means there's a process error. |
maruel | 12e3001 | 2015-10-09 11:55:35 -0700 | [diff] [blame] | 482 | logging.exception('Had difficulties removing out_dir %s: %s', out_dir, e) |
nodir | 6f80188 | 2016-04-29 14:41:50 -0700 | [diff] [blame] | 483 | stats = { |
| 484 | 'duration': time.time() - start, |
| 485 | 'items_cold': base64.b64encode(large.pack(cold)), |
| 486 | 'items_hot': base64.b64encode(large.pack(hot)), |
| 487 | } |
| 488 | return outputs_ref, success, stats |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 489 | |
| 490 | |
maruel | eb5fbee | 2015-09-17 13:01:36 -0700 | [diff] [blame] | 491 | def map_and_run( |
nodir | 26251c4 | 2017-05-11 13:21:53 -0700 | [diff] [blame] | 492 | command, isolated_hash, storage, isolate_cache, outputs, |
| 493 | install_named_caches, leak_temp_dir, root_dir, hard_timeout, grace_period, |
vadimsh | 8ec6682 | 2017-07-25 14:08:29 -0700 | [diff] [blame] | 494 | bot_file, switch_to_account, install_packages_fn, use_symlinks, |
| 495 | constant_run_path): |
nodir | 55be77b | 2016-05-03 09:39:57 -0700 | [diff] [blame] | 496 | """Runs a command with optional isolated input/output. |
| 497 | |
| 498 | See run_tha_test for argument documentation. |
| 499 | |
| 500 | Returns metadata about the result. |
| 501 | """ |
maruel | abec63c | 2017-04-26 11:53:24 -0700 | [diff] [blame] | 502 | assert isinstance(command, list), command |
nodir | 56efa45 | 2016-10-12 12:17:39 -0700 | [diff] [blame] | 503 | assert root_dir or root_dir is None |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 504 | result = { |
maruel | 064c0a3 | 2016-04-05 11:47:15 -0700 | [diff] [blame] | 505 | 'duration': None, |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 506 | 'exit_code': None, |
maruel | 6be7f9e | 2015-10-01 12:25:30 -0700 | [diff] [blame] | 507 | 'had_hard_timeout': False, |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 508 | 'internal_failure': None, |
maruel | 064c0a3 | 2016-04-05 11:47:15 -0700 | [diff] [blame] | 509 | 'stats': { |
nodir | 5571571 | 2016-06-03 12:28:19 -0700 | [diff] [blame] | 510 | # 'isolated': { |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 511 | # 'cipd': { |
| 512 | # 'duration': 0., |
| 513 | # 'get_client_duration': 0., |
| 514 | # }, |
nodir | 5571571 | 2016-06-03 12:28:19 -0700 | [diff] [blame] | 515 | # 'download': { |
| 516 | # 'duration': 0., |
| 517 | # 'initial_number_items': 0, |
| 518 | # 'initial_size': 0, |
| 519 | # 'items_cold': '<large.pack()>', |
| 520 | # 'items_hot': '<large.pack()>', |
| 521 | # }, |
| 522 | # 'upload': { |
| 523 | # 'duration': 0., |
| 524 | # 'items_cold': '<large.pack()>', |
| 525 | # 'items_hot': '<large.pack()>', |
| 526 | # }, |
maruel | 064c0a3 | 2016-04-05 11:47:15 -0700 | [diff] [blame] | 527 | # }, |
| 528 | }, |
iannucci | 96fcccc | 2016-08-30 15:52:22 -0700 | [diff] [blame] | 529 | # 'cipd_pins': { |
| 530 | # 'packages': [ |
| 531 | # {'package_name': ..., 'version': ..., 'path': ...}, |
| 532 | # ... |
| 533 | # ], |
| 534 | # 'client_package': {'package_name': ..., 'version': ...}, |
| 535 | # }, |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 536 | 'outputs_ref': None, |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 537 | 'version': 5, |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 538 | } |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 539 | |
maruel | eb5fbee | 2015-09-17 13:01:36 -0700 | [diff] [blame] | 540 | if root_dir: |
nodir | e5028a9 | 2016-04-29 14:38:21 -0700 | [diff] [blame] | 541 | file_path.ensure_tree(root_dir, 0700) |
nodir | 56efa45 | 2016-10-12 12:17:39 -0700 | [diff] [blame] | 542 | elif isolate_cache.cache_dir: |
| 543 | root_dir = os.path.dirname(isolate_cache.cache_dir) |
maruel | e2f2cb8 | 2016-07-13 14:41:03 -0700 | [diff] [blame] | 544 | # See comment for these constants. |
maruel | cffa054 | 2017-04-07 08:39:20 -0700 | [diff] [blame] | 545 | # If root_dir is not specified, it is not constant. |
| 546 | # TODO(maruel): This is not obvious. Change this to become an error once we |
| 547 | # make the constant_run_path an exposed flag. |
| 548 | if constant_run_path and root_dir: |
| 549 | run_dir = os.path.join(root_dir, ISOLATED_RUN_DIR) |
maruel | 13437a7 | 2017-05-26 05:33:40 -0700 | [diff] [blame] | 550 | if os.path.isdir(run_dir): |
| 551 | file_path.rmtree(run_dir) |
maruel | cffa054 | 2017-04-07 08:39:20 -0700 | [diff] [blame] | 552 | os.mkdir(run_dir) |
| 553 | else: |
| 554 | run_dir = make_temp_dir(ISOLATED_RUN_DIR, root_dir) |
maruel | 03e1184 | 2016-07-14 10:50:16 -0700 | [diff] [blame] | 555 | # storage should be normally set but don't crash if it is not. This can happen |
| 556 | # as Swarming task can run without an isolate server. |
maruel | e2f2cb8 | 2016-07-13 14:41:03 -0700 | [diff] [blame] | 557 | out_dir = make_temp_dir(ISOLATED_OUT_DIR, root_dir) if storage else None |
| 558 | tmp_dir = make_temp_dir(ISOLATED_TMP_DIR, root_dir) |
nodir | 55be77b | 2016-05-03 09:39:57 -0700 | [diff] [blame] | 559 | cwd = run_dir |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 560 | |
nodir | 55be77b | 2016-05-03 09:39:57 -0700 | [diff] [blame] | 561 | try: |
vadimsh | 232f5a8 | 2017-01-20 19:23:44 -0800 | [diff] [blame] | 562 | with install_packages_fn(run_dir) as cipd_info: |
| 563 | if cipd_info: |
| 564 | result['stats']['cipd'] = cipd_info.stats |
| 565 | result['cipd_pins'] = cipd_info.pins |
nodir | 90bc8dc | 2016-06-15 13:35:21 -0700 | [diff] [blame] | 566 | |
vadimsh | 232f5a8 | 2017-01-20 19:23:44 -0800 | [diff] [blame] | 567 | if isolated_hash: |
| 568 | isolated_stats = result['stats'].setdefault('isolated', {}) |
| 569 | bundle, isolated_stats['download'] = fetch_and_map( |
| 570 | isolated_hash=isolated_hash, |
| 571 | storage=storage, |
| 572 | cache=isolate_cache, |
| 573 | outdir=run_dir, |
| 574 | use_symlinks=use_symlinks) |
vadimsh | 232f5a8 | 2017-01-20 19:23:44 -0800 | [diff] [blame] | 575 | change_tree_read_only(run_dir, bundle.read_only) |
| 576 | cwd = os.path.normpath(os.path.join(cwd, bundle.relative_cwd)) |
maruel | abec63c | 2017-04-26 11:53:24 -0700 | [diff] [blame] | 577 | # Inject the command |
| 578 | if bundle.command: |
| 579 | command = bundle.command + command |
| 580 | |
| 581 | if not command: |
| 582 | # Handle this as a task failure, not an internal failure. |
| 583 | sys.stderr.write( |
| 584 | '<No command was specified!>\n' |
| 585 | '<Please secify a command when triggering your Swarming task>\n') |
| 586 | result['exit_code'] = 1 |
| 587 | return result |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 588 | |
vadimsh | 232f5a8 | 2017-01-20 19:23:44 -0800 | [diff] [blame] | 589 | # If we have an explicit list of files to return, make sure their |
| 590 | # directories exist now. |
| 591 | if storage and outputs: |
| 592 | isolateserver.create_directories(run_dir, outputs) |
aludwin | 0a8e17d | 2016-10-27 15:57:39 -0700 | [diff] [blame] | 593 | |
vadimsh | 232f5a8 | 2017-01-20 19:23:44 -0800 | [diff] [blame] | 594 | command = tools.fix_python_path(command) |
| 595 | command = process_command(command, out_dir, bot_file) |
| 596 | file_path.ensure_command_has_abs_path(command, cwd) |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 597 | |
nodir | 26251c4 | 2017-05-11 13:21:53 -0700 | [diff] [blame] | 598 | with install_named_caches(run_dir): |
nodir | d616068 | 2017-02-02 13:03:35 -0800 | [diff] [blame] | 599 | sys.stdout.flush() |
| 600 | start = time.time() |
| 601 | try: |
vadimsh | 8ec6682 | 2017-07-25 14:08:29 -0700 | [diff] [blame] | 602 | # Need to switch the default account before 'get_command_env' call, |
| 603 | # so it can grab correct value of LUCI_CONTEXT env var. |
| 604 | with set_luci_context_account(switch_to_account, tmp_dir): |
| 605 | result['exit_code'], result['had_hard_timeout'] = run_command( |
| 606 | command, cwd, get_command_env(tmp_dir, cipd_info), |
| 607 | hard_timeout, grace_period) |
nodir | d616068 | 2017-02-02 13:03:35 -0800 | [diff] [blame] | 608 | finally: |
| 609 | result['duration'] = max(time.time() - start, 0) |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 610 | except Exception as e: |
nodir | 90bc8dc | 2016-06-15 13:35:21 -0700 | [diff] [blame] | 611 | # An internal error occurred. Report accordingly so the swarming task will |
| 612 | # be retried automatically. |
maruel | 12e3001 | 2015-10-09 11:55:35 -0700 | [diff] [blame] | 613 | logging.exception('internal failure: %s', e) |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 614 | result['internal_failure'] = str(e) |
| 615 | on_error.report(None) |
aludwin | 0a8e17d | 2016-10-27 15:57:39 -0700 | [diff] [blame] | 616 | |
| 617 | # Clean up |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 618 | finally: |
| 619 | try: |
aludwin | 0a8e17d | 2016-10-27 15:57:39 -0700 | [diff] [blame] | 620 | # Try to link files to the output directory, if specified. |
| 621 | if out_dir: |
| 622 | link_outputs_to_outdir(run_dir, out_dir, outputs) |
| 623 | |
nodir | 32a1ec1 | 2016-10-26 18:34:07 -0700 | [diff] [blame] | 624 | success = False |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 625 | if leak_temp_dir: |
nodir | 32a1ec1 | 2016-10-26 18:34:07 -0700 | [diff] [blame] | 626 | success = True |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 627 | logging.warning( |
| 628 | 'Deliberately leaking %s for later examination', run_dir) |
maruel | eb5fbee | 2015-09-17 13:01:36 -0700 | [diff] [blame] | 629 | else: |
maruel | 84537cb | 2015-10-16 14:21:28 -0700 | [diff] [blame] | 630 | # On Windows rmtree(run_dir) call above has a synchronization effect: it |
| 631 | # finishes only when all task child processes terminate (since a running |
| 632 | # process locks *.exe file). Examine out_dir only after that call |
| 633 | # completes (since child processes may write to out_dir too and we need |
| 634 | # to wait for them to finish). |
| 635 | if fs.isdir(run_dir): |
| 636 | try: |
| 637 | success = file_path.rmtree(run_dir) |
| 638 | except OSError as e: |
| 639 | logging.error('Failure with %s', e) |
| 640 | success = False |
| 641 | if not success: |
maruel | 7eb6b56 | 2017-06-08 08:20:04 -0700 | [diff] [blame] | 642 | sys.stderr.write(OUTLIVING_ZOMBIE_MSG % ('run', grace_period)) |
maruel | 84537cb | 2015-10-16 14:21:28 -0700 | [diff] [blame] | 643 | if result['exit_code'] == 0: |
| 644 | result['exit_code'] = 1 |
| 645 | if fs.isdir(tmp_dir): |
| 646 | try: |
| 647 | success = file_path.rmtree(tmp_dir) |
| 648 | except OSError as e: |
| 649 | logging.error('Failure with %s', e) |
| 650 | success = False |
| 651 | if not success: |
maruel | 9832b05 | 2017-06-08 13:06:40 -0700 | [diff] [blame] | 652 | sys.stderr.write(OUTLIVING_ZOMBIE_MSG % ('temp', grace_period)) |
maruel | 84537cb | 2015-10-16 14:21:28 -0700 | [diff] [blame] | 653 | if result['exit_code'] == 0: |
| 654 | result['exit_code'] = 1 |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 655 | |
maruel | eb5fbee | 2015-09-17 13:01:36 -0700 | [diff] [blame] | 656 | # This deletes out_dir if leak_temp_dir is not set. |
nodir | 9130f07 | 2016-05-27 13:59:08 -0700 | [diff] [blame] | 657 | if out_dir: |
nodir | 5571571 | 2016-06-03 12:28:19 -0700 | [diff] [blame] | 658 | isolated_stats = result['stats'].setdefault('isolated', {}) |
| 659 | result['outputs_ref'], success, isolated_stats['upload'] = ( |
nodir | 9130f07 | 2016-05-27 13:59:08 -0700 | [diff] [blame] | 660 | delete_and_upload(storage, out_dir, leak_temp_dir)) |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 661 | if not success and result['exit_code'] == 0: |
| 662 | result['exit_code'] = 1 |
| 663 | except Exception as e: |
| 664 | # Swallow any exception in the main finally clause. |
nodir | 9130f07 | 2016-05-27 13:59:08 -0700 | [diff] [blame] | 665 | if out_dir: |
| 666 | logging.exception('Leaking out_dir %s: %s', out_dir, e) |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 667 | result['internal_failure'] = str(e) |
| 668 | return result |
Marc-Antoine Ruel | 2283ad1 | 2014-02-09 11:14:57 -0500 | [diff] [blame] | 669 | |
| 670 | |
Marc-Antoine Ruel | 0ec868b | 2015-08-12 14:12:46 -0400 | [diff] [blame] | 671 | def run_tha_test( |
nodir | 26251c4 | 2017-05-11 13:21:53 -0700 | [diff] [blame] | 672 | command, isolated_hash, storage, isolate_cache, outputs, |
| 673 | install_named_caches, leak_temp_dir, result_json, root_dir, hard_timeout, |
vadimsh | 8ec6682 | 2017-07-25 14:08:29 -0700 | [diff] [blame] | 674 | grace_period, bot_file, switch_to_account, install_packages_fn, |
| 675 | use_symlinks): |
nodir | 55be77b | 2016-05-03 09:39:57 -0700 | [diff] [blame] | 676 | """Runs an executable and records execution metadata. |
| 677 | |
| 678 | Either command or isolated_hash must be specified. |
| 679 | |
| 680 | If isolated_hash is specified, downloads the dependencies in the cache, |
| 681 | hardlinks them into a temporary directory and runs the command specified in |
| 682 | the .isolated. |
Marc-Antoine Ruel | 2283ad1 | 2014-02-09 11:14:57 -0500 | [diff] [blame] | 683 | |
| 684 | A temporary directory is created to hold the output files. The content inside |
| 685 | this directory will be uploaded back to |storage| packaged as a .isolated |
| 686 | file. |
| 687 | |
| 688 | Arguments: |
maruel | abec63c | 2017-04-26 11:53:24 -0700 | [diff] [blame] | 689 | command: a list of string; the command to run OR optional arguments to add |
| 690 | to the command stated in the .isolated file if a command was |
| 691 | specified. |
Marc-Antoine Ruel | 35b5843 | 2014-12-08 17:40:40 -0500 | [diff] [blame] | 692 | isolated_hash: the SHA-1 of the .isolated file that must be retrieved to |
Marc-Antoine Ruel | 2283ad1 | 2014-02-09 11:14:57 -0500 | [diff] [blame] | 693 | recreate the tree of files to run the target executable. |
nodir | 55be77b | 2016-05-03 09:39:57 -0700 | [diff] [blame] | 694 | The command specified in the .isolated is executed. |
| 695 | Mutually exclusive with command argument. |
Marc-Antoine Ruel | 2283ad1 | 2014-02-09 11:14:57 -0500 | [diff] [blame] | 696 | storage: an isolateserver.Storage object to retrieve remote objects. This |
| 697 | object has a reference to an isolateserver.StorageApi, which does |
| 698 | the actual I/O. |
nodir | 6b94569 | 2016-10-19 19:09:06 -0700 | [diff] [blame] | 699 | isolate_cache: an isolateserver.LocalCache to keep from retrieving the |
| 700 | same objects constantly by caching the objects retrieved. |
| 701 | Can be on-disk or in-memory. |
vadimsh | 8ec6682 | 2017-07-25 14:08:29 -0700 | [diff] [blame] | 702 | outputs: list of paths relative to root_dir to put into the output isolated |
| 703 | bundle upon task completion (see link_outputs_to_outdir). |
nodir | 26251c4 | 2017-05-11 13:21:53 -0700 | [diff] [blame] | 704 | install_named_caches: a function (run_dir) => context manager that installs |
vadimsh | 8ec6682 | 2017-07-25 14:08:29 -0700 | [diff] [blame] | 705 | named caches into |run_dir|. |
Kenneth Russell | 61d4235 | 2014-09-15 11:41:16 -0700 | [diff] [blame] | 706 | leak_temp_dir: if true, the temporary directory will be deliberately leaked |
| 707 | for later examination. |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 708 | result_json: file path to dump result metadata into. If set, the process |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 709 | exit code is always 0 unless an internal error occurred. |
nodir | 90bc8dc | 2016-06-15 13:35:21 -0700 | [diff] [blame] | 710 | root_dir: path to the directory to use to create the temporary directory. If |
maruel | eb5fbee | 2015-09-17 13:01:36 -0700 | [diff] [blame] | 711 | not specified, a random temporary directory is created. |
maruel | 6be7f9e | 2015-10-01 12:25:30 -0700 | [diff] [blame] | 712 | hard_timeout: kills the process if it lasts more than this amount of |
| 713 | seconds. |
| 714 | grace_period: number of seconds to wait between SIGTERM and SIGKILL. |
vadimsh | 8ec6682 | 2017-07-25 14:08:29 -0700 | [diff] [blame] | 715 | bot_file: path to a file with bot state, used in place of |
| 716 | ${SWARMING_BOT_FILE} task command line argument. |
| 717 | switch_to_account: a logical account to switch LUCI_CONTEXT into. |
iannucci | b58d10d | 2017-03-18 02:00:25 -0700 | [diff] [blame] | 718 | install_packages_fn: context manager dir => CipdInfo, see |
vadimsh | 8ec6682 | 2017-07-25 14:08:29 -0700 | [diff] [blame] | 719 | install_client_and_packages. |
maruel | 4409e30 | 2016-07-19 14:25:51 -0700 | [diff] [blame] | 720 | use_symlinks: create tree with symlinks instead of hardlinks. |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 721 | |
| 722 | Returns: |
| 723 | Process exit code that should be used. |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 724 | """ |
maruel | a76b9ee | 2015-12-15 06:18:08 -0800 | [diff] [blame] | 725 | if result_json: |
| 726 | # Write a json output file right away in case we get killed. |
| 727 | result = { |
| 728 | 'exit_code': None, |
| 729 | 'had_hard_timeout': False, |
| 730 | 'internal_failure': 'Was terminated before completion', |
| 731 | 'outputs_ref': None, |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 732 | 'version': 5, |
maruel | a76b9ee | 2015-12-15 06:18:08 -0800 | [diff] [blame] | 733 | } |
| 734 | tools.write_json(result_json, result, dense=True) |
| 735 | |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 736 | # run_isolated exit code. Depends on if result_json is used or not. |
| 737 | result = map_and_run( |
nodir | 220308c | 2017-02-01 19:32:53 -0800 | [diff] [blame] | 738 | command, isolated_hash, storage, isolate_cache, outputs, |
nodir | 26251c4 | 2017-05-11 13:21:53 -0700 | [diff] [blame] | 739 | install_named_caches, leak_temp_dir, root_dir, hard_timeout, grace_period, |
vadimsh | 8ec6682 | 2017-07-25 14:08:29 -0700 | [diff] [blame] | 740 | bot_file, switch_to_account, install_packages_fn, use_symlinks, True) |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 741 | logging.info('Result:\n%s', tools.format_json(result, dense=True)) |
bpastene | 3ae0952 | 2016-06-10 17:12:59 -0700 | [diff] [blame] | 742 | |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 743 | if result_json: |
maruel | 05d5a88 | 2015-09-21 13:59:02 -0700 | [diff] [blame] | 744 | # We've found tests to delete 'work' when quitting, causing an exception |
| 745 | # here. Try to recreate the directory if necessary. |
nodir | e5028a9 | 2016-04-29 14:38:21 -0700 | [diff] [blame] | 746 | file_path.ensure_tree(os.path.dirname(result_json)) |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 747 | tools.write_json(result_json, result, dense=True) |
| 748 | # Only return 1 if there was an internal error. |
| 749 | return int(bool(result['internal_failure'])) |
maruel@chromium.org | 781ccf6 | 2013-09-17 19:39:47 +0000 | [diff] [blame] | 750 | |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 751 | # Marshall into old-style inline output. |
| 752 | if result['outputs_ref']: |
| 753 | data = { |
| 754 | 'hash': result['outputs_ref']['isolated'], |
| 755 | 'namespace': result['outputs_ref']['namespace'], |
| 756 | 'storage': result['outputs_ref']['isolatedserver'], |
| 757 | } |
Marc-Antoine Ruel | c44f572 | 2015-01-08 16:10:01 -0500 | [diff] [blame] | 758 | sys.stdout.flush() |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 759 | print( |
| 760 | '[run_isolated_out_hack]%s[/run_isolated_out_hack]' % |
| 761 | tools.format_json(data, dense=True)) |
maruel | b76604c | 2015-11-11 11:53:44 -0800 | [diff] [blame] | 762 | sys.stdout.flush() |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 763 | return result['exit_code'] or int(bool(result['internal_failure'])) |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 764 | |
| 765 | |
iannucci | b58d10d | 2017-03-18 02:00:25 -0700 | [diff] [blame] | 766 | # Yielded by 'install_client_and_packages'. |
vadimsh | 232f5a8 | 2017-01-20 19:23:44 -0800 | [diff] [blame] | 767 | CipdInfo = collections.namedtuple('CipdInfo', [ |
| 768 | 'client', # cipd.CipdClient object |
| 769 | 'cache_dir', # absolute path to bot-global cipd tag and instance cache |
| 770 | 'stats', # dict with stats to return to the server |
| 771 | 'pins', # dict with installed cipd pins to return to the server |
| 772 | ]) |
| 773 | |
| 774 | |
| 775 | @contextlib.contextmanager |
| 776 | def noop_install_packages(_run_dir): |
iannucci | b58d10d | 2017-03-18 02:00:25 -0700 | [diff] [blame] | 777 | """Placeholder for 'install_client_and_packages' if cipd is disabled.""" |
vadimsh | 232f5a8 | 2017-01-20 19:23:44 -0800 | [diff] [blame] | 778 | yield None |
| 779 | |
| 780 | |
iannucci | b58d10d | 2017-03-18 02:00:25 -0700 | [diff] [blame] | 781 | def _install_packages(run_dir, cipd_cache_dir, client, packages, timeout): |
| 782 | """Calls 'cipd ensure' for packages. |
| 783 | |
| 784 | Args: |
| 785 | run_dir (str): root of installation. |
| 786 | cipd_cache_dir (str): the directory to use for the cipd package cache. |
| 787 | client (CipdClient): the cipd client to use |
| 788 | packages: packages to install, list [(path, package_name, version), ...]. |
| 789 | timeout: max duration in seconds that this function can take. |
| 790 | |
| 791 | Returns: list of pinned packages. Looks like [ |
| 792 | { |
| 793 | 'path': 'subdirectory', |
| 794 | 'package_name': 'resolved/package/name', |
| 795 | 'version': 'deadbeef...', |
| 796 | }, |
| 797 | ... |
| 798 | ] |
| 799 | """ |
| 800 | package_pins = [None]*len(packages) |
| 801 | def insert_pin(path, name, version, idx): |
| 802 | package_pins[idx] = { |
| 803 | 'package_name': name, |
| 804 | # swarming deals with 'root' as '.' |
| 805 | 'path': path or '.', |
| 806 | 'version': version, |
| 807 | } |
| 808 | |
| 809 | by_path = collections.defaultdict(list) |
| 810 | for i, (path, name, version) in enumerate(packages): |
| 811 | # cipd deals with 'root' as '' |
| 812 | if path == '.': |
| 813 | path = '' |
| 814 | by_path[path].append((name, version, i)) |
| 815 | |
| 816 | pins = client.ensure( |
| 817 | run_dir, |
| 818 | { |
| 819 | subdir: [(name, vers) for name, vers, _ in pkgs] |
| 820 | for subdir, pkgs in by_path.iteritems() |
| 821 | }, |
| 822 | cache_dir=cipd_cache_dir, |
| 823 | timeout=timeout, |
| 824 | ) |
| 825 | |
| 826 | for subdir, pin_list in sorted(pins.iteritems()): |
| 827 | this_subdir = by_path[subdir] |
| 828 | for i, (name, version) in enumerate(pin_list): |
| 829 | insert_pin(subdir, name, version, this_subdir[i][2]) |
| 830 | |
| 831 | assert None not in package_pins |
| 832 | |
| 833 | return package_pins |
| 834 | |
| 835 | |
vadimsh | 232f5a8 | 2017-01-20 19:23:44 -0800 | [diff] [blame] | 836 | @contextlib.contextmanager |
iannucci | b58d10d | 2017-03-18 02:00:25 -0700 | [diff] [blame] | 837 | def install_client_and_packages( |
nodir | ff531b4 | 2016-06-23 13:05:06 -0700 | [diff] [blame] | 838 | run_dir, packages, service_url, client_package_name, |
vadimsh | 232f5a8 | 2017-01-20 19:23:44 -0800 | [diff] [blame] | 839 | client_version, cache_dir, timeout=None): |
vadimsh | 902948e | 2017-01-20 15:57:32 -0800 | [diff] [blame] | 840 | """Bootstraps CIPD client and installs CIPD packages. |
iannucci | 96fcccc | 2016-08-30 15:52:22 -0700 | [diff] [blame] | 841 | |
vadimsh | 232f5a8 | 2017-01-20 19:23:44 -0800 | [diff] [blame] | 842 | Yields CipdClient, stats, client info and pins (as single CipdInfo object). |
| 843 | |
| 844 | Pins and the CIPD client info are in the form of: |
iannucci | 96fcccc | 2016-08-30 15:52:22 -0700 | [diff] [blame] | 845 | [ |
| 846 | { |
| 847 | "path": path, "package_name": package_name, "version": version, |
| 848 | }, |
| 849 | ... |
| 850 | ] |
vadimsh | 902948e | 2017-01-20 15:57:32 -0800 | [diff] [blame] | 851 | (the CIPD client info is a single dictionary instead of a list) |
iannucci | 96fcccc | 2016-08-30 15:52:22 -0700 | [diff] [blame] | 852 | |
| 853 | such that they correspond 1:1 to all input package arguments from the command |
| 854 | line. These dictionaries make their all the way back to swarming, where they |
| 855 | become the arguments of CipdPackage. |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 856 | |
vadimsh | 902948e | 2017-01-20 15:57:32 -0800 | [diff] [blame] | 857 | If 'packages' list is empty, will bootstrap CIPD client, but won't install |
| 858 | any packages. |
| 859 | |
| 860 | The bootstrapped client (regardless whether 'packages' list is empty or not), |
vadimsh | 232f5a8 | 2017-01-20 19:23:44 -0800 | [diff] [blame] | 861 | will be made available to the task via $PATH. |
vadimsh | 902948e | 2017-01-20 15:57:32 -0800 | [diff] [blame] | 862 | |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 863 | Args: |
nodir | 90bc8dc | 2016-06-15 13:35:21 -0700 | [diff] [blame] | 864 | run_dir (str): root of installation. |
vadimsh | 902948e | 2017-01-20 15:57:32 -0800 | [diff] [blame] | 865 | packages: packages to install, list [(path, package_name, version), ...]. |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 866 | service_url (str): CIPD server url, e.g. |
| 867 | "https://chrome-infra-packages.appspot.com." |
nodir | 90bc8dc | 2016-06-15 13:35:21 -0700 | [diff] [blame] | 868 | client_package_name (str): CIPD package name of CIPD client. |
| 869 | client_version (str): Version of CIPD client. |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 870 | cache_dir (str): where to keep cache of cipd clients, packages and tags. |
| 871 | timeout: max duration in seconds that this function can take. |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 872 | """ |
| 873 | assert cache_dir |
nodir | 90bc8dc | 2016-06-15 13:35:21 -0700 | [diff] [blame] | 874 | |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 875 | timeoutfn = tools.sliding_timeout(timeout) |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 876 | start = time.time() |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 877 | |
vadimsh | 902948e | 2017-01-20 15:57:32 -0800 | [diff] [blame] | 878 | cache_dir = os.path.abspath(cache_dir) |
vadimsh | 232f5a8 | 2017-01-20 19:23:44 -0800 | [diff] [blame] | 879 | cipd_cache_dir = os.path.join(cache_dir, 'cache') # tag and instance caches |
nodir | 90bc8dc | 2016-06-15 13:35:21 -0700 | [diff] [blame] | 880 | run_dir = os.path.abspath(run_dir) |
vadimsh | 902948e | 2017-01-20 15:57:32 -0800 | [diff] [blame] | 881 | packages = packages or [] |
nodir | 90bc8dc | 2016-06-15 13:35:21 -0700 | [diff] [blame] | 882 | |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 883 | get_client_start = time.time() |
| 884 | client_manager = cipd.get_client( |
| 885 | service_url, client_package_name, client_version, cache_dir, |
| 886 | timeout=timeoutfn()) |
iannucci | 96fcccc | 2016-08-30 15:52:22 -0700 | [diff] [blame] | 887 | |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 888 | with client_manager as client: |
| 889 | get_client_duration = time.time() - get_client_start |
nodir | 90bc8dc | 2016-06-15 13:35:21 -0700 | [diff] [blame] | 890 | |
iannucci | b58d10d | 2017-03-18 02:00:25 -0700 | [diff] [blame] | 891 | package_pins = [] |
| 892 | if packages: |
| 893 | package_pins = _install_packages( |
| 894 | run_dir, cipd_cache_dir, client, packages, timeoutfn()) |
| 895 | |
| 896 | file_path.make_tree_files_read_only(run_dir) |
nodir | 90bc8dc | 2016-06-15 13:35:21 -0700 | [diff] [blame] | 897 | |
vadimsh | 232f5a8 | 2017-01-20 19:23:44 -0800 | [diff] [blame] | 898 | total_duration = time.time() - start |
| 899 | logging.info( |
| 900 | 'Installing CIPD client and packages took %d seconds', total_duration) |
nodir | 90bc8dc | 2016-06-15 13:35:21 -0700 | [diff] [blame] | 901 | |
vadimsh | 232f5a8 | 2017-01-20 19:23:44 -0800 | [diff] [blame] | 902 | yield CipdInfo( |
| 903 | client=client, |
| 904 | cache_dir=cipd_cache_dir, |
| 905 | stats={ |
| 906 | 'duration': total_duration, |
| 907 | 'get_client_duration': get_client_duration, |
| 908 | }, |
| 909 | pins={ |
iannucci | b58d10d | 2017-03-18 02:00:25 -0700 | [diff] [blame] | 910 | 'client_package': { |
| 911 | 'package_name': client.package_name, |
| 912 | 'version': client.instance_id, |
| 913 | }, |
vadimsh | 232f5a8 | 2017-01-20 19:23:44 -0800 | [diff] [blame] | 914 | 'packages': package_pins, |
| 915 | }) |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 916 | |
| 917 | |
nodir | f33b8d6 | 2016-10-26 22:34:58 -0700 | [diff] [blame] | 918 | def clean_caches(options, isolate_cache, named_cache_manager): |
maruel | e6fc938 | 2017-05-04 09:03:48 -0700 | [diff] [blame] | 919 | """Trims isolated and named caches. |
| 920 | |
| 921 | The goal here is to coherently trim both caches, deleting older items |
| 922 | independent of which container they belong to. |
| 923 | """ |
| 924 | # TODO(maruel): Trim CIPD cache the same way. |
| 925 | total = 0 |
nodir | f33b8d6 | 2016-10-26 22:34:58 -0700 | [diff] [blame] | 926 | with named_cache_manager.open(): |
| 927 | oldest_isolated = isolate_cache.get_oldest() |
| 928 | oldest_named = named_cache_manager.get_oldest() |
| 929 | trimmers = [ |
| 930 | ( |
| 931 | isolate_cache.trim, |
| 932 | isolate_cache.get_timestamp(oldest_isolated) if oldest_isolated else 0, |
| 933 | ), |
| 934 | ( |
| 935 | lambda: named_cache_manager.trim(options.min_free_space), |
| 936 | named_cache_manager.get_timestamp(oldest_named) if oldest_named else 0, |
| 937 | ), |
| 938 | ] |
| 939 | trimmers.sort(key=lambda (_, ts): ts) |
maruel | e6fc938 | 2017-05-04 09:03:48 -0700 | [diff] [blame] | 940 | # TODO(maruel): This is incorrect, we want to trim 'items' that are strictly |
| 941 | # the oldest independent of in which cache they live in. Right now, the |
| 942 | # cache with the oldest item pays the price. |
nodir | f33b8d6 | 2016-10-26 22:34:58 -0700 | [diff] [blame] | 943 | for trim, _ in trimmers: |
maruel | e6fc938 | 2017-05-04 09:03:48 -0700 | [diff] [blame] | 944 | total += trim() |
nodir | f33b8d6 | 2016-10-26 22:34:58 -0700 | [diff] [blame] | 945 | isolate_cache.cleanup() |
maruel | e6fc938 | 2017-05-04 09:03:48 -0700 | [diff] [blame] | 946 | return total |
nodir | f33b8d6 | 2016-10-26 22:34:58 -0700 | [diff] [blame] | 947 | |
| 948 | |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 949 | def create_option_parser(): |
Marc-Antoine Ruel | f74cffe | 2015-07-15 15:21:34 -0400 | [diff] [blame] | 950 | parser = logging_utils.OptionParserWithLogging( |
nodir | 55be77b | 2016-05-03 09:39:57 -0700 | [diff] [blame] | 951 | usage='%prog <options> [command to run or extra args]', |
maruel@chromium.org | dedbf49 | 2013-09-12 20:42:11 +0000 | [diff] [blame] | 952 | version=__version__, |
| 953 | log_file=RUN_ISOLATED_LOG_FILE) |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 954 | parser.add_option( |
maruel | 36a963d | 2016-04-08 17:15:49 -0700 | [diff] [blame] | 955 | '--clean', action='store_true', |
| 956 | help='Cleans the cache, trimming it necessary and remove corrupted items ' |
| 957 | 'and returns without executing anything; use with -v to know what ' |
| 958 | 'was done') |
| 959 | parser.add_option( |
maruel | 2e8d0f5 | 2016-07-16 07:51:29 -0700 | [diff] [blame] | 960 | '--no-clean', action='store_true', |
| 961 | help='Do not clean the cache automatically on startup. This is meant for ' |
| 962 | 'bots where a separate execution with --clean was done earlier so ' |
| 963 | 'doing it again is redundant') |
| 964 | parser.add_option( |
maruel | 4409e30 | 2016-07-19 14:25:51 -0700 | [diff] [blame] | 965 | '--use-symlinks', action='store_true', |
| 966 | help='Use symlinks instead of hardlinks') |
| 967 | parser.add_option( |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 968 | '--json', |
| 969 | help='dump output metadata to json file. When used, run_isolated returns ' |
| 970 | 'non-zero only on internal failure') |
maruel | 6be7f9e | 2015-10-01 12:25:30 -0700 | [diff] [blame] | 971 | parser.add_option( |
maruel | 5c9e47b | 2015-12-18 13:02:30 -0800 | [diff] [blame] | 972 | '--hard-timeout', type='float', help='Enforce hard timeout in execution') |
maruel | 6be7f9e | 2015-10-01 12:25:30 -0700 | [diff] [blame] | 973 | parser.add_option( |
maruel | 5c9e47b | 2015-12-18 13:02:30 -0800 | [diff] [blame] | 974 | '--grace-period', type='float', |
maruel | 6be7f9e | 2015-10-01 12:25:30 -0700 | [diff] [blame] | 975 | help='Grace period between SIGTERM and SIGKILL') |
bpastene | 3ae0952 | 2016-06-10 17:12:59 -0700 | [diff] [blame] | 976 | parser.add_option( |
| 977 | '--bot-file', |
| 978 | help='Path to a file describing the state of the host. The content is ' |
| 979 | 'defined by on_before_task() in bot_config.') |
aludwin | 7556e0c | 2016-10-26 08:46:10 -0700 | [diff] [blame] | 980 | parser.add_option( |
vadimsh | 8ec6682 | 2017-07-25 14:08:29 -0700 | [diff] [blame] | 981 | '--switch-to-account', |
| 982 | help='If given, switches LUCI_CONTEXT to given logical service account ' |
| 983 | '(e.g. "task" or "system") before launching the isolated process.') |
| 984 | parser.add_option( |
aludwin | 0a8e17d | 2016-10-27 15:57:39 -0700 | [diff] [blame] | 985 | '--output', action='append', |
| 986 | help='Specifies an output to return. If no outputs are specified, all ' |
| 987 | 'files located in $(ISOLATED_OUTDIR) will be returned; ' |
| 988 | 'otherwise, outputs in both $(ISOLATED_OUTDIR) and those ' |
| 989 | 'specified by --output option (there can be multiple) will be ' |
| 990 | 'returned. Note that if a file in OUT_DIR has the same path ' |
| 991 | 'as an --output option, the --output version will be returned.') |
| 992 | parser.add_option( |
aludwin | 7556e0c | 2016-10-26 08:46:10 -0700 | [diff] [blame] | 993 | '-a', '--argsfile', |
| 994 | # This is actually handled in parse_args; it's included here purely so it |
| 995 | # can make it into the help text. |
| 996 | help='Specify a file containing a JSON array of arguments to this ' |
| 997 | 'script. If --argsfile is provided, no other argument may be ' |
| 998 | 'provided on the command line.') |
Marc-Antoine Ruel | 1687b5e | 2014-02-06 17:47:53 -0500 | [diff] [blame] | 999 | data_group = optparse.OptionGroup(parser, 'Data source') |
| 1000 | data_group.add_option( |
Marc-Antoine Ruel | 185ded4 | 2015-01-28 20:49:18 -0500 | [diff] [blame] | 1001 | '-s', '--isolated', |
nodir | 55be77b | 2016-05-03 09:39:57 -0700 | [diff] [blame] | 1002 | help='Hash of the .isolated to grab from the isolate server.') |
Marc-Antoine Ruel | f7d737d | 2014-12-10 15:36:29 -0500 | [diff] [blame] | 1003 | isolateserver.add_isolate_server_options(data_group) |
Marc-Antoine Ruel | 1687b5e | 2014-02-06 17:47:53 -0500 | [diff] [blame] | 1004 | parser.add_option_group(data_group) |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1005 | |
Marc-Antoine Ruel | a57d7db | 2014-10-15 20:31:19 -0400 | [diff] [blame] | 1006 | isolateserver.add_cache_options(parser) |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 1007 | |
| 1008 | cipd.add_cipd_options(parser) |
nodir | f33b8d6 | 2016-10-26 22:34:58 -0700 | [diff] [blame] | 1009 | named_cache.add_named_cache_options(parser) |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1010 | |
Kenneth Russell | 61d4235 | 2014-09-15 11:41:16 -0700 | [diff] [blame] | 1011 | debug_group = optparse.OptionGroup(parser, 'Debugging') |
| 1012 | debug_group.add_option( |
| 1013 | '--leak-temp-dir', |
| 1014 | action='store_true', |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 1015 | help='Deliberately leak isolate\'s temp dir for later examination. ' |
| 1016 | 'Default: %default') |
maruel | eb5fbee | 2015-09-17 13:01:36 -0700 | [diff] [blame] | 1017 | debug_group.add_option( |
| 1018 | '--root-dir', help='Use a directory instead of a random one') |
Kenneth Russell | 61d4235 | 2014-09-15 11:41:16 -0700 | [diff] [blame] | 1019 | parser.add_option_group(debug_group) |
| 1020 | |
Vadim Shtayura | e34e13a | 2014-02-02 11:23:26 -0800 | [diff] [blame] | 1021 | auth.add_auth_options(parser) |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 1022 | |
nodir | f33b8d6 | 2016-10-26 22:34:58 -0700 | [diff] [blame] | 1023 | parser.set_defaults( |
| 1024 | cache='cache', |
| 1025 | cipd_cache='cipd_cache', |
| 1026 | named_cache_root='named_caches') |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 1027 | return parser |
| 1028 | |
| 1029 | |
aludwin | 7556e0c | 2016-10-26 08:46:10 -0700 | [diff] [blame] | 1030 | def parse_args(args): |
| 1031 | # Create a fake mini-parser just to get out the "-a" command. Note that |
| 1032 | # it's not documented here; instead, it's documented in create_option_parser |
| 1033 | # even though that parser will never actually get to parse it. This is |
| 1034 | # because --argsfile is exclusive with all other options and arguments. |
| 1035 | file_argparse = argparse.ArgumentParser(add_help=False) |
| 1036 | file_argparse.add_argument('-a', '--argsfile') |
| 1037 | (file_args, nonfile_args) = file_argparse.parse_known_args(args) |
| 1038 | if file_args.argsfile: |
| 1039 | if nonfile_args: |
| 1040 | file_argparse.error('Can\'t specify --argsfile with' |
| 1041 | 'any other arguments (%s)' % nonfile_args) |
| 1042 | try: |
| 1043 | with open(file_args.argsfile, 'r') as f: |
| 1044 | args = json.load(f) |
| 1045 | except (IOError, OSError, ValueError) as e: |
| 1046 | # We don't need to error out here - "args" is now empty, |
| 1047 | # so the call below to parser.parse_args(args) will fail |
| 1048 | # and print the full help text. |
| 1049 | print >> sys.stderr, 'Couldn\'t read arguments: %s' % e |
| 1050 | |
| 1051 | # Even if we failed to read the args, just call the normal parser now since it |
| 1052 | # will print the correct help message. |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 1053 | parser = create_option_parser() |
Marc-Antoine Ruel | 90c9816 | 2013-12-18 15:11:57 -0500 | [diff] [blame] | 1054 | options, args = parser.parse_args(args) |
aludwin | 7556e0c | 2016-10-26 08:46:10 -0700 | [diff] [blame] | 1055 | return (parser, options, args) |
| 1056 | |
| 1057 | |
| 1058 | def main(args): |
| 1059 | (parser, options, args) = parse_args(args) |
maruel | 36a963d | 2016-04-08 17:15:49 -0700 | [diff] [blame] | 1060 | |
Marc-Antoine Ruel | c7a332f | 2017-08-25 17:37:51 -0400 | [diff] [blame^] | 1061 | if not file_path.enable_symlink(): |
| 1062 | logging.error('Symlink support is not enabled') |
| 1063 | |
nodir | f33b8d6 | 2016-10-26 22:34:58 -0700 | [diff] [blame] | 1064 | isolate_cache = isolateserver.process_cache_options(options, trim=False) |
| 1065 | named_cache_manager = named_cache.process_named_cache_options(parser, options) |
maruel | 36a963d | 2016-04-08 17:15:49 -0700 | [diff] [blame] | 1066 | if options.clean: |
| 1067 | if options.isolated: |
| 1068 | parser.error('Can\'t use --isolated with --clean.') |
| 1069 | if options.isolate_server: |
| 1070 | parser.error('Can\'t use --isolate-server with --clean.') |
| 1071 | if options.json: |
| 1072 | parser.error('Can\'t use --json with --clean.') |
nodir | f33b8d6 | 2016-10-26 22:34:58 -0700 | [diff] [blame] | 1073 | if options.named_caches: |
| 1074 | parser.error('Can\t use --named-cache with --clean.') |
| 1075 | clean_caches(options, isolate_cache, named_cache_manager) |
maruel | 36a963d | 2016-04-08 17:15:49 -0700 | [diff] [blame] | 1076 | return 0 |
nodir | f33b8d6 | 2016-10-26 22:34:58 -0700 | [diff] [blame] | 1077 | |
maruel | 2e8d0f5 | 2016-07-16 07:51:29 -0700 | [diff] [blame] | 1078 | if not options.no_clean: |
nodir | f33b8d6 | 2016-10-26 22:34:58 -0700 | [diff] [blame] | 1079 | clean_caches(options, isolate_cache, named_cache_manager) |
maruel | 36a963d | 2016-04-08 17:15:49 -0700 | [diff] [blame] | 1080 | |
nodir | 55be77b | 2016-05-03 09:39:57 -0700 | [diff] [blame] | 1081 | if not options.isolated and not args: |
| 1082 | parser.error('--isolated or command to run is required.') |
| 1083 | |
Vadim Shtayura | 5d1efce | 2014-02-04 10:55:43 -0800 | [diff] [blame] | 1084 | auth.process_auth_options(parser, options) |
nodir | 55be77b | 2016-05-03 09:39:57 -0700 | [diff] [blame] | 1085 | |
| 1086 | isolateserver.process_isolate_server_options( |
Marc-Antoine Ruel | c7a332f | 2017-08-25 17:37:51 -0400 | [diff] [blame^] | 1087 | parser, options, True, False) |
nodir | 55be77b | 2016-05-03 09:39:57 -0700 | [diff] [blame] | 1088 | if not options.isolate_server: |
| 1089 | if options.isolated: |
| 1090 | parser.error('--isolated requires --isolate-server') |
| 1091 | if ISOLATED_OUTDIR_PARAMETER in args: |
| 1092 | parser.error( |
| 1093 | '%s in args requires --isolate-server' % ISOLATED_OUTDIR_PARAMETER) |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1094 | |
nodir | 90bc8dc | 2016-06-15 13:35:21 -0700 | [diff] [blame] | 1095 | if options.root_dir: |
| 1096 | options.root_dir = unicode(os.path.abspath(options.root_dir)) |
maruel | 12e3001 | 2015-10-09 11:55:35 -0700 | [diff] [blame] | 1097 | if options.json: |
| 1098 | options.json = unicode(os.path.abspath(options.json)) |
nodir | 55be77b | 2016-05-03 09:39:57 -0700 | [diff] [blame] | 1099 | |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 1100 | cipd.validate_cipd_options(parser, options) |
| 1101 | |
vadimsh | 232f5a8 | 2017-01-20 19:23:44 -0800 | [diff] [blame] | 1102 | install_packages_fn = noop_install_packages |
vadimsh | 902948e | 2017-01-20 15:57:32 -0800 | [diff] [blame] | 1103 | if options.cipd_enabled: |
iannucci | b58d10d | 2017-03-18 02:00:25 -0700 | [diff] [blame] | 1104 | install_packages_fn = lambda run_dir: install_client_and_packages( |
vadimsh | 902948e | 2017-01-20 15:57:32 -0800 | [diff] [blame] | 1105 | run_dir, cipd.parse_package_args(options.cipd_packages), |
| 1106 | options.cipd_server, options.cipd_client_package, |
| 1107 | options.cipd_client_version, cache_dir=options.cipd_cache) |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 1108 | |
nodir | d616068 | 2017-02-02 13:03:35 -0800 | [diff] [blame] | 1109 | @contextlib.contextmanager |
nodir | 26251c4 | 2017-05-11 13:21:53 -0700 | [diff] [blame] | 1110 | def install_named_caches(run_dir): |
nodir | d616068 | 2017-02-02 13:03:35 -0800 | [diff] [blame] | 1111 | # WARNING: this function depends on "options" variable defined in the outer |
| 1112 | # function. |
nodir | 26251c4 | 2017-05-11 13:21:53 -0700 | [diff] [blame] | 1113 | caches = [ |
| 1114 | (os.path.join(run_dir, unicode(relpath)), name) |
| 1115 | for name, relpath in options.named_caches |
| 1116 | ] |
nodir | f33b8d6 | 2016-10-26 22:34:58 -0700 | [diff] [blame] | 1117 | with named_cache_manager.open(): |
nodir | 26251c4 | 2017-05-11 13:21:53 -0700 | [diff] [blame] | 1118 | for path, name in caches: |
| 1119 | named_cache_manager.install(path, name) |
nodir | d616068 | 2017-02-02 13:03:35 -0800 | [diff] [blame] | 1120 | try: |
| 1121 | yield |
| 1122 | finally: |
dnj | d5e4ecc | 2017-07-07 11:16:44 -0700 | [diff] [blame] | 1123 | # Uninstall each named cache, returning it to the cache pool. If an |
| 1124 | # uninstall fails for a given cache, it will remain in the task's |
| 1125 | # temporary space, get cleaned up by the Swarming bot, and be lost. |
| 1126 | # |
| 1127 | # If the Swarming bot cannot clean up the cache, it will handle it like |
| 1128 | # any other bot file that could not be removed. |
nodir | 26251c4 | 2017-05-11 13:21:53 -0700 | [diff] [blame] | 1129 | with named_cache_manager.open(): |
| 1130 | for path, name in caches: |
dnj | d5e4ecc | 2017-07-07 11:16:44 -0700 | [diff] [blame] | 1131 | try: |
| 1132 | named_cache_manager.uninstall(path, name) |
| 1133 | except named_cache.Error: |
| 1134 | logging.exception('Error while removing named cache %r at %r. ' |
| 1135 | 'The cache will be lost.', path, name) |
nodir | f33b8d6 | 2016-10-26 22:34:58 -0700 | [diff] [blame] | 1136 | |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 1137 | try: |
nodir | 90bc8dc | 2016-06-15 13:35:21 -0700 | [diff] [blame] | 1138 | if options.isolate_server: |
| 1139 | storage = isolateserver.get_storage( |
| 1140 | options.isolate_server, options.namespace) |
| 1141 | with storage: |
nodir | f33b8d6 | 2016-10-26 22:34:58 -0700 | [diff] [blame] | 1142 | # Hashing schemes used by |storage| and |isolate_cache| MUST match. |
| 1143 | assert storage.hash_algo == isolate_cache.hash_algo |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 1144 | return run_tha_test( |
maruel | abec63c | 2017-04-26 11:53:24 -0700 | [diff] [blame] | 1145 | args, |
nodir | f33b8d6 | 2016-10-26 22:34:58 -0700 | [diff] [blame] | 1146 | options.isolated, |
| 1147 | storage, |
| 1148 | isolate_cache, |
aludwin | 0a8e17d | 2016-10-27 15:57:39 -0700 | [diff] [blame] | 1149 | options.output, |
nodir | 26251c4 | 2017-05-11 13:21:53 -0700 | [diff] [blame] | 1150 | install_named_caches, |
nodir | f33b8d6 | 2016-10-26 22:34:58 -0700 | [diff] [blame] | 1151 | options.leak_temp_dir, |
| 1152 | options.json, options.root_dir, |
| 1153 | options.hard_timeout, |
| 1154 | options.grace_period, |
maruel | abec63c | 2017-04-26 11:53:24 -0700 | [diff] [blame] | 1155 | options.bot_file, |
vadimsh | 8ec6682 | 2017-07-25 14:08:29 -0700 | [diff] [blame] | 1156 | options.switch_to_account, |
nodir | f33b8d6 | 2016-10-26 22:34:58 -0700 | [diff] [blame] | 1157 | install_packages_fn, |
| 1158 | options.use_symlinks) |
maruel | 4409e30 | 2016-07-19 14:25:51 -0700 | [diff] [blame] | 1159 | return run_tha_test( |
maruel | abec63c | 2017-04-26 11:53:24 -0700 | [diff] [blame] | 1160 | args, |
nodir | f33b8d6 | 2016-10-26 22:34:58 -0700 | [diff] [blame] | 1161 | options.isolated, |
| 1162 | None, |
| 1163 | isolate_cache, |
aludwin | 0a8e17d | 2016-10-27 15:57:39 -0700 | [diff] [blame] | 1164 | options.output, |
nodir | 26251c4 | 2017-05-11 13:21:53 -0700 | [diff] [blame] | 1165 | install_named_caches, |
nodir | f33b8d6 | 2016-10-26 22:34:58 -0700 | [diff] [blame] | 1166 | options.leak_temp_dir, |
| 1167 | options.json, |
| 1168 | options.root_dir, |
| 1169 | options.hard_timeout, |
| 1170 | options.grace_period, |
maruel | abec63c | 2017-04-26 11:53:24 -0700 | [diff] [blame] | 1171 | options.bot_file, |
vadimsh | 8ec6682 | 2017-07-25 14:08:29 -0700 | [diff] [blame] | 1172 | options.switch_to_account, |
nodir | f33b8d6 | 2016-10-26 22:34:58 -0700 | [diff] [blame] | 1173 | install_packages_fn, |
maruel | 4409e30 | 2016-07-19 14:25:51 -0700 | [diff] [blame] | 1174 | options.use_symlinks) |
nodir | f33b8d6 | 2016-10-26 22:34:58 -0700 | [diff] [blame] | 1175 | except (cipd.Error, named_cache.Error) as ex: |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 1176 | print >> sys.stderr, ex.message |
| 1177 | return 1 |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1178 | |
| 1179 | |
| 1180 | if __name__ == '__main__': |
maruel | 8e4e40c | 2016-05-30 06:21:07 -0700 | [diff] [blame] | 1181 | subprocess42.inhibit_os_error_reporting() |
csharp@chromium.org | bfb9874 | 2013-03-26 20:28:36 +0000 | [diff] [blame] | 1182 | # Ensure that we are always running with the correct encoding. |
vadimsh@chromium.org | a432647 | 2013-08-24 02:05:41 +0000 | [diff] [blame] | 1183 | fix_encoding.fix_encoding() |
Marc-Antoine Ruel | 90c9816 | 2013-12-18 15:11:57 -0500 | [diff] [blame] | 1184 | sys.exit(main(sys.argv[1:])) |