| 1 | # Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | # All rights reserved. |
| 3 | # |
| 4 | # This source code is licensed under the terms described in the LICENSE file in |
| 5 | # the root directory of this source tree. |
| 6 | |
| 7 | import base64 |
| 8 | import json |
| 9 | import multiprocessing |
| 10 | import os |
| 11 | import re |
| 12 | import subprocess |
| 13 | import sys |
| 14 | import tempfile |
| 15 | import textwrap |
| 16 | import time |
| 17 | from dataclasses import dataclass |
| 18 | from datetime import datetime |
| 19 | from io import BytesIO |
| 20 | from pathlib import Path |
| 21 | from typing import List |
| 22 | |
| 23 | from PIL import Image |
| 24 | |
| 25 | from .utils import get_code_env_prefix |
| 26 | |
| 27 | TOOLS_ATTACHMENT_KEY = "__tools_attachment__" |
| 28 | TOOLS_ATTACHMENT_KEY_REGEX = re.compile(r"__tools_attachment__=(\{.*?\})") |
| 29 | |
| 30 | DIRNAME = Path(__file__).parent |
| 31 | |
| 32 | CODE_EXEC_TIMEOUT = 20 |
| 33 | CODE_ENV_PREFIX = get_code_env_prefix() |
| 34 | |
| 35 | STDOUTERR_SINK_WRAPPER_TEMPLATE = """\ |
| 36 | with _redirect_stdout(_IO_SINK), _redirect_stderr(_IO_SINK): |
| 37 | {code}\ |
| 38 | """ |
| 39 | |
| 40 | TRYEXCEPT_WRAPPER_TEMPLATE = """\ |
| 41 | try: |
| 42 | {code} |
| 43 | except: |
| 44 | pass\ |
| 45 | """ |
| 46 | |
| 47 | |
| 48 | def generate_bwrap_command(bind_dirs: List[str]) -> str: |
| 49 | """ |
| 50 | Generate the bwrap command string for binding all |
| 51 | directories in the current directory read-only. |
| 52 | """ |
| 53 | bwrap_args = "" |
| 54 | bwrap_args += "--ro-bind / / " |
| 55 | # Add the --dev flag to mount device files |
| 56 | bwrap_args += "--dev /dev " |
| 57 | for d in bind_dirs: |
| 58 | bwrap_args += f"--bind {d} {d} " |
| 59 | |
| 60 | # Add the --unshare-all flag to isolate the sandbox from the rest of the system |
| 61 | bwrap_args += "--unshare-all " |
| 62 | # Add the --die-with-parent flag to ensure the child process dies when bwrap's parent dies |
| 63 | bwrap_args += "--die-with-parent " |
| 64 | return bwrap_args |
| 65 | |
| 66 | |
| 67 | @dataclass |
| 68 | class CodeExecutionContext: |
| 69 | matplotlib_dump_dir: str |
| 70 | use_proxy: bool = False |
| 71 | |
| 72 | |
| 73 | @dataclass |
| 74 | class CodeExecutionRequest: |
| 75 | scripts: List[str] |
| 76 | only_last_cell_stdouterr: bool = True |
| 77 | only_last_cell_fail: bool = True |
| 78 | seed: int = 0 |
| 79 | strip_fpaths_in_stderr: bool = True |
| 80 | |
| 81 | |
| 82 | class CodeExecutor: |
| 83 | def __init__(self, context: CodeExecutionContext): |
| 84 | self.context = context |
| 85 | |
| 86 | def execute(self, req: CodeExecutionRequest) -> dict: |
| 87 | scripts = req.scripts |
| 88 | for i in range(len(scripts) - 1): |
| 89 | if req.only_last_cell_stdouterr: |
| 90 | scripts[i] = STDOUTERR_SINK_WRAPPER_TEMPLATE.format( |
| 91 | code=textwrap.indent(scripts[i], " " * 4) |
| 92 | ) |
| 93 | if req.only_last_cell_fail: |
| 94 | scripts[i] = TRYEXCEPT_WRAPPER_TEMPLATE.format( |
| 95 | code=textwrap.indent(scripts[i], " " * 4) |
| 96 | ) |
| 97 | |
| 98 | # Seeds prefix: |
| 99 | seed = req.seed |
| 100 | seeds_prefix = f"""\ |
| 101 | def _set_seeds(): |
| 102 | import random |
| 103 | random.seed({seed}) |
| 104 | import numpy as np |
| 105 | np.random.seed({seed}) |
| 106 | _set_seeds()\ |
| 107 | """ |
| 108 | |
| 109 | script = "\n\n".join([seeds_prefix] + [CODE_ENV_PREFIX] + scripts) |
| 110 | with tempfile.TemporaryDirectory() as dpath: |
| 111 | bwrap_prefix = "bwrap " + generate_bwrap_command(bind_dirs=[dpath]) |
| 112 | cmd = [*bwrap_prefix.split(), sys.executable, "-c", script] |
| 113 | code_fpath = os.path.join(dpath, "code.py") |
| 114 | with open(code_fpath, "w") as f: |
| 115 | f.write(script) |
| 116 | |
| 117 | try: |
| 118 | python_path = os.environ.get("PYTHONPATH", "") |
| 119 | env = dict( |
| 120 | os.environ, |
| 121 | PYTHONHASHSEED=str(seed), |
| 122 | MPLCONFIGDIR=dpath, |
| 123 | MPLBACKEND="module://matplotlib_custom_backend", |
| 124 | PYTHONPATH=f"{DIRNAME}:{python_path}", |
| 125 | ) |
| 126 | stdout, stderr, returncode = do_subprocess( |
| 127 | cmd=cmd, |
| 128 | env=env, |
| 129 | ctx=self.context, |
| 130 | ) |
| 131 | |
| 132 | stderr = stderr.strip() |
| 133 | if req.strip_fpaths_in_stderr: |
| 134 | pattern = r'File "([^"]+)", line (\d+)' |
| 135 | stderr = re.sub(pattern, r"line \2", stderr) |
| 136 | |
| 137 | return { |
| 138 | "process_status": "completed", |
| 139 | "returncode": returncode, |
| 140 | "stdout": stdout.strip(), |
| 141 | "stderr": stderr, |
| 142 | } |
| 143 | |
| 144 | except subprocess.TimeoutExpired: |
| 145 | return { |
| 146 | "process_status": "timeout", |
| 147 | "stdout": "Timed out", |
| 148 | "stderr": "Timed out", |
| 149 | } |
| 150 | |
| 151 | except Exception as e: |
| 152 | return { |
| 153 | "process_status": "error", |
| 154 | "error_type": type(e).__name__, |
| 155 | "stderr": str(e), |
| 156 | "stdout": str(e), |
| 157 | } |
| 158 | |
| 159 | |
| 160 | def process_matplotlib_response(response, matplotlib_dump_dir: str): |
| 161 | image_data = response["image_data"] |
| 162 | # Convert the base64 string to a bytes object |
| 163 | images = [base64.b64decode(d["image_base64"]) for d in image_data] |
| 164 | # Create a list of PIL images from the bytes objects |
| 165 | images = [Image.open(BytesIO(img)) for img in images] |
| 166 | # Create a list of image paths |
| 167 | image_paths = [] |
| 168 | for i, img in enumerate(images): |
| 169 | # create new directory for each day to better organize data: |
| 170 | dump_dname = datetime.today().strftime("%Y-%m-%d") |
| 171 | dump_dpath = Path(matplotlib_dump_dir, dump_dname) |
| 172 | dump_dpath.mkdir(parents=True, exist_ok=True) |
| 173 | # save image into a file |
| 174 | dump_fname = f"matplotlib_{str(time.time()).replace('.', '_')}_{i}.png" |
| 175 | dump_fpath = dump_dpath / dump_fname |
| 176 | img.save(dump_fpath, "PNG") |
| 177 | image_paths.append(str(dump_fpath)) |
| 178 | |
| 179 | # this is kind of convoluted, we send back this response to the subprocess which |
| 180 | # prints it out |
| 181 | info = { |
| 182 | "filepath": str(image_paths[-1]), |
| 183 | "mimetype": "image/png", |
| 184 | } |
| 185 | return f"{TOOLS_ATTACHMENT_KEY}={json.dumps(info)}" |
| 186 | |
| 187 | |
| 188 | def execute_subprocess_request(request, ctx: CodeExecutionContext): |
| 189 | "Route requests from the subprocess (via network Pipes) to the internet/tools." |
| 190 | if request["type"] == "matplotlib": |
| 191 | return process_matplotlib_response(request, ctx.matplotlib_dump_dir) |
| 192 | else: |
| 193 | raise Exception(f'Unrecognised network request type: {request["type"]}') |
| 194 | |
| 195 | |
| 196 | def do_subprocess(*, cmd: list, env: dict, ctx: CodeExecutionContext): |
| 197 | # Create Pipes to be used for any external tool/network requests. |
| 198 | req_r, req_w = multiprocessing.Pipe(duplex=False) |
| 199 | resp_r, resp_w = multiprocessing.Pipe(duplex=False) |
| 200 | |
| 201 | cmd += [str(req_w.fileno()), str(resp_r.fileno())] |
| 202 | proc = subprocess.Popen( |
| 203 | cmd, |
| 204 | pass_fds=(req_w.fileno(), resp_r.fileno()), |
| 205 | text=True, |
| 206 | stdout=subprocess.PIPE, |
| 207 | stderr=subprocess.PIPE, |
| 208 | close_fds=True, |
| 209 | env=env, |
| 210 | ) |
| 211 | |
| 212 | # Close unnecessary fds. |
| 213 | req_w.close() |
| 214 | resp_r.close() |
| 215 | |
| 216 | pipe_close = False |
| 217 | done_read = False |
| 218 | start = time.monotonic() |
| 219 | while proc.poll() is None and not pipe_close: |
| 220 | if req_r.poll(0.1): |
| 221 | # NB: Python pipe semantics for poll and recv mean that |
| 222 | # poll() returns True is a pipe is closed. |
| 223 | # CF old school PEP from '09 |
| 224 | # https://bugs.python.org/issue5573 |
| 225 | try: |
| 226 | request = json.loads(req_r.recv_bytes().decode("utf-8")) |
| 227 | response = execute_subprocess_request(request, ctx) |
| 228 | |
| 229 | resp_w.send_bytes(json.dumps(response).encode("utf-8")) |
| 230 | except EOFError: |
| 231 | # The request pipe is closed - set a marker to exit |
| 232 | # after the next attempt at reading stdout/stderr. |
| 233 | pipe_close = True |
| 234 | |
| 235 | try: |
| 236 | # If lots has been printed, pipe might be full but |
| 237 | # proc cannot exit until all the stdout/stderr |
| 238 | # been written/read. |
| 239 | stdout, stderr = proc.communicate(timeout=0.3) |
| 240 | done_read = True |
| 241 | except subprocess.TimeoutExpired: |
| 242 | # The program has not terminated. Ignore it, there |
| 243 | # may be more network/tool requests. |
| 244 | continue |
| 245 | if time.monotonic() - start > CODE_EXEC_TIMEOUT: |
| 246 | proc.terminate() |
| 247 | raise subprocess.TimeoutExpired(cmd, CODE_EXEC_TIMEOUT) |
| 248 | |
| 249 | if not done_read: |
| 250 | # Solve race condition where process terminates before |
| 251 | # we hit the while loop. |
| 252 | stdout, stderr = proc.communicate(timeout=0.3) |
| 253 | |
| 254 | resp_w.close() |
| 255 | req_r.close() |
| 256 | return stdout, stderr, proc.returncode |