Skip to content

API Reference

Executor

pybox.executor.Executor

Secure Docker-based executor with optional fast mode.

Source code in pybox/executor.py
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
class Executor:
    """Secure Docker-based executor with optional fast mode."""

    def __init__(self, config: Optional[Config] = None):
        self.config = config or Config()
        self._container_name = None

    # ========================================================
    # Docker command builders
    # ========================================================

    def _base_security_flags(self) -> list[str]:
        cfg = self.config

        flags = [
            "--cap-drop", "ALL",
            "--security-opt", "no-new-privileges",
            "--pids-limit", str(cfg.pids_limit),
            "--cpus", str(cfg.cpus),
            "--memory", cfg.memory,
            "--memory-swap", cfg.memory,
            "--tmpfs", f"/tmp:ro,noexec,nosuid,size={cfg.tmpfs_size}",
        ]

        if cfg.read_only_root:
            flags.append("--read-only")

        if cfg.network_disabled:
            flags += ["--network", "none"]

        if cfg.userns:
            flags += ["--userns", cfg.userns]

        if cfg.apparmor_profile:
            flags += ["--security-opt", f"apparmor={cfg.apparmor_profile}"]

        if cfg.seccomp_profile:
            flags += ["--security-opt", f"seccomp={cfg.seccomp_profile}"]

        # gVisor runtime
        if cfg.runtime:
            flags += ["--runtime", cfg.runtime]
        if cfg.runtime == "runsc" and self._have_selinux():
            flags += ["--security-opt", "label=disable"]

        return flags

    @staticmethod
    def _have_selinux():
        """Returns true if SELinux is available and enforced."""
        try:
            output = subprocess.check_output(["getenforce"], text=True)
        except:
            return False
        return output.strip() == "Enforcing"

    def _docker_run_cmd(self) -> list[str]:
        """Safe mode: one container per execution."""
        print("*** run")
        return [
            "docker", "run", "--rm", "-i",
            *_self_named_container(self),
            *self._base_security_flags(),
            self.config.image,
        ]

    def _start_fast_container(self):
        """Start long-lived container for fast mode."""
        if self._container_name:
            return

        name = f"pybox-fast-{uuid.uuid4()}"
        self._container_name = name

        cmd = [
            "docker", "run", "-d",
            "--name", name,
            *self._base_security_flags(),
            "--entrypoint", "sleep",  # override entrypoint
            self.config.image,
            "infinity",
        ]

        subprocess.run(cmd, check=True)
        logger.info("Started fast container %s", name)

    def _inspect_entrypoint(self) -> str:
        """Return the entrypoint (or cmd) in the image."""
        def inspect(conf):
            cmd = [
                "docker", "inspect", "-f",
                conf,
                self.config.image,
            ]
            return subprocess.check_output(cmd).decode().strip().strip("[]")
        entrypoint = inspect("{{.Config.Entrypoint}}")
        if not entrypoint:
            entrypoint = inspect("{{.Config.Cmd}}")
        if not entrypoint:
            raise ValueError(
                f"No Entrypoint or Cmd in Docker image: {self.config.image}"
            )
        return shlex.split(entrypoint)


    def _docker_exec_cmd(self) -> list[str]:
        """Exec command for fast mode."""
        cmd = [
            "docker", "exec",
            "-i",
            self._container_name,
        ] + self._inspect_entrypoint()
        return cmd


    # ========================================================
    # Resource stats
    # ========================================================

    def _get_stats(self) -> Dict[str, Any]:
        """Fetch container resource usage (fast mode only)."""
        if not self._container_name:
            return {}

        try:
            proc = subprocess.run(
                ["docker", "stats", self._container_name, "--no-stream", "--format", "{{json .}}"],
                capture_output=True,
                text=True,
                timeout=2,
            )
            return json.loads(proc.stdout.strip())
        except Exception:
            return {}

    # ========================================================
    # Execution
    # ========================================================

    def run(
        self,
        code: str,
        input: Optional[Dict[str, Any]] = None,
    ) -> Dict[str, Any]:

        payload = json.dumps({
            "code": code,
            "input": input or {},
        })

        start = time.time()

        if self.config.fast_mode:
            self._start_fast_container()
            cmd = self._docker_exec_cmd()
        else:
            cmd = self._docker_run_cmd()

        logger.info("Executing code (fast_mode=%s)", self.config.fast_mode)

        proc = subprocess.Popen(
            cmd,
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True,
        )

        try:
            stdout, stderr = proc.communicate(
                payload,
                timeout=self.config.timeout
            )
        except subprocess.TimeoutExpired:
            proc.kill()
            proc.wait()

            duration = time.time() - start

            return self._log_result({
                "status": "timeout",
                "result": None,
                "errmsg": "Execution timed out",
                "returncode": None,
                "duration": duration,
            })

        duration = time.time() - start

        status = "ok" if proc.returncode == 0 else "error"

        try:
            result = json.loads(stdout).get("result") if stdout else None
        except Exception:
            result = None
            stderr += "\nInvalid JSON output"

        payload = {
            "status": status,
            "result": result,
            "errmsg": stderr.strip() or None,
            "returncode": proc.returncode,
            "duration": duration,
        }

        # Add resource stats in fast mode
        if self.config.fast_mode:
            payload["resources"] = self._get_stats()

        return self._log_result(payload)

    # ========================================================
    # Logging
    # ========================================================

    def _log_result(self, payload: Dict[str, Any]) -> Dict[str, Any]:
        """Emit structured log."""
        logger.info(
            "pybox.execution",
            extra={"execution": payload},
        )
        return payload

    # ========================================================
    # Cleanup
    # ========================================================

    def close(self):
        if self._container_name:
            subprocess.run(
                ["docker", "rm", "-f", self._container_name],
                stdout=subprocess.DEVNULL,
                stderr=subprocess.DEVNULL,
            )
            logger.info("Removed fast container %s", self._container_name)
            self._container_name = None

Execute function

pybox.executor.execute(code, input=None, config=None)

Source code in pybox/executor.py
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
def execute(
    code: str,
    input: Optional[Dict[str, Any]] = None,
    config: Optional[Dict[str, Any]] = None,
) -> Any:
    cfg = Config(**(config or {}))
    executor = Executor(cfg)

    try:
        payload = executor.run(code, input)
    finally:
        if not cfg.fast_mode:
            executor.close()

    if payload["status"] == "ok":
        return payload["result"]

    raise ExecuteError(payload)

ExecuteError

pybox.executor.ExecuteError

Bases: Exception

Source code in pybox/executor.py
18
19
20
class ExecuteError(Exception):
    def __init__(self, payload: Dict[str, Any]):
        self.__dict__.update(payload)

Config

pybox.config.Config

Bases: BaseModel

Source code in pybox/config.py
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
class Config(BaseModel):
    image: str = Field(
        default="pybox:latest",
        #default="ghcr.io/sintef/pybox:latest",
        json_schema_extra={
            "description": "Container image used to execute workloads.",
            "example": "ghcr.io/sintef/pybox:latest",
        },
    )

    fast_mode: bool = Field(
        default=False,
        json_schema_extra={
            "description": "Whether to enable the fast mode.",
        },
    )

    cpus: float = Field(
        default=0.5,
        gt=0,
        json_schema_extra={
            "description": "Number of CPU cores allocated to the container.",
            "example": 0.5,
        },
    )

    memory: str = Field(
        default="128m",
        json_schema_extra={
            "description": "Memory limit for the container (Docker format, e.g. '128m', '1g').",
            "example": "256m",
        },
    )

    pids_limit: int = Field(
        default=64,
        gt=0,
        json_schema_extra={
            "description": "Maximum number of processes allowed in the container.",
            "example": 64,
        },
    )

    timeout: float = Field(
        default=5.0,
        gt=0,
        json_schema_extra={
            "description": "Execution timeout in seconds before the container is terminated.",
            "example": 10.0,
        },
    )

    tmpfs_size: str = Field(
        default="64m",
        json_schema_extra={
            "description": "Size of temporary filesystem mounted inside the container.",
            "example": "128m",
        },
    )

    network_disabled: bool = Field(
        default=True,
        json_schema_extra={
            "description": "Disable networking inside the container for security isolation.",
        },
    )

    read_only_root: bool = Field(
        default=True,
        json_schema_extra={
            "description": "Mount container root filesystem as read-only.",
        },
    )

    userns: str = Field(
        default="host",
        json_schema_extra={
            "description": "User namespace mode (e.g., 'host' or a remapped namespace).",
            "example": "host",
        },
    )

    runtime: Optional[str] = Field(
        default=None,
        json_schema_extra={
            "description": "Runtime to use for this container.",
            "example": "runsc",
        },
    )

    apparmor_profile: str = Field(
        default="docker-default",
        json_schema_extra={
            "description": "AppArmor profile applied to the container.",
            "example": "docker-default",
        },
    )

    seccomp_profile: Optional[str] = Field(
        default=None,
        json_schema_extra={
            "description": "Path to a seccomp JSON profile for syscall filtering.",
            "examples": ["/path/to/seccomp.json"],
        },
    )