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 | |
Marc-Antoine Ruel | eed2f3a | 2019-03-14 00:00:40 +0000 | [diff] [blame] | 8 | run_isolated takes cares of setting up a temporary environment, running a |
| 9 | command, and tearing it down. |
nodir | 55be77b | 2016-05-03 09:39:57 -0700 | [diff] [blame] | 10 | |
Marc-Antoine Ruel | eed2f3a | 2019-03-14 00:00:40 +0000 | [diff] [blame] | 11 | It handles downloading and uploading isolated files, mapping CIPD packages and |
| 12 | reusing stateful named caches. |
| 13 | |
| 14 | The isolated files, CIPD packages and named caches are kept as a global LRU |
| 15 | cache. |
Marc-Antoine Ruel | 2283ad1 | 2014-02-09 11:14:57 -0500 | [diff] [blame] | 16 | |
Roberto Carrillo | 71ade6d | 2018-10-08 22:30:24 +0000 | [diff] [blame] | 17 | Any ${EXECUTABLE_SUFFIX} on the command line or the environment variables passed |
| 18 | with the --env option will be replaced with ".exe" string on Windows and "" on |
| 19 | other platforms. |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 20 | |
Roberto Carrillo | 71ade6d | 2018-10-08 22:30:24 +0000 | [diff] [blame] | 21 | Any ${ISOLATED_OUTDIR} on the command line or the environment variables passed |
| 22 | with the --env option will be replaced by the location of a temporary directory |
| 23 | upon execution of the command specified in the .isolated file. All content |
| 24 | written to this directory will be uploaded upon termination and the .isolated |
| 25 | file describing this directory will be printed to stdout. |
bpastene | 447c199 | 2016-06-20 15:21:47 -0700 | [diff] [blame] | 26 | |
Marc-Antoine Ruel | eed2f3a | 2019-03-14 00:00:40 +0000 | [diff] [blame] | 27 | Any ${SWARMING_BOT_FILE} on the command line or the environment variables passed |
| 28 | with the --env option will be replaced by the value of the --bot-file parameter. |
| 29 | This file is used by a swarming bot to communicate state of the host to tasks. |
| 30 | It is written to by the swarming bot's on_before_task() hook in the swarming |
| 31 | server's custom bot_config.py. |
| 32 | |
Joanna Wang | 4cec0e4 | 2021-08-26 00:48:37 +0000 | [diff] [blame] | 33 | Any ${SWARMING_TASK_ID} on the command line will be replaced by the |
| 34 | SWARMING_TASK_ID value passed with the --env option. |
| 35 | |
Marc-Antoine Ruel | eed2f3a | 2019-03-14 00:00:40 +0000 | [diff] [blame] | 36 | See |
| 37 | https://chromium.googlesource.com/infra/luci/luci-py.git/+/master/appengine/swarming/doc/Magic-Values.md |
| 38 | for all the variables. |
| 39 | |
| 40 | See |
| 41 | https://chromium.googlesource.com/infra/luci/luci-py.git/+/master/appengine/swarming/swarming_bot/config/bot_config.py |
| 42 | for more information about bot_config.py. |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 43 | """ |
| 44 | |
Marc-Antoine Ruel | f899c48 | 2019-10-10 23:32:06 +0000 | [diff] [blame] | 45 | from __future__ import print_function |
| 46 | |
| 47 | __version__ = '1.0.1' |
maruel@chromium.org | dedbf49 | 2013-09-12 20:42:11 +0000 | [diff] [blame] | 48 | |
aludwin | 7556e0c | 2016-10-26 08:46:10 -0700 | [diff] [blame] | 49 | import argparse |
maruel | 064c0a3 | 2016-04-05 11:47:15 -0700 | [diff] [blame] | 50 | import base64 |
iannucci | 96fcccc | 2016-08-30 15:52:22 -0700 | [diff] [blame] | 51 | import collections |
vadimsh | 232f5a8 | 2017-01-20 19:23:44 -0800 | [diff] [blame] | 52 | import contextlib |
Ye Kuang | fff1e50 | 2020-07-13 13:21:57 +0000 | [diff] [blame] | 53 | import distutils |
Sadaf Matinkhoo | 10743a6 | 2018-03-29 16:28:58 -0400 | [diff] [blame] | 54 | import errno |
aludwin | 7556e0c | 2016-10-26 08:46:10 -0700 | [diff] [blame] | 55 | import json |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 56 | import logging |
| 57 | import optparse |
| 58 | import os |
Takuto Ikuta | 5c59a84 | 2020-01-24 03:05:24 +0000 | [diff] [blame] | 59 | import platform |
Marc-Antoine Ruel | 8b11dbd | 2018-05-18 14:31:22 -0400 | [diff] [blame] | 60 | import re |
Junji Watanabe | dc2f89e | 2021-11-08 08:44:30 +0000 | [diff] [blame] | 61 | import shutil |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 62 | import sys |
| 63 | import tempfile |
maruel | 064c0a3 | 2016-04-05 11:47:15 -0700 | [diff] [blame] | 64 | import time |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 65 | |
Marc-Antoine Ruel | 016c760 | 2019-04-02 18:31:13 +0000 | [diff] [blame] | 66 | from utils import tools |
| 67 | tools.force_local_third_party() |
vadimsh@chromium.org | a432647 | 2013-08-24 02:05:41 +0000 | [diff] [blame] | 68 | |
Marc-Antoine Ruel | 016c760 | 2019-04-02 18:31:13 +0000 | [diff] [blame] | 69 | # third_party/ |
| 70 | from depot_tools import fix_encoding |
| 71 | |
| 72 | # pylint: disable=ungrouped-imports |
Takuto Ikuta | d53d7bd | 2021-07-16 03:09:33 +0000 | [diff] [blame] | 73 | import DEPS |
Marc-Antoine Ruel | 016c760 | 2019-04-02 18:31:13 +0000 | [diff] [blame] | 74 | import auth |
| 75 | import cipd |
Marc-Antoine Ruel | 016c760 | 2019-04-02 18:31:13 +0000 | [diff] [blame] | 76 | import local_caching |
| 77 | from libs import luci_context |
Vadim Shtayura | 6b555c1 | 2014-07-23 16:22:18 -0700 | [diff] [blame] | 78 | from utils import file_path |
maruel | 12e3001 | 2015-10-09 11:55:35 -0700 | [diff] [blame] | 79 | from utils import fs |
Marc-Antoine Ruel | f74cffe | 2015-07-15 15:21:34 -0400 | [diff] [blame] | 80 | from utils import logging_utils |
Ye Kuang | 2dd1744 | 2020-04-22 08:45:52 +0000 | [diff] [blame] | 81 | from utils import net |
Marc-Antoine Ruel | cfb6085 | 2014-07-02 15:22:00 -0400 | [diff] [blame] | 82 | from utils import on_error |
Marc-Antoine Ruel | c44f572 | 2015-01-08 16:10:01 -0500 | [diff] [blame] | 83 | from utils import subprocess42 |
maruel@chromium.org | dedbf49 | 2013-09-12 20:42:11 +0000 | [diff] [blame] | 84 | |
vadimsh@chromium.org | a432647 | 2013-08-24 02:05:41 +0000 | [diff] [blame] | 85 | |
maruel | e2f2cb8 | 2016-07-13 14:41:03 -0700 | [diff] [blame] | 86 | # Magic variables that can be found in the isolate task command line. |
| 87 | ISOLATED_OUTDIR_PARAMETER = '${ISOLATED_OUTDIR}' |
| 88 | EXECUTABLE_SUFFIX_PARAMETER = '${EXECUTABLE_SUFFIX}' |
| 89 | SWARMING_BOT_FILE_PARAMETER = '${SWARMING_BOT_FILE}' |
Joanna Wang | 4cec0e4 | 2021-08-26 00:48:37 +0000 | [diff] [blame] | 90 | SWARMING_TASK_ID_PARAMETER = '${SWARMING_TASK_ID}' |
maruel | e2f2cb8 | 2016-07-13 14:41:03 -0700 | [diff] [blame] | 91 | |
| 92 | |
csharp@chromium.org | ff2a466 | 2012-11-21 20:49:32 +0000 | [diff] [blame] | 93 | # The name of the log file to use. |
| 94 | RUN_ISOLATED_LOG_FILE = 'run_isolated.log' |
| 95 | |
maruel | e2f2cb8 | 2016-07-13 14:41:03 -0700 | [diff] [blame] | 96 | |
maruel | e2f2cb8 | 2016-07-13 14:41:03 -0700 | [diff] [blame] | 97 | # Use short names for temporary directories. This is driven by Windows, which |
| 98 | # imposes a relatively short maximum path length of 260 characters, often |
| 99 | # referred to as MAX_PATH. It is relatively easy to create files with longer |
Marc-Antoine Ruel | 793bff3 | 2019-04-18 17:50:48 +0000 | [diff] [blame] | 100 | # path length. A use case is with recursive dependency trees like npm packages. |
maruel | e2f2cb8 | 2016-07-13 14:41:03 -0700 | [diff] [blame] | 101 | # |
| 102 | # It is recommended to start the script with a `root_dir` as short as |
| 103 | # possible. |
| 104 | # - ir stands for isolated_run |
| 105 | # - io stands for isolated_out |
| 106 | # - it stands for isolated_tmp |
Takuto Ikuta | b7ce0e3 | 2019-11-27 23:26:18 +0000 | [diff] [blame] | 107 | # - ic stands for isolated_client |
Anirudh Mathukumilli | 92d57b6 | 2021-08-04 23:21:57 +0000 | [diff] [blame] | 108 | # - ns stands for nsjail |
Junji Watanabe | 53d3188 | 2022-01-13 07:58:00 +0000 | [diff] [blame] | 109 | ISOLATED_RUN_DIR = 'ir' |
| 110 | ISOLATED_OUT_DIR = 'io' |
| 111 | ISOLATED_TMP_DIR = 'it' |
| 112 | ISOLATED_CLIENT_DIR = 'ic' |
| 113 | _CAS_CLIENT_DIR = 'cc' |
| 114 | _NSJAIL_DIR = 'ns' |
maruel | e2f2cb8 | 2016-07-13 14:41:03 -0700 | [diff] [blame] | 115 | |
Takuto Ikuta | 02edca2 | 2019-11-29 10:04:51 +0000 | [diff] [blame] | 116 | # TODO(tikuta): take these parameter from luci-config? |
Junji Watanabe | 4b890ef | 2020-09-16 01:43:27 +0000 | [diff] [blame] | 117 | _CAS_PACKAGE = 'infra/tools/luci/cas/${platform}' |
Takuto Ikuta | d53d7bd | 2021-07-16 03:09:33 +0000 | [diff] [blame] | 118 | _LUCI_GO_REVISION = DEPS.deps['luci-go']['packages'][0]['version'] |
Anirudh Mathukumilli | 92d57b6 | 2021-08-04 23:21:57 +0000 | [diff] [blame] | 119 | _NSJAIL_PACKAGE = 'infra/3pp/tools/nsjail/${platform}' |
| 120 | _NSJAIL_VERSION = DEPS.deps['nsjail']['packages'][0]['version'] |
maruel | e2f2cb8 | 2016-07-13 14:41:03 -0700 | [diff] [blame] | 121 | |
Marc-Antoine Ruel | 8b11dbd | 2018-05-18 14:31:22 -0400 | [diff] [blame] | 122 | # Keep synced with task_request.py |
Lei Lei | fe202df | 2019-06-11 17:33:34 +0000 | [diff] [blame] | 123 | CACHE_NAME_RE = re.compile(r'^[a-z0-9_]{1,4096}$') |
Marc-Antoine Ruel | 8b11dbd | 2018-05-18 14:31:22 -0400 | [diff] [blame] | 124 | |
Takuto Ikuta | c9ddff2 | 2021-02-18 07:58:39 +0000 | [diff] [blame] | 125 | _FREE_SPACE_BUFFER_FOR_CIPD_PACKAGES = 2 * 1024 * 1024 * 1024 |
Marc-Antoine Ruel | 8b11dbd | 2018-05-18 14:31:22 -0400 | [diff] [blame] | 126 | |
maruel | d928c86 | 2017-06-08 08:20:04 -0700 | [diff] [blame] | 127 | OUTLIVING_ZOMBIE_MSG = """\ |
| 128 | *** Swarming tried multiple times to delete the %s directory and failed *** |
| 129 | *** Hard failing the task *** |
| 130 | |
| 131 | Swarming detected that your testing script ran an executable, which may have |
| 132 | started a child executable, and the main script returned early, leaving the |
| 133 | children executables playing around unguided. |
| 134 | |
| 135 | You don't want to leave children processes outliving the task on the Swarming |
| 136 | bot, do you? The Swarming bot doesn't. |
| 137 | |
| 138 | How to fix? |
| 139 | - For any process that starts children processes, make sure all children |
| 140 | processes terminated properly before each parent process exits. This is |
| 141 | especially important in very deep process trees. |
| 142 | - This must be done properly both in normal successful task and in case of |
| 143 | task failure. Cleanup is very important. |
| 144 | - The Swarming bot sends a SIGTERM in case of timeout. |
| 145 | - You have %s seconds to comply after the signal was sent to the process |
| 146 | before the process is forcibly killed. |
| 147 | - To achieve not leaking children processes in case of signals on timeout, you |
| 148 | MUST handle signals in each executable / python script and propagate them to |
| 149 | children processes. |
| 150 | - When your test script (python or binary) receives a signal like SIGTERM or |
| 151 | CTRL_BREAK_EVENT on Windows), send it to all children processes and wait for |
| 152 | them to terminate before quitting. |
| 153 | |
| 154 | See |
Marc-Antoine Ruel | c724359 | 2018-05-24 17:04:04 -0400 | [diff] [blame] | 155 | https://chromium.googlesource.com/infra/luci/luci-py.git/+/master/appengine/swarming/doc/Bot.md#Graceful-termination_aka-the-SIGTERM-and-SIGKILL-dance |
maruel | d928c86 | 2017-06-08 08:20:04 -0700 | [diff] [blame] | 156 | for more information. |
| 157 | |
| 158 | *** May the SIGKILL force be with you *** |
| 159 | """ |
| 160 | |
| 161 | |
Marc-Antoine Ruel | 5d7606b | 2018-06-15 19:06:12 +0000 | [diff] [blame] | 162 | # Currently hardcoded. Eventually could be exposed as a flag once there's value. |
| 163 | # 3 weeks |
| 164 | MAX_AGE_SECS = 21*24*60*60 |
| 165 | |
Takuto Ikuta | 7ff4b24 | 2020-12-03 08:07:06 +0000 | [diff] [blame] | 166 | _CAS_KVS_CACHE_THRESHOLD = 5 * 1024 * 1024 * 1024 # 5 GiB |
| 167 | |
Marc-Antoine Ruel | 7de5259 | 2017-12-07 10:41:12 -0500 | [diff] [blame] | 168 | TaskData = collections.namedtuple( |
Marc-Antoine Ruel | 03c6fd1 | 2019-04-30 12:12:55 +0000 | [diff] [blame] | 169 | 'TaskData', |
| 170 | [ |
Takuto Ikuta | 9a31950 | 2019-11-26 07:40:14 +0000 | [diff] [blame] | 171 | # List of strings; the command line to use, independent of what was |
| 172 | # specified in the isolated file. |
| 173 | 'command', |
| 174 | # Relative directory to start command into. |
| 175 | 'relative_cwd', |
Junji Watanabe | 54925c3 | 2020-09-08 00:56:18 +0000 | [diff] [blame] | 176 | # Digest of the input root on RBE-CAS. |
| 177 | 'cas_digest', |
| 178 | # Full CAS instance name. |
| 179 | 'cas_instance', |
Takuto Ikuta | 9a31950 | 2019-11-26 07:40:14 +0000 | [diff] [blame] | 180 | # List of paths relative to root_dir to put into the output isolated |
| 181 | # bundle upon task completion (see link_outputs_to_outdir). |
| 182 | 'outputs', |
| 183 | # Function (run_dir) => context manager that installs named caches into |
| 184 | # |run_dir|. |
| 185 | 'install_named_caches', |
| 186 | # If True, the temporary directory will be deliberately leaked for later |
| 187 | # examination. |
| 188 | 'leak_temp_dir', |
| 189 | # Path to the directory to use to create the temporary directory. If not |
| 190 | # specified, a random temporary directory is created. |
| 191 | 'root_dir', |
| 192 | # Kills the process if it lasts more than this amount of seconds. |
| 193 | 'hard_timeout', |
| 194 | # Number of seconds to wait between SIGTERM and SIGKILL. |
| 195 | 'grace_period', |
| 196 | # Path to a file with bot state, used in place of ${SWARMING_BOT_FILE} |
| 197 | # task command line argument. |
| 198 | 'bot_file', |
| 199 | # Logical account to switch LUCI_CONTEXT into. |
| 200 | 'switch_to_account', |
| 201 | # Context manager dir => CipdInfo, see install_client_and_packages. |
| 202 | 'install_packages_fn', |
Junji Watanabe | b03450b | 2020-09-25 05:09:27 +0000 | [diff] [blame] | 203 | # Cache directory for `cas` client. |
| 204 | 'cas_cache_dir', |
| 205 | # Parameters passed to `cas` client. |
| 206 | 'cas_cache_policies', |
Takuto Ikuta | ae391c5 | 2020-12-03 08:43:45 +0000 | [diff] [blame] | 207 | # Parameters for kvs file used by `cas` client. |
| 208 | 'cas_kvs', |
Takuto Ikuta | 9a31950 | 2019-11-26 07:40:14 +0000 | [diff] [blame] | 209 | # Environment variables to set. |
| 210 | 'env', |
| 211 | # Environment variables to mutate with relative directories. |
| 212 | # Example: {"ENV_KEY": ['relative', 'paths', 'to', 'prepend']} |
| 213 | 'env_prefix', |
| 214 | # Lowers the task process priority. |
| 215 | 'lower_priority', |
| 216 | # subprocess42.Containment instance. Can be None. |
| 217 | 'containment', |
Junji Watanabe | aee69ad | 2021-04-28 03:17:34 +0000 | [diff] [blame] | 218 | # Function to trim caches before installing cipd packages and |
| 219 | # downloading isolated files. |
| 220 | 'trim_caches_fn', |
Marc-Antoine Ruel | 03c6fd1 | 2019-04-30 12:12:55 +0000 | [diff] [blame] | 221 | ]) |
Marc-Antoine Ruel | 7de5259 | 2017-12-07 10:41:12 -0500 | [diff] [blame] | 222 | |
| 223 | |
Justin Luong | 54fa959 | 2022-08-11 03:44:40 +0000 | [diff] [blame^] | 224 | class NonRecoverableException(Exception): |
| 225 | """For handling errors where we cannot recover from and should not retry.""" |
| 226 | |
| 227 | def __init__(self, status, msg): |
| 228 | super(Exception, self).__init__(msg) |
| 229 | self.status = status |
| 230 | |
| 231 | def to_dict(self): |
| 232 | """Returns a dictionary with the attributes serialised.""" |
| 233 | raise NotImplementedError() |
| 234 | |
| 235 | |
| 236 | class NonRetriableCasException(NonRecoverableException): |
| 237 | """For handling a bad CAS input where we should not attempt to retry.""" |
| 238 | |
| 239 | def __init__(self, status, digest, instance): |
| 240 | super(NonRetriableCasException, self).__init__( |
| 241 | status, "CAS error: {} with digest {} on instance {}".format( |
| 242 | status, digest, instance)) |
| 243 | self.digest = digest |
| 244 | self.instance = instance |
| 245 | |
| 246 | def to_dict(self): |
| 247 | return { |
| 248 | 'status': self.status, |
| 249 | 'digest': self.digest, |
| 250 | 'instance': self.instance, |
| 251 | } |
| 252 | |
| 253 | |
| 254 | class NonRetriableCipdException(NonRecoverableException): |
| 255 | """For handling a bad CIPD package where we should not attempt to retry.""" |
| 256 | |
| 257 | def __init__(self, status, package_name, path, version): |
| 258 | super(NonRetriableCipdException, self).__init__( |
| 259 | status, "CIPD error: {} with package {}, version {} on path {}".format( |
| 260 | status, package_name, version, path)) |
| 261 | self.package_name = package_name |
| 262 | self.path = path |
| 263 | self.version = version |
| 264 | |
| 265 | def to_dict(self): |
| 266 | return { |
| 267 | 'status': self.status, |
| 268 | 'package_name': self.package_name, |
| 269 | 'path': self.path, |
| 270 | 'version': self.version |
| 271 | } |
| 272 | |
| 273 | |
maruel | 03e1184 | 2016-07-14 10:50:16 -0700 | [diff] [blame] | 274 | def make_temp_dir(prefix, root_dir): |
| 275 | """Returns a new unique temporary directory.""" |
Junji Watanabe | 7a631b0 | 2022-01-13 02:30:29 +0000 | [diff] [blame] | 276 | return tempfile.mkdtemp(prefix=prefix, dir=root_dir) |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 277 | |
| 278 | |
vadimsh | 9c54b2c | 2017-07-25 14:08:29 -0700 | [diff] [blame] | 279 | @contextlib.contextmanager |
| 280 | def set_luci_context_account(account, tmp_dir): |
| 281 | """Sets LUCI_CONTEXT account to be used by the task. |
| 282 | |
| 283 | If 'account' is None or '', does nothing at all. This happens when |
| 284 | run_isolated.py is called without '--switch-to-account' flag. In this case, |
| 285 | if run_isolated.py is running in some LUCI_CONTEXT environment, the task will |
Takuto Ikuta | 33e2ff3 | 2019-09-30 12:44:03 +0000 | [diff] [blame] | 286 | just inherit whatever account is already set. This may happen if users invoke |
vadimsh | 9c54b2c | 2017-07-25 14:08:29 -0700 | [diff] [blame] | 287 | run_isolated.py explicitly from their code. |
| 288 | |
| 289 | If the requested account is not defined in the context, switches to |
| 290 | non-authenticated access. This happens for Swarming tasks that don't use |
| 291 | 'task' service accounts. |
| 292 | |
| 293 | If not using LUCI_CONTEXT-based auth, does nothing. |
| 294 | If already running as requested account, does nothing. |
| 295 | """ |
| 296 | if not account: |
| 297 | # Not actually switching. |
| 298 | yield |
| 299 | return |
| 300 | |
| 301 | local_auth = luci_context.read('local_auth') |
| 302 | if not local_auth: |
| 303 | # Not using LUCI_CONTEXT auth at all. |
| 304 | yield |
| 305 | return |
| 306 | |
| 307 | # See LUCI_CONTEXT.md for the format of 'local_auth'. |
| 308 | if local_auth.get('default_account_id') == account: |
| 309 | # Already set, no need to switch. |
| 310 | yield |
| 311 | return |
| 312 | |
| 313 | available = {a['id'] for a in local_auth.get('accounts') or []} |
| 314 | if account in available: |
| 315 | logging.info('Switching default LUCI_CONTEXT account to %r', account) |
| 316 | local_auth['default_account_id'] = account |
| 317 | else: |
| 318 | logging.warning( |
| 319 | 'Requested LUCI_CONTEXT account %r is not available (have only %r), ' |
| 320 | 'disabling authentication', account, sorted(available)) |
| 321 | local_auth.pop('default_account_id', None) |
| 322 | |
| 323 | with luci_context.write(_tmpdir=tmp_dir, local_auth=local_auth): |
| 324 | yield |
| 325 | |
| 326 | |
nodir | 90bc8dc | 2016-06-15 13:35:21 -0700 | [diff] [blame] | 327 | def process_command(command, out_dir, bot_file): |
Roberto Carrillo | 71ade6d | 2018-10-08 22:30:24 +0000 | [diff] [blame] | 328 | """Replaces parameters in a command line. |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 329 | |
| 330 | Raises: |
| 331 | ValueError if a parameter is requested in |command| but its value is not |
| 332 | provided. |
| 333 | """ |
Roberto Carrillo | 71ade6d | 2018-10-08 22:30:24 +0000 | [diff] [blame] | 334 | return [replace_parameters(arg, out_dir, bot_file) for arg in command] |
| 335 | |
| 336 | |
| 337 | def replace_parameters(arg, out_dir, bot_file): |
| 338 | """Replaces parameter tokens with appropriate values in a string. |
| 339 | |
| 340 | Raises: |
| 341 | ValueError if a parameter is requested in |arg| but its value is not |
| 342 | provided. |
| 343 | """ |
| 344 | arg = arg.replace(EXECUTABLE_SUFFIX_PARAMETER, cipd.EXECUTABLE_SUFFIX) |
| 345 | replace_slash = False |
| 346 | if ISOLATED_OUTDIR_PARAMETER in arg: |
| 347 | if not out_dir: |
| 348 | raise ValueError( |
| 349 | 'output directory is requested in command or env var, but not ' |
| 350 | 'provided; please specify one') |
| 351 | arg = arg.replace(ISOLATED_OUTDIR_PARAMETER, out_dir) |
| 352 | replace_slash = True |
| 353 | if SWARMING_BOT_FILE_PARAMETER in arg: |
| 354 | if bot_file: |
| 355 | arg = arg.replace(SWARMING_BOT_FILE_PARAMETER, bot_file) |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 356 | replace_slash = True |
Roberto Carrillo | 71ade6d | 2018-10-08 22:30:24 +0000 | [diff] [blame] | 357 | else: |
| 358 | logging.warning('SWARMING_BOT_FILE_PARAMETER found in command or env ' |
| 359 | 'var, but no bot_file specified. Leaving parameter ' |
| 360 | 'unchanged.') |
Joanna Wang | 4cec0e4 | 2021-08-26 00:48:37 +0000 | [diff] [blame] | 361 | if SWARMING_TASK_ID_PARAMETER in arg: |
| 362 | task_id = os.environ.get('SWARMING_TASK_ID') |
| 363 | if task_id: |
| 364 | arg = arg.replace(SWARMING_TASK_ID_PARAMETER, task_id) |
Roberto Carrillo | 71ade6d | 2018-10-08 22:30:24 +0000 | [diff] [blame] | 365 | if replace_slash: |
| 366 | # Replace slashes only if parameters are present |
| 367 | # because of arguments like '${ISOLATED_OUTDIR}/foo/bar' |
| 368 | arg = arg.replace('/', os.sep) |
| 369 | return arg |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 370 | |
| 371 | |
Takuto Ikuta | 0f8a19c | 2021-03-02 00:50:38 +0000 | [diff] [blame] | 372 | def set_temp_dir(env, tmp_dir): |
| 373 | """Set temp dir to given env var dictionary""" |
Takuto Ikuta | 0f8a19c | 2021-03-02 00:50:38 +0000 | [diff] [blame] | 374 | # pylint: disable=line-too-long |
| 375 | # * python respects $TMPDIR, $TEMP, and $TMP in this order, regardless of |
| 376 | # platform. So $TMPDIR must be set on all platforms. |
| 377 | # https://github.com/python/cpython/blob/2.7/Lib/tempfile.py#L155 |
| 378 | env['TMPDIR'] = tmp_dir |
| 379 | if sys.platform == 'win32': |
| 380 | # * chromium's base utils uses GetTempPath(). |
| 381 | # https://cs.chromium.org/chromium/src/base/files/file_util_win.cc?q=GetTempPath |
| 382 | # * Go uses GetTempPath(). |
| 383 | # * GetTempDir() uses %TMP%, then %TEMP%, then other stuff. So %TMP% must be |
| 384 | # set. |
| 385 | # https://docs.microsoft.com/en-us/windows/desktop/api/fileapi/nf-fileapi-gettemppathw |
| 386 | env['TMP'] = tmp_dir |
| 387 | # https://blogs.msdn.microsoft.com/oldnewthing/20150417-00/?p=44213 |
| 388 | env['TEMP'] = tmp_dir |
| 389 | elif sys.platform == 'darwin': |
| 390 | # * Chromium uses an hack on macOS before calling into |
| 391 | # NSTemporaryDirectory(). |
| 392 | # https://cs.chromium.org/chromium/src/base/files/file_util_mac.mm?q=GetTempDir |
| 393 | # https://developer.apple.com/documentation/foundation/1409211-nstemporarydirectory |
| 394 | env['MAC_CHROMIUM_TMPDIR'] = tmp_dir |
| 395 | else: |
| 396 | # TMPDIR is specified as the POSIX standard envvar for the temp directory. |
| 397 | # http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html |
| 398 | # * mktemp on linux respects $TMPDIR. |
| 399 | # * Chromium respects $TMPDIR on linux. |
| 400 | # https://cs.chromium.org/chromium/src/base/files/file_util_posix.cc?q=GetTempDir |
| 401 | # * Go uses $TMPDIR. |
| 402 | # https://go.googlesource.com/go/+/go1.10.3/src/os/file_unix.go#307 |
| 403 | pass |
| 404 | |
Roberto Carrillo | 71ade6d | 2018-10-08 22:30:24 +0000 | [diff] [blame] | 405 | |
| 406 | def get_command_env(tmp_dir, cipd_info, run_dir, env, env_prefixes, out_dir, |
| 407 | bot_file): |
vadimsh | 232f5a8 | 2017-01-20 19:23:44 -0800 | [diff] [blame] | 408 | """Returns full OS environment to run a command in. |
| 409 | |
Robert Iannucci | bf5f84c | 2017-11-22 12:56:50 -0800 | [diff] [blame] | 410 | Sets up TEMP, puts directory with cipd binary in front of PATH, exposes |
| 411 | CIPD_CACHE_DIR env var, and installs all env_prefixes. |
vadimsh | 232f5a8 | 2017-01-20 19:23:44 -0800 | [diff] [blame] | 412 | |
| 413 | Args: |
| 414 | tmp_dir: temp directory. |
| 415 | cipd_info: CipdInfo object is cipd client is used, None if not. |
Marc-Antoine Ruel | 9ec1e9f | 2017-12-20 16:36:54 -0500 | [diff] [blame] | 416 | run_dir: The root directory the isolated tree is mapped in. |
Marc-Antoine Ruel | 19dd887 | 2017-11-28 18:33:39 -0500 | [diff] [blame] | 417 | env: environment variables to use |
Robert Iannucci | bf5f84c | 2017-11-22 12:56:50 -0800 | [diff] [blame] | 418 | env_prefixes: {"ENV_KEY": ['cwd', 'relative', 'paths', 'to', 'prepend']} |
Roberto Carrillo | 71ade6d | 2018-10-08 22:30:24 +0000 | [diff] [blame] | 419 | out_dir: Isolated output directory. Required to be != None if any of the |
| 420 | env vars contain ISOLATED_OUTDIR_PARAMETER. |
| 421 | bot_file: Required to be != None if any of the env vars contain |
| 422 | SWARMING_BOT_FILE_PARAMETER. |
vadimsh | 232f5a8 | 2017-01-20 19:23:44 -0800 | [diff] [blame] | 423 | """ |
Marc-Antoine Ruel | 19dd887 | 2017-11-28 18:33:39 -0500 | [diff] [blame] | 424 | out = os.environ.copy() |
Marc-Antoine Ruel | 04903a3 | 2019-10-09 21:09:25 +0000 | [diff] [blame] | 425 | for k, v in env.items(): |
Marc-Antoine Ruel | 19dd887 | 2017-11-28 18:33:39 -0500 | [diff] [blame] | 426 | if not v: |
Marc-Antoine Ruel | 9ec1e9f | 2017-12-20 16:36:54 -0500 | [diff] [blame] | 427 | out.pop(k, None) |
Marc-Antoine Ruel | 19dd887 | 2017-11-28 18:33:39 -0500 | [diff] [blame] | 428 | else: |
Roberto Carrillo | 71ade6d | 2018-10-08 22:30:24 +0000 | [diff] [blame] | 429 | out[k] = replace_parameters(v, out_dir, bot_file) |
Marc-Antoine Ruel | 19dd887 | 2017-11-28 18:33:39 -0500 | [diff] [blame] | 430 | |
| 431 | if cipd_info: |
| 432 | bin_dir = os.path.dirname(cipd_info.client.binary_path) |
Junji Watanabe | 7a631b0 | 2022-01-13 02:30:29 +0000 | [diff] [blame] | 433 | out['PATH'] = '%s%s%s' % (bin_dir, os.pathsep, out['PATH']) |
| 434 | out['CIPD_CACHE_DIR'] = cipd_info.cache_dir |
Takuto Ikuta | 4ec3e8f | 2021-04-05 10:21:29 +0000 | [diff] [blame] | 435 | cipd_info_path = os.path.join(tmp_dir, 'cipd_info.json') |
| 436 | with open(cipd_info_path, 'w') as f: |
| 437 | json.dump(cipd_info.pins, f) |
| 438 | out['ISOLATED_RESOLVED_PACKAGE_VERSIONS_FILE'] = cipd_info_path |
Marc-Antoine Ruel | 19dd887 | 2017-11-28 18:33:39 -0500 | [diff] [blame] | 439 | |
Marc-Antoine Ruel | 04903a3 | 2019-10-09 21:09:25 +0000 | [diff] [blame] | 440 | for key, paths in env_prefixes.items(): |
Marc-Antoine Ruel | 9ec1e9f | 2017-12-20 16:36:54 -0500 | [diff] [blame] | 441 | assert isinstance(paths, list), paths |
| 442 | paths = [os.path.normpath(os.path.join(run_dir, p)) for p in paths] |
Marc-Antoine Ruel | 19dd887 | 2017-11-28 18:33:39 -0500 | [diff] [blame] | 443 | cur = out.get(key) |
| 444 | if cur: |
| 445 | paths.append(cur) |
Junji Watanabe | 7a631b0 | 2022-01-13 02:30:29 +0000 | [diff] [blame] | 446 | out[key] = os.path.pathsep.join(paths) |
vadimsh | 232f5a8 | 2017-01-20 19:23:44 -0800 | [diff] [blame] | 447 | |
Takuto Ikuta | 0f8a19c | 2021-03-02 00:50:38 +0000 | [diff] [blame] | 448 | set_temp_dir(out, tmp_dir) |
Marc-Antoine Ruel | 19dd887 | 2017-11-28 18:33:39 -0500 | [diff] [blame] | 449 | return out |
vadimsh | 232f5a8 | 2017-01-20 19:23:44 -0800 | [diff] [blame] | 450 | |
| 451 | |
Marc-Antoine Ruel | 1b65f4e | 2019-05-02 21:56:58 +0000 | [diff] [blame] | 452 | def run_command( |
| 453 | command, cwd, env, hard_timeout, grace_period, lower_priority, containment): |
maruel | 6be7f9e | 2015-10-01 12:25:30 -0700 | [diff] [blame] | 454 | """Runs the command. |
| 455 | |
| 456 | Returns: |
| 457 | tuple(process exit code, bool if had a hard timeout) |
| 458 | """ |
Jonah Hooper | 9b5bd8c | 2022-07-21 15:33:41 +0000 | [diff] [blame] | 459 | logging_utils.user_logs('run_command(%s, %s, %s, %s, %s, %s)', command, cwd, |
| 460 | hard_timeout, grace_period, lower_priority, |
| 461 | containment) |
maruel | eb5fbee | 2015-09-17 13:01:36 -0700 | [diff] [blame] | 462 | |
maruel | 6be7f9e | 2015-10-01 12:25:30 -0700 | [diff] [blame] | 463 | exit_code = None |
| 464 | had_hard_timeout = False |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 465 | with tools.Profiler('RunTest'): |
maruel | 6be7f9e | 2015-10-01 12:25:30 -0700 | [diff] [blame] | 466 | proc = None |
| 467 | had_signal = [] |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 468 | try: |
maruel | 6be7f9e | 2015-10-01 12:25:30 -0700 | [diff] [blame] | 469 | # TODO(maruel): This code is imperfect. It doesn't handle well signals |
| 470 | # during the download phase and there's short windows were things can go |
| 471 | # wrong. |
| 472 | def handler(signum, _frame): |
| 473 | if proc and not had_signal: |
| 474 | logging.info('Received signal %d', signum) |
| 475 | had_signal.append(True) |
maruel | 556d905 | 2015-10-05 11:12:44 -0700 | [diff] [blame] | 476 | raise subprocess42.TimeoutExpired(command, None) |
maruel | 6be7f9e | 2015-10-01 12:25:30 -0700 | [diff] [blame] | 477 | |
Marc-Antoine Ruel | 30b80fe | 2019-02-08 13:51:31 +0000 | [diff] [blame] | 478 | proc = subprocess42.Popen( |
Marc-Antoine Ruel | 03c6fd1 | 2019-04-30 12:12:55 +0000 | [diff] [blame] | 479 | command, cwd=cwd, env=env, detached=True, close_fds=True, |
Marc-Antoine Ruel | 1b65f4e | 2019-05-02 21:56:58 +0000 | [diff] [blame] | 480 | lower_priority=lower_priority, containment=containment) |
Joanna Wang | 40959bf | 2021-08-12 18:10:12 +0000 | [diff] [blame] | 481 | logging.info('Subprocess for command started') |
maruel | 6be7f9e | 2015-10-01 12:25:30 -0700 | [diff] [blame] | 482 | with subprocess42.set_signal_handler(subprocess42.STOP_SIGNALS, handler): |
| 483 | try: |
John Budorick | c398f09 | 2019-06-10 22:49:44 +0000 | [diff] [blame] | 484 | exit_code = proc.wait(hard_timeout or None) |
Takuto Ikuta | 88382c8 | 2022-02-03 08:46:17 +0000 | [diff] [blame] | 485 | logging.info("finished with exit code %d after hard_timeout %s", |
| 486 | exit_code, hard_timeout) |
maruel | 6be7f9e | 2015-10-01 12:25:30 -0700 | [diff] [blame] | 487 | except subprocess42.TimeoutExpired: |
| 488 | if not had_signal: |
| 489 | logging.warning('Hard timeout') |
| 490 | had_hard_timeout = True |
| 491 | logging.warning('Sending SIGTERM') |
| 492 | proc.terminate() |
| 493 | |
Takuto Ikuta | 684f791 | 2020-09-29 07:49:49 +0000 | [diff] [blame] | 494 | kill_sent = False |
maruel | 6be7f9e | 2015-10-01 12:25:30 -0700 | [diff] [blame] | 495 | # Ignore signals in grace period. Forcibly give the grace period to the |
| 496 | # child process. |
| 497 | if exit_code is None: |
| 498 | ignore = lambda *_: None |
| 499 | with subprocess42.set_signal_handler(subprocess42.STOP_SIGNALS, ignore): |
| 500 | try: |
| 501 | exit_code = proc.wait(grace_period or None) |
Takuto Ikuta | 88382c8 | 2022-02-03 08:46:17 +0000 | [diff] [blame] | 502 | logging.info("finished with exit code %d after grace_period %s", |
| 503 | exit_code, grace_period) |
maruel | 6be7f9e | 2015-10-01 12:25:30 -0700 | [diff] [blame] | 504 | except subprocess42.TimeoutExpired: |
| 505 | # Now kill for real. The user can distinguish between the |
| 506 | # following states: |
| 507 | # - signal but process exited within grace period, |
| 508 | # hard_timed_out will be set but the process exit code will be |
| 509 | # script provided. |
| 510 | # - processed exited late, exit code will be -9 on posix. |
| 511 | logging.warning('Grace exhausted; sending SIGKILL') |
| 512 | proc.kill() |
Takuto Ikuta | 684f791 | 2020-09-29 07:49:49 +0000 | [diff] [blame] | 513 | kill_sent = True |
martiniss | 5c8043e | 2017-08-01 17:09:43 -0700 | [diff] [blame] | 514 | logging.info('Waiting for process exit') |
maruel | 6be7f9e | 2015-10-01 12:25:30 -0700 | [diff] [blame] | 515 | exit_code = proc.wait() |
Takuto Ikuta | 684f791 | 2020-09-29 07:49:49 +0000 | [diff] [blame] | 516 | |
| 517 | # the process group / job object may be dangling so if we didn't kill |
| 518 | # it already, give it a poke now. |
| 519 | if not kill_sent: |
| 520 | proc.kill() |
Takuto Ikuta | eccf086 | 2020-03-19 03:05:55 +0000 | [diff] [blame] | 521 | except OSError as e: |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 522 | # This is not considered to be an internal error. The executable simply |
| 523 | # does not exit. |
maruel | a72f46e | 2016-02-24 11:05:45 -0800 | [diff] [blame] | 524 | sys.stderr.write( |
tikuta | 2d67821 | 2019-09-23 23:12:08 +0000 | [diff] [blame] | 525 | '<The executable does not exist, a dependent library is missing or ' |
| 526 | 'the command line is too long>\n' |
| 527 | '<Check for missing .so/.dll in the .isolate or GN file or length of ' |
| 528 | 'command line args>\n' |
Takuto Ikuta | e900df4 | 2021-04-14 04:40:11 +0000 | [diff] [blame] | 529 | '<Command: %s>\n' |
| 530 | '<Exception: %s>\n' % (command, e)) |
maruel | a72f46e | 2016-02-24 11:05:45 -0800 | [diff] [blame] | 531 | if os.environ.get('SWARMING_TASK_ID'): |
| 532 | # Give an additional hint when running as a swarming task. |
| 533 | sys.stderr.write( |
| 534 | '<See the task\'s page for commands to help diagnose this issue ' |
| 535 | 'by reproducing the task locally>\n') |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 536 | exit_code = 1 |
| 537 | logging.info( |
| 538 | 'Command finished with exit code %d (%s)', |
| 539 | exit_code, hex(0xffffffff & exit_code)) |
maruel | 6be7f9e | 2015-10-01 12:25:30 -0700 | [diff] [blame] | 540 | return exit_code, had_hard_timeout |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 541 | |
| 542 | |
Takuto Ikuta | 0f8a19c | 2021-03-02 00:50:38 +0000 | [diff] [blame] | 543 | def _run_go_cmd_and_wait(cmd, tmp_dir): |
Ye Kuang | c0cf9ca | 2020-07-16 08:56:51 +0000 | [diff] [blame] | 544 | """ |
Junji Watanabe | 4b890ef | 2020-09-16 01:43:27 +0000 | [diff] [blame] | 545 | Runs an external Go command, `isolated` or `cas`, and wait for its completion. |
Ye Kuang | c0cf9ca | 2020-07-16 08:56:51 +0000 | [diff] [blame] | 546 | |
| 547 | While this is a generic function to launch a subprocess, it has logic that |
Junji Watanabe | 4b890ef | 2020-09-16 01:43:27 +0000 | [diff] [blame] | 548 | is specific to Go `isolated` and `cas` for waiting and logging. |
Ye Kuang | c0cf9ca | 2020-07-16 08:56:51 +0000 | [diff] [blame] | 549 | |
| 550 | Returns: |
| 551 | The subprocess object |
| 552 | """ |
Ye Kuang | 3c40e9f | 2020-07-28 13:15:25 +0000 | [diff] [blame] | 553 | cmd_str = ' '.join(cmd) |
Ye Kuang | c1d800f | 2020-07-28 10:14:55 +0000 | [diff] [blame] | 554 | try: |
Takuto Ikuta | 0f8a19c | 2021-03-02 00:50:38 +0000 | [diff] [blame] | 555 | env = os.environ.copy() |
| 556 | set_temp_dir(env, tmp_dir) |
| 557 | proc = subprocess42.Popen(cmd, env=env) |
Ye Kuang | c0cf9ca | 2020-07-16 08:56:51 +0000 | [diff] [blame] | 558 | |
Ye Kuang | c1d800f | 2020-07-28 10:14:55 +0000 | [diff] [blame] | 559 | exceeded_max_timeout = True |
| 560 | check_period_sec = 30 |
| 561 | max_checks = 100 |
| 562 | # max timeout = max_checks * check_period_sec = 50 minutes |
| 563 | for i in range(max_checks): |
Junji Watanabe | 4b890ef | 2020-09-16 01:43:27 +0000 | [diff] [blame] | 564 | # This is to prevent I/O timeout error during setup. |
Ye Kuang | c1d800f | 2020-07-28 10:14:55 +0000 | [diff] [blame] | 565 | try: |
| 566 | retcode = proc.wait(check_period_sec) |
| 567 | if retcode != 0: |
Takuto Ikuta | 27f4b2f | 2021-04-26 07:18:55 +0000 | [diff] [blame] | 568 | raise subprocess42.CalledProcessError(retcode, cmd=cmd_str) |
Ye Kuang | c1d800f | 2020-07-28 10:14:55 +0000 | [diff] [blame] | 569 | exceeded_max_timeout = False |
| 570 | break |
| 571 | except subprocess42.TimeoutExpired: |
Junji Watanabe | 4b890ef | 2020-09-16 01:43:27 +0000 | [diff] [blame] | 572 | print('still running (after %d seconds)' % ((i + 1) * check_period_sec)) |
Ye Kuang | c0cf9ca | 2020-07-16 08:56:51 +0000 | [diff] [blame] | 573 | |
Ye Kuang | c1d800f | 2020-07-28 10:14:55 +0000 | [diff] [blame] | 574 | if exceeded_max_timeout: |
| 575 | proc.terminate() |
| 576 | try: |
| 577 | proc.wait(check_period_sec) |
| 578 | except subprocess42.TimeoutExpired: |
| 579 | logging.exception( |
| 580 | "failed to terminate? timeout happened after %d seconds", |
| 581 | check_period_sec) |
| 582 | proc.kill() |
| 583 | proc.wait() |
| 584 | # Raise unconditionally, because |proc| was forcefully terminated. |
| 585 | raise ValueError("timedout after %d seconds (cmd=%s)" % |
| 586 | (check_period_sec * max_checks, cmd_str)) |
Ye Kuang | c0cf9ca | 2020-07-16 08:56:51 +0000 | [diff] [blame] | 587 | |
Ye Kuang | c1d800f | 2020-07-28 10:14:55 +0000 | [diff] [blame] | 588 | return proc |
| 589 | except Exception: |
| 590 | logging.exception('Failed to run Go cmd %s', cmd_str) |
| 591 | raise |
Ye Kuang | c0cf9ca | 2020-07-16 08:56:51 +0000 | [diff] [blame] | 592 | |
| 593 | |
Takuto Ikuta | cd68ef5 | 2021-11-18 04:11:45 +0000 | [diff] [blame] | 594 | def _fetch_and_map(cas_client, digest, instance, output_dir, cache_dir, |
Takuto Ikuta | 91cb5ca | 2021-03-17 07:19:30 +0000 | [diff] [blame] | 595 | policies, kvs_dir, tmp_dir): |
Junji Watanabe | 4b890ef | 2020-09-16 01:43:27 +0000 | [diff] [blame] | 596 | """ |
| 597 | Fetches a CAS tree using cas client, create the tree and returns download |
| 598 | stats. |
| 599 | """ |
| 600 | |
| 601 | start = time.time() |
| 602 | result_json_handle, result_json_path = tempfile.mkstemp( |
Junji Watanabe | 53d3188 | 2022-01-13 07:58:00 +0000 | [diff] [blame] | 603 | prefix='fetch-and-map-result-', suffix='.json') |
Junji Watanabe | 4b890ef | 2020-09-16 01:43:27 +0000 | [diff] [blame] | 604 | os.close(result_json_handle) |
Takuto Ikuta | d5749ac | 2021-04-07 06:16:19 +0000 | [diff] [blame] | 605 | profile_dir = tempfile.mkdtemp(dir=tmp_dir) |
| 606 | |
Junji Watanabe | 4b890ef | 2020-09-16 01:43:27 +0000 | [diff] [blame] | 607 | try: |
| 608 | cmd = [ |
| 609 | cas_client, |
| 610 | 'download', |
| 611 | '-digest', |
| 612 | digest, |
Junji Watanabe | 4b890ef | 2020-09-16 01:43:27 +0000 | [diff] [blame] | 613 | # flags for cache. |
| 614 | '-cache-dir', |
| 615 | cache_dir, |
Junji Watanabe | 4b890ef | 2020-09-16 01:43:27 +0000 | [diff] [blame] | 616 | '-cache-max-size', |
| 617 | str(policies.max_cache_size), |
| 618 | '-cache-min-free-space', |
| 619 | str(policies.min_free_space), |
| 620 | # flags for output. |
| 621 | '-dir', |
| 622 | output_dir, |
Justin Luong | 54fa959 | 2022-08-11 03:44:40 +0000 | [diff] [blame^] | 623 | '-dump-json', |
Junji Watanabe | 4b890ef | 2020-09-16 01:43:27 +0000 | [diff] [blame] | 624 | result_json_path, |
Takuto Ikuta | 557025b | 2021-02-01 08:37:40 +0000 | [diff] [blame] | 625 | '-log-level', |
Takuto Ikuta | d5749ac | 2021-04-07 06:16:19 +0000 | [diff] [blame] | 626 | 'info', |
Junji Watanabe | 4b890ef | 2020-09-16 01:43:27 +0000 | [diff] [blame] | 627 | ] |
Takuto Ikuta | ae391c5 | 2020-12-03 08:43:45 +0000 | [diff] [blame] | 628 | |
Junji Watanabe | 66d807b | 2021-11-08 03:20:10 +0000 | [diff] [blame] | 629 | # When RUN_ISOLATED_CAS_ADDRESS is set in test mode, |
| 630 | # Use it and ignore CAS instance option. |
| 631 | cas_addr = os.environ.get('RUN_ISOLATED_CAS_ADDRESS') |
| 632 | if cas_addr: |
| 633 | cmd.extend([ |
| 634 | '-cas-addr', |
| 635 | cas_addr, |
| 636 | ]) |
| 637 | else: |
| 638 | cmd.extend([ |
| 639 | '-cas-instance', |
| 640 | instance |
| 641 | ]) |
| 642 | |
Takuto Ikuta | 91cb5ca | 2021-03-17 07:19:30 +0000 | [diff] [blame] | 643 | if kvs_dir: |
| 644 | cmd.extend(['-kvs-dir', kvs_dir]) |
Takuto Ikuta | ae391c5 | 2020-12-03 08:43:45 +0000 | [diff] [blame] | 645 | |
Justin Luong | 54fa959 | 2022-08-11 03:44:40 +0000 | [diff] [blame^] | 646 | def open_json_and_check(result_json_path, cleanup_dirs): |
| 647 | cas_error = False |
| 648 | result_json = {} |
| 649 | try: |
| 650 | with open(result_json_path) as json_file: |
| 651 | result_json = json.load(json_file) |
| 652 | cas_error = result_json.get('result') in ('digest_invalid', |
| 653 | 'authentication_error', |
| 654 | 'arguments_invalid') |
| 655 | except (IOError, ValueError): |
| 656 | logging.error('Failed to read json file: %s', result_json_path) |
| 657 | raise |
| 658 | finally: |
| 659 | if cleanup_dirs: |
| 660 | file_path.rmtree(kvs_dir) |
| 661 | file_path.rmtree(output_dir) |
| 662 | if cas_error: |
| 663 | raise NonRetriableCasException(result_json['result'], digest, instance) |
| 664 | return result_json |
| 665 | |
Takuto Ikuta | 27f4b2f | 2021-04-26 07:18:55 +0000 | [diff] [blame] | 666 | try: |
| 667 | _run_go_cmd_and_wait(cmd, tmp_dir) |
Takuto Ikuta | 0909eae | 2021-04-27 02:54:07 +0000 | [diff] [blame] | 668 | except subprocess42.CalledProcessError as ex: |
Takuto Ikuta | 27f4b2f | 2021-04-26 07:18:55 +0000 | [diff] [blame] | 669 | if not kvs_dir: |
Justin Luong | 54fa959 | 2022-08-11 03:44:40 +0000 | [diff] [blame^] | 670 | open_json_and_check(result_json_path, False) |
Takuto Ikuta | 27f4b2f | 2021-04-26 07:18:55 +0000 | [diff] [blame] | 671 | raise |
Justin Luong | 54fa959 | 2022-08-11 03:44:40 +0000 | [diff] [blame^] | 672 | open_json_and_check(result_json_path, True) |
Takuto Ikuta | 27f4b2f | 2021-04-26 07:18:55 +0000 | [diff] [blame] | 673 | logging.exception('Failed to run cas, removing kvs cache dir and retry.') |
Takuto Ikuta | 0909eae | 2021-04-27 02:54:07 +0000 | [diff] [blame] | 674 | on_error.report("Failed to run cas %s" % ex) |
Takuto Ikuta | 27f4b2f | 2021-04-26 07:18:55 +0000 | [diff] [blame] | 675 | _run_go_cmd_and_wait(cmd, tmp_dir) |
| 676 | |
Justin Luong | 54fa959 | 2022-08-11 03:44:40 +0000 | [diff] [blame^] | 677 | result_json = open_json_and_check(result_json_path, False) |
Junji Watanabe | 4b890ef | 2020-09-16 01:43:27 +0000 | [diff] [blame] | 678 | |
| 679 | return { |
| 680 | 'duration': time.time() - start, |
| 681 | 'items_cold': result_json['items_cold'], |
| 682 | 'items_hot': result_json['items_hot'], |
| 683 | } |
| 684 | finally: |
| 685 | fs.remove(result_json_path) |
Takuto Ikuta | d5749ac | 2021-04-07 06:16:19 +0000 | [diff] [blame] | 686 | file_path.rmtree(profile_dir) |
Junji Watanabe | 4b890ef | 2020-09-16 01:43:27 +0000 | [diff] [blame] | 687 | |
| 688 | |
aludwin | 0a8e17d | 2016-10-27 15:57:39 -0700 | [diff] [blame] | 689 | def link_outputs_to_outdir(run_dir, out_dir, outputs): |
| 690 | """Links any named outputs to out_dir so they can be uploaded. |
| 691 | |
| 692 | Raises an error if the file already exists in that directory. |
| 693 | """ |
| 694 | if not outputs: |
| 695 | return |
Takuto Ikuta | e0dce46 | 2021-11-16 08:49:46 +0000 | [diff] [blame] | 696 | file_path.create_directories(out_dir, outputs) |
aludwin | 0a8e17d | 2016-10-27 15:57:39 -0700 | [diff] [blame] | 697 | for o in outputs: |
Sadaf Matinkhoo | 10743a6 | 2018-03-29 16:28:58 -0400 | [diff] [blame] | 698 | copy_recursively(os.path.join(run_dir, o), os.path.join(out_dir, o)) |
| 699 | |
| 700 | |
| 701 | def copy_recursively(src, dst): |
| 702 | """Efficiently copies a file or directory from src_dir to dst_dir. |
| 703 | |
| 704 | `item` may be a file, directory, or a symlink to a file or directory. |
| 705 | All symlinks are replaced with their targets, so the resulting |
| 706 | directory structure in dst_dir will never have any symlinks. |
| 707 | |
| 708 | To increase speed, copy_recursively hardlinks individual files into the |
| 709 | (newly created) directory structure if possible, unlike Python's |
| 710 | shutil.copytree(). |
| 711 | """ |
| 712 | orig_src = src |
| 713 | try: |
| 714 | # Replace symlinks with their final target. |
| 715 | while fs.islink(src): |
| 716 | res = fs.readlink(src) |
Takuto Ikuta | f2ad0a0 | 2021-06-24 08:38:40 +0000 | [diff] [blame] | 717 | src = os.path.realpath(os.path.join(os.path.dirname(src), res)) |
Sadaf Matinkhoo | 10743a6 | 2018-03-29 16:28:58 -0400 | [diff] [blame] | 718 | # TODO(sadafm): Explicitly handle cyclic symlinks. |
| 719 | |
Takuto Ikuta | f2ad0a0 | 2021-06-24 08:38:40 +0000 | [diff] [blame] | 720 | if not fs.exists(src): |
| 721 | logging.warning('Path %s does not exist or %s is a broken symlink', src, |
| 722 | orig_src) |
| 723 | return |
| 724 | |
Sadaf Matinkhoo | 10743a6 | 2018-03-29 16:28:58 -0400 | [diff] [blame] | 725 | if fs.isfile(src): |
| 726 | file_path.link_file(dst, src, file_path.HARDLINK_WITH_FALLBACK) |
| 727 | return |
| 728 | |
| 729 | if not fs.exists(dst): |
| 730 | os.makedirs(dst) |
| 731 | |
| 732 | for child in fs.listdir(src): |
| 733 | copy_recursively(os.path.join(src, child), os.path.join(dst, child)) |
| 734 | |
| 735 | except OSError as e: |
| 736 | if e.errno == errno.ENOENT: |
| 737 | logging.warning('Path %s does not exist or %s is a broken symlink', |
| 738 | src, orig_src) |
| 739 | else: |
| 740 | logging.info("Couldn't collect output file %s: %s", src, e) |
aludwin | 0a8e17d | 2016-10-27 15:57:39 -0700 | [diff] [blame] | 741 | |
| 742 | |
Takuto Ikuta | cd68ef5 | 2021-11-18 04:11:45 +0000 | [diff] [blame] | 743 | def upload_outdir(cas_client, cas_instance, outdir, tmp_dir): |
Junji Watanabe | 1adba7b | 2020-09-18 07:03:58 +0000 | [diff] [blame] | 744 | """Uploads the results in |outdir|, if there is any. |
| 745 | |
| 746 | Returns: |
| 747 | tuple(root_digest, stats) |
| 748 | - root_digest: a digest of the output directory. |
| 749 | - stats: uploading stats. |
| 750 | """ |
Junji Watanabe | 15f9e04 | 2021-11-12 07:13:50 +0000 | [diff] [blame] | 751 | if not fs.listdir(outdir): |
| 752 | return None, None |
Junji Watanabe | 53d3188 | 2022-01-13 07:58:00 +0000 | [diff] [blame] | 753 | digest_file_handle, digest_path = tempfile.mkstemp(prefix='cas-digest', |
| 754 | suffix='.txt') |
Junji Watanabe | 1adba7b | 2020-09-18 07:03:58 +0000 | [diff] [blame] | 755 | os.close(digest_file_handle) |
Junji Watanabe | 53d3188 | 2022-01-13 07:58:00 +0000 | [diff] [blame] | 756 | stats_json_handle, stats_json_path = tempfile.mkstemp(prefix='upload-stats', |
| 757 | suffix='.json') |
Junji Watanabe | 1adba7b | 2020-09-18 07:03:58 +0000 | [diff] [blame] | 758 | os.close(stats_json_handle) |
| 759 | |
| 760 | try: |
| 761 | cmd = [ |
| 762 | cas_client, |
| 763 | 'archive', |
Junji Watanabe | 1adba7b | 2020-09-18 07:03:58 +0000 | [diff] [blame] | 764 | '-paths', |
| 765 | # Format: <working directory>:<relative path to dir> |
| 766 | outdir + ':', |
| 767 | # output |
| 768 | '-dump-digest', |
| 769 | digest_path, |
Justin Luong | 54fa959 | 2022-08-11 03:44:40 +0000 | [diff] [blame^] | 770 | '-dump-json', |
Junji Watanabe | 1adba7b | 2020-09-18 07:03:58 +0000 | [diff] [blame] | 771 | stats_json_path, |
| 772 | ] |
| 773 | |
Junji Watanabe | 66d807b | 2021-11-08 03:20:10 +0000 | [diff] [blame] | 774 | # When RUN_ISOLATED_CAS_ADDRESS is set in test mode, |
| 775 | # Use it and ignore CAS instance option. |
| 776 | cas_addr = os.environ.get('RUN_ISOLATED_CAS_ADDRESS') |
| 777 | if cas_addr: |
| 778 | cmd.extend([ |
| 779 | '-cas-addr', |
| 780 | cas_addr, |
| 781 | ]) |
| 782 | else: |
| 783 | cmd.extend([ |
| 784 | '-cas-instance', |
| 785 | cas_instance |
| 786 | ]) |
| 787 | |
Takuto Ikuta | 23388f5 | 2022-02-01 01:39:00 +0000 | [diff] [blame] | 788 | if sys.platform == 'linux': |
Takuto Ikuta | bfcef25 | 2021-08-25 07:46:19 +0000 | [diff] [blame] | 789 | # TODO(crbug.com/1243194): remove this after investigation. |
| 790 | cmd.extend(['-log-level', 'debug']) |
| 791 | |
Junji Watanabe | 1adba7b | 2020-09-18 07:03:58 +0000 | [diff] [blame] | 792 | start = time.time() |
| 793 | |
Takuto Ikuta | 0f8a19c | 2021-03-02 00:50:38 +0000 | [diff] [blame] | 794 | _run_go_cmd_and_wait(cmd, tmp_dir) |
Junji Watanabe | 1adba7b | 2020-09-18 07:03:58 +0000 | [diff] [blame] | 795 | |
| 796 | with open(digest_path) as digest_file: |
| 797 | digest = digest_file.read() |
Junji Watanabe | c208b30 | 2020-09-25 09:18:27 +0000 | [diff] [blame] | 798 | h, s = digest.split('/') |
| 799 | cas_output_root = { |
| 800 | 'cas_instance': cas_instance, |
| 801 | 'digest': { |
| 802 | 'hash': h, |
| 803 | 'size_bytes': int(s) |
| 804 | } |
| 805 | } |
Junji Watanabe | 1adba7b | 2020-09-18 07:03:58 +0000 | [diff] [blame] | 806 | with open(stats_json_path) as stats_file: |
| 807 | stats = json.load(stats_file) |
| 808 | |
| 809 | stats['duration'] = time.time() - start |
| 810 | |
Junji Watanabe | c208b30 | 2020-09-25 09:18:27 +0000 | [diff] [blame] | 811 | return cas_output_root, stats |
Junji Watanabe | 1adba7b | 2020-09-18 07:03:58 +0000 | [diff] [blame] | 812 | finally: |
| 813 | fs.remove(digest_path) |
| 814 | fs.remove(stats_json_path) |
| 815 | |
| 816 | |
Marc-Antoine Ruel | 7de5259 | 2017-12-07 10:41:12 -0500 | [diff] [blame] | 817 | def map_and_run(data, constant_run_path): |
nodir | 55be77b | 2016-05-03 09:39:57 -0700 | [diff] [blame] | 818 | """Runs a command with optional isolated input/output. |
| 819 | |
Marc-Antoine Ruel | 7de5259 | 2017-12-07 10:41:12 -0500 | [diff] [blame] | 820 | Arguments: |
| 821 | - data: TaskData instance. |
| 822 | - constant_run_path: TODO |
nodir | 55be77b | 2016-05-03 09:39:57 -0700 | [diff] [blame] | 823 | |
| 824 | Returns metadata about the result. |
| 825 | """ |
Takuto Ikuta | 00cf8fc | 2020-01-14 01:36:00 +0000 | [diff] [blame] | 826 | |
Takuto Ikuta | a71c656 | 2021-11-18 06:07:55 +0000 | [diff] [blame] | 827 | # TODO(tikuta): take stats from state.json in this case too. |
| 828 | download_stats = { |
| 829 | # 'duration': 0., |
| 830 | # 'initial_number_items': len(data.cas_cache), |
| 831 | # 'initial_size': data.cas_cache.total_size, |
| 832 | # 'items_cold': '<large.pack()>', |
| 833 | # 'items_hot': '<large.pack()>', |
| 834 | } |
Takuto Ikuta | 00cf8fc | 2020-01-14 01:36:00 +0000 | [diff] [blame] | 835 | |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 836 | result = { |
Takuto Ikuta | 5ed62ad | 2019-09-26 09:16:00 +0000 | [diff] [blame] | 837 | 'duration': None, |
| 838 | 'exit_code': None, |
| 839 | 'had_hard_timeout': False, |
| 840 | 'internal_failure': 'run_isolated did not complete properly', |
| 841 | 'stats': { |
Junji Watanabe | aee69ad | 2021-04-28 03:17:34 +0000 | [diff] [blame] | 842 | 'trim_caches': { |
| 843 | 'duration': 0, |
| 844 | }, |
Takuto Ikuta | 5ed62ad | 2019-09-26 09:16:00 +0000 | [diff] [blame] | 845 | #'cipd': { |
| 846 | # 'duration': 0., |
| 847 | # 'get_client_duration': 0., |
| 848 | #}, |
| 849 | 'isolated': { |
Takuto Ikuta | 00cf8fc | 2020-01-14 01:36:00 +0000 | [diff] [blame] | 850 | 'download': download_stats, |
Takuto Ikuta | 5ed62ad | 2019-09-26 09:16:00 +0000 | [diff] [blame] | 851 | #'upload': { |
| 852 | # 'duration': 0., |
| 853 | # 'items_cold': '<large.pack()>', |
| 854 | # 'items_hot': '<large.pack()>', |
| 855 | #}, |
| 856 | }, |
Junji Watanabe | aee69ad | 2021-04-28 03:17:34 +0000 | [diff] [blame] | 857 | 'named_caches': { |
| 858 | 'install': { |
| 859 | 'duration': 0, |
| 860 | }, |
| 861 | 'uninstall': { |
| 862 | 'duration': 0, |
| 863 | }, |
| 864 | }, |
| 865 | 'cleanup': { |
| 866 | 'duration': 0, |
| 867 | } |
Marc-Antoine Ruel | 5d7606b | 2018-06-15 19:06:12 +0000 | [diff] [blame] | 868 | }, |
Takuto Ikuta | 5ed62ad | 2019-09-26 09:16:00 +0000 | [diff] [blame] | 869 | #'cipd_pins': { |
| 870 | # 'packages': [ |
| 871 | # {'package_name': ..., 'version': ..., 'path': ...}, |
| 872 | # ... |
| 873 | # ], |
| 874 | # 'client_package': {'package_name': ..., 'version': ...}, |
| 875 | #}, |
| 876 | 'outputs_ref': None, |
Junji Watanabe | 54925c3 | 2020-09-08 00:56:18 +0000 | [diff] [blame] | 877 | 'cas_output_root': None, |
Takuto Ikuta | 5ed62ad | 2019-09-26 09:16:00 +0000 | [diff] [blame] | 878 | 'version': 5, |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 879 | } |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 880 | |
Takuto Ikuta | d46ea76 | 2020-10-07 05:43:22 +0000 | [diff] [blame] | 881 | assert os.path.isabs(data.root_dir), ("data.root_dir is not abs path: %s" % |
| 882 | data.root_dir) |
| 883 | file_path.ensure_tree(data.root_dir, 0o700) |
| 884 | |
maruel | e2f2cb8 | 2016-07-13 14:41:03 -0700 | [diff] [blame] | 885 | # See comment for these constants. |
maruel | cffa054 | 2017-04-07 08:39:20 -0700 | [diff] [blame] | 886 | # TODO(maruel): This is not obvious. Change this to become an error once we |
| 887 | # make the constant_run_path an exposed flag. |
Marc-Antoine Ruel | 7de5259 | 2017-12-07 10:41:12 -0500 | [diff] [blame] | 888 | if constant_run_path and data.root_dir: |
| 889 | run_dir = os.path.join(data.root_dir, ISOLATED_RUN_DIR) |
maruel | 5c4eed8 | 2017-05-26 05:33:40 -0700 | [diff] [blame] | 890 | if os.path.isdir(run_dir): |
| 891 | file_path.rmtree(run_dir) |
Lei Lei | fe202df | 2019-06-11 17:33:34 +0000 | [diff] [blame] | 892 | os.mkdir(run_dir, 0o700) |
maruel | cffa054 | 2017-04-07 08:39:20 -0700 | [diff] [blame] | 893 | else: |
Marc-Antoine Ruel | 7de5259 | 2017-12-07 10:41:12 -0500 | [diff] [blame] | 894 | run_dir = make_temp_dir(ISOLATED_RUN_DIR, data.root_dir) |
Junji Watanabe | 1adba7b | 2020-09-18 07:03:58 +0000 | [diff] [blame] | 895 | |
maruel | 03e1184 | 2016-07-14 10:50:16 -0700 | [diff] [blame] | 896 | # storage should be normally set but don't crash if it is not. This can happen |
| 897 | # as Swarming task can run without an isolate server. |
Takuto Ikuta | 417388f | 2021-11-18 07:39:52 +0000 | [diff] [blame] | 898 | out_dir = make_temp_dir(ISOLATED_OUT_DIR, data.root_dir) |
Marc-Antoine Ruel | 7de5259 | 2017-12-07 10:41:12 -0500 | [diff] [blame] | 899 | tmp_dir = make_temp_dir(ISOLATED_TMP_DIR, data.root_dir) |
nodir | 55be77b | 2016-05-03 09:39:57 -0700 | [diff] [blame] | 900 | cwd = run_dir |
Marc-Antoine Ruel | 95068cf | 2017-12-07 21:35:05 -0500 | [diff] [blame] | 901 | if data.relative_cwd: |
| 902 | cwd = os.path.normpath(os.path.join(cwd, data.relative_cwd)) |
Marc-Antoine Ruel | 7de5259 | 2017-12-07 10:41:12 -0500 | [diff] [blame] | 903 | command = data.command |
Junji Watanabe | 1adba7b | 2020-09-18 07:03:58 +0000 | [diff] [blame] | 904 | |
Junji Watanabe | 4b890ef | 2020-09-16 01:43:27 +0000 | [diff] [blame] | 905 | cas_client_dir = make_temp_dir(_CAS_CLIENT_DIR, data.root_dir) |
Takuto Ikuta | 417388f | 2021-11-18 07:39:52 +0000 | [diff] [blame] | 906 | cas_client = os.path.join(cas_client_dir, 'cas' + cipd.EXECUTABLE_SUFFIX) |
Junji Watanabe | 4b890ef | 2020-09-16 01:43:27 +0000 | [diff] [blame] | 907 | |
Junji Watanabe | aee69ad | 2021-04-28 03:17:34 +0000 | [diff] [blame] | 908 | data.trim_caches_fn(result['stats']['trim_caches']) |
| 909 | |
Anirudh Mathukumilli | 92d57b6 | 2021-08-04 23:21:57 +0000 | [diff] [blame] | 910 | nsjail_dir = None |
| 911 | if (sys.platform == "linux" and cipd.get_platform() == "amd64" and |
| 912 | data.containment.containment_type == subprocess42.Containment.NSJAIL): |
| 913 | nsjail_dir = make_temp_dir(_NSJAIL_DIR, data.root_dir) |
| 914 | |
nodir | 55be77b | 2016-05-03 09:39:57 -0700 | [diff] [blame] | 915 | try: |
Takuto Ikuta | 1ce6136 | 2021-11-16 05:44:17 +0000 | [diff] [blame] | 916 | with data.install_packages_fn(run_dir, cas_client_dir, |
Anirudh Mathukumilli | 92d57b6 | 2021-08-04 23:21:57 +0000 | [diff] [blame] | 917 | nsjail_dir) as cipd_info: |
vadimsh | 232f5a8 | 2017-01-20 19:23:44 -0800 | [diff] [blame] | 918 | if cipd_info: |
| 919 | result['stats']['cipd'] = cipd_info.stats |
| 920 | result['cipd_pins'] = cipd_info.pins |
nodir | 90bc8dc | 2016-06-15 13:35:21 -0700 | [diff] [blame] | 921 | |
Junji Watanabe | 4b890ef | 2020-09-16 01:43:27 +0000 | [diff] [blame] | 922 | isolated_stats = result['stats'].setdefault('isolated', {}) |
Takuto Ikuta | b58dbd1 | 2020-06-05 09:29:14 +0000 | [diff] [blame] | 923 | |
Takuto Ikuta | cd68ef5 | 2021-11-18 04:11:45 +0000 | [diff] [blame] | 924 | if data.cas_digest: |
| 925 | stats = _fetch_and_map( |
Junji Watanabe | 4b890ef | 2020-09-16 01:43:27 +0000 | [diff] [blame] | 926 | cas_client=cas_client, |
| 927 | digest=data.cas_digest, |
| 928 | instance=data.cas_instance, |
| 929 | output_dir=run_dir, |
Junji Watanabe | b03450b | 2020-09-25 05:09:27 +0000 | [diff] [blame] | 930 | cache_dir=data.cas_cache_dir, |
Takuto Ikuta | ae391c5 | 2020-12-03 08:43:45 +0000 | [diff] [blame] | 931 | policies=data.cas_cache_policies, |
Takuto Ikuta | 91cb5ca | 2021-03-17 07:19:30 +0000 | [diff] [blame] | 932 | kvs_dir=data.cas_kvs, |
Takuto Ikuta | 0f8a19c | 2021-03-02 00:50:38 +0000 | [diff] [blame] | 933 | tmp_dir=tmp_dir) |
Junji Watanabe | 4b890ef | 2020-09-16 01:43:27 +0000 | [diff] [blame] | 934 | isolated_stats['download'].update(stats) |
Junji Watanabe | 54925c3 | 2020-09-08 00:56:18 +0000 | [diff] [blame] | 935 | |
maruel | abec63c | 2017-04-26 11:53:24 -0700 | [diff] [blame] | 936 | if not command: |
| 937 | # Handle this as a task failure, not an internal failure. |
| 938 | sys.stderr.write( |
| 939 | '<No command was specified!>\n' |
| 940 | '<Please secify a command when triggering your Swarming task>\n') |
| 941 | result['exit_code'] = 1 |
| 942 | return result |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 943 | |
Marc-Antoine Ruel | 95068cf | 2017-12-07 21:35:05 -0500 | [diff] [blame] | 944 | if not cwd.startswith(run_dir): |
| 945 | # Handle this as a task failure, not an internal failure. This is a |
| 946 | # 'last chance' way to gate against directory escape. |
| 947 | sys.stderr.write('<Relative CWD is outside of run directory!>\n') |
| 948 | result['exit_code'] = 1 |
| 949 | return result |
| 950 | |
| 951 | if not os.path.isdir(cwd): |
| 952 | # Accepts relative_cwd that does not exist. |
Lei Lei | fe202df | 2019-06-11 17:33:34 +0000 | [diff] [blame] | 953 | os.makedirs(cwd, 0o700) |
Marc-Antoine Ruel | 95068cf | 2017-12-07 21:35:05 -0500 | [diff] [blame] | 954 | |
vadimsh | 232f5a8 | 2017-01-20 19:23:44 -0800 | [diff] [blame] | 955 | # If we have an explicit list of files to return, make sure their |
| 956 | # directories exist now. |
Takuto Ikuta | ab8d023 | 2021-11-16 12:12:09 +0000 | [diff] [blame] | 957 | if data.outputs: |
Takuto Ikuta | e0dce46 | 2021-11-16 08:49:46 +0000 | [diff] [blame] | 958 | file_path.create_directories(run_dir, data.outputs) |
aludwin | 0a8e17d | 2016-10-27 15:57:39 -0700 | [diff] [blame] | 959 | |
Junji Watanabe | aee69ad | 2021-04-28 03:17:34 +0000 | [diff] [blame] | 960 | with data.install_named_caches(run_dir, result['stats']['named_caches']): |
nodir | d616068 | 2017-02-02 13:03:35 -0800 | [diff] [blame] | 961 | sys.stdout.flush() |
| 962 | start = time.time() |
| 963 | try: |
vadimsh | 9c54b2c | 2017-07-25 14:08:29 -0700 | [diff] [blame] | 964 | # Need to switch the default account before 'get_command_env' call, |
| 965 | # so it can grab correct value of LUCI_CONTEXT env var. |
Marc-Antoine Ruel | 7de5259 | 2017-12-07 10:41:12 -0500 | [diff] [blame] | 966 | with set_luci_context_account(data.switch_to_account, tmp_dir): |
| 967 | env = get_command_env( |
Roberto Carrillo | 71ade6d | 2018-10-08 22:30:24 +0000 | [diff] [blame] | 968 | tmp_dir, cipd_info, run_dir, data.env, data.env_prefix, out_dir, |
| 969 | data.bot_file) |
Brian Sheedy | 7a76117 | 2019-08-30 22:55:14 +0000 | [diff] [blame] | 970 | command = tools.find_executable(command, env) |
Robert Iannucci | 24ae76a | 2018-02-26 12:51:18 -0800 | [diff] [blame] | 971 | command = process_command(command, out_dir, data.bot_file) |
| 972 | file_path.ensure_command_has_abs_path(command, cwd) |
| 973 | |
vadimsh | 9c54b2c | 2017-07-25 14:08:29 -0700 | [diff] [blame] | 974 | result['exit_code'], result['had_hard_timeout'] = run_command( |
Marc-Antoine Ruel | 03c6fd1 | 2019-04-30 12:12:55 +0000 | [diff] [blame] | 975 | command, cwd, env, data.hard_timeout, data.grace_period, |
Marc-Antoine Ruel | 1b65f4e | 2019-05-02 21:56:58 +0000 | [diff] [blame] | 976 | data.lower_priority, data.containment) |
nodir | d616068 | 2017-02-02 13:03:35 -0800 | [diff] [blame] | 977 | finally: |
| 978 | result['duration'] = max(time.time() - start, 0) |
Seth Koehler | 4913981 | 2017-12-19 13:59:33 -0500 | [diff] [blame] | 979 | |
Takuto Ikuta | 417388f | 2021-11-18 07:39:52 +0000 | [diff] [blame] | 980 | # Try to link files to the output directory, if specified. |
| 981 | link_outputs_to_outdir(run_dir, out_dir, data.outputs) |
| 982 | isolated_stats = result['stats'].setdefault('isolated', {}) |
| 983 | result['cas_output_root'], upload_stats = upload_outdir( |
| 984 | cas_client, data.cas_instance, out_dir, tmp_dir) |
| 985 | if upload_stats: |
| 986 | isolated_stats['upload'] = upload_stats |
Takuto Ikuta | cd68ef5 | 2021-11-18 04:11:45 +0000 | [diff] [blame] | 987 | |
Seth Koehler | 4913981 | 2017-12-19 13:59:33 -0500 | [diff] [blame] | 988 | # We successfully ran the command, set internal_failure back to |
| 989 | # None (even if the command failed, it's not an internal error). |
| 990 | result['internal_failure'] = None |
Justin Luong | 54fa959 | 2022-08-11 03:44:40 +0000 | [diff] [blame^] | 991 | except NonRetriableCasException as e: |
| 992 | # We could not find the CAS package. The swarming task should not |
| 993 | # be retried automatically |
| 994 | result['missing_cas'] = e.to_dict() |
| 995 | logging.exception('internal failure: %s', e) |
| 996 | result['internal_failure'] = str(e) |
| 997 | on_error.report(None) |
| 998 | |
| 999 | except NonRetriableCipdException as e: |
| 1000 | # We could not find the CIPD package. The swarming task should not |
| 1001 | # be retried automatically |
| 1002 | result['missing_cipd'] = [e.to_dict()] |
| 1003 | logging.exception('internal failure: %s', e) |
| 1004 | result['internal_failure'] = str(e) |
| 1005 | on_error.report(None) |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 1006 | except Exception as e: |
nodir | 90bc8dc | 2016-06-15 13:35:21 -0700 | [diff] [blame] | 1007 | # An internal error occurred. Report accordingly so the swarming task will |
| 1008 | # be retried automatically. |
maruel | 12e3001 | 2015-10-09 11:55:35 -0700 | [diff] [blame] | 1009 | logging.exception('internal failure: %s', e) |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 1010 | result['internal_failure'] = str(e) |
| 1011 | on_error.report(None) |
aludwin | 0a8e17d | 2016-10-27 15:57:39 -0700 | [diff] [blame] | 1012 | |
| 1013 | # Clean up |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 1014 | finally: |
| 1015 | try: |
Junji Watanabe | aee69ad | 2021-04-28 03:17:34 +0000 | [diff] [blame] | 1016 | cleanup_start = time.time() |
Ye Kuang | bc4e840 | 2020-07-29 09:54:30 +0000 | [diff] [blame] | 1017 | success = True |
Marc-Antoine Ruel | 7de5259 | 2017-12-07 10:41:12 -0500 | [diff] [blame] | 1018 | if data.leak_temp_dir: |
nodir | 32a1ec1 | 2016-10-26 18:34:07 -0700 | [diff] [blame] | 1019 | success = True |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 1020 | logging.warning( |
| 1021 | 'Deliberately leaking %s for later examination', run_dir) |
maruel | eb5fbee | 2015-09-17 13:01:36 -0700 | [diff] [blame] | 1022 | else: |
maruel | 84537cb | 2015-10-16 14:21:28 -0700 | [diff] [blame] | 1023 | # On Windows rmtree(run_dir) call above has a synchronization effect: it |
| 1024 | # finishes only when all task child processes terminate (since a running |
| 1025 | # process locks *.exe file). Examine out_dir only after that call |
| 1026 | # completes (since child processes may write to out_dir too and we need |
| 1027 | # to wait for them to finish). |
Takuto Ikuta | 1ce6136 | 2021-11-16 05:44:17 +0000 | [diff] [blame] | 1028 | dirs_to_remove = [run_dir, tmp_dir, cas_client_dir] |
Ye Kuang | bc4e840 | 2020-07-29 09:54:30 +0000 | [diff] [blame] | 1029 | if out_dir: |
| 1030 | dirs_to_remove.append(out_dir) |
| 1031 | for directory in dirs_to_remove: |
Takuto Ikuta | 69c0d66 | 2019-11-27 01:18:08 +0000 | [diff] [blame] | 1032 | if not fs.isdir(directory): |
| 1033 | continue |
Junji Watanabe | 9cdfff5 | 2021-01-08 07:20:35 +0000 | [diff] [blame] | 1034 | start = time.time() |
maruel | 84537cb | 2015-10-16 14:21:28 -0700 | [diff] [blame] | 1035 | try: |
Junji Watanabe | cc4eefd | 2021-01-19 01:46:10 +0000 | [diff] [blame] | 1036 | file_path.rmtree(directory) |
maruel | 84537cb | 2015-10-16 14:21:28 -0700 | [diff] [blame] | 1037 | except OSError as e: |
Takuto Ikuta | 69c0d66 | 2019-11-27 01:18:08 +0000 | [diff] [blame] | 1038 | logging.error('rmtree(%r) failed: %s', directory, e) |
maruel | 84537cb | 2015-10-16 14:21:28 -0700 | [diff] [blame] | 1039 | success = False |
Junji Watanabe | 9cdfff5 | 2021-01-08 07:20:35 +0000 | [diff] [blame] | 1040 | finally: |
| 1041 | logging.info('Cleanup: rmtree(%r) took %d seconds', directory, |
| 1042 | time.time() - start) |
maruel | 84537cb | 2015-10-16 14:21:28 -0700 | [diff] [blame] | 1043 | if not success: |
Takuto Ikuta | 69c0d66 | 2019-11-27 01:18:08 +0000 | [diff] [blame] | 1044 | sys.stderr.write( |
| 1045 | OUTLIVING_ZOMBIE_MSG % (directory, data.grace_period)) |
Junji Watanabe | d952bf1 | 2021-05-13 03:15:54 +0000 | [diff] [blame] | 1046 | if sys.platform == 'win32': |
| 1047 | subprocess42.check_call(['tasklist.exe', '/V'], stdout=sys.stderr) |
| 1048 | else: |
| 1049 | subprocess42.check_call(['ps', 'axu'], stdout=sys.stderr) |
maruel | 84537cb | 2015-10-16 14:21:28 -0700 | [diff] [blame] | 1050 | if result['exit_code'] == 0: |
| 1051 | result['exit_code'] = 1 |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 1052 | |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 1053 | if not success and result['exit_code'] == 0: |
| 1054 | result['exit_code'] = 1 |
| 1055 | except Exception as e: |
| 1056 | # Swallow any exception in the main finally clause. |
nodir | 9130f07 | 2016-05-27 13:59:08 -0700 | [diff] [blame] | 1057 | if out_dir: |
| 1058 | logging.exception('Leaking out_dir %s: %s', out_dir, e) |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 1059 | result['internal_failure'] = str(e) |
Takuto Ikuta | a9a907b | 2020-04-17 08:50:50 +0000 | [diff] [blame] | 1060 | on_error.report(None) |
Junji Watanabe | aee69ad | 2021-04-28 03:17:34 +0000 | [diff] [blame] | 1061 | finally: |
| 1062 | cleanup_duration = time.time() - cleanup_start |
| 1063 | result['stats']['cleanup']['duration'] = cleanup_duration |
| 1064 | logging.info('Cleanup: removing directories took %d seconds', |
| 1065 | cleanup_duration) |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 1066 | return result |
Marc-Antoine Ruel | 2283ad1 | 2014-02-09 11:14:57 -0500 | [diff] [blame] | 1067 | |
| 1068 | |
Marc-Antoine Ruel | 7de5259 | 2017-12-07 10:41:12 -0500 | [diff] [blame] | 1069 | def run_tha_test(data, result_json): |
nodir | 55be77b | 2016-05-03 09:39:57 -0700 | [diff] [blame] | 1070 | """Runs an executable and records execution metadata. |
| 1071 | |
nodir | 55be77b | 2016-05-03 09:39:57 -0700 | [diff] [blame] | 1072 | If isolated_hash is specified, downloads the dependencies in the cache, |
| 1073 | hardlinks them into a temporary directory and runs the command specified in |
| 1074 | the .isolated. |
Marc-Antoine Ruel | 2283ad1 | 2014-02-09 11:14:57 -0500 | [diff] [blame] | 1075 | |
| 1076 | A temporary directory is created to hold the output files. The content inside |
| 1077 | this directory will be uploaded back to |storage| packaged as a .isolated |
| 1078 | file. |
| 1079 | |
| 1080 | Arguments: |
Marc-Antoine Ruel | 7de5259 | 2017-12-07 10:41:12 -0500 | [diff] [blame] | 1081 | - data: TaskData instance. |
| 1082 | - result_json: File path to dump result metadata into. If set, the process |
| 1083 | exit code is always 0 unless an internal error occurred. |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 1084 | |
| 1085 | Returns: |
| 1086 | Process exit code that should be used. |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1087 | """ |
maruel | a76b9ee | 2015-12-15 06:18:08 -0800 | [diff] [blame] | 1088 | if result_json: |
| 1089 | # Write a json output file right away in case we get killed. |
| 1090 | result = { |
Junji Watanabe | 54925c3 | 2020-09-08 00:56:18 +0000 | [diff] [blame] | 1091 | 'exit_code': None, |
| 1092 | 'had_hard_timeout': False, |
| 1093 | 'internal_failure': 'Was terminated before completion', |
| 1094 | 'outputs_ref': None, |
| 1095 | 'cas_output_root': None, |
| 1096 | 'version': 5, |
maruel | a76b9ee | 2015-12-15 06:18:08 -0800 | [diff] [blame] | 1097 | } |
| 1098 | tools.write_json(result_json, result, dense=True) |
| 1099 | |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 1100 | # run_isolated exit code. Depends on if result_json is used or not. |
Marc-Antoine Ruel | 7de5259 | 2017-12-07 10:41:12 -0500 | [diff] [blame] | 1101 | result = map_and_run(data, True) |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 1102 | logging.info('Result:\n%s', tools.format_json(result, dense=True)) |
bpastene | 3ae0952 | 2016-06-10 17:12:59 -0700 | [diff] [blame] | 1103 | |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 1104 | if result_json: |
maruel | 05d5a88 | 2015-09-21 13:59:02 -0700 | [diff] [blame] | 1105 | # We've found tests to delete 'work' when quitting, causing an exception |
| 1106 | # here. Try to recreate the directory if necessary. |
nodir | e5028a9 | 2016-04-29 14:38:21 -0700 | [diff] [blame] | 1107 | file_path.ensure_tree(os.path.dirname(result_json)) |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 1108 | tools.write_json(result_json, result, dense=True) |
| 1109 | # Only return 1 if there was an internal error. |
| 1110 | return int(bool(result['internal_failure'])) |
maruel@chromium.org | 781ccf6 | 2013-09-17 19:39:47 +0000 | [diff] [blame] | 1111 | |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 1112 | # Marshall into old-style inline output. |
| 1113 | if result['outputs_ref']: |
Marc-Antoine Ruel | 793bff3 | 2019-04-18 17:50:48 +0000 | [diff] [blame] | 1114 | # pylint: disable=unsubscriptable-object |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 1115 | data = { |
Junji Watanabe | 38b28b0 | 2020-04-23 10:23:30 +0000 | [diff] [blame] | 1116 | 'hash': result['outputs_ref']['isolated'], |
| 1117 | 'namespace': result['outputs_ref']['namespace'], |
| 1118 | 'storage': result['outputs_ref']['isolatedserver'], |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 1119 | } |
Marc-Antoine Ruel | c44f572 | 2015-01-08 16:10:01 -0500 | [diff] [blame] | 1120 | sys.stdout.flush() |
Junji Watanabe | 38b28b0 | 2020-04-23 10:23:30 +0000 | [diff] [blame] | 1121 | print('[run_isolated_out_hack]%s[/run_isolated_out_hack]' % |
| 1122 | tools.format_json(data, dense=True)) |
maruel | b76604c | 2015-11-11 11:53:44 -0800 | [diff] [blame] | 1123 | sys.stdout.flush() |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 1124 | return result['exit_code'] or int(bool(result['internal_failure'])) |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1125 | |
| 1126 | |
iannucci | b58d10d | 2017-03-18 02:00:25 -0700 | [diff] [blame] | 1127 | # Yielded by 'install_client_and_packages'. |
vadimsh | 232f5a8 | 2017-01-20 19:23:44 -0800 | [diff] [blame] | 1128 | CipdInfo = collections.namedtuple('CipdInfo', [ |
| 1129 | 'client', # cipd.CipdClient object |
| 1130 | 'cache_dir', # absolute path to bot-global cipd tag and instance cache |
| 1131 | 'stats', # dict with stats to return to the server |
| 1132 | 'pins', # dict with installed cipd pins to return to the server |
| 1133 | ]) |
| 1134 | |
| 1135 | |
| 1136 | @contextlib.contextmanager |
Takuto Ikuta | 1ce6136 | 2021-11-16 05:44:17 +0000 | [diff] [blame] | 1137 | def copy_local_packages(_run_dir, cas_dir, _nsjail_dir): |
Junji Watanabe | dc2f89e | 2021-11-08 08:44:30 +0000 | [diff] [blame] | 1138 | """Copies CIPD packages from luci/luci-go dir.""" |
| 1139 | go_client_dir = os.environ.get('LUCI_GO_CLIENT_DIR') |
| 1140 | assert go_client_dir, ('Please set LUCI_GO_CLIENT_DIR env var to install CIPD' |
| 1141 | ' packages locally.') |
| 1142 | shutil.copy2(os.path.join(go_client_dir, 'cas' + cipd.EXECUTABLE_SUFFIX), |
| 1143 | os.path.join(cas_dir, 'cas' + cipd.EXECUTABLE_SUFFIX)) |
vadimsh | 232f5a8 | 2017-01-20 19:23:44 -0800 | [diff] [blame] | 1144 | yield None |
| 1145 | |
| 1146 | |
Takuto Ikuta | 2efc779 | 2019-11-27 14:33:34 +0000 | [diff] [blame] | 1147 | def _install_packages(run_dir, cipd_cache_dir, client, packages): |
iannucci | b58d10d | 2017-03-18 02:00:25 -0700 | [diff] [blame] | 1148 | """Calls 'cipd ensure' for packages. |
| 1149 | |
| 1150 | Args: |
| 1151 | run_dir (str): root of installation. |
| 1152 | cipd_cache_dir (str): the directory to use for the cipd package cache. |
| 1153 | client (CipdClient): the cipd client to use |
| 1154 | packages: packages to install, list [(path, package_name, version), ...]. |
iannucci | b58d10d | 2017-03-18 02:00:25 -0700 | [diff] [blame] | 1155 | |
| 1156 | Returns: list of pinned packages. Looks like [ |
| 1157 | { |
| 1158 | 'path': 'subdirectory', |
| 1159 | 'package_name': 'resolved/package/name', |
| 1160 | 'version': 'deadbeef...', |
| 1161 | }, |
| 1162 | ... |
| 1163 | ] |
| 1164 | """ |
| 1165 | package_pins = [None]*len(packages) |
| 1166 | def insert_pin(path, name, version, idx): |
| 1167 | package_pins[idx] = { |
| 1168 | 'package_name': name, |
| 1169 | # swarming deals with 'root' as '.' |
| 1170 | 'path': path or '.', |
| 1171 | 'version': version, |
| 1172 | } |
| 1173 | |
| 1174 | by_path = collections.defaultdict(list) |
| 1175 | for i, (path, name, version) in enumerate(packages): |
| 1176 | # cipd deals with 'root' as '' |
| 1177 | if path == '.': |
| 1178 | path = '' |
| 1179 | by_path[path].append((name, version, i)) |
| 1180 | |
| 1181 | pins = client.ensure( |
Takuto Ikuta | 2efc779 | 2019-11-27 14:33:34 +0000 | [diff] [blame] | 1182 | run_dir, |
| 1183 | { |
| 1184 | subdir: [(name, vers) for name, vers, _ in pkgs |
| 1185 | ] for subdir, pkgs in by_path.items() |
| 1186 | }, |
| 1187 | cache_dir=cipd_cache_dir, |
iannucci | b58d10d | 2017-03-18 02:00:25 -0700 | [diff] [blame] | 1188 | ) |
| 1189 | |
Marc-Antoine Ruel | 04903a3 | 2019-10-09 21:09:25 +0000 | [diff] [blame] | 1190 | for subdir, pin_list in sorted(pins.items()): |
iannucci | b58d10d | 2017-03-18 02:00:25 -0700 | [diff] [blame] | 1191 | this_subdir = by_path[subdir] |
| 1192 | for i, (name, version) in enumerate(pin_list): |
| 1193 | insert_pin(subdir, name, version, this_subdir[i][2]) |
| 1194 | |
Robert Iannucci | 461b30d | 2017-12-13 11:34:03 -0800 | [diff] [blame] | 1195 | assert None not in package_pins, (packages, pins, package_pins) |
iannucci | b58d10d | 2017-03-18 02:00:25 -0700 | [diff] [blame] | 1196 | |
| 1197 | return package_pins |
| 1198 | |
| 1199 | |
vadimsh | 232f5a8 | 2017-01-20 19:23:44 -0800 | [diff] [blame] | 1200 | @contextlib.contextmanager |
Takuto Ikuta | 2efc779 | 2019-11-27 14:33:34 +0000 | [diff] [blame] | 1201 | def install_client_and_packages(run_dir, packages, service_url, |
Takuto Ikuta | b7ce0e3 | 2019-11-27 23:26:18 +0000 | [diff] [blame] | 1202 | client_package_name, client_version, cache_dir, |
Takuto Ikuta | 1ce6136 | 2021-11-16 05:44:17 +0000 | [diff] [blame] | 1203 | cas_dir, nsjail_dir): |
vadimsh | 902948e | 2017-01-20 15:57:32 -0800 | [diff] [blame] | 1204 | """Bootstraps CIPD client and installs CIPD packages. |
iannucci | 96fcccc | 2016-08-30 15:52:22 -0700 | [diff] [blame] | 1205 | |
vadimsh | 232f5a8 | 2017-01-20 19:23:44 -0800 | [diff] [blame] | 1206 | Yields CipdClient, stats, client info and pins (as single CipdInfo object). |
| 1207 | |
| 1208 | Pins and the CIPD client info are in the form of: |
iannucci | 96fcccc | 2016-08-30 15:52:22 -0700 | [diff] [blame] | 1209 | [ |
| 1210 | { |
| 1211 | "path": path, "package_name": package_name, "version": version, |
| 1212 | }, |
| 1213 | ... |
| 1214 | ] |
vadimsh | 902948e | 2017-01-20 15:57:32 -0800 | [diff] [blame] | 1215 | (the CIPD client info is a single dictionary instead of a list) |
iannucci | 96fcccc | 2016-08-30 15:52:22 -0700 | [diff] [blame] | 1216 | |
| 1217 | such that they correspond 1:1 to all input package arguments from the command |
| 1218 | line. These dictionaries make their all the way back to swarming, where they |
| 1219 | become the arguments of CipdPackage. |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 1220 | |
vadimsh | 902948e | 2017-01-20 15:57:32 -0800 | [diff] [blame] | 1221 | If 'packages' list is empty, will bootstrap CIPD client, but won't install |
| 1222 | any packages. |
| 1223 | |
| 1224 | The bootstrapped client (regardless whether 'packages' list is empty or not), |
vadimsh | 232f5a8 | 2017-01-20 19:23:44 -0800 | [diff] [blame] | 1225 | will be made available to the task via $PATH. |
vadimsh | 902948e | 2017-01-20 15:57:32 -0800 | [diff] [blame] | 1226 | |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 1227 | Args: |
nodir | 90bc8dc | 2016-06-15 13:35:21 -0700 | [diff] [blame] | 1228 | run_dir (str): root of installation. |
vadimsh | 902948e | 2017-01-20 15:57:32 -0800 | [diff] [blame] | 1229 | packages: packages to install, list [(path, package_name, version), ...]. |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 1230 | service_url (str): CIPD server url, e.g. |
| 1231 | "https://chrome-infra-packages.appspot.com." |
nodir | 90bc8dc | 2016-06-15 13:35:21 -0700 | [diff] [blame] | 1232 | client_package_name (str): CIPD package name of CIPD client. |
| 1233 | client_version (str): Version of CIPD client. |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 1234 | cache_dir (str): where to keep cache of cipd clients, packages and tags. |
Junji Watanabe | 4b890ef | 2020-09-16 01:43:27 +0000 | [diff] [blame] | 1235 | cas_dir (str): where to download cas client. |
Anirudh Mathukumilli | 92d57b6 | 2021-08-04 23:21:57 +0000 | [diff] [blame] | 1236 | nsjail_dir (str): where to download nsjail. If set to None, nsjail is not |
| 1237 | downloaded. |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 1238 | """ |
| 1239 | assert cache_dir |
nodir | 90bc8dc | 2016-06-15 13:35:21 -0700 | [diff] [blame] | 1240 | |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 1241 | start = time.time() |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 1242 | |
vadimsh | 902948e | 2017-01-20 15:57:32 -0800 | [diff] [blame] | 1243 | cache_dir = os.path.abspath(cache_dir) |
vadimsh | 232f5a8 | 2017-01-20 19:23:44 -0800 | [diff] [blame] | 1244 | cipd_cache_dir = os.path.join(cache_dir, 'cache') # tag and instance caches |
nodir | 90bc8dc | 2016-06-15 13:35:21 -0700 | [diff] [blame] | 1245 | run_dir = os.path.abspath(run_dir) |
vadimsh | 902948e | 2017-01-20 15:57:32 -0800 | [diff] [blame] | 1246 | packages = packages or [] |
nodir | 90bc8dc | 2016-06-15 13:35:21 -0700 | [diff] [blame] | 1247 | |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 1248 | get_client_start = time.time() |
Junji Watanabe | 4b890ef | 2020-09-16 01:43:27 +0000 | [diff] [blame] | 1249 | client_manager = cipd.get_client(cache_dir, service_url, client_package_name, |
| 1250 | client_version) |
iannucci | 96fcccc | 2016-08-30 15:52:22 -0700 | [diff] [blame] | 1251 | |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 1252 | with client_manager as client: |
| 1253 | get_client_duration = time.time() - get_client_start |
nodir | 90bc8dc | 2016-06-15 13:35:21 -0700 | [diff] [blame] | 1254 | |
iannucci | b58d10d | 2017-03-18 02:00:25 -0700 | [diff] [blame] | 1255 | package_pins = [] |
| 1256 | if packages: |
Takuto Ikuta | 2efc779 | 2019-11-27 14:33:34 +0000 | [diff] [blame] | 1257 | package_pins = _install_packages(run_dir, cipd_cache_dir, client, |
| 1258 | packages) |
iannucci | b58d10d | 2017-03-18 02:00:25 -0700 | [diff] [blame] | 1259 | |
Junji Watanabe | 4b890ef | 2020-09-16 01:43:27 +0000 | [diff] [blame] | 1260 | # Install cas client to |cas_dir|. |
| 1261 | _install_packages(cas_dir, cipd_cache_dir, client, |
Takuto Ikuta | 9c4eb1d | 2020-10-05 03:40:14 +0000 | [diff] [blame] | 1262 | [('', _CAS_PACKAGE, _LUCI_GO_REVISION)]) |
Junji Watanabe | 4b890ef | 2020-09-16 01:43:27 +0000 | [diff] [blame] | 1263 | |
Anirudh Mathukumilli | 92d57b6 | 2021-08-04 23:21:57 +0000 | [diff] [blame] | 1264 | # Install nsjail to |nsjail_dir|. |
| 1265 | if nsjail_dir is not None: |
| 1266 | _install_packages(nsjail_dir, cipd_cache_dir, client, |
| 1267 | [('', _NSJAIL_PACKAGE, _NSJAIL_VERSION)]) |
| 1268 | |
iannucci | b58d10d | 2017-03-18 02:00:25 -0700 | [diff] [blame] | 1269 | file_path.make_tree_files_read_only(run_dir) |
nodir | 90bc8dc | 2016-06-15 13:35:21 -0700 | [diff] [blame] | 1270 | |
vadimsh | 232f5a8 | 2017-01-20 19:23:44 -0800 | [diff] [blame] | 1271 | total_duration = time.time() - start |
Junji Watanabe | 38b28b0 | 2020-04-23 10:23:30 +0000 | [diff] [blame] | 1272 | logging.info('Installing CIPD client and packages took %d seconds', |
| 1273 | total_duration) |
nodir | 90bc8dc | 2016-06-15 13:35:21 -0700 | [diff] [blame] | 1274 | |
vadimsh | 232f5a8 | 2017-01-20 19:23:44 -0800 | [diff] [blame] | 1275 | yield CipdInfo( |
Junji Watanabe | 38b28b0 | 2020-04-23 10:23:30 +0000 | [diff] [blame] | 1276 | client=client, |
| 1277 | cache_dir=cipd_cache_dir, |
| 1278 | stats={ |
| 1279 | 'duration': total_duration, |
| 1280 | 'get_client_duration': get_client_duration, |
iannucci | b58d10d | 2017-03-18 02:00:25 -0700 | [diff] [blame] | 1281 | }, |
Junji Watanabe | 38b28b0 | 2020-04-23 10:23:30 +0000 | [diff] [blame] | 1282 | pins={ |
| 1283 | 'client_package': { |
| 1284 | 'package_name': client.package_name, |
| 1285 | 'version': client.instance_id, |
| 1286 | }, |
| 1287 | 'packages': package_pins, |
| 1288 | }) |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 1289 | |
| 1290 | |
| 1291 | def create_option_parser(): |
Marc-Antoine Ruel | f74cffe | 2015-07-15 15:21:34 -0400 | [diff] [blame] | 1292 | parser = logging_utils.OptionParserWithLogging( |
nodir | 55be77b | 2016-05-03 09:39:57 -0700 | [diff] [blame] | 1293 | usage='%prog <options> [command to run or extra args]', |
maruel@chromium.org | dedbf49 | 2013-09-12 20:42:11 +0000 | [diff] [blame] | 1294 | version=__version__, |
| 1295 | log_file=RUN_ISOLATED_LOG_FILE) |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 1296 | parser.add_option( |
Junji Watanabe | 38b28b0 | 2020-04-23 10:23:30 +0000 | [diff] [blame] | 1297 | '--clean', |
| 1298 | action='store_true', |
maruel | 36a963d | 2016-04-08 17:15:49 -0700 | [diff] [blame] | 1299 | help='Cleans the cache, trimming it necessary and remove corrupted items ' |
Junji Watanabe | 38b28b0 | 2020-04-23 10:23:30 +0000 | [diff] [blame] | 1300 | 'and returns without executing anything; use with -v to know what ' |
| 1301 | 'was done') |
maruel | 36a963d | 2016-04-08 17:15:49 -0700 | [diff] [blame] | 1302 | parser.add_option( |
maruel | a9cfd6f | 2015-09-15 11:03:15 -0700 | [diff] [blame] | 1303 | '--json', |
| 1304 | help='dump output metadata to json file. When used, run_isolated returns ' |
Junji Watanabe | 38b28b0 | 2020-04-23 10:23:30 +0000 | [diff] [blame] | 1305 | 'non-zero only on internal failure') |
maruel | 6be7f9e | 2015-10-01 12:25:30 -0700 | [diff] [blame] | 1306 | parser.add_option( |
maruel | 5c9e47b | 2015-12-18 13:02:30 -0800 | [diff] [blame] | 1307 | '--hard-timeout', type='float', help='Enforce hard timeout in execution') |
maruel | 6be7f9e | 2015-10-01 12:25:30 -0700 | [diff] [blame] | 1308 | parser.add_option( |
Junji Watanabe | 38b28b0 | 2020-04-23 10:23:30 +0000 | [diff] [blame] | 1309 | '--grace-period', |
| 1310 | type='float', |
maruel | 6be7f9e | 2015-10-01 12:25:30 -0700 | [diff] [blame] | 1311 | help='Grace period between SIGTERM and SIGKILL') |
bpastene | 3ae0952 | 2016-06-10 17:12:59 -0700 | [diff] [blame] | 1312 | parser.add_option( |
Marc-Antoine Ruel | 95068cf | 2017-12-07 21:35:05 -0500 | [diff] [blame] | 1313 | '--relative-cwd', |
Takuto Ikuta | 18ca29a | 2020-12-04 07:34:20 +0000 | [diff] [blame] | 1314 | help='Ignore the isolated \'relative_cwd\' and use this one instead') |
Marc-Antoine Ruel | 95068cf | 2017-12-07 21:35:05 -0500 | [diff] [blame] | 1315 | parser.add_option( |
Junji Watanabe | 38b28b0 | 2020-04-23 10:23:30 +0000 | [diff] [blame] | 1316 | '--env', |
| 1317 | default=[], |
| 1318 | action='append', |
Marc-Antoine Ruel | 19dd887 | 2017-11-28 18:33:39 -0500 | [diff] [blame] | 1319 | help='Environment variables to set for the child process') |
| 1320 | parser.add_option( |
Junji Watanabe | 38b28b0 | 2020-04-23 10:23:30 +0000 | [diff] [blame] | 1321 | '--env-prefix', |
| 1322 | default=[], |
| 1323 | action='append', |
Robert Iannucci | bf5f84c | 2017-11-22 12:56:50 -0800 | [diff] [blame] | 1324 | help='Specify a VAR=./path/fragment to put in the environment variable ' |
Junji Watanabe | 38b28b0 | 2020-04-23 10:23:30 +0000 | [diff] [blame] | 1325 | 'before executing the command. The path fragment must be relative ' |
| 1326 | 'to the isolated run directory, and must not contain a `..` token. ' |
| 1327 | 'The path will be made absolute and prepended to the indicated ' |
| 1328 | '$VAR using the OS\'s path separator. Multiple items for the same ' |
| 1329 | '$VAR will be prepended in order.') |
Robert Iannucci | bf5f84c | 2017-11-22 12:56:50 -0800 | [diff] [blame] | 1330 | parser.add_option( |
bpastene | 3ae0952 | 2016-06-10 17:12:59 -0700 | [diff] [blame] | 1331 | '--bot-file', |
| 1332 | help='Path to a file describing the state of the host. The content is ' |
Junji Watanabe | 38b28b0 | 2020-04-23 10:23:30 +0000 | [diff] [blame] | 1333 | 'defined by on_before_task() in bot_config.') |
aludwin | 7556e0c | 2016-10-26 08:46:10 -0700 | [diff] [blame] | 1334 | parser.add_option( |
vadimsh | 9c54b2c | 2017-07-25 14:08:29 -0700 | [diff] [blame] | 1335 | '--switch-to-account', |
| 1336 | help='If given, switches LUCI_CONTEXT to given logical service account ' |
Junji Watanabe | 38b28b0 | 2020-04-23 10:23:30 +0000 | [diff] [blame] | 1337 | '(e.g. "task" or "system") before launching the isolated process.') |
vadimsh | 9c54b2c | 2017-07-25 14:08:29 -0700 | [diff] [blame] | 1338 | parser.add_option( |
Junji Watanabe | 38b28b0 | 2020-04-23 10:23:30 +0000 | [diff] [blame] | 1339 | '--output', |
| 1340 | action='append', |
aludwin | 0a8e17d | 2016-10-27 15:57:39 -0700 | [diff] [blame] | 1341 | help='Specifies an output to return. If no outputs are specified, all ' |
Junji Watanabe | 38b28b0 | 2020-04-23 10:23:30 +0000 | [diff] [blame] | 1342 | 'files located in $(ISOLATED_OUTDIR) will be returned; ' |
| 1343 | 'otherwise, outputs in both $(ISOLATED_OUTDIR) and those ' |
| 1344 | 'specified by --output option (there can be multiple) will be ' |
| 1345 | 'returned. Note that if a file in OUT_DIR has the same path ' |
| 1346 | 'as an --output option, the --output version will be returned.') |
aludwin | 0a8e17d | 2016-10-27 15:57:39 -0700 | [diff] [blame] | 1347 | parser.add_option( |
Junji Watanabe | 38b28b0 | 2020-04-23 10:23:30 +0000 | [diff] [blame] | 1348 | '-a', |
| 1349 | '--argsfile', |
aludwin | 7556e0c | 2016-10-26 08:46:10 -0700 | [diff] [blame] | 1350 | # This is actually handled in parse_args; it's included here purely so it |
| 1351 | # can make it into the help text. |
| 1352 | help='Specify a file containing a JSON array of arguments to this ' |
Junji Watanabe | 38b28b0 | 2020-04-23 10:23:30 +0000 | [diff] [blame] | 1353 | 'script. If --argsfile is provided, no other argument may be ' |
| 1354 | 'provided on the command line.') |
Takuto Ikuta | d4be2f1 | 2020-05-12 02:15:25 +0000 | [diff] [blame] | 1355 | parser.add_option( |
| 1356 | '--report-on-exception', |
| 1357 | action='store_true', |
| 1358 | help='Whether report exception during execution to isolate server. ' |
| 1359 | 'This flag should only be used in swarming bot.') |
Marc-Antoine Ruel | 1b65f4e | 2019-05-02 21:56:58 +0000 | [diff] [blame] | 1360 | |
Junji Watanabe | 4b890ef | 2020-09-16 01:43:27 +0000 | [diff] [blame] | 1361 | group = optparse.OptionGroup(parser, |
| 1362 | 'Data source - Content Addressed Storage') |
Junji Watanabe | 54925c3 | 2020-09-08 00:56:18 +0000 | [diff] [blame] | 1363 | group.add_option( |
| 1364 | '--cas-instance', help='Full CAS instance name for input/output files.') |
| 1365 | group.add_option( |
| 1366 | '--cas-digest', |
| 1367 | help='Digest of the input root on RBE-CAS. The format is ' |
| 1368 | '`{hash}/{size_bytes}`.') |
Marc-Antoine Ruel | 1b65f4e | 2019-05-02 21:56:58 +0000 | [diff] [blame] | 1369 | parser.add_option_group(group) |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1370 | |
Junji Watanabe | b03450b | 2020-09-25 05:09:27 +0000 | [diff] [blame] | 1371 | # Cache options. |
Junji Watanabe | b03450b | 2020-09-25 05:09:27 +0000 | [diff] [blame] | 1372 | add_cas_cache_options(parser) |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 1373 | |
| 1374 | cipd.add_cipd_options(parser) |
Marc-Antoine Ruel | 8b11dbd | 2018-05-18 14:31:22 -0400 | [diff] [blame] | 1375 | |
| 1376 | group = optparse.OptionGroup(parser, 'Named caches') |
| 1377 | group.add_option( |
| 1378 | '--named-cache', |
| 1379 | dest='named_caches', |
| 1380 | action='append', |
Marc-Antoine Ruel | c7a704b | 2018-08-29 19:02:23 +0000 | [diff] [blame] | 1381 | nargs=3, |
Marc-Antoine Ruel | 8b11dbd | 2018-05-18 14:31:22 -0400 | [diff] [blame] | 1382 | default=[], |
Marc-Antoine Ruel | c7a704b | 2018-08-29 19:02:23 +0000 | [diff] [blame] | 1383 | help='A named cache to request. Accepts 3 arguments: name, path, hint. ' |
Junji Watanabe | 38b28b0 | 2020-04-23 10:23:30 +0000 | [diff] [blame] | 1384 | 'name identifies the cache, must match regex [a-z0-9_]{1,4096}. ' |
| 1385 | 'path is a path relative to the run dir where the cache directory ' |
| 1386 | 'must be put to. ' |
| 1387 | 'This option can be specified more than once.') |
Marc-Antoine Ruel | 8b11dbd | 2018-05-18 14:31:22 -0400 | [diff] [blame] | 1388 | group.add_option( |
Junji Watanabe | 38b28b0 | 2020-04-23 10:23:30 +0000 | [diff] [blame] | 1389 | '--named-cache-root', |
| 1390 | default='named_caches', |
Marc-Antoine Ruel | 8b11dbd | 2018-05-18 14:31:22 -0400 | [diff] [blame] | 1391 | help='Cache root directory. Default=%default') |
| 1392 | parser.add_option_group(group) |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1393 | |
Marc-Antoine Ruel | 1b65f4e | 2019-05-02 21:56:58 +0000 | [diff] [blame] | 1394 | group = optparse.OptionGroup(parser, 'Process containment') |
| 1395 | parser.add_option( |
| 1396 | '--lower-priority', action='store_true', |
| 1397 | help='Lowers the child process priority') |
| 1398 | parser.add_option( |
Junji Watanabe | 38b28b0 | 2020-04-23 10:23:30 +0000 | [diff] [blame] | 1399 | '--containment-type', |
Anirudh Mathukumilli | 92d57b6 | 2021-08-04 23:21:57 +0000 | [diff] [blame] | 1400 | choices=('NONE', 'AUTO', 'JOB_OBJECT', 'NSJAIL'), |
Marc-Antoine Ruel | 1b65f4e | 2019-05-02 21:56:58 +0000 | [diff] [blame] | 1401 | default='NONE', |
| 1402 | help='Type of container to use') |
| 1403 | parser.add_option( |
Junji Watanabe | 38b28b0 | 2020-04-23 10:23:30 +0000 | [diff] [blame] | 1404 | '--limit-processes', |
| 1405 | type='int', |
| 1406 | default=0, |
Marc-Antoine Ruel | 1b65f4e | 2019-05-02 21:56:58 +0000 | [diff] [blame] | 1407 | help='Maximum number of active processes in the containment') |
| 1408 | parser.add_option( |
Junji Watanabe | 38b28b0 | 2020-04-23 10:23:30 +0000 | [diff] [blame] | 1409 | '--limit-total-committed-memory', |
| 1410 | type='int', |
| 1411 | default=0, |
Marc-Antoine Ruel | 1b65f4e | 2019-05-02 21:56:58 +0000 | [diff] [blame] | 1412 | help='Maximum sum of committed memory in the containment') |
| 1413 | parser.add_option_group(group) |
| 1414 | |
| 1415 | group = optparse.OptionGroup(parser, 'Debugging') |
| 1416 | group.add_option( |
Kenneth Russell | 61d4235 | 2014-09-15 11:41:16 -0700 | [diff] [blame] | 1417 | '--leak-temp-dir', |
| 1418 | action='store_true', |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 1419 | help='Deliberately leak isolate\'s temp dir for later examination. ' |
Junji Watanabe | 38b28b0 | 2020-04-23 10:23:30 +0000 | [diff] [blame] | 1420 | 'Default: %default') |
| 1421 | group.add_option('--root-dir', help='Use a directory instead of a random one') |
Marc-Antoine Ruel | 1b65f4e | 2019-05-02 21:56:58 +0000 | [diff] [blame] | 1422 | parser.add_option_group(group) |
Kenneth Russell | 61d4235 | 2014-09-15 11:41:16 -0700 | [diff] [blame] | 1423 | |
Vadim Shtayura | e34e13a | 2014-02-02 11:23:26 -0800 | [diff] [blame] | 1424 | auth.add_auth_options(parser) |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 1425 | |
Ye Kuang | 1d096cb | 2020-06-26 08:38:21 +0000 | [diff] [blame] | 1426 | parser.set_defaults(cache='cache') |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 1427 | return parser |
| 1428 | |
| 1429 | |
Junji Watanabe | b03450b | 2020-09-25 05:09:27 +0000 | [diff] [blame] | 1430 | def add_cas_cache_options(parser): |
| 1431 | group = optparse.OptionGroup(parser, 'CAS cache management') |
| 1432 | group.add_option( |
| 1433 | '--cas-cache', |
| 1434 | metavar='DIR', |
| 1435 | default='cas-cache', |
| 1436 | help='Directory to keep a local cache of the files. Accelerates download ' |
| 1437 | 'by reusing already downloaded files. Default=%default') |
Takuto Ikuta | 7ff4b24 | 2020-12-03 08:07:06 +0000 | [diff] [blame] | 1438 | group.add_option( |
Takuto Ikuta | 91cb5ca | 2021-03-17 07:19:30 +0000 | [diff] [blame] | 1439 | '--kvs-dir', |
Takuto Ikuta | 7ff4b24 | 2020-12-03 08:07:06 +0000 | [diff] [blame] | 1440 | default='', |
Takuto Ikuta | 91cb5ca | 2021-03-17 07:19:30 +0000 | [diff] [blame] | 1441 | help='CAS cache dir using kvs for small files. Default=%default') |
Takuto Ikuta | a71c656 | 2021-11-18 06:07:55 +0000 | [diff] [blame] | 1442 | group.add_option( |
| 1443 | '--max-cache-size', |
| 1444 | type='int', |
| 1445 | metavar='NNN', |
| 1446 | default=50 * 1024 * 1024 * 1024, |
| 1447 | help='Trim if the cache gets larger than this value, default=%default') |
| 1448 | group.add_option( |
| 1449 | '--min-free-space', |
| 1450 | type='int', |
| 1451 | metavar='NNN', |
| 1452 | default=2 * 1024 * 1024 * 1024, |
| 1453 | help='Trim if disk free space becomes lower than this value, ' |
| 1454 | 'default=%default') |
Junji Watanabe | b03450b | 2020-09-25 05:09:27 +0000 | [diff] [blame] | 1455 | parser.add_option_group(group) |
| 1456 | |
| 1457 | |
| 1458 | def process_cas_cache_options(options): |
| 1459 | if options.cas_cache: |
| 1460 | policies = local_caching.CachePolicies( |
| 1461 | max_cache_size=options.max_cache_size, |
| 1462 | min_free_space=options.min_free_space, |
| 1463 | # max_items isn't used for CAS cache for now. |
| 1464 | max_items=None, |
| 1465 | max_age_secs=MAX_AGE_SECS) |
| 1466 | |
Junji Watanabe | 7a631b0 | 2022-01-13 02:30:29 +0000 | [diff] [blame] | 1467 | return local_caching.DiskContentAddressedCache(os.path.abspath( |
| 1468 | options.cas_cache), |
| 1469 | policies, |
| 1470 | trim=False) |
Junji Watanabe | b03450b | 2020-09-25 05:09:27 +0000 | [diff] [blame] | 1471 | return local_caching.MemoryContentAddressedCache() |
| 1472 | |
| 1473 | |
Marc-Antoine Ruel | 49f9f8d | 2018-05-24 15:57:06 -0400 | [diff] [blame] | 1474 | def process_named_cache_options(parser, options, time_fn=None): |
Marc-Antoine Ruel | 8b11dbd | 2018-05-18 14:31:22 -0400 | [diff] [blame] | 1475 | """Validates named cache options and returns a CacheManager.""" |
| 1476 | if options.named_caches and not options.named_cache_root: |
| 1477 | parser.error('--named-cache is specified, but --named-cache-root is empty') |
Marc-Antoine Ruel | c7a704b | 2018-08-29 19:02:23 +0000 | [diff] [blame] | 1478 | for name, path, hint in options.named_caches: |
Marc-Antoine Ruel | 8b11dbd | 2018-05-18 14:31:22 -0400 | [diff] [blame] | 1479 | if not CACHE_NAME_RE.match(name): |
| 1480 | parser.error( |
| 1481 | 'cache name %r does not match %r' % (name, CACHE_NAME_RE.pattern)) |
| 1482 | if not path: |
| 1483 | parser.error('cache path cannot be empty') |
Marc-Antoine Ruel | c7a704b | 2018-08-29 19:02:23 +0000 | [diff] [blame] | 1484 | try: |
Takuto Ikuta | 630f99d | 2020-07-02 12:59:35 +0000 | [diff] [blame] | 1485 | int(hint) |
Marc-Antoine Ruel | c7a704b | 2018-08-29 19:02:23 +0000 | [diff] [blame] | 1486 | except ValueError: |
| 1487 | parser.error('cache hint must be a number') |
Marc-Antoine Ruel | 8b11dbd | 2018-05-18 14:31:22 -0400 | [diff] [blame] | 1488 | if options.named_cache_root: |
| 1489 | # Make these configurable later if there is use case but for now it's fairly |
| 1490 | # safe values. |
| 1491 | # In practice, a fair chunk of bots are already recycled on a daily schedule |
| 1492 | # so this code doesn't have any effect to them, unless they are preloaded |
| 1493 | # with a really old cache. |
| 1494 | policies = local_caching.CachePolicies( |
| 1495 | # 1TiB. |
| 1496 | max_cache_size=1024*1024*1024*1024, |
| 1497 | min_free_space=options.min_free_space, |
| 1498 | max_items=50, |
Marc-Antoine Ruel | 5d7606b | 2018-06-15 19:06:12 +0000 | [diff] [blame] | 1499 | max_age_secs=MAX_AGE_SECS) |
Junji Watanabe | 7a631b0 | 2022-01-13 02:30:29 +0000 | [diff] [blame] | 1500 | root_dir = os.path.abspath(options.named_cache_root) |
John Budorick | c618697 | 2020-02-26 00:58:14 +0000 | [diff] [blame] | 1501 | cache = local_caching.NamedCache(root_dir, policies, time_fn=time_fn) |
| 1502 | # Touch any named caches we're going to use to minimize thrashing |
| 1503 | # between tasks that request some (but not all) of the same named caches. |
John Budorick | 0a4dab6 | 2020-03-02 22:23:35 +0000 | [diff] [blame] | 1504 | cache.touch(*[name for name, _, _ in options.named_caches]) |
John Budorick | c618697 | 2020-02-26 00:58:14 +0000 | [diff] [blame] | 1505 | return cache |
Marc-Antoine Ruel | 8b11dbd | 2018-05-18 14:31:22 -0400 | [diff] [blame] | 1506 | return None |
| 1507 | |
| 1508 | |
aludwin | 7556e0c | 2016-10-26 08:46:10 -0700 | [diff] [blame] | 1509 | def parse_args(args): |
| 1510 | # Create a fake mini-parser just to get out the "-a" command. Note that |
| 1511 | # it's not documented here; instead, it's documented in create_option_parser |
| 1512 | # even though that parser will never actually get to parse it. This is |
| 1513 | # because --argsfile is exclusive with all other options and arguments. |
| 1514 | file_argparse = argparse.ArgumentParser(add_help=False) |
| 1515 | file_argparse.add_argument('-a', '--argsfile') |
| 1516 | (file_args, nonfile_args) = file_argparse.parse_known_args(args) |
| 1517 | if file_args.argsfile: |
| 1518 | if nonfile_args: |
| 1519 | file_argparse.error('Can\'t specify --argsfile with' |
| 1520 | 'any other arguments (%s)' % nonfile_args) |
| 1521 | try: |
| 1522 | with open(file_args.argsfile, 'r') as f: |
| 1523 | args = json.load(f) |
| 1524 | except (IOError, OSError, ValueError) as e: |
| 1525 | # We don't need to error out here - "args" is now empty, |
| 1526 | # so the call below to parser.parse_args(args) will fail |
| 1527 | # and print the full help text. |
Marc-Antoine Ruel | f899c48 | 2019-10-10 23:32:06 +0000 | [diff] [blame] | 1528 | print('Couldn\'t read arguments: %s' % e, file=sys.stderr) |
aludwin | 7556e0c | 2016-10-26 08:46:10 -0700 | [diff] [blame] | 1529 | |
| 1530 | # Even if we failed to read the args, just call the normal parser now since it |
| 1531 | # will print the correct help message. |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 1532 | parser = create_option_parser() |
Marc-Antoine Ruel | 90c9816 | 2013-12-18 15:11:57 -0500 | [diff] [blame] | 1533 | options, args = parser.parse_args(args) |
Ye Kuang | fff1e50 | 2020-07-13 13:21:57 +0000 | [diff] [blame] | 1534 | if not isinstance(options.cipd_enabled, (bool, int)): |
| 1535 | options.cipd_enabled = distutils.util.strtobool(options.cipd_enabled) |
aludwin | 7556e0c | 2016-10-26 08:46:10 -0700 | [diff] [blame] | 1536 | return (parser, options, args) |
| 1537 | |
| 1538 | |
Marc-Antoine Ruel | c7a704b | 2018-08-29 19:02:23 +0000 | [diff] [blame] | 1539 | def _calc_named_cache_hint(named_cache, named_caches): |
| 1540 | """Returns the expected size of the missing named caches.""" |
| 1541 | present = named_cache.available |
| 1542 | size = 0 |
Takuto Ikuta | d169bfd | 2021-08-02 05:45:09 +0000 | [diff] [blame] | 1543 | logging.info('available named cache %s', present) |
Marc-Antoine Ruel | c7a704b | 2018-08-29 19:02:23 +0000 | [diff] [blame] | 1544 | for name, _, hint in named_caches: |
| 1545 | if name not in present: |
Takuto Ikuta | 630f99d | 2020-07-02 12:59:35 +0000 | [diff] [blame] | 1546 | hint = int(hint) |
Marc-Antoine Ruel | c7a704b | 2018-08-29 19:02:23 +0000 | [diff] [blame] | 1547 | if hint > 0: |
Takuto Ikuta | 7468684 | 2021-07-30 04:11:03 +0000 | [diff] [blame] | 1548 | logging.info("named cache hint: %s, %d", name, hint) |
Marc-Antoine Ruel | c7a704b | 2018-08-29 19:02:23 +0000 | [diff] [blame] | 1549 | size += hint |
Takuto Ikuta | 7468684 | 2021-07-30 04:11:03 +0000 | [diff] [blame] | 1550 | logging.info("total size of named cache hint: %d", size) |
Marc-Antoine Ruel | c7a704b | 2018-08-29 19:02:23 +0000 | [diff] [blame] | 1551 | return size |
| 1552 | |
| 1553 | |
Takuto Ikuta | ae391c5 | 2020-12-03 08:43:45 +0000 | [diff] [blame] | 1554 | def _clean_cmd(parser, options, caches, root): |
Takuto Ikuta | 7ff4b24 | 2020-12-03 08:07:06 +0000 | [diff] [blame] | 1555 | """Cleanup cache dirs/files.""" |
Takuto Ikuta | 7ff4b24 | 2020-12-03 08:07:06 +0000 | [diff] [blame] | 1556 | if options.json: |
| 1557 | parser.error('Can\'t use --json with --clean.') |
| 1558 | if options.named_caches: |
| 1559 | parser.error('Can\t use --named-cache with --clean.') |
| 1560 | if options.cas_instance or options.cas_digest: |
| 1561 | parser.error('Can\t use --cas-instance, --cas-digest with --clean.') |
| 1562 | |
| 1563 | logging.info("initial free space: %d", file_path.get_free_space(root)) |
| 1564 | |
Junji Watanabe | 7a631b0 | 2022-01-13 02:30:29 +0000 | [diff] [blame] | 1565 | if options.kvs_dir and fs.isdir(options.kvs_dir): |
Takuto Ikuta | 7ff4b24 | 2020-12-03 08:07:06 +0000 | [diff] [blame] | 1566 | # Remove kvs file if its size exceeds fixed threshold. |
Junji Watanabe | 7a631b0 | 2022-01-13 02:30:29 +0000 | [diff] [blame] | 1567 | kvs_dir = options.kvs_dir |
Takuto Ikuta | b1b7006 | 2021-03-22 01:02:41 +0000 | [diff] [blame] | 1568 | size = file_path.get_recursive_size(kvs_dir) |
Takuto Ikuta | 91cb5ca | 2021-03-17 07:19:30 +0000 | [diff] [blame] | 1569 | if size >= _CAS_KVS_CACHE_THRESHOLD: |
| 1570 | logging.info("remove kvs dir with size: %d", size) |
Takuto Ikuta | b1b7006 | 2021-03-22 01:02:41 +0000 | [diff] [blame] | 1571 | file_path.rmtree(kvs_dir) |
Takuto Ikuta | 7ff4b24 | 2020-12-03 08:07:06 +0000 | [diff] [blame] | 1572 | |
| 1573 | # Trim first, then clean. |
| 1574 | local_caching.trim_caches( |
| 1575 | caches, |
| 1576 | root, |
| 1577 | min_free_space=options.min_free_space, |
| 1578 | max_age_secs=MAX_AGE_SECS) |
| 1579 | logging.info("free space after trim: %d", file_path.get_free_space(root)) |
| 1580 | for c in caches: |
| 1581 | c.cleanup() |
| 1582 | logging.info("free space after cleanup: %d", file_path.get_free_space(root)) |
| 1583 | |
| 1584 | |
aludwin | 7556e0c | 2016-10-26 08:46:10 -0700 | [diff] [blame] | 1585 | def main(args): |
Marc-Antoine Ruel | ee6ca62 | 2017-11-29 11:19:16 -0500 | [diff] [blame] | 1586 | # Warning: when --argsfile is used, the strings are unicode instances, when |
| 1587 | # parsed normally, the strings are str instances. |
aludwin | 7556e0c | 2016-10-26 08:46:10 -0700 | [diff] [blame] | 1588 | (parser, options, args) = parse_args(args) |
maruel | 36a963d | 2016-04-08 17:15:49 -0700 | [diff] [blame] | 1589 | |
Jonah Hooper | 9b5bd8c | 2022-07-21 15:33:41 +0000 | [diff] [blame] | 1590 | # adds another log level for logs which are directed to standard output |
| 1591 | # these logs will be uploaded to cloudstorage |
| 1592 | logging_utils.set_user_level_logging() |
| 1593 | |
Joanna Wang | 40959bf | 2021-08-12 18:10:12 +0000 | [diff] [blame] | 1594 | # Must be logged after parse_args(), which eventually calls |
| 1595 | # logging_utils.prepare_logging() which expects no logs before its call. |
Jonah Hooper | 9b5bd8c | 2022-07-21 15:33:41 +0000 | [diff] [blame] | 1596 | logging_utils.user_logs('Starting run_isolated script') |
Joanna Wang | 40959bf | 2021-08-12 18:10:12 +0000 | [diff] [blame] | 1597 | |
Junji Watanabe | 1d83d28 | 2021-05-11 05:50:40 +0000 | [diff] [blame] | 1598 | SWARMING_SERVER = os.environ.get('SWARMING_SERVER') |
| 1599 | SWARMING_TASK_ID = os.environ.get('SWARMING_TASK_ID') |
| 1600 | if options.report_on_exception and SWARMING_SERVER: |
| 1601 | task_url = None |
| 1602 | if SWARMING_TASK_ID: |
| 1603 | task_url = '%s/task?id=%s' % (SWARMING_SERVER, SWARMING_TASK_ID) |
| 1604 | on_error.report_on_exception_exit(SWARMING_SERVER, source=task_url) |
Takuto Ikuta | d4be2f1 | 2020-05-12 02:15:25 +0000 | [diff] [blame] | 1605 | |
Marc-Antoine Ruel | 5028ba2 | 2017-08-25 17:37:51 -0400 | [diff] [blame] | 1606 | if not file_path.enable_symlink(): |
Marc-Antoine Ruel | 5a02427 | 2019-01-15 20:11:16 +0000 | [diff] [blame] | 1607 | logging.warning('Symlink support is not enabled') |
Marc-Antoine Ruel | 5028ba2 | 2017-08-25 17:37:51 -0400 | [diff] [blame] | 1608 | |
Marc-Antoine Ruel | c7a704b | 2018-08-29 19:02:23 +0000 | [diff] [blame] | 1609 | named_cache = process_named_cache_options(parser, options) |
Marc-Antoine Ruel | 0d8b0f6 | 2018-09-10 14:40:35 +0000 | [diff] [blame] | 1610 | # hint is 0 if there's no named cache. |
Marc-Antoine Ruel | c7a704b | 2018-08-29 19:02:23 +0000 | [diff] [blame] | 1611 | hint = _calc_named_cache_hint(named_cache, options.named_caches) |
| 1612 | if hint: |
| 1613 | # Increase the --min-free-space value by the hint, and recreate the |
| 1614 | # NamedCache instance so it gets the updated CachePolicy. |
| 1615 | options.min_free_space += hint |
| 1616 | named_cache = process_named_cache_options(parser, options) |
| 1617 | |
Marc-Antoine Ruel | 7139d91 | 2018-06-15 20:04:42 +0000 | [diff] [blame] | 1618 | # TODO(maruel): CIPD caches should be defined at an higher level here too, so |
| 1619 | # they can be cleaned the same way. |
Takuto Ikuta | f1c5844 | 2020-10-20 09:03:27 +0000 | [diff] [blame] | 1620 | |
Takuto Ikuta | f1c5844 | 2020-10-20 09:03:27 +0000 | [diff] [blame] | 1621 | cas_cache = process_cas_cache_options(options) |
Takuto Ikuta | 00cf8fc | 2020-01-14 01:36:00 +0000 | [diff] [blame] | 1622 | |
Marc-Antoine Ruel | 7139d91 | 2018-06-15 20:04:42 +0000 | [diff] [blame] | 1623 | caches = [] |
Junji Watanabe | b03450b | 2020-09-25 05:09:27 +0000 | [diff] [blame] | 1624 | if cas_cache: |
| 1625 | caches.append(cas_cache) |
Marc-Antoine Ruel | 7139d91 | 2018-06-15 20:04:42 +0000 | [diff] [blame] | 1626 | if named_cache: |
| 1627 | caches.append(named_cache) |
Junji Watanabe | 7a631b0 | 2022-01-13 02:30:29 +0000 | [diff] [blame] | 1628 | root = caches[0].cache_dir if caches else os.getcwd() |
maruel | 36a963d | 2016-04-08 17:15:49 -0700 | [diff] [blame] | 1629 | if options.clean: |
Takuto Ikuta | ae391c5 | 2020-12-03 08:43:45 +0000 | [diff] [blame] | 1630 | _clean_cmd(parser, options, caches, root) |
maruel | 36a963d | 2016-04-08 17:15:49 -0700 | [diff] [blame] | 1631 | return 0 |
Marc-Antoine Ruel | c7a704b | 2018-08-29 19:02:23 +0000 | [diff] [blame] | 1632 | |
| 1633 | # Trim must still be done for the following case: |
| 1634 | # - named-cache was used |
| 1635 | # - some entries, with a large hint, where missing |
| 1636 | # - --min-free-space was increased accordingly, thus trimming is needed |
| 1637 | # Otherwise, this will have no effect, as bot_main calls run_isolated with |
| 1638 | # --clean after each task. |
Takuto Ikuta | c9ddff2 | 2021-02-18 07:58:39 +0000 | [diff] [blame] | 1639 | additional_buffer = _FREE_SPACE_BUFFER_FOR_CIPD_PACKAGES |
Takuto Ikuta | 91cb5ca | 2021-03-17 07:19:30 +0000 | [diff] [blame] | 1640 | if options.kvs_dir: |
Takuto Ikuta | 7f45c59 | 2021-02-09 05:57:05 +0000 | [diff] [blame] | 1641 | additional_buffer += _CAS_KVS_CACHE_THRESHOLD |
Junji Watanabe | aee69ad | 2021-04-28 03:17:34 +0000 | [diff] [blame] | 1642 | # Add some buffer for Go CLI. |
| 1643 | min_free_space = options.min_free_space + additional_buffer |
| 1644 | |
| 1645 | def trim_caches_fn(stats): |
| 1646 | start = time.time() |
| 1647 | local_caching.trim_caches( |
| 1648 | caches, root, min_free_space=min_free_space, max_age_secs=MAX_AGE_SECS) |
| 1649 | duration = time.time() - start |
| 1650 | stats['duration'] = duration |
Jonah Hooper | 9b5bd8c | 2022-07-21 15:33:41 +0000 | [diff] [blame] | 1651 | logging_utils.user_logs('trim_caches: took %d seconds', duration) |
maruel | 36a963d | 2016-04-08 17:15:49 -0700 | [diff] [blame] | 1652 | |
Takuto Ikuta | 1ce6136 | 2021-11-16 05:44:17 +0000 | [diff] [blame] | 1653 | # Save state of cas cache not to overwrite state from go client. |
Takuto Ikuta | f1c5844 | 2020-10-20 09:03:27 +0000 | [diff] [blame] | 1654 | if cas_cache: |
| 1655 | cas_cache.save() |
| 1656 | cas_cache = None |
| 1657 | |
Takuto Ikuta | dc49667 | 2021-11-12 05:58:59 +0000 | [diff] [blame] | 1658 | if not args: |
| 1659 | parser.error('command to run is required.') |
nodir | 55be77b | 2016-05-03 09:39:57 -0700 | [diff] [blame] | 1660 | |
Vadim Shtayura | 5d1efce | 2014-02-04 10:55:43 -0800 | [diff] [blame] | 1661 | auth.process_auth_options(parser, options) |
nodir | 55be77b | 2016-05-03 09:39:57 -0700 | [diff] [blame] | 1662 | |
Takuto Ikuta | a71c656 | 2021-11-18 06:07:55 +0000 | [diff] [blame] | 1663 | if ISOLATED_OUTDIR_PARAMETER in args and not options.cas_instance: |
| 1664 | parser.error('%s in args requires --cas-instance' % |
Junji Watanabe | ed9ce35 | 2020-09-25 12:32:07 +0000 | [diff] [blame] | 1665 | ISOLATED_OUTDIR_PARAMETER) |
| 1666 | |
nodir | 90bc8dc | 2016-06-15 13:35:21 -0700 | [diff] [blame] | 1667 | if options.root_dir: |
Junji Watanabe | 7a631b0 | 2022-01-13 02:30:29 +0000 | [diff] [blame] | 1668 | options.root_dir = os.path.abspath(options.root_dir) |
Takuto Ikuta | d46ea76 | 2020-10-07 05:43:22 +0000 | [diff] [blame] | 1669 | else: |
Junji Watanabe | 7a631b0 | 2022-01-13 02:30:29 +0000 | [diff] [blame] | 1670 | options.root_dir = tempfile.mkdtemp(prefix='root') |
maruel | 12e3001 | 2015-10-09 11:55:35 -0700 | [diff] [blame] | 1671 | if options.json: |
Junji Watanabe | 7a631b0 | 2022-01-13 02:30:29 +0000 | [diff] [blame] | 1672 | options.json = os.path.abspath(options.json) |
nodir | 55be77b | 2016-05-03 09:39:57 -0700 | [diff] [blame] | 1673 | |
Marc-Antoine Ruel | 19dd887 | 2017-11-28 18:33:39 -0500 | [diff] [blame] | 1674 | if any('=' not in i for i in options.env): |
| 1675 | parser.error( |
| 1676 | '--env required key=value form. value can be skipped to delete ' |
| 1677 | 'the variable') |
Marc-Antoine Ruel | 7a68f71 | 2017-12-01 18:45:18 -0500 | [diff] [blame] | 1678 | options.env = dict(i.split('=', 1) for i in options.env) |
Marc-Antoine Ruel | 19dd887 | 2017-11-28 18:33:39 -0500 | [diff] [blame] | 1679 | |
| 1680 | prefixes = {} |
| 1681 | cwd = os.path.realpath(os.getcwd()) |
| 1682 | for item in options.env_prefix: |
| 1683 | if '=' not in item: |
| 1684 | parser.error( |
| 1685 | '--env-prefix %r is malformed, must be in the form `VAR=./path`' |
| 1686 | % item) |
Marc-Antoine Ruel | 7a68f71 | 2017-12-01 18:45:18 -0500 | [diff] [blame] | 1687 | key, opath = item.split('=', 1) |
Marc-Antoine Ruel | 19dd887 | 2017-11-28 18:33:39 -0500 | [diff] [blame] | 1688 | if os.path.isabs(opath): |
| 1689 | parser.error('--env-prefix %r path is bad, must be relative.' % opath) |
| 1690 | opath = os.path.normpath(opath) |
| 1691 | if not os.path.realpath(os.path.join(cwd, opath)).startswith(cwd): |
| 1692 | parser.error( |
Junji Watanabe | 38b28b0 | 2020-04-23 10:23:30 +0000 | [diff] [blame] | 1693 | '--env-prefix %r path is bad, must be relative and not contain `..`.' |
| 1694 | % opath) |
Marc-Antoine Ruel | 19dd887 | 2017-11-28 18:33:39 -0500 | [diff] [blame] | 1695 | prefixes.setdefault(key, []).append(opath) |
| 1696 | options.env_prefix = prefixes |
Robert Iannucci | bf5f84c | 2017-11-22 12:56:50 -0800 | [diff] [blame] | 1697 | |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 1698 | cipd.validate_cipd_options(parser, options) |
| 1699 | |
Junji Watanabe | dc2f89e | 2021-11-08 08:44:30 +0000 | [diff] [blame] | 1700 | install_packages_fn = copy_local_packages |
Ye Kuang | 1d096cb | 2020-06-26 08:38:21 +0000 | [diff] [blame] | 1701 | tmp_cipd_cache_dir = None |
vadimsh | 902948e | 2017-01-20 15:57:32 -0800 | [diff] [blame] | 1702 | if options.cipd_enabled: |
Ye Kuang | 1d096cb | 2020-06-26 08:38:21 +0000 | [diff] [blame] | 1703 | cache_dir = options.cipd_cache |
| 1704 | if not cache_dir: |
Junji Watanabe | 7a631b0 | 2022-01-13 02:30:29 +0000 | [diff] [blame] | 1705 | tmp_cipd_cache_dir = tempfile.mkdtemp() |
Ye Kuang | 1d096cb | 2020-06-26 08:38:21 +0000 | [diff] [blame] | 1706 | cache_dir = tmp_cipd_cache_dir |
Takuto Ikuta | 1ce6136 | 2021-11-16 05:44:17 +0000 | [diff] [blame] | 1707 | install_packages_fn = ( |
| 1708 | lambda run_dir, cas_dir, nsjail_dir: install_client_and_packages( |
| 1709 | run_dir, |
| 1710 | cipd.parse_package_args(options.cipd_packages), |
| 1711 | options.cipd_server, |
| 1712 | options.cipd_client_package, |
| 1713 | options.cipd_client_version, |
| 1714 | cache_dir=cache_dir, |
| 1715 | cas_dir=cas_dir, |
| 1716 | nsjail_dir=nsjail_dir, |
| 1717 | )) |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 1718 | |
nodir | d616068 | 2017-02-02 13:03:35 -0800 | [diff] [blame] | 1719 | @contextlib.contextmanager |
Junji Watanabe | aee69ad | 2021-04-28 03:17:34 +0000 | [diff] [blame] | 1720 | def install_named_caches(run_dir, stats): |
nodir | d616068 | 2017-02-02 13:03:35 -0800 | [diff] [blame] | 1721 | # WARNING: this function depends on "options" variable defined in the outer |
| 1722 | # function. |
Junji Watanabe | 7a631b0 | 2022-01-13 02:30:29 +0000 | [diff] [blame] | 1723 | assert str(run_dir), repr(run_dir) |
Marc-Antoine Ruel | 49f9f8d | 2018-05-24 15:57:06 -0400 | [diff] [blame] | 1724 | assert os.path.isabs(run_dir), run_dir |
Junji Watanabe | 7a631b0 | 2022-01-13 02:30:29 +0000 | [diff] [blame] | 1725 | named_caches = [(os.path.join(run_dir, str(relpath)), name) |
Takuto Ikuta | 6e2ff96 | 2019-10-29 12:35:27 +0000 | [diff] [blame] | 1726 | for name, relpath, _ in options.named_caches] |
Junji Watanabe | aee69ad | 2021-04-28 03:17:34 +0000 | [diff] [blame] | 1727 | install_start = time.time() |
Marc-Antoine Ruel | c7a704b | 2018-08-29 19:02:23 +0000 | [diff] [blame] | 1728 | for path, name in named_caches: |
Marc-Antoine Ruel | e79ddbf | 2018-06-13 18:33:07 +0000 | [diff] [blame] | 1729 | named_cache.install(path, name) |
Junji Watanabe | aee69ad | 2021-04-28 03:17:34 +0000 | [diff] [blame] | 1730 | install_duration = time.time() - install_start |
| 1731 | stats['install']['duration'] = install_duration |
| 1732 | logging.info('named_caches: install took %d seconds', install_duration) |
nodir | d616068 | 2017-02-02 13:03:35 -0800 | [diff] [blame] | 1733 | try: |
| 1734 | yield |
| 1735 | finally: |
dnj | e289d13 | 2017-07-07 11:16:44 -0700 | [diff] [blame] | 1736 | # Uninstall each named cache, returning it to the cache pool. If an |
| 1737 | # uninstall fails for a given cache, it will remain in the task's |
| 1738 | # temporary space, get cleaned up by the Swarming bot, and be lost. |
| 1739 | # |
| 1740 | # If the Swarming bot cannot clean up the cache, it will handle it like |
| 1741 | # any other bot file that could not be removed. |
Junji Watanabe | aee69ad | 2021-04-28 03:17:34 +0000 | [diff] [blame] | 1742 | uninstall_start = time.time() |
Marc-Antoine Ruel | c7a704b | 2018-08-29 19:02:23 +0000 | [diff] [blame] | 1743 | for path, name in reversed(named_caches): |
Marc-Antoine Ruel | e79ddbf | 2018-06-13 18:33:07 +0000 | [diff] [blame] | 1744 | try: |
Marc-Antoine Ruel | e955837 | 2018-08-03 03:41:22 +0000 | [diff] [blame] | 1745 | # uninstall() doesn't trim but does call save() implicitly. Trimming |
| 1746 | # *must* be done manually via periodic 'run_isolated.py --clean'. |
Marc-Antoine Ruel | e79ddbf | 2018-06-13 18:33:07 +0000 | [diff] [blame] | 1747 | named_cache.uninstall(path, name) |
| 1748 | except local_caching.NamedCacheError: |
Takuto Ikuta | 463ecdd | 2021-03-05 09:35:38 +0000 | [diff] [blame] | 1749 | if sys.platform == 'win32': |
| 1750 | # Show running processes. |
| 1751 | sys.stderr.write("running process\n") |
| 1752 | subprocess42.check_call(['tasklist.exe', '/V'], stdout=sys.stderr) |
| 1753 | |
Junji Watanabe | d2ab86b | 2021-08-13 07:20:23 +0000 | [diff] [blame] | 1754 | error = ( |
| 1755 | 'Error while removing named cache %r at %r. The cache will be' |
| 1756 | ' lost.' % (path, name)) |
| 1757 | logging.exception(error) |
| 1758 | on_error.report(error) |
Junji Watanabe | aee69ad | 2021-04-28 03:17:34 +0000 | [diff] [blame] | 1759 | uninstall_duration = time.time() - uninstall_start |
| 1760 | stats['uninstall']['duration'] = uninstall_duration |
| 1761 | logging.info('named_caches: uninstall took %d seconds', |
| 1762 | uninstall_duration) |
nodir | f33b8d6 | 2016-10-26 22:34:58 -0700 | [diff] [blame] | 1763 | |
Takuto Ikuta | f3caa9b | 2020-11-02 05:38:26 +0000 | [diff] [blame] | 1764 | command = args |
| 1765 | if options.relative_cwd: |
| 1766 | a = os.path.normpath(os.path.abspath(options.relative_cwd)) |
| 1767 | if not a.startswith(os.getcwd()): |
| 1768 | parser.error( |
| 1769 | '--relative-cwd must not try to escape the working directory') |
Marc-Antoine Ruel | 7de5259 | 2017-12-07 10:41:12 -0500 | [diff] [blame] | 1770 | |
Marc-Antoine Ruel | 1b65f4e | 2019-05-02 21:56:58 +0000 | [diff] [blame] | 1771 | containment_type = subprocess42.Containment.NONE |
| 1772 | if options.containment_type == 'AUTO': |
| 1773 | containment_type = subprocess42.Containment.AUTO |
| 1774 | if options.containment_type == 'JOB_OBJECT': |
| 1775 | containment_type = subprocess42.Containment.JOB_OBJECT |
Anirudh Mathukumilli | 92d57b6 | 2021-08-04 23:21:57 +0000 | [diff] [blame] | 1776 | if options.containment_type == 'NSJAIL': |
| 1777 | containment_type = subprocess42.Containment.NSJAIL |
| 1778 | # TODO(https://crbug.com/1227833): This object should eventually contain the |
| 1779 | # path to the nsjail binary and the nsjail configuration file. |
Marc-Antoine Ruel | 1b65f4e | 2019-05-02 21:56:58 +0000 | [diff] [blame] | 1780 | containment = subprocess42.Containment( |
| 1781 | containment_type=containment_type, |
| 1782 | limit_processes=options.limit_processes, |
| 1783 | limit_total_committed_memory=options.limit_total_committed_memory) |
| 1784 | |
Junji Watanabe | 7a631b0 | 2022-01-13 02:30:29 +0000 | [diff] [blame] | 1785 | data = TaskData(command=command, |
| 1786 | relative_cwd=options.relative_cwd, |
| 1787 | cas_instance=options.cas_instance, |
| 1788 | cas_digest=options.cas_digest, |
| 1789 | outputs=options.output, |
| 1790 | install_named_caches=install_named_caches, |
| 1791 | leak_temp_dir=options.leak_temp_dir, |
| 1792 | root_dir=options.root_dir, |
| 1793 | hard_timeout=options.hard_timeout, |
| 1794 | grace_period=options.grace_period, |
| 1795 | bot_file=options.bot_file, |
| 1796 | switch_to_account=options.switch_to_account, |
| 1797 | install_packages_fn=install_packages_fn, |
| 1798 | cas_cache_dir=options.cas_cache, |
| 1799 | cas_cache_policies=local_caching.CachePolicies( |
| 1800 | max_cache_size=options.max_cache_size, |
| 1801 | min_free_space=options.min_free_space, |
| 1802 | max_items=None, |
| 1803 | max_age_secs=None, |
| 1804 | ), |
| 1805 | cas_kvs=options.kvs_dir, |
| 1806 | env=options.env, |
| 1807 | env_prefix=options.env_prefix, |
| 1808 | lower_priority=bool(options.lower_priority), |
| 1809 | containment=containment, |
| 1810 | trim_caches_fn=trim_caches_fn) |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 1811 | try: |
Marc-Antoine Ruel | 7de5259 | 2017-12-07 10:41:12 -0500 | [diff] [blame] | 1812 | return run_tha_test(data, options.json) |
Junji Watanabe | 38b28b0 | 2020-04-23 10:23:30 +0000 | [diff] [blame] | 1813 | except (cipd.Error, local_caching.NamedCacheError, |
| 1814 | local_caching.NoMoreSpace) as ex: |
Marc-Antoine Ruel | f899c48 | 2019-10-10 23:32:06 +0000 | [diff] [blame] | 1815 | print(ex.message, file=sys.stderr) |
Junji Watanabe | d2ab86b | 2021-08-13 07:20:23 +0000 | [diff] [blame] | 1816 | on_error.report(None) |
nodir | be642ff | 2016-06-09 15:51:51 -0700 | [diff] [blame] | 1817 | return 1 |
Ye Kuang | 1d096cb | 2020-06-26 08:38:21 +0000 | [diff] [blame] | 1818 | finally: |
| 1819 | if tmp_cipd_cache_dir is not None: |
| 1820 | try: |
| 1821 | file_path.rmtree(tmp_cipd_cache_dir) |
| 1822 | except OSError: |
| 1823 | logging.exception('Remove tmp_cipd_cache_dir=%s failed', |
| 1824 | tmp_cipd_cache_dir) |
| 1825 | # Best effort clean up. Failed to do so doesn't affect the outcome. |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1826 | |
| 1827 | |
| 1828 | if __name__ == '__main__': |
maruel | 8e4e40c | 2016-05-30 06:21:07 -0700 | [diff] [blame] | 1829 | subprocess42.inhibit_os_error_reporting() |
csharp@chromium.org | bfb9874 | 2013-03-26 20:28:36 +0000 | [diff] [blame] | 1830 | # Ensure that we are always running with the correct encoding. |
vadimsh@chromium.org | a432647 | 2013-08-24 02:05:41 +0000 | [diff] [blame] | 1831 | fix_encoding.fix_encoding() |
Ye Kuang | 2dd1744 | 2020-04-22 08:45:52 +0000 | [diff] [blame] | 1832 | net.set_user_agent('run_isolated.py/' + __version__) |
Marc-Antoine Ruel | 90c9816 | 2013-12-18 15:11:57 -0500 | [diff] [blame] | 1833 | sys.exit(main(sys.argv[1:])) |