inferyx-codegate 1.1.0__py3-none-any.whl
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.
- codegate/__init__.py +8 -0
- codegate/__main__.py +3 -0
- codegate/api/__init__.py +0 -0
- codegate/api/admin.py +457 -0
- codegate/api/deps.py +36 -0
- codegate/api/devproxy.py +132 -0
- codegate/api/public.py +371 -0
- codegate/app.py +115 -0
- codegate/auth/__init__.py +0 -0
- codegate/auth/csrf.py +43 -0
- codegate/auth/native.py +111 -0
- codegate/auth/passwords.py +88 -0
- codegate/auth/saml.py +222 -0
- codegate/auth/sessions.py +121 -0
- codegate/cli/__init__.py +0 -0
- codegate/cli/auth_cmd.py +168 -0
- codegate/cli/backup_cmd.py +114 -0
- codegate/cli/common.py +103 -0
- codegate/cli/doctor_cmd.py +136 -0
- codegate/cli/main.py +526 -0
- codegate/cli/nginx_setup.py +220 -0
- codegate/cli/setup_cmd.py +401 -0
- codegate/cli/ssh_setup.py +114 -0
- codegate/cli/upgrade_cmd.py +209 -0
- codegate/config.py +161 -0
- codegate/db.py +297 -0
- codegate/errors.py +122 -0
- codegate/jobs.py +133 -0
- codegate/pages.py +177 -0
- codegate/resources/__init__.py +20 -0
- codegate/resources/docker/Dockerfile +36 -0
- codegate/resources/nginx/codegate.conf.tmpl +51 -0
- codegate/resources/nginx/map.conf +5 -0
- codegate/resources/nginx/site.conf.tmpl +9 -0
- codegate/resources/nginx/user.conf.tmpl +19 -0
- codegate/resources/systemd/codegate-backup.service.tmpl +7 -0
- codegate/resources/systemd/codegate-backup.timer +10 -0
- codegate/resources/systemd/codegate.service.tmpl +20 -0
- codegate/static/admin/3rdpartylicenses.txt +614 -0
- codegate/static/admin/chunk-0r_p7pcB.js +672 -0
- codegate/static/admin/chunk-BoGqYCjO.js +1260 -0
- codegate/static/admin/chunk-BqiJ460N.js +1269 -0
- codegate/static/admin/chunk-BtoaIoDj.js +449 -0
- codegate/static/admin/chunk-CB4E-q63.js +255 -0
- codegate/static/admin/chunk-CMN75K3s.js +181 -0
- codegate/static/admin/chunk-CW_CPa20.js +106 -0
- codegate/static/admin/chunk-CcgsCK7w.js +393 -0
- codegate/static/admin/chunk-Cjwyuum6.js +375 -0
- codegate/static/admin/chunk-D6j6hnz3.js +1 -0
- codegate/static/admin/chunk-D9RytJgO.js +1 -0
- codegate/static/admin/chunk-DA6TldFU.js +35 -0
- codegate/static/admin/chunk-DFGdyoNb.js +1 -0
- codegate/static/admin/chunk-DXvCZ3pT.js +1 -0
- codegate/static/admin/chunk-DstgVdtz.js +27 -0
- codegate/static/admin/chunk-kPDFCwHP.js +102 -0
- codegate/static/admin/chunk-yikJ2ObQ.js +1 -0
- codegate/static/admin/favicon.ico +0 -0
- codegate/static/admin/index.html +14 -0
- codegate/static/admin/main-LWBML7JF.js +2347 -0
- codegate/static/admin/media/material-icons-JLIDJUWE.woff +0 -0
- codegate/static/admin/media/material-icons-LEZCGFVT.woff2 +0 -0
- codegate/static/admin/styles-YWRWGLKG.css +1 -0
- codegate/system/__init__.py +27 -0
- codegate/system/base.py +165 -0
- codegate/system/devdocker.py +90 -0
- codegate/system/fake.py +199 -0
- codegate/system/real.py +493 -0
- codegate/system/shell.py +40 -0
- codegate/users.py +262 -0
- codegate/workspace.py +355 -0
- inferyx_codegate-1.1.0.dist-info/METADATA +217 -0
- inferyx_codegate-1.1.0.dist-info/RECORD +74 -0
- inferyx_codegate-1.1.0.dist-info/WHEEL +4 -0
- inferyx_codegate-1.1.0.dist-info/entry_points.txt +2 -0
codegate/system/real.py
ADDED
|
@@ -0,0 +1,493 @@
|
|
|
1
|
+
"""Real system implementation for Ubuntu 24.04 (must run as root)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import grp
|
|
5
|
+
import logging
|
|
6
|
+
import os
|
|
7
|
+
import pwd
|
|
8
|
+
import shutil
|
|
9
|
+
import socket
|
|
10
|
+
import stat
|
|
11
|
+
import tarfile
|
|
12
|
+
from datetime import datetime, timezone
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
import psutil
|
|
16
|
+
|
|
17
|
+
from .. import resources
|
|
18
|
+
from ..config import get_settings
|
|
19
|
+
from ..db import utcnow
|
|
20
|
+
from ..errors import DockerError, NginxError, SystemCommandError
|
|
21
|
+
from .base import ContainerStats, System, WorkspaceSpec, container_name
|
|
22
|
+
from .shell import ok, run
|
|
23
|
+
|
|
24
|
+
log = logging.getLogger("codegate.system")
|
|
25
|
+
|
|
26
|
+
CODE_PORT = 8080
|
|
27
|
+
HEARTBEAT_REL = ".local/share/code-server/heartbeat"
|
|
28
|
+
NOLOGIN = "/usr/sbin/nologin"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class RealSystem(System):
|
|
32
|
+
name = "real"
|
|
33
|
+
|
|
34
|
+
def __init__(self) -> None:
|
|
35
|
+
self._docker = None
|
|
36
|
+
|
|
37
|
+
# ================= docker client =================
|
|
38
|
+
@property
|
|
39
|
+
def docker(self):
|
|
40
|
+
if self._docker is None:
|
|
41
|
+
try:
|
|
42
|
+
import docker
|
|
43
|
+
self._docker = docker.from_env(timeout=60)
|
|
44
|
+
self._docker.ping()
|
|
45
|
+
except Exception as exc:
|
|
46
|
+
self._docker = None
|
|
47
|
+
raise DockerError(f"Docker is not reachable: {exc}",
|
|
48
|
+
code="docker_unavailable") from exc
|
|
49
|
+
return self._docker
|
|
50
|
+
|
|
51
|
+
def _get(self, username: str):
|
|
52
|
+
import docker.errors
|
|
53
|
+
try:
|
|
54
|
+
return self.docker.containers.get(container_name(username))
|
|
55
|
+
except docker.errors.NotFound:
|
|
56
|
+
return None
|
|
57
|
+
except docker.errors.APIError as exc:
|
|
58
|
+
raise DockerError(f"Docker error: {exc.explanation or exc}") from exc
|
|
59
|
+
|
|
60
|
+
# ================= linux users =================
|
|
61
|
+
def linux_user(self, username):
|
|
62
|
+
try:
|
|
63
|
+
pw = pwd.getpwnam(username)
|
|
64
|
+
return pw.pw_uid, pw.pw_gid, pw.pw_dir
|
|
65
|
+
except KeyError:
|
|
66
|
+
return None
|
|
67
|
+
|
|
68
|
+
def uid_in_use(self, uid):
|
|
69
|
+
try:
|
|
70
|
+
pwd.getpwuid(uid)
|
|
71
|
+
return True
|
|
72
|
+
except KeyError:
|
|
73
|
+
pass
|
|
74
|
+
try:
|
|
75
|
+
grp.getgrgid(uid)
|
|
76
|
+
return True
|
|
77
|
+
except KeyError:
|
|
78
|
+
return False
|
|
79
|
+
|
|
80
|
+
def create_linux_user(self, username, uid, home):
|
|
81
|
+
if not self._group_exists(username):
|
|
82
|
+
run(["groupadd", "-g", str(uid), username])
|
|
83
|
+
# no host shell: the user's terminal runs inside the container (its own /etc/passwd)
|
|
84
|
+
run(["useradd", "-u", str(uid), "-g", str(uid), "-d", str(home), "-M",
|
|
85
|
+
"-s", NOLOGIN, "-c", "codegate workspace user", username])
|
|
86
|
+
self.restrict_host_login(username)
|
|
87
|
+
|
|
88
|
+
def restrict_host_login(self, username):
|
|
89
|
+
s = get_settings()
|
|
90
|
+
if not self._group_exists(s.login_group):
|
|
91
|
+
run(["groupadd", "--system", s.login_group])
|
|
92
|
+
run(["usermod", "-s", NOLOGIN, "-aG", s.login_group, username])
|
|
93
|
+
|
|
94
|
+
def delete_linux_user(self, username):
|
|
95
|
+
if self.linux_user(username) is None:
|
|
96
|
+
return
|
|
97
|
+
run(["userdel", username], check=False)
|
|
98
|
+
if self._group_exists(username):
|
|
99
|
+
run(["groupdel", username], check=False)
|
|
100
|
+
|
|
101
|
+
@staticmethod
|
|
102
|
+
def _group_exists(name: str) -> bool:
|
|
103
|
+
try:
|
|
104
|
+
grp.getgrnam(name)
|
|
105
|
+
return True
|
|
106
|
+
except KeyError:
|
|
107
|
+
return False
|
|
108
|
+
|
|
109
|
+
def ensure_home(self, username, uid, gid, home):
|
|
110
|
+
created = False
|
|
111
|
+
if not home.exists():
|
|
112
|
+
home.mkdir(parents=True, mode=0o750)
|
|
113
|
+
skel = Path("/etc/skel")
|
|
114
|
+
if skel.is_dir():
|
|
115
|
+
for item in skel.iterdir():
|
|
116
|
+
dest = home / item.name
|
|
117
|
+
if item.is_dir():
|
|
118
|
+
shutil.copytree(item, dest, dirs_exist_ok=True)
|
|
119
|
+
else:
|
|
120
|
+
shutil.copy2(item, dest)
|
|
121
|
+
created = True
|
|
122
|
+
# always (re)apply ownership of the top dir; recursive only when new
|
|
123
|
+
if created:
|
|
124
|
+
run(["chown", "-R", f"{uid}:{gid}", str(home)])
|
|
125
|
+
else:
|
|
126
|
+
os.chown(home, uid, gid)
|
|
127
|
+
os.chmod(home, 0o750)
|
|
128
|
+
return created
|
|
129
|
+
|
|
130
|
+
def archive_home(self, username, home):
|
|
131
|
+
s = get_settings()
|
|
132
|
+
s.archive_dir.mkdir(parents=True, exist_ok=True)
|
|
133
|
+
dest = s.archive_dir / f"{username}-{utcnow():%Y%m%d-%H%M%S}.tar.gz"
|
|
134
|
+
with tarfile.open(dest, "w:gz") as tar:
|
|
135
|
+
tar.add(home, arcname=username)
|
|
136
|
+
return str(dest)
|
|
137
|
+
|
|
138
|
+
def remove_home(self, home):
|
|
139
|
+
s = get_settings()
|
|
140
|
+
home = home.resolve()
|
|
141
|
+
# safety: only ever delete direct children of home_root
|
|
142
|
+
if home.parent != s.home_root.resolve() or home == s.home_root.resolve():
|
|
143
|
+
raise SystemCommandError(f"Refusing to delete unexpected path {home}")
|
|
144
|
+
shutil.rmtree(home, ignore_errors=True)
|
|
145
|
+
|
|
146
|
+
def home_usage_mb(self, home):
|
|
147
|
+
if not home.exists():
|
|
148
|
+
return 0.0
|
|
149
|
+
proc = run(["du", "-sm", str(home)], check=False, timeout=300)
|
|
150
|
+
try:
|
|
151
|
+
return float(proc.stdout.split()[0])
|
|
152
|
+
except (IndexError, ValueError):
|
|
153
|
+
return 0.0
|
|
154
|
+
|
|
155
|
+
def heartbeat(self, home):
|
|
156
|
+
f = home / HEARTBEAT_REL
|
|
157
|
+
try:
|
|
158
|
+
return datetime.fromtimestamp(f.stat().st_mtime, timezone.utc).replace(tzinfo=None)
|
|
159
|
+
except OSError:
|
|
160
|
+
return None
|
|
161
|
+
|
|
162
|
+
def strip_setuid(self, path):
|
|
163
|
+
"""Root inside a sudo-enabled container can leave setuid-root files in the mounted
|
|
164
|
+
home or shared folder. Clear those bits from the host side. Uses fd-relative,
|
|
165
|
+
no-follow access so a user cannot redirect the chmod to a host file via symlinks."""
|
|
166
|
+
changed: list[str] = []
|
|
167
|
+
if not path.is_dir() or path.is_symlink():
|
|
168
|
+
return changed
|
|
169
|
+
flags = os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | getattr(os, "O_NOCTTY", 0)
|
|
170
|
+
for dirpath, _dirs, files, dfd in os.fwalk(path, follow_symlinks=False):
|
|
171
|
+
for name in files:
|
|
172
|
+
try:
|
|
173
|
+
st = os.stat(name, dir_fd=dfd, follow_symlinks=False)
|
|
174
|
+
if not stat.S_ISREG(st.st_mode) or not st.st_mode & (stat.S_ISUID | stat.S_ISGID):
|
|
175
|
+
continue
|
|
176
|
+
fd = os.open(name, flags, dir_fd=dfd)
|
|
177
|
+
try:
|
|
178
|
+
fst = os.fstat(fd)
|
|
179
|
+
if (fst.st_dev, fst.st_ino) != (st.st_dev, st.st_ino):
|
|
180
|
+
continue # swapped under us
|
|
181
|
+
os.fchmod(fd, stat.S_IMODE(fst.st_mode) & ~(stat.S_ISUID | stat.S_ISGID))
|
|
182
|
+
finally:
|
|
183
|
+
os.close(fd)
|
|
184
|
+
changed.append(os.path.join(dirpath, name))
|
|
185
|
+
except OSError:
|
|
186
|
+
continue
|
|
187
|
+
return changed
|
|
188
|
+
|
|
189
|
+
def add_to_shared_group(self, username, enabled):
|
|
190
|
+
s = get_settings()
|
|
191
|
+
if not self._group_exists(s.shared_group):
|
|
192
|
+
run(["groupadd", s.shared_group])
|
|
193
|
+
s.shared_dir.mkdir(parents=True, exist_ok=True)
|
|
194
|
+
gid = grp.getgrnam(s.shared_group).gr_gid
|
|
195
|
+
os.chown(s.shared_dir, 0, gid)
|
|
196
|
+
os.chmod(s.shared_dir, 0o2775)
|
|
197
|
+
if enabled:
|
|
198
|
+
run(["usermod", "-aG", s.shared_group, username], check=False)
|
|
199
|
+
else:
|
|
200
|
+
run(["gpasswd", "-d", username, s.shared_group], check=False)
|
|
201
|
+
|
|
202
|
+
# ================= quota =================
|
|
203
|
+
def quota_supported(self):
|
|
204
|
+
s = get_settings()
|
|
205
|
+
if not shutil.which("setquota"):
|
|
206
|
+
return False
|
|
207
|
+
mount = _mount_point(s.home_root)
|
|
208
|
+
proc = run(["quotaon", "-p", "-u", mount], check=False)
|
|
209
|
+
return "is on" in (proc.stdout + proc.stderr)
|
|
210
|
+
|
|
211
|
+
def set_quota(self, username, disk_gb):
|
|
212
|
+
s = get_settings()
|
|
213
|
+
if not self.quota_supported():
|
|
214
|
+
return
|
|
215
|
+
hard_kb = int(disk_gb) * 1024 * 1024
|
|
216
|
+
soft_kb = int(hard_kb * 0.95)
|
|
217
|
+
run(["setquota", "-u", username, str(soft_kb), str(hard_kb), "0", "0",
|
|
218
|
+
_mount_point(s.home_root)])
|
|
219
|
+
|
|
220
|
+
def clear_quota(self, username):
|
|
221
|
+
s = get_settings()
|
|
222
|
+
if self.quota_supported():
|
|
223
|
+
run(["setquota", "-u", username, "0", "0", "0", "0", _mount_point(s.home_root)],
|
|
224
|
+
check=False)
|
|
225
|
+
|
|
226
|
+
# ================= etc files =================
|
|
227
|
+
def write_user_etc(self, spec):
|
|
228
|
+
s = get_settings()
|
|
229
|
+
d = s.etc_dir / spec.username
|
|
230
|
+
d.mkdir(parents=True, exist_ok=True)
|
|
231
|
+
shared_gid = None
|
|
232
|
+
if spec.shared_folder and self._group_exists(s.shared_group):
|
|
233
|
+
shared_gid = grp.getgrnam(s.shared_group).gr_gid
|
|
234
|
+
passwd = (
|
|
235
|
+
"root:x:0:0:root:/root:/bin/bash\n"
|
|
236
|
+
"nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin\n"
|
|
237
|
+
f"{spec.username}:x:{spec.uid}:{spec.gid}:{spec.username}:{spec.home}:/bin/bash\n"
|
|
238
|
+
)
|
|
239
|
+
group = "root:x:0:\nnogroup:x:65534:\n" f"{spec.username}:x:{spec.gid}:\n"
|
|
240
|
+
if spec.sudo:
|
|
241
|
+
group += f"sudo:x:27:{spec.username}\n"
|
|
242
|
+
if shared_gid is not None:
|
|
243
|
+
group += f"{s.shared_group}:x:{shared_gid}:{spec.username}\n"
|
|
244
|
+
(d / "passwd").write_text(passwd)
|
|
245
|
+
(d / "group").write_text(group)
|
|
246
|
+
sudoers = d / "sudoers"
|
|
247
|
+
if spec.sudo:
|
|
248
|
+
sudoers.write_text(f"{spec.username} ALL=(ALL) NOPASSWD:ALL\n")
|
|
249
|
+
os.chmod(sudoers, 0o440)
|
|
250
|
+
elif sudoers.exists():
|
|
251
|
+
sudoers.unlink()
|
|
252
|
+
for f in ("passwd", "group"):
|
|
253
|
+
os.chmod(d / f, 0o644)
|
|
254
|
+
|
|
255
|
+
def remove_user_etc(self, username):
|
|
256
|
+
shutil.rmtree(get_settings().etc_dir / username, ignore_errors=True)
|
|
257
|
+
|
|
258
|
+
# ================= ports =================
|
|
259
|
+
def port_free(self, port):
|
|
260
|
+
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
|
|
261
|
+
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
|
262
|
+
try:
|
|
263
|
+
sock.bind(("127.0.0.1", port))
|
|
264
|
+
return True
|
|
265
|
+
except OSError:
|
|
266
|
+
return False
|
|
267
|
+
|
|
268
|
+
# ================= docker =================
|
|
269
|
+
def docker_ok(self):
|
|
270
|
+
try:
|
|
271
|
+
self.docker
|
|
272
|
+
return True
|
|
273
|
+
except DockerError:
|
|
274
|
+
return False
|
|
275
|
+
|
|
276
|
+
def ensure_network(self):
|
|
277
|
+
import docker.errors
|
|
278
|
+
import docker.types
|
|
279
|
+
s = get_settings()
|
|
280
|
+
try:
|
|
281
|
+
self.docker.networks.get(s.docker_network)
|
|
282
|
+
return
|
|
283
|
+
except docker.errors.NotFound:
|
|
284
|
+
pass
|
|
285
|
+
ipam = docker.types.IPAMConfig(pool_configs=[docker.types.IPAMPool(subnet=s.docker_subnet)])
|
|
286
|
+
self.docker.networks.create(
|
|
287
|
+
s.docker_network, driver="bridge", ipam=ipam,
|
|
288
|
+
options={"com.docker.network.bridge.enable_icc": "false",
|
|
289
|
+
"com.docker.network.bridge.name": "cg0"},
|
|
290
|
+
labels={"codegate.managed": "1"},
|
|
291
|
+
)
|
|
292
|
+
|
|
293
|
+
def image_exists(self, image):
|
|
294
|
+
import docker.errors
|
|
295
|
+
try:
|
|
296
|
+
self.docker.images.get(image)
|
|
297
|
+
return True
|
|
298
|
+
except docker.errors.ImageNotFound:
|
|
299
|
+
return False
|
|
300
|
+
|
|
301
|
+
def container_create(self, spec):
|
|
302
|
+
import docker.errors
|
|
303
|
+
s = get_settings()
|
|
304
|
+
self.ensure_network()
|
|
305
|
+
if not self.image_exists(spec.image):
|
|
306
|
+
raise DockerError(f"Workspace image '{spec.image}' not found. Run: sudo codegate image build",
|
|
307
|
+
code="image_missing")
|
|
308
|
+
etc = s.etc_dir / spec.username
|
|
309
|
+
volumes = {
|
|
310
|
+
str(spec.home): {"bind": str(spec.home), "mode": "rw"},
|
|
311
|
+
str(etc / "passwd"): {"bind": "/etc/passwd", "mode": "ro"},
|
|
312
|
+
str(etc / "group"): {"bind": "/etc/group", "mode": "ro"},
|
|
313
|
+
}
|
|
314
|
+
if spec.sudo:
|
|
315
|
+
volumes[str(etc / "sudoers")] = {"bind": "/etc/sudoers.d/codegate", "mode": "ro"}
|
|
316
|
+
if spec.shared_folder:
|
|
317
|
+
volumes[str(s.shared_dir)] = {"bind": "/shared", "mode": "rw"}
|
|
318
|
+
|
|
319
|
+
kwargs = dict(
|
|
320
|
+
image=spec.image,
|
|
321
|
+
name=container_name(spec.username),
|
|
322
|
+
hostname=f"ws-{spec.username}",
|
|
323
|
+
user=f"{spec.uid}:{spec.gid}",
|
|
324
|
+
command=["code-server", "--bind-addr", f"0.0.0.0:{CODE_PORT}", "--auth", "none",
|
|
325
|
+
"--disable-telemetry", "--disable-update-check", str(spec.home)],
|
|
326
|
+
environment={"HOME": str(spec.home), "USER": spec.username, "SHELL": "/bin/bash",
|
|
327
|
+
"CODEGATE_USER": spec.username},
|
|
328
|
+
working_dir=str(spec.home),
|
|
329
|
+
volumes=volumes,
|
|
330
|
+
ports={f"{CODE_PORT}/tcp": ("127.0.0.1", spec.port)},
|
|
331
|
+
nano_cpus=int(float(spec.cpu) * 1e9),
|
|
332
|
+
mem_limit=f"{int(spec.mem_mb)}m",
|
|
333
|
+
memswap_limit=f"{int(spec.mem_mb)}m",
|
|
334
|
+
pids_limit=int(spec.pids),
|
|
335
|
+
init=True,
|
|
336
|
+
detach=True,
|
|
337
|
+
restart_policy={"Name": "unless-stopped"},
|
|
338
|
+
labels={"codegate.managed": "1", "codegate.user": spec.username, **spec.labels},
|
|
339
|
+
network=None,
|
|
340
|
+
)
|
|
341
|
+
if not spec.sudo:
|
|
342
|
+
kwargs["cap_drop"] = ["ALL"]
|
|
343
|
+
kwargs["security_opt"] = ["no-new-privileges:true"]
|
|
344
|
+
try:
|
|
345
|
+
# create on the default bridge first, then attach to codegate-net with a fixed IP
|
|
346
|
+
kwargs.pop("network")
|
|
347
|
+
container = self.docker.containers.create(network_disabled=False, **kwargs)
|
|
348
|
+
try:
|
|
349
|
+
self.docker.networks.get("bridge").disconnect(container)
|
|
350
|
+
except docker.errors.APIError:
|
|
351
|
+
pass
|
|
352
|
+
self.docker.networks.get(s.docker_network).connect(container, ipv4_address=spec.ip)
|
|
353
|
+
container.start()
|
|
354
|
+
except docker.errors.APIError as exc:
|
|
355
|
+
try:
|
|
356
|
+
c = self._get(spec.username)
|
|
357
|
+
if c:
|
|
358
|
+
c.remove(force=True)
|
|
359
|
+
except Exception:
|
|
360
|
+
pass
|
|
361
|
+
raise DockerError(f"Could not create container: {exc.explanation or exc}") from exc
|
|
362
|
+
self.set_internet(spec.username, spec.ip, spec.internet)
|
|
363
|
+
return container.id
|
|
364
|
+
|
|
365
|
+
def container_remove(self, username):
|
|
366
|
+
c = self._get(username)
|
|
367
|
+
if c is not None:
|
|
368
|
+
try:
|
|
369
|
+
c.remove(force=True)
|
|
370
|
+
except Exception as exc:
|
|
371
|
+
raise DockerError(f"Could not remove container: {exc}") from exc
|
|
372
|
+
|
|
373
|
+
def container_status(self, username):
|
|
374
|
+
try:
|
|
375
|
+
c = self._get(username)
|
|
376
|
+
except DockerError:
|
|
377
|
+
return "unknown"
|
|
378
|
+
return "missing" if c is None else c.status
|
|
379
|
+
|
|
380
|
+
def _must(self, username):
|
|
381
|
+
c = self._get(username)
|
|
382
|
+
if c is None:
|
|
383
|
+
raise DockerError("Workspace container does not exist", code="container_missing",
|
|
384
|
+
status_code=404)
|
|
385
|
+
return c
|
|
386
|
+
|
|
387
|
+
def container_start(self, username):
|
|
388
|
+
self._must(username).start()
|
|
389
|
+
|
|
390
|
+
def container_stop(self, username):
|
|
391
|
+
c = self._get(username)
|
|
392
|
+
if c is not None and c.status == "running":
|
|
393
|
+
c.stop(timeout=15)
|
|
394
|
+
|
|
395
|
+
def container_restart(self, username):
|
|
396
|
+
self._must(username).restart(timeout=15)
|
|
397
|
+
|
|
398
|
+
def container_update(self, username, cpu, mem_mb, pids):
|
|
399
|
+
c = self._get(username)
|
|
400
|
+
if c is None:
|
|
401
|
+
return
|
|
402
|
+
try:
|
|
403
|
+
# docker-py's update() has no nano_cpus, so call the Engine API directly
|
|
404
|
+
api = self.docker.api
|
|
405
|
+
mem = int(mem_mb) * 1024 * 1024
|
|
406
|
+
res = api._post_json(api._url("/containers/{0}/update", c.id), data={
|
|
407
|
+
"NanoCpus": int(float(cpu) * 1e9), "Memory": mem, "MemorySwap": mem,
|
|
408
|
+
"PidsLimit": int(pids)})
|
|
409
|
+
api._raise_for_status(res)
|
|
410
|
+
except Exception as exc:
|
|
411
|
+
raise DockerError(f"Could not update limits: {exc}") from exc
|
|
412
|
+
|
|
413
|
+
def container_stats(self, username):
|
|
414
|
+
c = self._get(username)
|
|
415
|
+
if c is None or c.status != "running":
|
|
416
|
+
return ContainerStats(running=False)
|
|
417
|
+
try:
|
|
418
|
+
st = c.stats(stream=False)
|
|
419
|
+
cpu_delta = st["cpu_stats"]["cpu_usage"]["total_usage"] - \
|
|
420
|
+
st["precpu_stats"]["cpu_usage"]["total_usage"]
|
|
421
|
+
sys_delta = st["cpu_stats"].get("system_cpu_usage", 0) - \
|
|
422
|
+
st["precpu_stats"].get("system_cpu_usage", 0)
|
|
423
|
+
ncpu = st["cpu_stats"].get("online_cpus") or 1
|
|
424
|
+
cpu_pct = (cpu_delta / sys_delta) * ncpu * 100 if sys_delta > 0 else 0.0
|
|
425
|
+
mem = st["memory_stats"].get("usage", 0) - \
|
|
426
|
+
st["memory_stats"].get("stats", {}).get("inactive_file", 0)
|
|
427
|
+
return ContainerStats(running=True, cpu_pct=round(cpu_pct, 1),
|
|
428
|
+
mem_mb=round(mem / 1048576, 1))
|
|
429
|
+
except Exception:
|
|
430
|
+
return ContainerStats(running=True)
|
|
431
|
+
|
|
432
|
+
def set_internet(self, username, ip, allowed):
|
|
433
|
+
"""Block/allow outbound traffic from the container (DOCKER-USER chain).
|
|
434
|
+
Host <-> container traffic (nginx -> published port) is unaffected."""
|
|
435
|
+
if not shutil.which("iptables"):
|
|
436
|
+
return
|
|
437
|
+
rule = ["DOCKER-USER", "-s", ip, "-m", "conntrack", "!", "--ctstate",
|
|
438
|
+
"ESTABLISHED,RELATED", "-m", "comment", "--comment", f"codegate:{username}",
|
|
439
|
+
"-j", "DROP"]
|
|
440
|
+
exists = ok(["iptables", "-C", *rule])
|
|
441
|
+
if allowed and exists:
|
|
442
|
+
run(["iptables", "-D", *rule], check=False)
|
|
443
|
+
elif not allowed and not exists:
|
|
444
|
+
run(["iptables", "-I", *rule])
|
|
445
|
+
|
|
446
|
+
# ================= nginx =================
|
|
447
|
+
def nginx_write_user(self, username, port):
|
|
448
|
+
s = get_settings()
|
|
449
|
+
s.users_nginx_dir.mkdir(parents=True, exist_ok=True)
|
|
450
|
+
conf = resources.render("nginx/user.conf.tmpl", base=s.base_path, user=username, port=port)
|
|
451
|
+
_atomic_write(s.users_nginx_dir / f"{username}.conf", conf)
|
|
452
|
+
|
|
453
|
+
def nginx_remove_user(self, username):
|
|
454
|
+
f = get_settings().users_nginx_dir / f"{username}.conf"
|
|
455
|
+
if f.exists():
|
|
456
|
+
f.unlink()
|
|
457
|
+
|
|
458
|
+
def nginx_apply(self):
|
|
459
|
+
s = get_settings()
|
|
460
|
+
test = run(s.nginx_test_cmd, check=False)
|
|
461
|
+
if test.returncode != 0:
|
|
462
|
+
raise NginxError("nginx config test failed", details={"stderr": test.stderr[-2000:]})
|
|
463
|
+
run(s.nginx_reload_cmd)
|
|
464
|
+
|
|
465
|
+
# ================= host =================
|
|
466
|
+
def host_stats(self):
|
|
467
|
+
s = get_settings()
|
|
468
|
+
vm = psutil.virtual_memory()
|
|
469
|
+
du = psutil.disk_usage(str(s.home_root))
|
|
470
|
+
return {
|
|
471
|
+
"cpu_count": psutil.cpu_count(),
|
|
472
|
+
"cpu_pct": psutil.cpu_percent(interval=0.2),
|
|
473
|
+
"load": list(os.getloadavg()),
|
|
474
|
+
"mem_total_mb": round(vm.total / 1048576),
|
|
475
|
+
"mem_used_mb": round((vm.total - vm.available) / 1048576),
|
|
476
|
+
"disk_total_gb": round(du.total / 1073741824, 1),
|
|
477
|
+
"disk_used_gb": round(du.used / 1073741824, 1),
|
|
478
|
+
"quota_enabled": self.quota_supported(),
|
|
479
|
+
"docker_ok": self.docker_ok(),
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
|
|
483
|
+
def _mount_point(path: Path) -> str:
|
|
484
|
+
p = path.resolve()
|
|
485
|
+
while not os.path.ismount(p):
|
|
486
|
+
p = p.parent
|
|
487
|
+
return str(p)
|
|
488
|
+
|
|
489
|
+
|
|
490
|
+
def _atomic_write(path: Path, content: str) -> None:
|
|
491
|
+
tmp = path.with_suffix(path.suffix + ".tmp")
|
|
492
|
+
tmp.write_text(content)
|
|
493
|
+
os.replace(tmp, path)
|
codegate/system/shell.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""Run shell commands with clear errors."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import logging
|
|
5
|
+
import shlex
|
|
6
|
+
import subprocess
|
|
7
|
+
from typing import Sequence
|
|
8
|
+
|
|
9
|
+
from ..errors import SystemCommandError
|
|
10
|
+
|
|
11
|
+
log = logging.getLogger("codegate.shell")
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def run(cmd: Sequence[str] | str, *, check: bool = True, timeout: int = 120,
|
|
15
|
+
input_text: str | None = None) -> subprocess.CompletedProcess:
|
|
16
|
+
args = shlex.split(cmd) if isinstance(cmd, str) else list(cmd)
|
|
17
|
+
log.debug("run: %s", " ".join(args))
|
|
18
|
+
try:
|
|
19
|
+
proc = subprocess.run(args, capture_output=True, text=True, timeout=timeout,
|
|
20
|
+
input=input_text)
|
|
21
|
+
except FileNotFoundError as exc:
|
|
22
|
+
raise SystemCommandError(f"Command not found: {args[0]}",
|
|
23
|
+
details={"cmd": " ".join(args)}) from exc
|
|
24
|
+
except subprocess.TimeoutExpired as exc:
|
|
25
|
+
raise SystemCommandError(f"Command timed out after {timeout}s: {args[0]}",
|
|
26
|
+
details={"cmd": " ".join(args)}) from exc
|
|
27
|
+
if check and proc.returncode != 0:
|
|
28
|
+
raise SystemCommandError(
|
|
29
|
+
f"Command failed: {' '.join(args[:3])}",
|
|
30
|
+
details={"cmd": " ".join(args), "rc": proc.returncode,
|
|
31
|
+
"stderr": (proc.stderr or "").strip()[-2000:]},
|
|
32
|
+
)
|
|
33
|
+
return proc
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def ok(cmd: Sequence[str] | str) -> bool:
|
|
37
|
+
try:
|
|
38
|
+
return run(cmd, check=False, timeout=30).returncode == 0
|
|
39
|
+
except SystemCommandError:
|
|
40
|
+
return False
|