-
Notifications
You must be signed in to change notification settings - Fork 12
/
run_code.py
2263 lines (2081 loc) · 90.8 KB
/
run_code.py
1
2
3
4
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
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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
id: run_code
title: Run code
description: Run arbitrary Python or Bash code safely in a gVisor sandbox.
author: EtiennePerot
author_url: https://github.com/EtiennePerot/open-webui-code-execution
funding_url: https://github.com/EtiennePerot/open-webui-code-execution
version: 0.4.0
license: Apache-2.0
"""
# This is an OpenWebUI *tool*. It allows an LLM to generate and call code on its own.
# If you are looking for an OpenWebUI *function* to allow you to manually execute blocks
# of code in the LLM output, see here instead:
# https://openwebui.com/f/etienneperot/run_code/
# See https://github.com/EtiennePerot/open-webui-code-execution for more info.
# Protip: You can test this tool manually outside of OpenWebUI by running it like this:
#
# echo 'print("Hello world!")' | python3 run_code.py
#
# This will simulate that OpenWebUI would do if it asked this tool to evaluate the Python code `print("Hello world!")`.
# This can be useful when setting up this tool to verify that it works in your environment.
import asyncio
import argparse
import base64
import contextlib
import copy
import json
import hashlib
import inspect
import os
import os.path
import platform
import pydantic
import re
import shutil
import subprocess
import sys
import tempfile
import time
import typing
import urllib.request
class _Tools:
class Valves(pydantic.BaseModel):
_VALVE_OVERRIDE_ENVIRONMENT_VARIABLE_NAME_PREFIX = "CODE_EVAL_VALVE_OVERRIDE_"
NETWORKING_ALLOWED: bool = pydantic.Field(
default=True,
description=f"Whether to allow network access during code execution; may be overridden by environment variable {_VALVE_OVERRIDE_ENVIRONMENT_VARIABLE_NAME_PREFIX}NETWORKING_ALLOWED.",
)
MAX_RUNTIME_SECONDS: int = pydantic.Field(
ge=1,
default=30,
description=f"Maximum number of seconds code is given to run; may be overridden by environment variable {_VALVE_OVERRIDE_ENVIRONMENT_VARIABLE_NAME_PREFIX}MAX_RUNTIME_SECONDS.",
)
MAX_RAM_MEGABYTES: int = pydantic.Field(
ge=0,
default=128,
description=f"Maximum number of megabytes that the interpreter has when running. Must run as root with host cgroups writable (`--mount=type=bind,source=/sys/fs/cgroup,target=/sys/fs/cgroup,readonly=false`) for this to work. Set to 0 to disable memory limits. May be overridden by environment variable {_VALVE_OVERRIDE_ENVIRONMENT_VARIABLE_NAME_PREFIX}MAX_RAM_MEGABYTES",
)
AUTO_INSTALL: bool = pydantic.Field(
default=True,
description=f"Whether to automatically install gVisor if not installed on the system; may be overridden by environment variable {_VALVE_OVERRIDE_ENVIRONMENT_VARIABLE_NAME_PREFIX}AUTO_INSTALL.",
)
DEBUG: bool = pydantic.Field(
default=False,
description=f"Whether to produce debug logs during execution; may be overridden by environment variable {_VALVE_OVERRIDE_ENVIRONMENT_VARIABLE_NAME_PREFIX}DEBUG.",
)
def __init__(self, valves):
self.valves = valves
for valve_name, valve_value in valves.dict().items():
override = os.getenv(
self.valves._VALVE_OVERRIDE_ENVIRONMENT_VARIABLE_NAME_PREFIX
+ valve_name
)
if override is None:
continue
try:
if type(valve_value) is type(True):
assert override.lower() in (
"true",
"false",
), 'Value must be "true" or "false"'
override = override.lower() == "true"
elif type(valve_value) is type(42):
override = int(override)
else:
valve_value_type = type(valve_value)
raise ValueError(f"Unknown valve type: {valve_value_type}")
except Exception as e:
raise ValueError(
f"Valve override {self.valves._VALVE_OVERRIDE_ENVIRONMENT_VARIABLE_NAME_PREFIX}{valve_name}={valve_value}: bad value: {e}"
)
else:
setattr(self.valves, valve_name, override)
async def run_bash_command(
self,
bash_command: str,
__event_emitter__: typing.Callable[[dict], typing.Any] = None,
) -> str:
"""
Run a bash command-line or script safely in a gVisor sandbox.
:param bash_command: Bash command or script to run.
:return: A JSON object with the following fields: `status`, `output`. In most cases, when `status` is "OK", the user is interested in the content of the `output` field. Otherwise, report the `status` field first.
"""
return await self._run_code(
language=Sandbox.LANGUAGE_BASH,
code=bash_command,
event_emitter=__event_emitter__,
)
async def run_python_code(
self,
python_code: str,
__event_emitter__: typing.Callable[[dict], typing.Any] = None,
) -> str:
"""
Run Python code safely in a gVisor sandbox.
:param python_code: Python code to run.
:return: A JSON object with the following fields: `status`, `output`. In most cases, when `status` is "OK", the user is interested in the content of the `output` field. Otherwise, report the `status` field first.
"""
return await self._run_code(
language=Sandbox.LANGUAGE_PYTHON,
code=python_code,
event_emitter=__event_emitter__,
)
class _EventEmitter:
"""
Helper wrapper for event emissions.
"""
def __init__(
self,
event_emitter: typing.Callable[[dict], typing.Any] = None,
debug: bool = False,
):
self.event_emitter = event_emitter
self._debug = debug
async def _emit(self, typ, data):
if self._debug:
print(f"Emitting {typ} event: {data}", file=sys.stderr)
if not self.event_emitter:
return None
maybe_future = self.event_emitter(
{
"type": typ,
"data": data,
}
)
if asyncio.isfuture(maybe_future) or inspect.isawaitable(maybe_future):
return await maybe_future
async def status(
self, description="Unknown state", status="in_progress", done=False
):
await self._emit(
"status",
{
"status": status,
"description": description,
"done": done,
},
)
async def fail(self, description="Unknown error"):
await self.status(description=description, status="error", done=True)
async def _run_code(
self,
language: str,
code: str,
event_emitter: typing.Callable[[dict], typing.Any] = None,
) -> str:
"""
Run code safely in a gVisor sandbox.
:param language: Programming language of the code.
:param code: The code to run.
:param event_emitter: Event emitter to send status updates to.
:return: A JSON object with the following fields: `status`, `output`. In most cases, when `status` is "OK", the user is interested in the content of the `output` field. Otherwise, report the `status` field first.
"""
valves = self.valves
debug = valves.DEBUG
emitter = self._EventEmitter(event_emitter, debug=debug)
async def _fail(error_message):
if debug:
await emitter.fail(
f"[DEBUG MODE] {error_message}; language={language}; code={code}; valves=[{valves}]"
)
else:
await emitter.fail(error_message)
return json.dumps({"status": "SANDBOX_ERROR", "output": error_message})
try:
max_ram_bytes = None
if valves.MAX_RAM_MEGABYTES != 0:
max_ram_bytes = valves.MAX_RAM_MEGABYTES * 1024 * 1024
await emitter.status("Checking if environment supports sandboxing...")
Sandbox.check_setup(
language=language,
auto_install_allowed=valves.AUTO_INSTALL,
)
if valves.AUTO_INSTALL and Sandbox.runsc_needs_installation():
await emitter.status("Auto-installing gVisor...")
Sandbox.install_runsc()
await emitter.status("Initializing sandbox configuration...")
status = "UNKNOWN"
output = None
language_title = language.title()
# If the provided code starts/ends with "```" or
# "```SOME_LANGUAGE", remove that.
code = code.strip()
code = code.removeprefix("```" + language)
code = code.removeprefix("```")
code = code.removesuffix("```")
# If the provided code is a single line enclosed in
# "`"s, strip those and whitespace away.
code = code.strip()
code = code.strip("`")
code = code.strip()
with tempfile.TemporaryDirectory(prefix="sandbox_") as tmp_dir:
sandbox = Sandbox(
tmp_dir=tmp_dir,
language=language,
code=code,
debug=debug,
networking_allowed=valves.NETWORKING_ALLOWED,
max_runtime_seconds=valves.MAX_RUNTIME_SECONDS,
max_ram_bytes=max_ram_bytes,
)
await emitter.status(
f"Running {language_title} code in gVisor sandbox..."
)
try:
result = sandbox.run()
except Sandbox.ExecutionTimeoutError as e:
await emitter.fail(
f"Code timed out after {valves.MAX_RUNTIME_SECONDS} seconds"
)
status = "TIMEOUT"
output = e.stderr
except Sandbox.InterruptedExecutionError as e:
await emitter.fail(f"Code used too many resources")
status = "INTERRUPTED"
output = e.stderr
except Sandbox.CodeExecutionError as e:
await emitter.fail(f"{language_title}: {e}")
status = "ERROR"
output = e.stderr
else:
await emitter.status(
status="complete",
done=True,
description=f"{language_title} code executed successfully.",
)
status = "OK"
output = result.stdout or result.stderr
if output:
output = output.strip()
if debug:
per_file_logs = {}
def _log(filename: str, log_line: str):
print(f"[{filename}] {log_line}", file=sys.stderr)
if filename not in per_file_logs:
per_file_logs[filename] = []
per_file_logs[filename].append(log_line)
sandbox.debug_logs(_log)
await emitter.status(
status="complete" if status == "OK" else "error",
done=True,
description=f"[DEBUG MODE] status={status}; output={output}; valves=[{valves}]; debug={per_file_logs}",
)
return json.dumps(
{
"status": status,
"output": output,
},
ensure_ascii=False,
)
except Sandbox.PlatformNotSupportedException as e:
return await _fail(f"Sandbox cannot run on this machine: {e}")
except Sandbox.SandboxRuntimeException as e:
return await _fail(f"Sandbox runtime failed: {e}")
except Sandbox.FixableException as e:
return await _fail(f"Environment needs setup work: {e}")
except Sandbox.SandboxException as e:
return await _fail(f"Sandbox exception: {e}")
except Exception as e:
return await _fail(f"Unhandled exception: {e}")
class Tools:
Valves = _Tools.Valves
def __init__(self):
self.valves = self.Valves()
async def run_bash_command(
self,
bash_command: str,
__event_emitter__: typing.Callable[[dict], typing.Any] = None,
) -> str:
"""
Run a bash command-line or script safely in a gVisor sandbox.
:param bash_command: Bash command or script to run.
:return: A JSON object with the following fields: `status`, `output`. In most cases, when `status` is "OK", the user is interested in the content of the `output` field. Otherwise, report the `status` field first.
"""
return await _Tools(self.valves).run_bash_command(
bash_command=bash_command,
__event_emitter__=__event_emitter__,
)
async def run_python_code(
self,
python_code: str,
__event_emitter__: typing.Callable[[dict], typing.Any] = None,
) -> str:
"""
Run Python code safely in a gVisor sandbox.
:param python_code: Python code to run.
:return: A JSON object with the following fields: `status`, `output`. In most cases, when `status` is "OK", the user is interested in the content of the `output` field. Otherwise, report the `status` field first.
"""
return await _Tools(self.valves).run_python_code(
python_code=python_code,
__event_emitter__=__event_emitter__,
)
class Sandbox:
"""
Sandbox manages a gVisor sandbox's lifecycle.
"""
# Set of supported programming langauges.
LANGUAGE_PYTHON = "python"
LANGUAGE_BASH = "bash"
SUPPORTED_LANGUAGES = [LANGUAGE_PYTHON, LANGUAGE_BASH]
# The following directories will be exposed as read-only to the
# sandboxed environment. This must contain at least the necessary
# files and libraries necessary to run the code interpreter.
# Subdirectories of these directories may be hidden by adding them
# to the `EMPTY_READ_ONLY_DIRECTORIES` or `EMPTY_WRITABLE_DIRECTORIES`
# lists below.
EXPOSED_SYSTEM_DIRECTORIES = [
"/bin",
"/etc/alternatives",
"/etc/ssl/certs",
"/lib",
"/lib32",
"/lib64",
"/opt",
"/sbin",
"/usr",
"/var/lib",
]
# The following files will be exposed as read-only to the sandboxed
# environment. This should contain the set of files necessary by the
# code interpreter to function correctly, e.g. `/etc/resolv.conf`
# is necessary to properly resolve hosts through DNS.
EXPOSED_SYSTEM_FILES = [
"/etc/hosts",
"/etc/localtime",
"/etc/mime.types",
"/etc/nsswitch.conf",
"/etc/os-release",
"/etc/resolv.conf",
"/etc/shells",
]
# The following directories will exist in the sandbox environment but
# will appear as empty and read-only.
# This is useful to have a filesystem that feels like a normal Linux
# environment without actually revealing these directories to the
# sandbox.
EMPTY_READ_ONLY_DIRECTORIES = [
"/etc",
"/home",
"/lost+found",
"/root",
"/run",
"/run/user",
"/sys",
"/var",
]
# The following directories will exist in the sandbox environment but
# will appear as empty and writable.
# This is useful to have a filesystem that feels like a normal Linux
# environment without actually revealing these directories to the
# sandbox.
EMPTY_WRITABLE_DIRECTORIES = [
"/dev/shm",
"/home/user",
"/run/user/1000",
"/var/run",
"/var/tmp",
"/tmp",
]
# Static parts of the OCI configuration.
OCI_CONFIG_SKELETON = {
"ociVersion": "1.0.0",
"process": {
"user": {"uid": 1000, "gid": 1000},
"args": ["/bin/INVALID"], # Will be filled in.
"env": [
# Basic environment variables.
"EDITOR=cat",
"LANG=C.UTF-8",
"LC_ALL=C.UTF-8",
"LC_CTYPE=C.UTF-8",
"HOME=/home/user",
"HOSTNAME=sandbox",
"PAGER=cat",
"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
"PWD=/home/user",
"SHLVL=1",
"TERM=xterm",
"USER=user",
],
"cwd": "/home/user",
"capabilities": {
# No capabilities whatsoever.
"bounding": [],
"effective": [],
"inheritable": [],
"permitted": [],
},
"rlimits": [
{"type": "RLIMIT_NOFILE", "hard": 1048576, "soft": 1048576},
],
"noNewPrivileges": True,
},
"root": {
"path": "/invalid", # Will be filled in.
"readonly": True,
},
"hostname": "sandbox",
"mounts": [
{"destination": "/dev", "type": "dev"},
{"destination": "/proc", "type": "proc"},
],
"linux": {
"namespaces": [
{"type": "pid"},
{"type": "ipc"},
{"type": "uts"},
{"type": "mount"},
],
"resources": {
"memory": {
# `limit` may be be filled in here depending on user configuration.
"disableOOMKiller": False,
},
},
},
}
# The path where the `runsc` binary will be downloaded and installed if
# requested.
AUTO_INSTALLATION_PATH = "/tmp/gvisor/runsc"
# Regular expression for log filename prefixes generated by `runsc`.
_LOG_FILENAME_TRUNCATE_RE = re.compile(r"^runsc\.log\.\d{8}-\d{6}(?:\.\d+)?\.")
# Other files worth logging when dumping debug logs.
_EXTRA_DEBUG_LOG_PATHS = (
"/etc/os-release",
"/proc/self/cgroup",
"/proc/self/personality",
"/proc/self/mountinfo",
"/proc/self/setgroups",
"/proc/self/status",
"/proc/self/uid_map",
"/proc/self/gid_map",
"/proc/cmdline",
"/proc/cpuinfo",
"/proc/cgroups",
"/proc/mounts",
"/proc/version",
)
# Other commands worth running when dumping debug logs.
_EXTRA_DEBUG_LOG_COMMANDS = (
("pwd",),
("id",),
("uname", "-a"),
("ls", "-l", "/proc/self/ns"),
(sys.executable, "--version"),
)
# Environment variable used to detect interpreter re-execution.
_MARKER_ENVIRONMENT_VARIABLE = "__CODE_EXECUTION_STAGE"
class _Switcheroo:
"""
Management of the switcheroo procedure for running in a usable cgroup namespace and node.
"""
_CGROUP_ROOT = "/sys/fs/cgroup"
_CGROUP_NAME_PREFIX = "codeeval_"
_CGROUP_MAX_COUNT = 4096
_CGROUP_SANDBOX_NAME = "sandbox"
_CGROUP_SUPERVISOR_NAME = "supervisor"
_CGROUP_LEAF = "leaf"
def __init__(self, log_path, max_sandbox_ram_bytes):
self._log_path = log_path
self._max_sandbox_ram_bytes = max_sandbox_ram_bytes
self._my_euid = None
self._my_egid = None
self._checkpoint = None
self._cgroup_controllers = None
self._needed_controllers = set()
if max_sandbox_ram_bytes is not None:
self._needed_controllers.add("memory")
self._initial_cgroup_name = None
self._codeeval_cgroup_name = None
self._moved = False
self._operations = (
# Save EUID and EGID before we move to a new user namespace.
("save_euid", self._save_euid),
("save_egid", self._save_egid),
("unshare_user", self._unshare_user),
# Map our current user as being root in the new user namespace.
("write_uid_map", self._write_uid_map),
("write_setgroups", self._write_setgroups),
("write_gid_map", self._write_gid_map),
# cgroupfs's view does not take into account cgroup namespaces.
# Weird, right?
# This means `/proc/PID/cgroup` will show the namespaced view of
# the cgroup that the PID is in, but `/sys/fs/cgroup` will still
# contain the whole system cgroup hierarchy regardless of namespace.
# Instead, namespaces act as "boundary box" around process movement
# requests when writing to cgroup.procs or creating new cgroups.
# So our first order of business here is to find out which cgroup we
# are running in. We do this by scanning the whole cgroupfs hierarchy
# and looking for our PID. This will populate
# `self._initial_cgroup_name`.
("find_self_in_cgroup_hierarchy", self._find_self_in_cgroup_hierarchy),
# The cgroup nesting rules are complicated, but the short of it is:
# A cgroup can either **contain processes** OR **have limits**.
# Also, cgroups that contain processes must be leaf nodes.
# Also, cgroups that enforce limits must have their parent cgroup
# also have the same limit "controller" be active.
# So we will have two types of cgroups:
# - Leaf nodes with no controllers
# - Non-leaf nodes with controllers
# So initially, all the processes in the container's initial
# namespace need to be moved out to a new leaf node,
# otherwise we cannot turn on controllers on the initial
# cgroup.
# So we will set up the following hierarchy:
# /sys/fs/cgroup/$INITIAL:
# The cgroup where the container's processes were running
# the first time we run any Sandbox in the container.
# It may initially have no controllers enabled, but we will
# turn them on later.
# /sys/fs/cgroup/$INITIAL/leaf:
# The cgroup where the container's processes are moved to
# from the $INITIAL cgroup upon first run of any Sandbox in
# this container. When this code runs again, processes that
# are already in `$INITIAL/leaf` are not moved.
# /sys/fs/cgroup/$INITIAL/codeeval_$NUM:
# A per-Sandbox cgroup that never contains any processes.
# It will have controllers enabled on it but will never have
# specific limits enforced.
# /sys/fs/cgroup/$INITIAL/codeeval_$NUM/sandbox:
# A per-Sandbox cgroup that never contains any processes.
# It will have controllers enabled on it and will enforce
# resource limits for the processes running in its /leaf.
# /sys/fs/cgroup/$INITIAL/codeeval_$NUM/sandbox/leaf:
# A per-Sandbox cgroup that is running `runsc` (gVisor).
# It has no controllers enabled on it, but resources are
# being enforced by virtue of being a child of
# `$INITIAL/codeeval_$NUM/sandbox` which does enforce limits.
# /sys/fs/cgroup/$INITIAL/codeeval_$NUM/supervisor:
# A per-Sandbox cgroup that never contains any processes.
# It will have controllers enabled on it and will enforce
# resource limits for the processes running in its /leaf.
# /sys/fs/cgroup/$INITIAL/codeeval_$NUM/supervisor/leaf:
# A per-Sandbox cgroup that is running a Python interpreter
# that manages the lifetime of the `runsc` process.
# It will run `Sandbox.maybe_main`.
# It has no controllers enabled on it, but resources are
# being enforced by virtue of being a child of
# `$INITIAL/codeeval_$NUM/sandbox` which does enforce limits.
#
# This particular step creates the `$INITIAL/leaf` cgroup.
# If already created, it does nothing.
("create_initial_leaf_cgroup", self._create_initial_leaf_cgroup),
# Move all processes in `$INITIAL` to `$INITIAL/leaf`.
(
"move_initial_cgroup_processes_to_initial_leaf_cgroup",
self._move_initial_cgroup_processes_to_initial_leaf_cgroup,
),
# Read the cgroup controllers enabled in `$INITIAL`. This acts
# as a bounding set on the ones we can enable in any child of it.
("read_cgroup_controllers", self._read_cgroup_controllers),
# Cleanup old `$INITIAL/codeeval_*` cgroups that may be lying
# around from past runs.
("cleanup_old_cgroups", self._cleanup_old_cgroups),
# Create a new `$INITIAL/codeeval_$NUM` cgroup.
("create_codeeval_cgroup", self._create_codeeval_cgroup),
# Create a new `$INITIAL/codeeval_$NUM/sandbox` cgroup.
("create_sandbox_cgroup", self._create_sandbox_cgroup),
# Create a new `$INITIAL/codeeval_$NUM/sandbox/leaf` cgroup.
("create_sandbox_leaf_cgroup", self._create_sandbox_leaf_cgroup),
# Create a new `$INITIAL/codeeval_$NUM/supervisor` cgroup.
("create_supervisor_cgroup", self._create_supervisor_cgroup),
# Create a new `$INITIAL/codeeval_$NUM/supervisor/leaf` cgroup.
("create_supervisor_leaf_cgroup", self._create_supervisor_leaf_cgroup),
# Add controllers to `$INITIAL`.
(
"add_cgroup_controllers_to_root",
self._add_cgroup_controllers_to_root,
),
# Add controllers to `$INITIAL/codeeval_$NUM`.
(
"add_cgroup_controllers_to_codeeval",
self._add_cgroup_controllers_to_codeeval,
),
# Add controllers to `$INITIAL/codeeval_$NUM/sandbox`.
(
"add_cgroup_controllers_to_sandbox",
self._add_cgroup_controllers_to_sandbox,
),
# Set resource limits on `$INITIAL/codeeval_$NUM`.
("set_sandbox_cgroup_limits", self._set_sandbox_cgroup_limits),
# Add controllers to `$INITIAL/codeeval_$NUM/supervisor`.
(
"add_cgroup_controllers_to_supervisor",
self._add_cgroup_controllers_to_supervisor,
),
# Set resource limits on `$INITIAL/codeeval_$NUM/supervisor`.
("set_supervisor_cgroup_limits", self._set_supervisor_cgroup_limits),
# Move current process to
# `$INITIAL/codeeval_$NUM/supervisor/leaf`.
(
"move_process_to_supervisor_leaf",
self._move_process_to_supervisor_leaf,
),
# Double-check that we have moved to
# `$INITIAL/codeeval_$NUM/supervisor/leaf`.
("sanity_check_own_cgroup", self._sanity_check_own_cgroup),
)
def _status(self):
"""
Return the current switcheroo status.
:return: The last successful operation name, "UNSTARTED" if unstarted, or "OK" if all done, and some information.
"""
main_status = self._checkpoint
if self._checkpoint is None:
main_status = "UNSTARTED"
if self._checkpoint == self._operations[-1][0]:
main_status = "OK"
my_pid = os.getpid()
status_line = f"{main_status} (euid={self._my_euid} egid={self._my_egid} pid={my_pid} initial_cgroup_name={self._initial_cgroup_name} codeeval_cgroup_name={self._codeeval_cgroup_name} controllers={self._cgroup_controllers})"
cgroupfs_data = []
for cgroup_components in (
(self._initial_cgroup_name,),
(self._initial_cgroup_name, self._CGROUP_LEAF),
(self._initial_cgroup_name, self._codeeval_cgroup_name),
(
self._initial_cgroup_name,
self._codeeval_cgroup_name,
self._CGROUP_LEAF,
),
(
self._initial_cgroup_name,
self._codeeval_cgroup_name,
self._CGROUP_SUPERVISOR_NAME,
),
(
self._initial_cgroup_name,
self._codeeval_cgroup_name,
self._CGROUP_SUPERVISOR_NAME,
self._CGROUP_LEAF,
),
(
self._initial_cgroup_name,
self._codeeval_cgroup_name,
self._CGROUP_SANDBOX_NAME,
),
(
self._initial_cgroup_name,
self._codeeval_cgroup_name,
self._CGROUP_SANDBOX_NAME,
self._CGROUP_LEAF,
),
):
if any(c is None for c in cgroup_components):
continue
file_data = []
for filename in ("procs", "controllers", "subtree_control"):
data = None
try:
with self._open(
self._cgroup_path(
*(cgroup_components + (f"cgroup.{filename}",))
),
"rb",
) as f:
data = f.read().decode("ascii").replace("\n", " ")
except Exception as e:
data = f"[fail: {e}]"
file_data.append(f"{filename}: {data}")
cgroup_components_joined = os.sep.join(cgroup_components)
file_data_joined = ", ".join(file_data)
cgroupfs_data.append(f"{cgroup_components_joined}=[{file_data_joined}]")
if len(cgroupfs_data) > 0:
cgroupfs_data_joined = " ".join(cgroupfs_data)
status_line += f" {cgroupfs_data_joined}"
return status_line
def _cgroup_path(self, *components):
assert all(
c is not None for c in components
), f"Tried to build cgroup path with not-yet-determined component: {components}"
return os.path.join(self._CGROUP_ROOT, *(c for c in components if c))
def _log(self, log_f, message):
"""
Log a message to `log_f`.
:param log_f: Log file object.
"""
timestamp = time.strftime("%H:%M:%S")
status = self._status()
log_f.write(f"[{timestamp}] {message} [{status}]\n".encode("utf-8"))
def do(self):
"""
Do the switcheroo.
:raises OSError: If anything goes wrong. Progress is saved.
"""
op_index = -1
for i, (op, _) in enumerate(self._operations):
if self._checkpoint == op:
op_index = i
break
with self._open(self._log_path, "ab") as log_f:
do_log = lambda s: self._log(log_f, s)
for op, fn in self._operations[op_index + 1 :]:
do_log(f"Starting operation: {op}")
errors = []
success = False
for attempt in range(1, 4):
try:
fn()
except OSError as e:
do_log(f"OSError #{attempt}: {op}: {e}")
errors.append(OSError(f"OSError in {op} (#{attempt}): {e}"))
except Exception as e:
do_log(f"Exception #{attempt}: {op}: {e}")
errors.append(OSError(f"{op} failed (#{attempt}): {e}"))
else:
success = True
break
time.sleep(0.1)
if success:
self._checkpoint = op
do_log(f"Success: {op}")
continue
assert len(errors) > 0, "Logic error"
first_exception = errors[0]
if len(errors) == 1:
raise first_exception
other_exceptions = "; ".join(str(e) for e in errors[1:])
raise errors[0].__class__(
f"{first_exception} (other attempts: {other_exceptions})"
)
def _best_effort_remove_cgroup_subtree(self, codeeval_name):
for cgroup_components in (
(
self._initial_cgroup_name,
codeeval_name,
self._CGROUP_SANDBOX_NAME,
self._CGROUP_LEAF,
),
(
self._initial_cgroup_name,
codeeval_name,
self._CGROUP_SUPERVISOR_NAME,
self._CGROUP_LEAF,
),
(self._initial_cgroup_name, codeeval_name, self._CGROUP_SANDBOX_NAME),
(
self._initial_cgroup_name,
codeeval_name,
self._CGROUP_SUPERVISOR_NAME,
),
(self._initial_cgroup_name, codeeval_name),
):
try:
os.rmdir(self._cgroup_path(*cgroup_components))
except OSError:
pass
def cleanup(self):
if self._moved:
self._move_process_back()
if self._codeeval_cgroup_name is not None:
self._best_effort_remove_cgroup_subtree(self._codeeval_cgroup_name)
def _open(self, path, mode):
try:
return open(path, mode)
except OSError as e:
raise OSError(f"opening {path} mode={mode}: {e}")
def _save_euid(self):
self._my_euid = os.geteuid()
def _save_egid(self):
self._my_egid = os.getegid()
def _unshare_user(self):
Sandbox.unshare(
os.CLONE_NEWUSER if "CLONE_NEWUSER" in os.__dict__ else 0x10000000
)
def _write_uid_map(self):
with self._open("/proc/self/uid_map", "wb") as uid_map_f:
uid_map_f.write(f"0 {self._my_euid} 1\n".encode("ascii"))
def _write_setgroups(self):
with self._open("/proc/self/setgroups", "wb") as setgroups_f:
setgroups_f.write(b"deny")
def _write_gid_map(self):
with self._open("/proc/self/gid_map", "wb") as gid_map_f:
gid_map_f.write(f"0 {self._my_egid} 1\n".encode("ascii"))
def _find_self_in_cgroup_hierarchy(self):
my_pid = os.getpid()
cgroup_root_slash = self._CGROUP_ROOT + os.sep
found_cgroup = None
num_checked = 0
num_except = 0
sample_exception = None
for dirpath, _, subfiles in os.walk(
self._CGROUP_ROOT, onerror=None, followlinks=False
):
if not dirpath.startswith(cgroup_root_slash):
continue
if "cgroup.procs" not in subfiles:
continue
num_checked += 1
found_pid = False
try:
with self._open(
os.path.join(dirpath, "cgroup.procs"), "rb"
) as cgroup_procs_f:
for line in cgroup_procs_f:
for pid_str in line.strip().split(b" "):
if not pid_str:
continue
try:
pid = int(pid_str)
except ValueError:
continue
if pid == my_pid:
found_pid = True
break
except Exception as e:
num_except += 1
if sample_exception is None:
sample_exception = e.__class__(f"{dirpath}: {e}")
continue
if not found_pid:
continue
current_cgroup = dirpath[len(cgroup_root_slash) :]
if found_cgroup is not None:
raise OSError(
f"Found PID {my_pid} in two separate cgroups: {found_cgroup} and {current_cgroup}; racing with another process?"
)
found_cgroup = current_cgroup
if found_cgroup is None:
raise OSError(
f"PID {my_pid} could not be found in any cgroup (checked {num_checked} cgroups, {num_except} exceptions; sample: {sample_exception})"
)
if found_cgroup.endswith(os.sep + self._CGROUP_LEAF):
found_cgroup = found_cgroup[: -len(os.sep + self._CGROUP_LEAF)]
self._initial_cgroup_name = found_cgroup
def _read_cgroup_controllers(self):
cgroup_controllers = []
with self._open(
self._cgroup_path(self._initial_cgroup_name, "cgroup.controllers"), "rb"
) as cgroup_controllers_f:
for line in cgroup_controllers_f:
for controller in line.strip().split(b" "):
if controller and controller not in cgroup_controllers:
cgroup_controllers.append(controller.decode("ascii"))
self._cgroup_controllers = cgroup_controllers
def _cleanup_old_cgroups(self):
initial_cgroup_path = self._cgroup_path(self._initial_cgroup_name)
for filename in os.listdir(initial_cgroup_path):
if not filename.startswith(self._CGROUP_NAME_PREFIX):
continue
cgroup_path = os.path.join(initial_cgroup_path, filename)
if not os.path.isdir(cgroup_path):
continue
self._best_effort_remove_cgroup_subtree(filename)
def _create_initial_leaf_cgroup(self):
try:
os.mkdir(
self._cgroup_path(self._initial_cgroup_name, self._CGROUP_LEAF),
mode=0o755,
)
except FileExistsError:
pass
def _create_codeeval_cgroup(self):
for counter in range(0, self._CGROUP_MAX_COUNT):
codeeval_cgroup_name_candidate = f"{self._CGROUP_NAME_PREFIX}{counter}"
cgroup_path = self._cgroup_path(
self._initial_cgroup_name, codeeval_cgroup_name_candidate
)
try:
os.mkdir(cgroup_path, mode=0o755)
except FileExistsError:
pass
else:
self._codeeval_cgroup_name = codeeval_cgroup_name_candidate
return
initial_cgroup_path_prefix = self._cgroup_path(
self._initial_cgroup_name, self._CGROUP_NAME_PREFIX
)
raise OSError(
f"Out of cgroups (tried {initial_cgroup_path_prefix}NUM with NUM from 0 to {self._CGROUP_MAX_COUNT-1} and they all already exist)"
)
def _create_sandbox_cgroup(self):
os.mkdir(
self._cgroup_path(
self._initial_cgroup_name,
self._codeeval_cgroup_name,
self._CGROUP_SANDBOX_NAME,
),
mode=0o755,
)
def _create_sandbox_leaf_cgroup(self):
os.mkdir(
self._cgroup_path(
self._initial_cgroup_name,
self._codeeval_cgroup_name,
self._CGROUP_SANDBOX_NAME,
self._CGROUP_LEAF,
),
mode=0o755,
)
def _create_supervisor_cgroup(self):
os.mkdir(
self._cgroup_path(
self._initial_cgroup_name,
self._codeeval_cgroup_name,
self._CGROUP_SUPERVISOR_NAME,
),
mode=0o755,
)
def _create_supervisor_leaf_cgroup(self):