gvisor 0.0.2__tar.gz → 0.0.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: gvisor
3
- Version: 0.0.2
3
+ Version: 0.0.3
4
4
  Summary: Python bindings for gVisor.
5
5
  License: Apache-2.0
6
6
  Project-URL: Homepage, https://gvisor.dev
@@ -15,4 +15,7 @@
15
15
  """gVisor sandboxexec sandbox package."""
16
16
 
17
17
  from .sandbox import Error
18
+ from .sandbox import Mount
19
+ from .sandbox import MountType
20
+ from .sandbox import NetworkMode
18
21
  from .sandbox import Sandbox
@@ -0,0 +1,636 @@
1
+ # Copyright 2026 The gVisor Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # https://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Python binding for gVisor sandbox.
16
+
17
+ This module provides a Python API for creating gVisor sandboxes and executing
18
+ commands inside them.
19
+ """
20
+
21
+ import dataclasses
22
+ import enum
23
+ import json
24
+ import os
25
+ import posixpath
26
+ import random
27
+ import shutil
28
+ import subprocess
29
+ import tempfile
30
+ from typing import Any, Dict, List, Optional, Sequence, Tuple, Union
31
+
32
+
33
+ class Error(Exception):
34
+ """Base exception for Sandbox operations."""
35
+
36
+
37
+ class MountType(str, enum.Enum):
38
+ """Type of mount point inside the sandbox."""
39
+
40
+ BIND = "bind"
41
+ TMPFS = "tmpfs"
42
+ PROC = "proc"
43
+
44
+
45
+ class NetworkMode(str, enum.Enum):
46
+ """Network isolation mode for the sandbox."""
47
+
48
+ NONE = "none"
49
+ HOST = "host"
50
+ SANDBOX = "sandbox"
51
+
52
+
53
+ @dataclasses.dataclass(frozen=True)
54
+ class Mount:
55
+ """Represents a mount configuration inside the sandbox.
56
+
57
+ Attributes:
58
+ destination: Destination path inside the sandbox.
59
+ source: Source path on the host (for bind mounts) or mount source
60
+ identifier.
61
+ type: Mount type ('bind', 'tmpfs', 'proc').
62
+ readonly: Whether the mount is read-only (applies to bind mounts).
63
+ """
64
+
65
+ destination: str
66
+ source: Optional[str] = None
67
+ type: Union[MountType, str] = MountType.BIND
68
+ readonly: bool = False
69
+
70
+ @classmethod
71
+ def bind(
72
+ cls, source: str, destination: str, readonly: bool = False
73
+ ) -> "Mount":
74
+ """Creates a host bind mount."""
75
+ return cls(
76
+ destination=destination,
77
+ source=source,
78
+ type=MountType.BIND,
79
+ readonly=readonly,
80
+ )
81
+
82
+ @classmethod
83
+ def tmpfs(cls, destination: str) -> "Mount":
84
+ """Creates an in-memory tmpfs mount."""
85
+ return cls(
86
+ destination=destination,
87
+ source="tmpfs",
88
+ type=MountType.TMPFS,
89
+ readonly=False,
90
+ )
91
+
92
+ @classmethod
93
+ def proc(cls, destination: str) -> "Mount":
94
+ """Creates an isolated procfs mount."""
95
+ return cls(
96
+ destination=destination,
97
+ source="proc",
98
+ type=MountType.PROC,
99
+ readonly=False,
100
+ )
101
+
102
+
103
+ def _normalize_env(
104
+ env: Optional[Union[List[str], Dict[str, str]]],
105
+ base_env: Optional[Dict[str, str]] = None,
106
+ ) -> List[str]:
107
+ """Normalizes environment variables into a list of 'KEY=VALUE' strings.
108
+
109
+ Args:
110
+ env: A list of 'KEY=VALUE' strings or a dict mapping keys to values.
111
+ base_env: Optional default environment dictionary to merge over.
112
+
113
+ Returns:
114
+ A deduplicated list of 'KEY=VALUE' strings.
115
+
116
+ Raises:
117
+ ValueError: If a list entry is missing '=' or a dict key contains '='.
118
+ TypeError: If env is not a list, tuple, or dict.
119
+ """
120
+ merged = dict(base_env) if base_env else {}
121
+ if not env:
122
+ return [f"{k}={v}" for k, v in merged.items()]
123
+
124
+ if isinstance(env, dict):
125
+ for k, v in env.items():
126
+ if "=" in str(k):
127
+ raise ValueError(f"Environment variable key cannot contain '=': {k!r}")
128
+ merged[str(k)] = str(v)
129
+ elif isinstance(env, (list, tuple)):
130
+ for item in env:
131
+ if not isinstance(item, str) or "=" not in item:
132
+ raise ValueError(
133
+ f"Invalid environment variable format, expected KEY=VALUE: {item!r}"
134
+ )
135
+ k, _, v = item.partition("=")
136
+ merged[k] = v
137
+ else:
138
+ raise TypeError(
139
+ f"env must be a list of 'KEY=VALUE' strings or a dict, got {type(env)}"
140
+ )
141
+
142
+ return [f"{k}={v}" for k, v in merged.items()]
143
+
144
+
145
+ def _normalize_working_dir(
146
+ working_dir: Optional[str], param_name: str = "working_dir"
147
+ ) -> str:
148
+ """Normalizes and validates working directory into an absolute POSIX path.
149
+
150
+ Relative paths are resolved and normalized relative to the container root
151
+ ('/').
152
+
153
+ Args:
154
+ working_dir: The working directory path.
155
+ param_name: Parameter name for error messages (e.g. 'working_dir' or 'cwd').
156
+
157
+ Returns:
158
+ The normalized absolute POSIX working directory path.
159
+
160
+ Raises:
161
+ TypeError: If working_dir is not a string.
162
+ ValueError: If working_dir is empty or whitespace.
163
+ """
164
+ if working_dir is None:
165
+ return "/"
166
+ if not isinstance(working_dir, str):
167
+ raise TypeError(f"{param_name} must be a str, got {type(working_dir)}")
168
+ if not working_dir.strip():
169
+ err_msg = (
170
+ "working directory cannot be empty"
171
+ if param_name == "working_dir"
172
+ else f"{param_name} cannot be empty"
173
+ )
174
+ raise ValueError(err_msg)
175
+ return posixpath.normpath(posixpath.join("/", working_dir))
176
+
177
+
178
+ def _normalize_mounts(
179
+ mounts: Optional[Sequence[Union[Mount, Dict[str, Any]]]],
180
+ ) -> List[Mount]:
181
+ """Normalizes and validates mount configurations into a list of Mount objects.
182
+
183
+ Args:
184
+ mounts: A sequence of Mount objects or dictionaries specifying mounts.
185
+
186
+ Returns:
187
+ A list of normalized Mount objects.
188
+
189
+ Raises:
190
+ TypeError: If mounts is not a sequence, or an item is neither a Mount nor
191
+ a dict.
192
+ ValueError: If a mount dictionary contains unrecognized keys, destination
193
+ is missing or empty, bind mount source is empty, or mount type is invalid.
194
+ """
195
+ if not mounts:
196
+ return []
197
+
198
+ if not isinstance(mounts, (list, tuple)):
199
+ raise TypeError(
200
+ "mounts must be a list or tuple of Mount objects or dicts, got"
201
+ f" {type(mounts)}"
202
+ )
203
+
204
+ normalized = []
205
+ for item in mounts:
206
+ if isinstance(item, Mount):
207
+ m_dest = item.destination
208
+ m_source = item.source
209
+ m_type = item.type
210
+ m_readonly = item.readonly
211
+ elif isinstance(item, dict):
212
+ allowed_keys = {"destination", "source", "type", "readonly"}
213
+ extra_keys = set(item.keys()) - allowed_keys
214
+ if extra_keys:
215
+ raise ValueError(
216
+ f"Unrecognized keys in mount dict: {sorted(extra_keys)}"
217
+ )
218
+ if "destination" not in item:
219
+ raise ValueError(f"Mount dictionary missing 'destination': {item!r}")
220
+ m_dest = item["destination"]
221
+ m_source = item.get("source")
222
+ m_type = item.get("type", MountType.BIND)
223
+ m_readonly = item.get("readonly", False)
224
+ else:
225
+ raise TypeError(
226
+ f"Mount item must be a Mount instance or dict, got {type(item)}"
227
+ )
228
+
229
+ if not isinstance(m_dest, str) or not m_dest.strip():
230
+ raise ValueError(f"Mount destination cannot be empty: {m_dest!r}")
231
+
232
+ clean_dest = posixpath.normpath(posixpath.join("/", m_dest))
233
+
234
+ if isinstance(m_type, MountType):
235
+ type_str = m_type.value
236
+ elif isinstance(m_type, str):
237
+ type_str = m_type.lower()
238
+ if type_str not in (
239
+ MountType.BIND.value,
240
+ MountType.TMPFS.value,
241
+ MountType.PROC.value,
242
+ ):
243
+ raise ValueError(
244
+ f"Invalid mount type '{m_type}'. Valid types are 'bind', 'tmpfs',"
245
+ " 'proc'."
246
+ )
247
+ else:
248
+ raise TypeError(
249
+ f"Mount type must be a MountType enum or str, got {type(m_type)}"
250
+ )
251
+
252
+ if type_str == MountType.BIND.value:
253
+ if not m_source or not isinstance(m_source, str) or not m_source.strip():
254
+ raise ValueError(f"Bind mount source cannot be empty: {m_source!r}")
255
+ clean_source = os.path.abspath(m_source)
256
+ normalized.append(
257
+ Mount(
258
+ destination=clean_dest,
259
+ source=clean_source,
260
+ type=MountType.BIND,
261
+ readonly=bool(m_readonly),
262
+ )
263
+ )
264
+ elif type_str == MountType.TMPFS.value:
265
+ normalized.append(
266
+ Mount(
267
+ destination=clean_dest,
268
+ source="tmpfs",
269
+ type=MountType.TMPFS,
270
+ readonly=False,
271
+ )
272
+ )
273
+ elif type_str == MountType.PROC.value:
274
+ normalized.append(
275
+ Mount(
276
+ destination=clean_dest,
277
+ source="proc",
278
+ type=MountType.PROC,
279
+ readonly=False,
280
+ )
281
+ )
282
+
283
+ return normalized
284
+
285
+
286
+ class Sandbox:
287
+ """Represents a running gVisor sandbox."""
288
+
289
+ def __init__(
290
+ self,
291
+ runtime_dir: Optional[str] = None,
292
+ sandbox_id: Optional[str] = None,
293
+ network: Union[NetworkMode, str] = NetworkMode.NONE,
294
+ env: Optional[Union[List[str], Dict[str, str]]] = None,
295
+ mounts: Optional[Sequence[Union[Mount, Dict[str, Any]]]] = None,
296
+ working_dir: str = "/",
297
+ ):
298
+ """Initializes and starts a new sandbox.
299
+
300
+ Args:
301
+ runtime_dir: Custom runtime directory where bundle and state files are
302
+ written. If not set, a temporary directory is created.
303
+ sandbox_id: Specific sandbox ID. If not set, a unique ID is generated
304
+ automatically.
305
+ network: The networking mode for runsc ('none', 'sandbox', 'host', or
306
+ NetworkMode enum). Defaults to NetworkMode.NONE ('none').
307
+ env: Optional environment variables for the sandbox container.
308
+ mounts: Optional sequence of Mount objects or dicts defining mounts.
309
+ working_dir: The initial working directory inside the sandbox. Relative
310
+ paths are normalized relative to container root ('/'). Defaults to "/".
311
+
312
+ Raises:
313
+ Error: If sandbox creation fails.
314
+ ValueError: If an invalid network mode, working_dir, mount, or environment
315
+ variable format is provided.
316
+ TypeError: If env, mounts, or network has an invalid type.
317
+ """
318
+ if isinstance(network, NetworkMode):
319
+ self._network = network.value
320
+ elif isinstance(network, str):
321
+ mode_lower = network.lower()
322
+ if mode_lower not in (
323
+ NetworkMode.NONE.value,
324
+ NetworkMode.HOST.value,
325
+ NetworkMode.SANDBOX.value,
326
+ ):
327
+ raise ValueError(
328
+ f"Invalid network mode '{network}'. Valid options are 'none',"
329
+ " 'host', 'sandbox'."
330
+ )
331
+ self._network = mode_lower
332
+ else:
333
+ raise TypeError(
334
+ f"network must be a NetworkMode or str, got {type(network)}"
335
+ )
336
+
337
+ self._env = env
338
+ self._working_dir = _normalize_working_dir(working_dir)
339
+ self._mounts = _normalize_mounts(mounts)
340
+ self._runtime_dir = ""
341
+ self._owns_runtime_dir = False
342
+ self._id = ""
343
+ self._state_dir = ""
344
+ self._bundle_dir = ""
345
+ self._closed = False
346
+ self._runsc_path = self._find_runsc()
347
+
348
+ if runtime_dir is None:
349
+ try:
350
+ self._runtime_dir = tempfile.mkdtemp(prefix="gvisor-sandbox-")
351
+ except OSError as e:
352
+ raise Error(f"failed to create runtime directory: {e}") from e
353
+ self._owns_runtime_dir = True
354
+ else:
355
+ self._runtime_dir = runtime_dir
356
+ self._owns_runtime_dir = False
357
+
358
+ self._id = sandbox_id or self._generate_id()
359
+
360
+ try:
361
+ if os.geteuid() != 0 and self._network == NetworkMode.SANDBOX.value:
362
+ raise Error("sandbox networking requires running as root")
363
+
364
+ self._state_dir = os.path.join(self._runtime_dir, "state")
365
+ try:
366
+ os.makedirs(self._state_dir, mode=0o700, exist_ok=True)
367
+ except OSError as e:
368
+ raise Error(f"failed to create sandbox state directory: {e}") from e
369
+
370
+ # Verify permissions (mode might be different if directory already
371
+ # existed).
372
+ try:
373
+ stat_info = os.stat(self._state_dir)
374
+ if (stat_info.st_mode & 0o777) != 0o700:
375
+ os.chmod(self._state_dir, 0o700)
376
+ except OSError as e:
377
+ raise Error(
378
+ "sandbox state directory has incorrect permissions and failed to"
379
+ f" chmod: {e}"
380
+ ) from e
381
+
382
+ self._bundle_dir = self._create_bundle()
383
+
384
+ # Launch the sandbox in detached mode.
385
+ args = ["--root", self._state_dir]
386
+ if os.geteuid() != 0:
387
+ args.append("--ignore-cgroups")
388
+
389
+ args.append(f"--network={self._network}")
390
+
391
+ args.extend(["run", "--bundle", self._bundle_dir, "--detach", self._id])
392
+
393
+ # We must use a file for stderr because runsc run with --detach spawns a
394
+ # grandchild process. If we use pipes (e.g. capture_output=True), Python's
395
+ # subprocess.run will hang waiting for the pipes to close. Writing to a
396
+ # file avoids this hang while still allowing us to capture errors.
397
+ stderr_path = os.path.join(self._runtime_dir, "runsc-stderr.log")
398
+ try:
399
+ with open(stderr_path, "w+b") as stderr_file:
400
+ subprocess.run(
401
+ [self._runsc_path] + args,
402
+ check=True,
403
+ stdout=subprocess.DEVNULL,
404
+ stderr=stderr_file,
405
+ timeout=30,
406
+ )
407
+ except subprocess.TimeoutExpired as e:
408
+ raise Error("sandbox creation timed out (runsc run hung)") from e
409
+ except subprocess.CalledProcessError as e:
410
+ stderr_content = ""
411
+ if os.path.exists(stderr_path):
412
+ try:
413
+ with open(stderr_path, "r", errors="replace") as f:
414
+ stderr_content = f.read()
415
+ except OSError:
416
+ pass
417
+ raise Error(
418
+ "failed to create sandbox via subprocess: exit code"
419
+ f" {e.returncode}, stderr: {stderr_content}"
420
+ ) from e
421
+ except Exception:
422
+ self.close()
423
+ raise
424
+
425
+ def __enter__(self) -> "Sandbox":
426
+ return self
427
+
428
+ def __exit__(self, exc_type, exc_val, exc_tb):
429
+ self.close()
430
+
431
+ @property
432
+ def id(self) -> str:
433
+ """Returns the sandbox ID."""
434
+ return self._id
435
+
436
+ @property
437
+ def bundle_dir(self) -> str:
438
+ """Returns the path to the OCI bundle directory."""
439
+ return self._bundle_dir
440
+
441
+ def _generate_id(self) -> str:
442
+ return f"{random.getrandbits(128):032x}"
443
+
444
+ def _find_runsc(self) -> str:
445
+ if "RUNSC_PATH" in os.environ:
446
+ return os.environ["RUNSC_PATH"]
447
+ path = shutil.which("runsc")
448
+ if path is not None:
449
+ return path
450
+ raise Error("runsc binary is not found")
451
+
452
+ def _create_bundle(self) -> str:
453
+ """Creates the OCI bundle directory and config.json.
454
+
455
+ Returns:
456
+ The path to the created bundle directory.
457
+
458
+ Raises:
459
+ Error: If bundle creation fails.
460
+ """
461
+ bundle_dir = os.path.join(self._runtime_dir, self._id)
462
+ rootfs_dir = os.path.join(bundle_dir, "rootfs")
463
+ try:
464
+ os.makedirs(rootfs_dir, mode=0o755, exist_ok=True)
465
+ except OSError as e:
466
+ raise Error(f"failed to create bundle directories: {e}") from e
467
+
468
+ namespaces = [
469
+ {"type": "pid"},
470
+ {"type": "mount"},
471
+ {"type": "uts"},
472
+ {"type": "ipc"},
473
+ ]
474
+ if os.geteuid() != 0:
475
+ namespaces.append({"type": "user"})
476
+ if self._network == NetworkMode.SANDBOX.value:
477
+ namespaces.append({"type": "network"})
478
+
479
+ mounts = [
480
+ {"destination": "/proc", "type": "proc", "source": "proc"},
481
+ {"destination": "/dev", "type": "tmpfs", "source": "tmpfs"},
482
+ ]
483
+
484
+ for p in ["/bin", "/usr", "/lib", "/lib64", "/etc/alternatives"]:
485
+ if os.path.exists(p):
486
+ opts = ["rbind", "ro", "nosuid", "nodev"]
487
+ if p == "/etc/alternatives":
488
+ opts = ["rbind", "ro"]
489
+ mounts.append({
490
+ "destination": p,
491
+ "type": "bind",
492
+ "source": p,
493
+ "options": opts,
494
+ })
495
+
496
+ for m in self._mounts:
497
+ if m.type == MountType.BIND:
498
+ opts = ["rbind", "ro" if m.readonly else "rw"]
499
+ mounts.append({
500
+ "destination": m.destination,
501
+ "type": "bind",
502
+ "source": m.source,
503
+ "options": opts,
504
+ })
505
+ elif m.type == MountType.TMPFS:
506
+ mounts.append({
507
+ "destination": m.destination,
508
+ "type": "tmpfs",
509
+ "source": "tmpfs",
510
+ })
511
+ elif m.type == MountType.PROC:
512
+ mounts.append({
513
+ "destination": m.destination,
514
+ "type": "proc",
515
+ "source": "proc",
516
+ })
517
+
518
+ linux = {
519
+ "namespaces": namespaces,
520
+ }
521
+ if os.geteuid() != 0:
522
+ linux["uidMappings"] = [
523
+ {"containerID": 0, "hostID": os.geteuid(), "size": 1}
524
+ ]
525
+ linux["gidMappings"] = [
526
+ {"containerID": 0, "hostID": os.getegid(), "size": 1}
527
+ ]
528
+
529
+ base_env = {"PATH": "/bin:/usr/bin:/usr/local/bin"}
530
+ process_env = _normalize_env(self._env, base_env=base_env)
531
+
532
+ spec = {
533
+ "ociVersion": "1.0.0",
534
+ "root": {
535
+ "path": "rootfs",
536
+ "readonly": True,
537
+ },
538
+ "process": {
539
+ "terminal": False,
540
+ "user": {"uid": 0, "gid": 0},
541
+ "args": ["sleep", "infinity"],
542
+ "cwd": self._working_dir,
543
+ "env": process_env,
544
+ },
545
+ "mounts": mounts,
546
+ "linux": linux,
547
+ }
548
+
549
+ config_path = os.path.join(bundle_dir, "config.json")
550
+ try:
551
+ with open(config_path, "w") as f:
552
+ json.dump(spec, f, indent=2)
553
+ except OSError as e:
554
+ raise Error(f"failed to create config.json: {e}") from e
555
+
556
+ return bundle_dir
557
+
558
+ def exec(
559
+ self,
560
+ cmd: str,
561
+ *args: str,
562
+ env: Optional[Union[List[str], Dict[str, str]]] = None,
563
+ cwd: Optional[str] = None,
564
+ timeout: Optional[float] = None,
565
+ ) -> Tuple[str, str]:
566
+ """Runs the given command inside the running sandbox.
567
+
568
+ Args:
569
+ cmd: The command to run.
570
+ *args: Arguments to the command.
571
+ env: Optional environment variables for this command execution.
572
+ cwd: Optional working directory for this command execution. Relative paths
573
+ are normalized relative to container root ('/').
574
+ timeout: Timeout in seconds.
575
+
576
+ Returns:
577
+ A tuple of (stdout, stderr) strings.
578
+
579
+ Raises:
580
+ Error: If the command execution fails or times out.
581
+ ValueError: If environment variable formatting or cwd is invalid.
582
+ TypeError: If env or cwd has an invalid type.
583
+ """
584
+ runsc_args = ["--root", self._state_dir, "exec"]
585
+ if cwd is not None:
586
+ clean_cwd = _normalize_working_dir(cwd, param_name="cwd")
587
+ runsc_args.extend(["--cwd", clean_cwd])
588
+ if env:
589
+ for env_str in _normalize_env(env):
590
+ runsc_args.extend(["--env", env_str])
591
+ runsc_args.extend([self._id, cmd] + list(args))
592
+ try:
593
+ result = subprocess.run(
594
+ [self._runsc_path] + runsc_args,
595
+ capture_output=True,
596
+ text=True,
597
+ check=True,
598
+ timeout=timeout,
599
+ )
600
+ return result.stdout, result.stderr
601
+ except subprocess.TimeoutExpired as e:
602
+ raise Error(f"exec timed out after {timeout} seconds") from e
603
+ except subprocess.CalledProcessError as e:
604
+ raise Error(f"exec failed: {e.stderr}") from e
605
+
606
+ def close(self):
607
+ """Kills the sandbox processes and cleans up directories."""
608
+ if self._closed:
609
+ return
610
+ self._closed = True
611
+
612
+ if self._state_dir:
613
+ kill_args = ["--root", self._state_dir, "kill", self._id, "SIGKILL"]
614
+ subprocess.run(
615
+ [self._runsc_path] + kill_args, capture_output=True, check=False
616
+ )
617
+
618
+ delete_args = ["--root", self._state_dir, "delete", "--force", self._id]
619
+ delete_result = subprocess.run(
620
+ [self._runsc_path] + delete_args, capture_output=True, check=False
621
+ )
622
+ if delete_result.returncode != 0:
623
+ # We might want to log this, but we continue cleanup anyway.
624
+ pass
625
+
626
+ if self._bundle_dir and os.path.exists(self._bundle_dir):
627
+ try:
628
+ shutil.rmtree(self._bundle_dir)
629
+ except OSError:
630
+ pass
631
+
632
+ if self._owns_runtime_dir and os.path.exists(self._runtime_dir):
633
+ try:
634
+ shutil.rmtree(self._runtime_dir)
635
+ except OSError:
636
+ pass
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: gvisor
3
- Version: 0.0.2
3
+ Version: 0.0.3
4
4
  Summary: Python bindings for gVisor.
5
5
  License: Apache-2.0
6
6
  Project-URL: Homepage, https://gvisor.dev
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "gvisor"
7
- version = "0.0.2"
7
+ version = "0.0.3"
8
8
  description = "Python bindings for gVisor."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.7"
@@ -1,309 +0,0 @@
1
- # Copyright 2026 The gVisor Authors.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # https://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
-
15
- """Python binding for gVisor sandbox.
16
-
17
- This module provides a Python API for creating gVisor sandboxes and executing
18
- commands inside them.
19
- """
20
-
21
- import json
22
- import os
23
- import random
24
- import shutil
25
- import subprocess
26
- import tempfile
27
- from typing import Optional, Tuple
28
-
29
-
30
- class Error(Exception):
31
- """Base exception for Sandbox operations."""
32
-
33
-
34
- class Sandbox:
35
- """Represents a running gVisor sandbox."""
36
-
37
- def __init__(
38
- self,
39
- runtime_dir: Optional[str] = None,
40
- sandbox_id: Optional[str] = None,
41
- enable_networking: bool = True,
42
- ):
43
- """Initializes and starts a new sandbox.
44
-
45
- Args:
46
- runtime_dir: Custom runtime directory where bundle and state files are
47
- written. If not set, a temporary directory is created.
48
- sandbox_id: Specific sandbox ID. If not set, a unique ID is generated
49
- automatically.
50
- enable_networking: Whether networking is enabled inside the sandbox.
51
-
52
- Raises:
53
- Error: If sandbox creation fails.
54
- """
55
- self._enable_networking = enable_networking
56
- self._runtime_dir = ""
57
- self._owns_runtime_dir = False
58
- self._id = ""
59
- self._state_dir = ""
60
- self._bundle_dir = ""
61
- self._closed = False
62
- self._runsc_path = self._find_runsc()
63
-
64
- if runtime_dir is None:
65
- try:
66
- self._runtime_dir = tempfile.mkdtemp(prefix="gvisor-sandbox-")
67
- except OSError as e:
68
- raise Error(f"failed to create runtime directory: {e}") from e
69
- self._owns_runtime_dir = True
70
- else:
71
- self._runtime_dir = runtime_dir
72
- self._owns_runtime_dir = False
73
-
74
- self._id = sandbox_id or self._generate_id()
75
-
76
- try:
77
- if os.geteuid() != 0 and self._enable_networking:
78
- raise Error("enabling networking requires running as root")
79
-
80
- self._state_dir = os.path.join(self._runtime_dir, "state")
81
- try:
82
- os.makedirs(self._state_dir, mode=0o700, exist_ok=True)
83
- except OSError as e:
84
- raise Error(f"failed to create sandbox state directory: {e}") from e
85
-
86
- # Verify permissions (mode might be different if directory already
87
- # existed).
88
- try:
89
- stat_info = os.stat(self._state_dir)
90
- if (stat_info.st_mode & 0o777) != 0o700:
91
- os.chmod(self._state_dir, 0o700)
92
- except OSError as e:
93
- raise Error(
94
- "sandbox state directory has incorrect permissions and failed to"
95
- f" chmod: {e}"
96
- ) from e
97
-
98
- self._bundle_dir = self._create_bundle()
99
-
100
- # Launch the sandbox in detached mode.
101
- args = ["--root", self._state_dir]
102
- if os.geteuid() != 0:
103
- args.append("--ignore-cgroups")
104
- if not self._enable_networking:
105
- args.append("--network=none")
106
- args.extend(["run", "--bundle", self._bundle_dir, "--detach", self._id])
107
-
108
- # We must use a file for stderr because runsc run with --detach spawns a
109
- # grandchild process. If we use pipes (e.g. capture_output=True), Python's
110
- # subprocess.run will hang waiting for the pipes to close. Writing to a
111
- # file avoids this hang while still allowing us to capture errors.
112
- stderr_path = os.path.join(self._runtime_dir, "runsc-stderr.log")
113
- try:
114
- with open(stderr_path, "w+b") as stderr_file:
115
- subprocess.run(
116
- [self._runsc_path] + args,
117
- check=True,
118
- stdout=subprocess.DEVNULL,
119
- stderr=stderr_file,
120
- timeout=30,
121
- )
122
- except subprocess.TimeoutExpired as e:
123
- raise Error("sandbox creation timed out (runsc run hung)") from e
124
- except subprocess.CalledProcessError as e:
125
- stderr_content = ""
126
- if os.path.exists(stderr_path):
127
- try:
128
- with open(stderr_path, "r", errors="replace") as f:
129
- stderr_content = f.read()
130
- except OSError:
131
- pass
132
- raise Error(
133
- "failed to create sandbox via subprocess: exit code"
134
- f" {e.returncode}, stderr: {stderr_content}"
135
- ) from e
136
- except Exception:
137
- self.close()
138
- raise
139
-
140
- def __enter__(self) -> "Sandbox":
141
- return self
142
-
143
- def __exit__(self, exc_type, exc_val, exc_tb):
144
- self.close()
145
-
146
- @property
147
- def id(self) -> str:
148
- """Returns the sandbox ID."""
149
- return self._id
150
-
151
- @property
152
- def bundle_dir(self) -> str:
153
- """Returns the path to the OCI bundle directory."""
154
- return self._bundle_dir
155
-
156
- def _generate_id(self) -> str:
157
- return f"{random.getrandbits(128):032x}"
158
-
159
- def _find_runsc(self) -> str:
160
- if "RUNSC_PATH" in os.environ:
161
- return os.environ["RUNSC_PATH"]
162
- path = shutil.which("runsc")
163
- if path is not None:
164
- return path
165
- raise Error("runsc binary is not found")
166
-
167
- def _create_bundle(self) -> str:
168
- """Creates the OCI bundle directory and config.json.
169
-
170
- Returns:
171
- The path to the created bundle directory.
172
-
173
- Raises:
174
- Error: If bundle creation fails.
175
- """
176
- bundle_dir = os.path.join(self._runtime_dir, self._id)
177
- rootfs_dir = os.path.join(bundle_dir, "rootfs")
178
- try:
179
- os.makedirs(rootfs_dir, mode=0o755, exist_ok=True)
180
- except OSError as e:
181
- raise Error(f"failed to create bundle directories: {e}") from e
182
-
183
- namespaces = [
184
- {"type": "pid"},
185
- {"type": "mount"},
186
- {"type": "uts"},
187
- {"type": "ipc"},
188
- ]
189
- if os.geteuid() != 0:
190
- namespaces.append({"type": "user"})
191
- if self._enable_networking:
192
- namespaces.append({"type": "network"})
193
-
194
- mounts = [
195
- {"destination": "/proc", "type": "proc", "source": "proc"},
196
- {"destination": "/dev", "type": "tmpfs", "source": "tmpfs"},
197
- ]
198
-
199
- for p in ["/bin", "/usr", "/lib", "/lib64", "/etc/alternatives"]:
200
- if os.path.exists(p):
201
- opts = ["rbind", "ro", "nosuid", "nodev"]
202
- if p == "/etc/alternatives":
203
- opts = ["rbind", "ro"]
204
- mounts.append({
205
- "destination": p,
206
- "type": "bind",
207
- "source": p,
208
- "options": opts,
209
- })
210
-
211
- linux = {
212
- "namespaces": namespaces,
213
- }
214
- if os.geteuid() != 0:
215
- linux["uidMappings"] = [
216
- {"containerID": 0, "hostID": os.geteuid(), "size": 1}
217
- ]
218
- linux["gidMappings"] = [
219
- {"containerID": 0, "hostID": os.getegid(), "size": 1}
220
- ]
221
-
222
- spec = {
223
- "ociVersion": "1.0.0",
224
- "root": {
225
- "path": "rootfs",
226
- "readonly": True,
227
- },
228
- "process": {
229
- "terminal": False,
230
- "user": {"uid": 0, "gid": 0},
231
- "args": ["sleep", "infinity"],
232
- "cwd": "/",
233
- "env": ["PATH=/bin:/usr/bin:/usr/local/bin"],
234
- },
235
- "mounts": mounts,
236
- "linux": linux,
237
- }
238
-
239
- config_path = os.path.join(bundle_dir, "config.json")
240
- try:
241
- with open(config_path, "w") as f:
242
- json.dump(spec, f, indent=2)
243
- except OSError as e:
244
- raise Error(f"failed to create config.json: {e}") from e
245
-
246
- return bundle_dir
247
-
248
- def exec(
249
- self, cmd: str, *args: str, timeout: Optional[float] = None
250
- ) -> Tuple[str, str]:
251
- """Runs the given command inside the running sandbox.
252
-
253
- Args:
254
- cmd: The command to run.
255
- *args: Arguments to the command.
256
- timeout: Timeout in seconds.
257
-
258
- Returns:
259
- A tuple of (stdout, stderr) strings.
260
-
261
- Raises:
262
- Error: If the command execution fails or times out.
263
- """
264
- runsc_args = ["--root", self._state_dir, "exec", self._id, cmd] + list(args)
265
- try:
266
- result = subprocess.run(
267
- [self._runsc_path] + runsc_args,
268
- capture_output=True,
269
- text=True,
270
- check=True,
271
- timeout=timeout,
272
- )
273
- return result.stdout, result.stderr
274
- except subprocess.TimeoutExpired as e:
275
- raise Error(f"exec timed out after {timeout} seconds") from e
276
- except subprocess.CalledProcessError as e:
277
- raise Error(f"exec failed: {e.stderr}") from e
278
-
279
- def close(self):
280
- """Kills the sandbox processes and cleans up directories."""
281
- if self._closed:
282
- return
283
- self._closed = True
284
-
285
- if self._state_dir:
286
- kill_args = ["--root", self._state_dir, "kill", self._id, "SIGKILL"]
287
- subprocess.run(
288
- [self._runsc_path] + kill_args, capture_output=True, check=False
289
- )
290
-
291
- delete_args = ["--root", self._state_dir, "delete", "--force", self._id]
292
- delete_result = subprocess.run(
293
- [self._runsc_path] + delete_args, capture_output=True, check=False
294
- )
295
- if delete_result.returncode != 0:
296
- # We might want to log this, but we continue cleanup anyway.
297
- pass
298
-
299
- if self._bundle_dir and os.path.exists(self._bundle_dir):
300
- try:
301
- shutil.rmtree(self._bundle_dir)
302
- except OSError:
303
- pass
304
-
305
- if self._owns_runtime_dir and os.path.exists(self._runtime_dir):
306
- try:
307
- shutil.rmtree(self._runtime_dir)
308
- except OSError:
309
- pass
File without changes
File without changes