blob: a963e8795c960b5bc3602887deb911a4c2f0a704 [file] [log] [blame]
maruel@chromium.org9c72d4e2012-09-28 19:20:25 +00001#!/usr/bin/env python
Marc-Antoine Ruel8add1242013-11-05 17:28:27 -05002# Copyright 2012 The Swarming Authors. All rights reserved.
Marc-Antoine Ruele98b1122013-11-05 20:27:57 -05003# Use of this source code is governed under the Apache License, Version 2.0 that
4# can be found in the LICENSE file.
maruel@chromium.org9c72d4e2012-09-28 19:20:25 +00005
maruel@chromium.org0cd0b182012-10-22 13:34:15 +00006"""Reads a .isolated, creates a tree of hardlinks and runs the test.
maruel@chromium.org9c72d4e2012-09-28 19:20:25 +00007
Marc-Antoine Ruel2283ad12014-02-09 11:14:57 -05008To improve performance, it keeps a local cache. The local cache can safely be
9deleted.
10
11Any ${ISOLATED_OUTDIR} on the command line will be replaced by the location of a
12temporary directory upon execution of the command specified in the .isolated
13file. All content written to this directory will be uploaded upon termination
14and the .isolated file describing this directory will be printed to stdout.
maruel@chromium.org9c72d4e2012-09-28 19:20:25 +000015"""
16
marueleb5fbee2015-09-17 13:01:36 -070017__version__ = '0.5.1'
maruel@chromium.orgdedbf492013-09-12 20:42:11 +000018
maruel@chromium.org9c72d4e2012-09-28 19:20:25 +000019import logging
20import optparse
21import os
maruel@chromium.org9c72d4e2012-09-28 19:20:25 +000022import sys
23import tempfile
maruel@chromium.org9c72d4e2012-09-28 19:20:25 +000024
vadimsh@chromium.orga4326472013-08-24 02:05:41 +000025from third_party.depot_tools import fix_encoding
26
Vadim Shtayura6b555c12014-07-23 16:22:18 -070027from utils import file_path
Marc-Antoine Ruelf74cffe2015-07-15 15:21:34 -040028from utils import logging_utils
Marc-Antoine Ruelcfb60852014-07-02 15:22:00 -040029from utils import on_error
Marc-Antoine Ruelc44f5722015-01-08 16:10:01 -050030from utils import subprocess42
vadimsh@chromium.orga4326472013-08-24 02:05:41 +000031from utils import tools
vadimsh@chromium.org3e97deb2013-08-24 00:56:44 +000032from utils import zip_package
vadimsh@chromium.org8b9d56b2013-08-21 22:24:35 +000033
Vadim Shtayurae34e13a2014-02-02 11:23:26 -080034import auth
Marc-Antoine Ruel8bee66d2014-08-28 19:02:07 -040035import isolated_format
maruel@chromium.orgdedbf492013-09-12 20:42:11 +000036import isolateserver
maruel@chromium.orgdedbf492013-09-12 20:42:11 +000037
vadimsh@chromium.orga4326472013-08-24 02:05:41 +000038
vadimsh@chromium.org85071062013-08-21 23:37:45 +000039# Absolute path to this file (can be None if running from zip on Mac).
40THIS_FILE_PATH = os.path.abspath(__file__) if __file__ else None
vadimsh@chromium.org8b9d56b2013-08-21 22:24:35 +000041
42# Directory that contains this file (might be inside zip package).
vadimsh@chromium.org85071062013-08-21 23:37:45 +000043BASE_DIR = os.path.dirname(THIS_FILE_PATH) if __file__ else None
vadimsh@chromium.org8b9d56b2013-08-21 22:24:35 +000044
45# Directory that contains currently running script file.
maruel@chromium.org814d23f2013-10-01 19:08:00 +000046if zip_package.get_main_script_path():
47 MAIN_DIR = os.path.dirname(
48 os.path.abspath(zip_package.get_main_script_path()))
49else:
50 # This happens when 'import run_isolated' is executed at the python
51 # interactive prompt, in that case __file__ is undefined.
52 MAIN_DIR = None
vadimsh@chromium.org8b9d56b2013-08-21 22:24:35 +000053
csharp@chromium.orgff2a4662012-11-21 20:49:32 +000054# The name of the log file to use.
55RUN_ISOLATED_LOG_FILE = 'run_isolated.log'
56
csharp@chromium.orge217f302012-11-22 16:51:53 +000057# The name of the log to use for the run_test_cases.py command
vadimsh@chromium.org8b9d56b2013-08-21 22:24:35 +000058RUN_TEST_CASES_LOG = 'run_test_cases.log'
csharp@chromium.orge217f302012-11-22 16:51:53 +000059
vadimsh@chromium.org87d63262013-04-04 19:34:21 +000060
vadimsh@chromium.org8b9d56b2013-08-21 22:24:35 +000061def get_as_zip_package(executable=True):
62 """Returns ZipPackage with this module and all its dependencies.
63
64 If |executable| is True will store run_isolated.py as __main__.py so that
65 zip package is directly executable be python.
66 """
67 # Building a zip package when running from another zip package is
68 # unsupported and probably unneeded.
69 assert not zip_package.is_zipped_module(sys.modules[__name__])
vadimsh@chromium.org85071062013-08-21 23:37:45 +000070 assert THIS_FILE_PATH
71 assert BASE_DIR
vadimsh@chromium.org8b9d56b2013-08-21 22:24:35 +000072 package = zip_package.ZipPackage(root=BASE_DIR)
73 package.add_python_file(THIS_FILE_PATH, '__main__.py' if executable else None)
Marc-Antoine Ruel8bee66d2014-08-28 19:02:07 -040074 package.add_python_file(os.path.join(BASE_DIR, 'isolated_format.py'))
maruel@chromium.orgdedbf492013-09-12 20:42:11 +000075 package.add_python_file(os.path.join(BASE_DIR, 'isolateserver.py'))
Vadim Shtayurae34e13a2014-02-02 11:23:26 -080076 package.add_python_file(os.path.join(BASE_DIR, 'auth.py'))
vadimsh@chromium.org8b9d56b2013-08-21 22:24:35 +000077 package.add_directory(os.path.join(BASE_DIR, 'third_party'))
78 package.add_directory(os.path.join(BASE_DIR, 'utils'))
79 return package
80
81
Vadim Shtayuracb0b7432015-07-31 13:26:50 -070082def make_temp_dir(prefix, root_dir=None):
83 """Returns a temporary directory.
84
85 If root_dir is given and /tmp is on same file system as root_dir, uses /tmp.
86 Otherwise makes a new temp directory under root_dir.
87 """
maruel@chromium.org9c72d4e2012-09-28 19:20:25 +000088 base_temp_dir = None
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -040089 if (root_dir and
90 not file_path.is_same_filesystem(root_dir, tempfile.gettempdir())):
Paweł Hajdan, Jrf7d58722015-04-27 14:54:42 +020091 base_temp_dir = root_dir
marueleb5fbee2015-09-17 13:01:36 -070092 return unicode(tempfile.mkdtemp(prefix=prefix, dir=base_temp_dir))
maruel@chromium.org9c72d4e2012-09-28 19:20:25 +000093
94
Marc-Antoine Ruel7124e392014-01-09 11:49:21 -050095def change_tree_read_only(rootdir, read_only):
96 """Changes the tree read-only bits according to the read_only specification.
97
98 The flag can be 0, 1 or 2, which will affect the possibility to modify files
99 and create or delete files.
100 """
101 if read_only == 2:
102 # Files and directories (except on Windows) are marked read only. This
103 # inhibits modifying, creating or deleting files in the test directory,
104 # except on Windows where creating and deleting files is still possible.
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -0400105 file_path.make_tree_read_only(rootdir)
Marc-Antoine Ruel7124e392014-01-09 11:49:21 -0500106 elif read_only == 1:
107 # Files are marked read only but not the directories. This inhibits
108 # modifying files but creating or deleting files is still possible.
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -0400109 file_path.make_tree_files_read_only(rootdir)
Marc-Antoine Ruel7124e392014-01-09 11:49:21 -0500110 elif read_only in (0, None):
Marc-Antoine Ruelf1d827c2014-11-24 15:22:25 -0500111 # Anything can be modified.
Marc-Antoine Ruel7124e392014-01-09 11:49:21 -0500112 # TODO(maruel): This is currently dangerous as long as DiskCache.touch()
113 # is not yet changed to verify the hash of the content of the files it is
114 # looking at, so that if a test modifies an input file, the file must be
115 # deleted.
Marc-Antoine Ruele4ad07e2014-10-15 20:22:29 -0400116 file_path.make_tree_writeable(rootdir)
Marc-Antoine Ruel7124e392014-01-09 11:49:21 -0500117 else:
118 raise ValueError(
119 'change_tree_read_only(%s, %s): Unknown flag %s' %
120 (rootdir, read_only, read_only))
121
122
Marc-Antoine Ruel2283ad12014-02-09 11:14:57 -0500123def process_command(command, out_dir):
124 """Replaces isolated specific variables in a command line."""
maruela9cfd6f2015-09-15 11:03:15 -0700125 def fix(arg):
Vadim Shtayura51aba362014-05-14 15:39:23 -0700126 if '${ISOLATED_OUTDIR}' in arg:
maruela9cfd6f2015-09-15 11:03:15 -0700127 return arg.replace('${ISOLATED_OUTDIR}', out_dir).replace('/', os.sep)
128 return arg
129
130 return [fix(arg) for arg in command]
131
132
marueleb5fbee2015-09-17 13:01:36 -0700133def run_command(command, cwd, tmp_dir):
maruela9cfd6f2015-09-15 11:03:15 -0700134 """Runs the command, returns the process exit code."""
135 logging.info('run_command(%s, %s)' % (command, cwd))
136 sys.stdout.flush()
marueleb5fbee2015-09-17 13:01:36 -0700137
138 env = os.environ.copy()
139 if sys.platform == 'darwin':
140 env['TMPDIR'] = tmp_dir.encode('ascii')
141 elif sys.platform == 'win32':
maruelf71d1a32015-09-18 11:27:35 -0700142 # Temporarily disable this behavior on Windows while investigating
143 # https://crbug.com/533552.
144 # env['TEMP'] = tmp_dir.encode('ascii')
145 pass
marueleb5fbee2015-09-17 13:01:36 -0700146 else:
147 env['TMP'] = tmp_dir.encode('ascii')
maruela9cfd6f2015-09-15 11:03:15 -0700148 with tools.Profiler('RunTest'):
149 try:
marueleb5fbee2015-09-17 13:01:36 -0700150 with subprocess42.Popen_with_handler(command, cwd=cwd, env=env) as p:
maruela9cfd6f2015-09-15 11:03:15 -0700151 p.communicate()
152 exit_code = p.returncode
153 except OSError:
154 # This is not considered to be an internal error. The executable simply
155 # does not exit.
156 exit_code = 1
157 logging.info(
158 'Command finished with exit code %d (%s)',
159 exit_code, hex(0xffffffff & exit_code))
160 return exit_code
161
162
163def delete_and_upload(storage, out_dir, leak_temp_dir):
164 """Deletes the temporary run directory and uploads results back.
165
166 Returns:
167 tuple(outputs_ref, success)
168 - outputs_ref is a dict referring to the results archived back to the
169 isolated server, if applicable.
170 - success is False if something occurred that means that the task must
171 forcibly be considered a failure, e.g. zombie processes were left behind.
172 """
173
174 # Upload out_dir and generate a .isolated file out of this directory. It is
175 # only done if files were written in the directory.
176 outputs_ref = None
177 if os.path.isdir(out_dir) and os.listdir(out_dir):
178 with tools.Profiler('ArchiveOutput'):
179 try:
180 results = isolateserver.archive_files_to_storage(
181 storage, [out_dir], None)
182 outputs_ref = {
183 'isolated': results[0][0],
184 'isolatedserver': storage.location,
185 'namespace': storage.namespace,
186 }
187 except isolateserver.Aborted:
188 # This happens when a signal SIGTERM was received while uploading data.
189 # There is 2 causes:
190 # - The task was too slow and was about to be killed anyway due to
191 # exceeding the hard timeout.
192 # - The amount of data uploaded back is very large and took too much
193 # time to archive.
194 sys.stderr.write('Received SIGTERM while uploading')
195 # Re-raise, so it will be treated as an internal failure.
196 raise
197 try:
maruel6eeea7d2015-09-16 12:17:42 -0700198 if (not leak_temp_dir and os.path.isdir(out_dir) and
199 not file_path.rmtree(out_dir)):
maruela9cfd6f2015-09-15 11:03:15 -0700200 logging.error('Had difficulties removing out_dir %s', out_dir)
201 return outputs_ref, False
202 except OSError as e:
203 # When this happens, it means there's a process error.
204 logging.error('Had difficulties removing out_dir %s: %s', out_dir, e)
205 return outputs_ref, False
206 return outputs_ref, True
207
208
marueleb5fbee2015-09-17 13:01:36 -0700209def map_and_run(
210 isolated_hash, storage, cache, leak_temp_dir, root_dir, extra_args):
maruela9cfd6f2015-09-15 11:03:15 -0700211 """Maps and run the command. Returns metadata about the result."""
212 # TODO(maruel): Include performance statistics.
213 result = {
214 'exit_code': None,
215 'internal_failure': None,
216 'outputs_ref': None,
217 'version': 1,
218 }
marueleb5fbee2015-09-17 13:01:36 -0700219 if root_dir:
220 if not os.path.isdir(root_dir):
221 os.makedirs(root_dir, 0700)
222 prefix = u''
223 else:
224 root_dir = os.path.dirname(cache.cache_dir) if cache.cache_dir else None
225 prefix = u'isolated_'
226 run_dir = make_temp_dir(prefix + u'run', root_dir)
227 out_dir = make_temp_dir(prefix + u'out', root_dir)
228 tmp_dir = make_temp_dir(prefix + u'tmp', root_dir)
maruela9cfd6f2015-09-15 11:03:15 -0700229 try:
230 bundle = isolateserver.fetch_isolated(
231 isolated_hash=isolated_hash,
232 storage=storage,
233 cache=cache,
234 outdir=run_dir,
235 require_command=True)
236
237 change_tree_read_only(run_dir, bundle.read_only)
238 cwd = os.path.normpath(os.path.join(run_dir, bundle.relative_cwd))
239 command = bundle.command + extra_args
240 file_path.ensure_command_has_abs_path(command, cwd)
marueleb5fbee2015-09-17 13:01:36 -0700241 result['exit_code'] = run_command(
242 process_command(command, out_dir), cwd, tmp_dir)
maruela9cfd6f2015-09-15 11:03:15 -0700243 except Exception as e:
244 # An internal error occured. Report accordingly so the swarming task will be
245 # retried automatically.
246 logging.error('internal failure: %s', e)
247 result['internal_failure'] = str(e)
248 on_error.report(None)
249 finally:
250 try:
251 if leak_temp_dir:
252 logging.warning(
253 'Deliberately leaking %s for later examination', run_dir)
marueleb5fbee2015-09-17 13:01:36 -0700254 else:
255 if os.path.isdir(run_dir) and not file_path.rmtree(run_dir):
256 # On Windows rmtree(run_dir) call above has a synchronization effect:
257 # it finishes only when all task child processes terminate (since a
258 # running process locks *.exe file). Examine out_dir only after that
259 # call completes (since child processes may write to out_dir too and
260 # we need to wait for them to finish).
261 print >> sys.stderr, (
262 'Failed to delete the run directory, forcibly failing\n'
263 'the task because of it. No zombie process can outlive a\n'
264 'successful task run and still be marked as successful.\n'
265 'Fix your stuff.')
266 if result['exit_code'] == 0:
267 result['exit_code'] = 1
268 if os.path.isdir(tmp_dir) and not file_path.rmtree(tmp_dir):
269 print >> sys.stderr, (
270 'Failed to delete the temporary directory, forcibly failing\n'
271 'the task because of it. No zombie process can outlive a\n'
272 'successful task run and still be marked as successful.\n'
273 'Fix your stuff.')
274 if result['exit_code'] == 0:
275 result['exit_code'] = 1
maruela9cfd6f2015-09-15 11:03:15 -0700276
marueleb5fbee2015-09-17 13:01:36 -0700277 # This deletes out_dir if leak_temp_dir is not set.
maruela9cfd6f2015-09-15 11:03:15 -0700278 result['outputs_ref'], success = delete_and_upload(
279 storage, out_dir, leak_temp_dir)
280 if not success and result['exit_code'] == 0:
281 result['exit_code'] = 1
282 except Exception as e:
283 # Swallow any exception in the main finally clause.
284 logging.error('Leaking out_dir %s: %s', out_dir, e)
285 result['internal_failure'] = str(e)
286 return result
Marc-Antoine Ruel2283ad12014-02-09 11:14:57 -0500287
288
Marc-Antoine Ruel0ec868b2015-08-12 14:12:46 -0400289def run_tha_test(
marueleb5fbee2015-09-17 13:01:36 -0700290 isolated_hash, storage, cache, leak_temp_dir, result_json, root_dir,
291 extra_args):
Marc-Antoine Ruel2283ad12014-02-09 11:14:57 -0500292 """Downloads the dependencies in the cache, hardlinks them into a temporary
293 directory and runs the executable from there.
294
295 A temporary directory is created to hold the output files. The content inside
296 this directory will be uploaded back to |storage| packaged as a .isolated
297 file.
298
299 Arguments:
Marc-Antoine Ruel35b58432014-12-08 17:40:40 -0500300 isolated_hash: the SHA-1 of the .isolated file that must be retrieved to
Marc-Antoine Ruel2283ad12014-02-09 11:14:57 -0500301 recreate the tree of files to run the target executable.
302 storage: an isolateserver.Storage object to retrieve remote objects. This
303 object has a reference to an isolateserver.StorageApi, which does
304 the actual I/O.
305 cache: an isolateserver.LocalCache to keep from retrieving the same objects
306 constantly by caching the objects retrieved. Can be on-disk or
307 in-memory.
Kenneth Russell61d42352014-09-15 11:41:16 -0700308 leak_temp_dir: if true, the temporary directory will be deliberately leaked
309 for later examination.
maruela9cfd6f2015-09-15 11:03:15 -0700310 result_json: file path to dump result metadata into. If set, the process
311 exit code is always 0 unless an internal error occured.
marueleb5fbee2015-09-17 13:01:36 -0700312 root_dir: directory to the path to use to create the temporary directory. If
313 not specified, a random temporary directory is created.
Marc-Antoine Ruel2283ad12014-02-09 11:14:57 -0500314 extra_args: optional arguments to add to the command stated in the .isolate
315 file.
maruela9cfd6f2015-09-15 11:03:15 -0700316
317 Returns:
318 Process exit code that should be used.
maruel@chromium.org9c72d4e2012-09-28 19:20:25 +0000319 """
maruela9cfd6f2015-09-15 11:03:15 -0700320 # run_isolated exit code. Depends on if result_json is used or not.
321 result = map_and_run(
marueleb5fbee2015-09-17 13:01:36 -0700322 isolated_hash, storage, cache, leak_temp_dir, root_dir, extra_args)
maruela9cfd6f2015-09-15 11:03:15 -0700323 logging.info('Result:\n%s', tools.format_json(result, dense=True))
324 if result_json:
325 tools.write_json(result_json, result, dense=True)
326 # Only return 1 if there was an internal error.
327 return int(bool(result['internal_failure']))
maruel@chromium.org781ccf62013-09-17 19:39:47 +0000328
maruela9cfd6f2015-09-15 11:03:15 -0700329 # Marshall into old-style inline output.
330 if result['outputs_ref']:
331 data = {
332 'hash': result['outputs_ref']['isolated'],
333 'namespace': result['outputs_ref']['namespace'],
334 'storage': result['outputs_ref']['isolatedserver'],
335 }
Marc-Antoine Ruelc44f5722015-01-08 16:10:01 -0500336 sys.stdout.flush()
maruela9cfd6f2015-09-15 11:03:15 -0700337 print(
338 '[run_isolated_out_hack]%s[/run_isolated_out_hack]' %
339 tools.format_json(data, dense=True))
340 return result['exit_code'] or int(bool(result['internal_failure']))
maruel@chromium.org9c72d4e2012-09-28 19:20:25 +0000341
342
Marc-Antoine Ruel90c98162013-12-18 15:11:57 -0500343def main(args):
vadimsh@chromium.orga4326472013-08-24 02:05:41 +0000344 tools.disable_buffering()
Marc-Antoine Ruelf74cffe2015-07-15 15:21:34 -0400345 parser = logging_utils.OptionParserWithLogging(
maruel@chromium.orgdedbf492013-09-12 20:42:11 +0000346 usage='%prog <options>',
347 version=__version__,
348 log_file=RUN_ISOLATED_LOG_FILE)
maruela9cfd6f2015-09-15 11:03:15 -0700349 parser.add_option(
350 '--json',
351 help='dump output metadata to json file. When used, run_isolated returns '
352 'non-zero only on internal failure')
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500353 data_group = optparse.OptionGroup(parser, 'Data source')
354 data_group.add_option(
Marc-Antoine Ruel185ded42015-01-28 20:49:18 -0500355 '-s', '--isolated',
356 help='Hash of the .isolated to grab from the isolate server')
Marc-Antoine Ruelf7d737d2014-12-10 15:36:29 -0500357 isolateserver.add_isolate_server_options(data_group)
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -0500358 parser.add_option_group(data_group)
maruel@chromium.org9c72d4e2012-09-28 19:20:25 +0000359
Marc-Antoine Ruela57d7db2014-10-15 20:31:19 -0400360 isolateserver.add_cache_options(parser)
361 parser.set_defaults(cache='cache')
maruel@chromium.org9c72d4e2012-09-28 19:20:25 +0000362
Kenneth Russell61d42352014-09-15 11:41:16 -0700363 debug_group = optparse.OptionGroup(parser, 'Debugging')
364 debug_group.add_option(
365 '--leak-temp-dir',
366 action='store_true',
367 help='Deliberately leak isolate\'s temp dir for later examination '
368 '[default: %default]')
marueleb5fbee2015-09-17 13:01:36 -0700369 debug_group.add_option(
370 '--root-dir', help='Use a directory instead of a random one')
Kenneth Russell61d42352014-09-15 11:41:16 -0700371 parser.add_option_group(debug_group)
372
Vadim Shtayurae34e13a2014-02-02 11:23:26 -0800373 auth.add_auth_options(parser)
Marc-Antoine Ruel90c98162013-12-18 15:11:57 -0500374 options, args = parser.parse_args(args)
Marc-Antoine Ruel185ded42015-01-28 20:49:18 -0500375 if not options.isolated:
376 parser.error('--isolated is required.')
Vadim Shtayura5d1efce2014-02-04 10:55:43 -0800377 auth.process_auth_options(parser, options)
Marc-Antoine Ruele290ada2014-12-10 19:48:49 -0500378 isolateserver.process_isolate_server_options(parser, options, True)
maruel@chromium.org9c72d4e2012-09-28 19:20:25 +0000379
Marc-Antoine Ruela57d7db2014-10-15 20:31:19 -0400380 cache = isolateserver.process_cache_options(options)
Marc-Antoine Ruelf7d737d2014-12-10 15:36:29 -0500381 with isolateserver.get_storage(
382 options.isolate_server, options.namespace) as storage:
Marc-Antoine Ruelcfb60852014-07-02 15:22:00 -0400383 # Hashing schemes used by |storage| and |cache| MUST match.
384 assert storage.hash_algo == cache.hash_algo
385 return run_tha_test(
Marc-Antoine Ruel0ec868b2015-08-12 14:12:46 -0400386 options.isolated, storage, cache, options.leak_temp_dir, options.json,
marueleb5fbee2015-09-17 13:01:36 -0700387 options.root_dir, args)
maruel@chromium.org9c72d4e2012-09-28 19:20:25 +0000388
389
390if __name__ == '__main__':
csharp@chromium.orgbfb98742013-03-26 20:28:36 +0000391 # Ensure that we are always running with the correct encoding.
vadimsh@chromium.orga4326472013-08-24 02:05:41 +0000392 fix_encoding.fix_encoding()
Marc-Antoine Ruel90c98162013-12-18 15:11:57 -0500393 sys.exit(main(sys.argv[1:]))