1#!/usr/bin/env python3 2# Copyright (C) 2019 The Android Open Source Project 3# 4# Licensed under the Apache License, Version 2.0 (the "License"); 5# you may not use this file except in compliance with the License. 6# You may obtain a copy of the License at 7# 8# http://www.apache.org/licenses/LICENSE-2.0 9# 10# Unless required by applicable law or agreed to in writing, software 11# distributed under the License is distributed on an "AS IS" BASIS, 12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13# See the License for the specific language governing permissions and 14# limitations under the License. 15''' Runs the given job in an isolated docker container. 16 17Also streams stdout/err onto the firebase realtime DB. 18''' 19 20import fcntl 21import logging 22import os 23import queue 24import signal 25import socket 26import subprocess 27import sys 28import threading 29import time 30 31from config import DB, SANDBOX_IMG 32from common_utils import init_logging, req, SCOPES 33 34CUR_DIR = os.path.dirname(__file__) 35SCOPES.append('https://www.googleapis.com/auth/firebase.database') 36SCOPES.append('https://www.googleapis.com/auth/userinfo.email') 37 38 39def read_nonblock(fd): 40 fcntl.fcntl(fd, fcntl.F_SETFL, fcntl.fcntl(fd, fcntl.F_GETFL) | os.O_NONBLOCK) 41 res = '' 42 while True: 43 try: 44 buf = os.read(fd.fileno(), 8192) 45 if not buf: 46 break 47 # There are two reasons for the errors='ignore' here: 48 # 1: By reading the pipe in chunks of N bytes, we can end up truncating 49 # a valid multi-byte character and cause an "unexpected end of data". 50 # This means that we will skip valid unicode chars if they happen to 51 # span across two read() chunks. 52 # 2: The job output might just emit some invalid unicode in stdout. We 53 # don't want to crash when that happens. 54 # See b/194053229 for more context. 55 res += buf.decode('utf-8', errors='ignore') 56 except OSError: 57 break 58 return res 59 60 61def log_thread(job_id, queue): 62 ''' Uploads stdout/stderr from the queue to the firebase DB. 63 64 Each line is logged as an invidivual entry in the DB, as follows: 65 MMMMMM-NNNN log line, where M: hex-encodeed timestamp, N: monotonic counter. 66 ''' 67 uri = '%s/logs/%s.json' % (DB, job_id) 68 req('DELETE', uri) 69 while True: 70 batch = queue.get() 71 if batch is None: 72 break # EOF 73 req('PATCH', uri, body=batch) 74 logging.debug('Uploader thread terminated') 75 76 77def main(argv): 78 init_logging() 79 if len(argv) != 2: 80 print('Usage: %s job_id' % argv[0]) 81 return 1 82 83 job_id = argv[1] 84 res = 42 85 86 # The container name will be worker-N-sandbox. 87 container = socket.gethostname() + '-sandbox' 88 89 # Remove stale jobs, if any. 90 subprocess.call(['sudo', 'docker', 'rm', '-f', container]) 91 92 q = queue.Queue() 93 94 # Conversely to real programs, signal handlers in python aren't really async 95 # but are queued on the main thread. Hence We need to keep the main thread 96 # responsive to react to signals. This is to handle timeouts and graceful 97 # termination of the worker container, which dispatches a SIGTERM on stop. 98 def sig_handler(sig, _): 99 logging.warning('Job runner got signal %s, terminating job %s', sig, job_id) 100 subprocess.call(['sudo', 'docker', 'kill', container]) 101 os._exit(1) # sys.exit throws a SystemExit exception, _exit really exits. 102 103 signal.signal(signal.SIGTERM, sig_handler) 104 105 log_thd = threading.Thread(target=log_thread, args=(job_id, q)) 106 log_thd.start() 107 108 # SYS_PTRACE is required for gtest death tests and LSan. 109 cmd = [ 110 'sudo', 'docker', 'run', '--name', container, '--hostname', container, 111 '--cap-add', 'SYS_PTRACE', '--rm', '--env', 112 'PERFETTO_TEST_JOB=%s' % job_id, '--tmpfs', '/tmp:exec' 113 ] 114 115 # Propagate environment variables coming from the job config. 116 for kv in [kv for kv in os.environ.items() if kv[0].startswith('PERFETTO_')]: 117 cmd += ['--env', '%s=%s' % kv] 118 119 # We use the tmpfs mount created by gce-startup-script.sh, if present. The 120 # problem is that Docker doesn't allow to both override the tmpfs-size and 121 # prevent the "-o noexec". In turn the default tmpfs-size depends on the host 122 # phisical memory size. 123 if os.getenv('SANDBOX_TMP'): 124 cmd += ['-v', '%s:/ci/ramdisk' % os.getenv('SANDBOX_TMP')] 125 else: 126 cmd += ['--tmpfs', '/ci/ramdisk:exec'] 127 128 # Rationale for the conditional branches below: when running in the real GCE 129 # environment, the gce-startup-script.sh mounts these directories in the right 130 # locations, so that they are shared between all workers. 131 # When running the worker container outside of GCE (i.e.for local testing) we 132 # leave these empty. The VOLUME directive in the dockerfile will cause docker 133 # to automatically mount a scratch volume for those. 134 # This is so that the CI containers can be tested without having to do the 135 # work that gce-startup-script.sh does. 136 if os.getenv('SHARED_WORKER_CACHE'): 137 cmd += ['--volume=%s:/ci/cache' % os.getenv('SHARED_WORKER_CACHE')] 138 139 artifacts_dir = None 140 if os.getenv('ARTIFACTS_DIR'): 141 artifacts_dir = os.path.join(os.getenv('ARTIFACTS_DIR'), job_id) 142 subprocess.call(['sudo', 'rm', '-rf', artifacts_dir]) 143 os.mkdir(artifacts_dir) 144 cmd += ['--volume=%s:/ci/artifacts' % artifacts_dir] 145 146 cmd += os.getenv('SANDBOX_NETWORK_ARGS', '').split() 147 cmd += [SANDBOX_IMG] 148 149 logging.info('Starting %s', ' '.join(cmd)) 150 proc = subprocess.Popen( 151 cmd, 152 stdin=open(os.devnull), 153 stdout=subprocess.PIPE, 154 stderr=subprocess.STDOUT, 155 bufsize=65536) 156 stdout = '' 157 tstart = time.time() 158 while True: 159 ms_elapsed = int((time.time() - tstart) * 1000) 160 stdout += read_nonblock(proc.stdout) 161 162 # stdout/err pipes are not atomic w.r.t. '\n'. Extract whole lines out into 163 # |olines| and keep the last partial line (-1) in the |stdout| buffer. 164 lines = stdout.split('\n') 165 stdout = lines[-1] 166 lines = lines[:-1] 167 168 # Each line has a key of the form <time-from-start><out|err><counter> 169 # |counter| is relative to the batch and is only used to disambiguate lines 170 # fetched at the same time, preserving the ordering. 171 batch = {} 172 for counter, line in enumerate(lines): 173 batch['%06x-%04x' % (ms_elapsed, counter)] = line 174 if batch: 175 q.put(batch) 176 if proc.poll() is not None: 177 res = proc.returncode 178 logging.info('Job subprocess terminated with code %s', res) 179 break 180 181 # Large sleeps favour batching in the log uploader. 182 # Small sleeps favour responsiveness of the signal handler. 183 time.sleep(1) 184 185 q.put(None) # EOF maker 186 log_thd.join() 187 188 if artifacts_dir: 189 artifacts_uploader = os.path.join(CUR_DIR, 'artifacts_uploader.py') 190 cmd = ['setsid', artifacts_uploader, '--job-id=%s' % job_id, '--rm'] 191 subprocess.call(cmd) 192 193 return res 194 195 196if __name__ == '__main__': 197 sys.exit(main(sys.argv)) 198