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/users.py
ADDED
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
"""User management (used by both the admin API and the CLI)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from datetime import datetime
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from sqlalchemy import select
|
|
8
|
+
from sqlalchemy.orm import Session
|
|
9
|
+
|
|
10
|
+
from . import workspace
|
|
11
|
+
from .auth.sessions import end_user_sessions
|
|
12
|
+
from .config import get_settings
|
|
13
|
+
from .db import User, audit, get_setting, utcnow
|
|
14
|
+
from .errors import Conflict, NotFound, ValidationFailed
|
|
15
|
+
|
|
16
|
+
EDITABLE = {"display_name", "is_admin", "has_workspace", "plan", "cpu", "mem_mb", "disk_gb", "pids",
|
|
17
|
+
"sudo", "internet", "shared_folder", "image", "expires_at", "notes"}
|
|
18
|
+
LIMITS = {"cpu": (0.25, 64), "mem_mb": (256, 262144), "disk_gb": (1, 4096), "pids": (64, 65536)}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def get_user(db: Session, ident: str | int) -> User:
|
|
22
|
+
if isinstance(ident, int) or (isinstance(ident, str) and ident.isdigit()):
|
|
23
|
+
u = db.get(User, int(ident))
|
|
24
|
+
else:
|
|
25
|
+
ident = ident.lower()
|
|
26
|
+
u = db.scalar(select(User).where((User.username == ident) | (User.email == ident)))
|
|
27
|
+
if u is None:
|
|
28
|
+
raise NotFound(f"User '{ident}' not found")
|
|
29
|
+
return u
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _check_email(email: str) -> str:
|
|
33
|
+
email = (email or "").strip().lower()
|
|
34
|
+
if "@" not in email or len(email) > 320 or " " in email:
|
|
35
|
+
raise ValidationFailed("Invalid email", details={"email": email})
|
|
36
|
+
return email
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def create_user(db: Session, *, email: str, actor: str, username: str | None = None,
|
|
40
|
+
display_name: str = "", plan: str | None = None, is_admin: bool = False,
|
|
41
|
+
has_workspace: bool = True, status: str = "active", provision: bool = True,
|
|
42
|
+
password: str | None = None, must_change_password: bool = True,
|
|
43
|
+
**opts: Any) -> User:
|
|
44
|
+
email = _check_email(email)
|
|
45
|
+
if db.scalar(select(User).where(User.email == email)):
|
|
46
|
+
raise Conflict(f"User {email} already exists", code="user_exists")
|
|
47
|
+
if username:
|
|
48
|
+
username = workspace.validate_username(username)
|
|
49
|
+
if db.scalar(select(User).where(User.username == username)):
|
|
50
|
+
raise Conflict(f"Username '{username}' is taken", code="username_taken")
|
|
51
|
+
else:
|
|
52
|
+
username = workspace.username_from_email(db, email)
|
|
53
|
+
user = User(email=email, username=username, display_name=display_name or "",
|
|
54
|
+
is_admin=is_admin, has_workspace=has_workspace, status=status,
|
|
55
|
+
internet=bool(get_setting(db, "default_internet")))
|
|
56
|
+
workspace.apply_plan(db, user, plan)
|
|
57
|
+
if _apply_fields(user, opts) & set(LIMITS):
|
|
58
|
+
user.plan = "custom"
|
|
59
|
+
if password:
|
|
60
|
+
from .auth.native import set_password
|
|
61
|
+
set_password(db, user, password, must_change=must_change_password)
|
|
62
|
+
if status == "active":
|
|
63
|
+
user.approved_at = utcnow()
|
|
64
|
+
user.approved_by = actor
|
|
65
|
+
db.add(user)
|
|
66
|
+
db.flush()
|
|
67
|
+
audit(db, "user.create", actor=actor, target=email, username=username, plan=user.plan,
|
|
68
|
+
is_admin=is_admin, status=status, password_login=bool(password))
|
|
69
|
+
if provision and status == "active" and has_workspace:
|
|
70
|
+
workspace.provision(db, user, actor)
|
|
71
|
+
return user
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _apply_fields(user: User, data: dict[str, Any]) -> set[str]:
|
|
75
|
+
changed: set[str] = set()
|
|
76
|
+
for key, value in data.items():
|
|
77
|
+
if key not in EDITABLE or value is None and key not in {"expires_at"}:
|
|
78
|
+
continue
|
|
79
|
+
if key in LIMITS:
|
|
80
|
+
lo, hi = LIMITS[key]
|
|
81
|
+
value = type(getattr(user, key))(value)
|
|
82
|
+
if not lo <= value <= hi:
|
|
83
|
+
raise ValidationFailed(f"{key} must be between {lo} and {hi}")
|
|
84
|
+
if key == "expires_at" and isinstance(value, str):
|
|
85
|
+
value = datetime.fromisoformat(value.replace("Z", "")) if value else None
|
|
86
|
+
if getattr(user, key) != value:
|
|
87
|
+
setattr(user, key, value)
|
|
88
|
+
changed.add(key)
|
|
89
|
+
return changed
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def update_user(db: Session, user: User, data: dict[str, Any], actor: str) -> dict[str, Any]:
|
|
93
|
+
data = {k: v for k, v in data.items() if k in EDITABLE}
|
|
94
|
+
before = {k: getattr(user, k) for k in data}
|
|
95
|
+
plan = data.pop("plan", None)
|
|
96
|
+
changed: set[str] = set()
|
|
97
|
+
if plan and plan != user.plan:
|
|
98
|
+
old = {k: getattr(user, k) for k in ("cpu", "mem_mb", "disk_gb", "pids")}
|
|
99
|
+
workspace.apply_plan(db, user, plan)
|
|
100
|
+
changed |= {"plan"} | {k for k, v in old.items() if getattr(user, k) != v}
|
|
101
|
+
if any(k in data for k in LIMITS) and plan in (None, user.plan):
|
|
102
|
+
# editing raw limits turns the plan into "custom"
|
|
103
|
+
if any(data.get(k) is not None and type(getattr(user, k))(data[k]) != getattr(user, k)
|
|
104
|
+
for k in LIMITS):
|
|
105
|
+
user.plan = "custom"
|
|
106
|
+
changed.add("plan")
|
|
107
|
+
changed |= _apply_fields(user, data)
|
|
108
|
+
if user.is_admin is False and before.get("is_admin") is True:
|
|
109
|
+
_ensure_other_admin(db, user)
|
|
110
|
+
actions: list[str] = []
|
|
111
|
+
if "has_workspace" in changed:
|
|
112
|
+
if user.has_workspace and user.status == "active":
|
|
113
|
+
workspace.provision(db, user, actor)
|
|
114
|
+
actions.append("provisioned")
|
|
115
|
+
elif not user.has_workspace and user.provisioned:
|
|
116
|
+
workspace.deprovision(db, user, keep_home=True, actor=actor)
|
|
117
|
+
actions.append("deprovisioned")
|
|
118
|
+
elif changed:
|
|
119
|
+
actions += workspace.apply_changes(db, user, changed, actor)
|
|
120
|
+
audit(db, "user.update", actor=actor, target=user.email, changed=sorted(changed),
|
|
121
|
+
actions=actions)
|
|
122
|
+
return {"changed": sorted(changed), "actions": actions}
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _ensure_other_admin(db: Session, user: User) -> None:
|
|
126
|
+
others = db.scalar(select(User).where(User.is_admin.is_(True), User.id != user.id,
|
|
127
|
+
User.status == "active"))
|
|
128
|
+
if others is None:
|
|
129
|
+
raise Conflict("Cannot remove the last active admin", code="last_admin")
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def approve(db: Session, user: User, actor: str, plan: str | None = None) -> User:
|
|
133
|
+
if user.status == "active":
|
|
134
|
+
raise Conflict("User is already active")
|
|
135
|
+
if plan:
|
|
136
|
+
workspace.apply_plan(db, user, plan)
|
|
137
|
+
user.status = "active"
|
|
138
|
+
user.approved_at = utcnow()
|
|
139
|
+
user.approved_by = actor
|
|
140
|
+
audit(db, "user.approve", actor=actor, target=user.email, plan=user.plan)
|
|
141
|
+
if user.has_workspace:
|
|
142
|
+
workspace.provision(db, user, actor)
|
|
143
|
+
return user
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def reject(db: Session, user: User, actor: str) -> None:
|
|
147
|
+
if user.status != "pending":
|
|
148
|
+
raise Conflict("Only pending users can be rejected")
|
|
149
|
+
audit(db, "user.reject", actor=actor, target=user.email)
|
|
150
|
+
db.delete(user)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def disable(db: Session, user: User, actor: str) -> None:
|
|
154
|
+
if user.is_admin:
|
|
155
|
+
_ensure_other_admin(db, user)
|
|
156
|
+
user.status = "disabled"
|
|
157
|
+
n = end_user_sessions(db, user.id)
|
|
158
|
+
if user.provisioned:
|
|
159
|
+
workspace.stop(user) # cuts open VS Code tabs immediately
|
|
160
|
+
workspace.mark_running(db, user, False)
|
|
161
|
+
audit(db, "user.disable", actor=actor, target=user.email, sessions_ended=n)
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def enable(db: Session, user: User, actor: str) -> None:
|
|
165
|
+
user.status = "active"
|
|
166
|
+
if not user.approved_at:
|
|
167
|
+
user.approved_at = utcnow()
|
|
168
|
+
user.approved_by = actor
|
|
169
|
+
audit(db, "user.enable", actor=actor, target=user.email)
|
|
170
|
+
if user.has_workspace and not user.provisioned:
|
|
171
|
+
workspace.provision(db, user, actor)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def delete(db: Session, user: User, actor: str, keep_home: bool = True) -> dict:
|
|
175
|
+
if user.is_admin:
|
|
176
|
+
_ensure_other_admin(db, user)
|
|
177
|
+
end_user_sessions(db, user.id)
|
|
178
|
+
result = workspace.deprovision(db, user, keep_home=keep_home, actor=actor) \
|
|
179
|
+
if user.provisioned or not keep_home else {"errors": [], "archive": None}
|
|
180
|
+
audit(db, "user.delete", actor=actor, target=user.email, keep_home=keep_home)
|
|
181
|
+
db.delete(user)
|
|
182
|
+
return result
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def force_logout(db: Session, user: User, actor: str, disconnect: bool = True) -> int:
|
|
186
|
+
n = end_user_sessions(db, user.id)
|
|
187
|
+
if disconnect and user.provisioned and workspace.get_system().container_status(
|
|
188
|
+
user.username) == "running":
|
|
189
|
+
workspace.get_system().container_restart(user.username) # closes open websockets
|
|
190
|
+
audit(db, "session.force_logout", actor=actor, target=user.email, sessions=n,
|
|
191
|
+
disconnected=disconnect)
|
|
192
|
+
return n
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
# ---------------------------------------------------------------- SSO login
|
|
196
|
+
def on_sso_login(db: Session, email: str, name: str) -> User:
|
|
197
|
+
"""Find or register the user after a successful SSO login."""
|
|
198
|
+
s = get_settings()
|
|
199
|
+
email = email.lower()
|
|
200
|
+
user = db.scalar(select(User).where(User.email == email))
|
|
201
|
+
bootstrap_admin = email in s.admin_email_list
|
|
202
|
+
if user is None:
|
|
203
|
+
domain = email.split("@")[-1]
|
|
204
|
+
auto = domain in [d.lower().lstrip("@") for d in (get_setting(db, "auto_approve_domains") or [])]
|
|
205
|
+
status = "active" if (bootstrap_admin or auto) else "pending"
|
|
206
|
+
user = create_user(db, email=email, actor="sso", display_name=name,
|
|
207
|
+
is_admin=bootstrap_admin, has_workspace=not bootstrap_admin,
|
|
208
|
+
status=status, provision=False)
|
|
209
|
+
audit(db, "user.register", actor=email, target=email, status=status,
|
|
210
|
+
auto_approved=auto, bootstrap_admin=bootstrap_admin)
|
|
211
|
+
else:
|
|
212
|
+
if bootstrap_admin and not user.is_admin:
|
|
213
|
+
user.is_admin = True
|
|
214
|
+
if user.status == "pending":
|
|
215
|
+
user.status = "active"
|
|
216
|
+
if name and not user.display_name:
|
|
217
|
+
user.display_name = name
|
|
218
|
+
return user
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def landing_path(user: User) -> str:
|
|
222
|
+
base = get_settings().base_path
|
|
223
|
+
if user.status == "pending":
|
|
224
|
+
return f"{base}/pending"
|
|
225
|
+
if user.status == "disabled" or _expired(user):
|
|
226
|
+
return f"{base}/forbidden"
|
|
227
|
+
if user.must_change_password:
|
|
228
|
+
return f"{base}/account/password"
|
|
229
|
+
if user.is_admin:
|
|
230
|
+
return f"{base}/admin/"
|
|
231
|
+
if user.has_workspace:
|
|
232
|
+
return f"{base}/editor/{user.username}/"
|
|
233
|
+
return f"{base}/forbidden"
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def _expired(user: User) -> bool:
|
|
237
|
+
return bool(user.expires_at and user.expires_at <= utcnow())
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def can_use_editor(user: User, username: str) -> bool:
|
|
241
|
+
return (user.status == "active" and not _expired(user) and user.has_workspace
|
|
242
|
+
and not user.must_change_password and user.username == username)
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def user_dict(user: User, usage: Any = None) -> dict[str, Any]:
|
|
246
|
+
d = {c: getattr(user, c) for c in (
|
|
247
|
+
"id", "email", "username", "display_name", "uid", "gid", "status", "is_admin",
|
|
248
|
+
"has_workspace", "plan", "cpu", "mem_mb", "disk_gb", "pids", "sudo", "internet",
|
|
249
|
+
"shared_folder", "image", "expires_at", "port", "provisioned", "linked_existing",
|
|
250
|
+
"over_quota", "created_at", "approved_at", "approved_by", "last_login", "notes")}
|
|
251
|
+
d["editor_url"] = f"{get_settings().base_path}/editor/{user.username}/"
|
|
252
|
+
d["expired"] = _expired(user)
|
|
253
|
+
# never the hash itself
|
|
254
|
+
d["has_password"] = bool(user.password_hash)
|
|
255
|
+
d["must_change_password"] = bool(user.must_change_password)
|
|
256
|
+
d["password_changed_at"] = user.password_changed_at
|
|
257
|
+
d["locked"] = bool(user.locked_until and user.locked_until > utcnow())
|
|
258
|
+
if usage is not None:
|
|
259
|
+
d["usage"] = {"running": usage.running, "cpu_pct": usage.cpu_pct, "mem_mb": usage.mem_mb,
|
|
260
|
+
"disk_mb": usage.disk_mb, "last_active": usage.last_active,
|
|
261
|
+
"updated_at": usage.updated_at}
|
|
262
|
+
return d
|
codegate/workspace.py
ADDED
|
@@ -0,0 +1,355 @@
|
|
|
1
|
+
"""Workspace lifecycle: provision / deprovision / update / start / stop.
|
|
2
|
+
|
|
3
|
+
Provisioning is a list of steps. If any step fails, every completed step is
|
|
4
|
+
undone in reverse order, so a user is never left half-created.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import logging
|
|
9
|
+
import re
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Callable
|
|
13
|
+
|
|
14
|
+
from sqlalchemy import select
|
|
15
|
+
from sqlalchemy.orm import Session
|
|
16
|
+
|
|
17
|
+
from .config import get_settings
|
|
18
|
+
from .db import User, Usage, audit, audit_now, get_setting
|
|
19
|
+
from .errors import AppError, Conflict, ProvisionError, ValidationFailed
|
|
20
|
+
from .system import get_system
|
|
21
|
+
from .system.base import WorkspaceSpec, ip_for_port
|
|
22
|
+
|
|
23
|
+
log = logging.getLogger("codegate.workspace")
|
|
24
|
+
|
|
25
|
+
USERNAME_RE = re.compile(r"^[a-z][a-z0-9-]{1,30}$")
|
|
26
|
+
# names that collide with portal routes or system accounts
|
|
27
|
+
RESERVED = {"admin", "root", "api", "login", "logout", "saml", "editor", "users", "sessions",
|
|
28
|
+
"audit", "settings", "pending", "static", "assets", "codegate", "nginx", "docker",
|
|
29
|
+
"www-data", "nobody", "daemon", "bin", "sys", "ubuntu", "forbidden", "healthz"}
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
# ---------------------------------------------------------------- names / ids
|
|
33
|
+
def validate_username(name: str) -> str:
|
|
34
|
+
name = (name or "").strip().lower()
|
|
35
|
+
if not USERNAME_RE.match(name):
|
|
36
|
+
raise ValidationFailed("Username must be 2-31 chars: lowercase letters, digits, '-', "
|
|
37
|
+
"starting with a letter", details={"username": name})
|
|
38
|
+
if name in RESERVED:
|
|
39
|
+
raise ValidationFailed(f"Username '{name}' is reserved", details={"username": name})
|
|
40
|
+
return name
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def username_from_email(db: Session, email: str) -> str:
|
|
44
|
+
local = email.split("@")[0].lower()
|
|
45
|
+
base = re.sub(r"[^a-z0-9-]", "-", local).strip("-")
|
|
46
|
+
if not base or not base[0].isalpha():
|
|
47
|
+
base = "u-" + base
|
|
48
|
+
base = base[:28] or "user"
|
|
49
|
+
if base in RESERVED:
|
|
50
|
+
base = base + "-u"
|
|
51
|
+
candidate, n = base, 1
|
|
52
|
+
while db.scalar(select(User).where(User.username == candidate)) is not None:
|
|
53
|
+
n += 1
|
|
54
|
+
candidate = f"{base[:26]}{n}"
|
|
55
|
+
return candidate
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def allocate_uid(db: Session) -> int:
|
|
59
|
+
s = get_settings()
|
|
60
|
+
system = get_system()
|
|
61
|
+
used = set(db.scalars(select(User.uid).where(User.uid.is_not(None))))
|
|
62
|
+
uid = s.uid_start
|
|
63
|
+
while uid in used or system.uid_in_use(uid):
|
|
64
|
+
uid += 1
|
|
65
|
+
return uid
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def allocate_port(db: Session) -> int:
|
|
69
|
+
s = get_settings()
|
|
70
|
+
system = get_system()
|
|
71
|
+
used = set(db.scalars(select(User.port).where(User.port.is_not(None))))
|
|
72
|
+
for port in range(s.port_range_start, s.port_range_end + 1):
|
|
73
|
+
if port not in used and system.port_free(port):
|
|
74
|
+
return port
|
|
75
|
+
raise Conflict("No free workspace ports left", code="no_free_ports")
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def apply_plan(db: Session, user: User, plan: str | None) -> None:
|
|
79
|
+
plans = get_setting(db, "plans") or {}
|
|
80
|
+
plan = plan or get_setting(db, "default_plan") or "small"
|
|
81
|
+
if plan == "custom":
|
|
82
|
+
user.plan = "custom"
|
|
83
|
+
return
|
|
84
|
+
if plan not in plans:
|
|
85
|
+
raise ValidationFailed(f"Unknown plan '{plan}'", details={"plans": list(plans)})
|
|
86
|
+
p = plans[plan]
|
|
87
|
+
user.plan = plan
|
|
88
|
+
user.cpu = float(p["cpu"])
|
|
89
|
+
user.mem_mb = int(p["mem_mb"])
|
|
90
|
+
user.disk_gb = int(p["disk_gb"])
|
|
91
|
+
user.pids = int(p.get("pids", 512))
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def home_of(user: User) -> Path:
|
|
95
|
+
return get_settings().home_root / user.username
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def spec_for(user: User) -> WorkspaceSpec:
|
|
99
|
+
s = get_settings()
|
|
100
|
+
assert user.uid is not None and user.gid is not None and user.port is not None
|
|
101
|
+
return WorkspaceSpec(
|
|
102
|
+
username=user.username, uid=user.uid, gid=user.gid, home=home_of(user), port=user.port,
|
|
103
|
+
ip=ip_for_port(user.port), image=user.image or s.workspace_image, cpu=user.cpu,
|
|
104
|
+
mem_mb=user.mem_mb, pids=user.pids, sudo=user.sudo, internet=user.internet,
|
|
105
|
+
shared_folder=user.shared_folder,
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
# ---------------------------------------------------------------- saga
|
|
110
|
+
@dataclass
|
|
111
|
+
class Step:
|
|
112
|
+
name: str
|
|
113
|
+
do: Callable[[], object]
|
|
114
|
+
undo: Callable[[], object] | None = None
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def run_steps(steps: list[Step], *, action: str, username: str) -> list[str]:
|
|
118
|
+
done: list[Step] = []
|
|
119
|
+
for step in steps:
|
|
120
|
+
try:
|
|
121
|
+
log.info("[%s %s] step %s", action, username, step.name)
|
|
122
|
+
step.do()
|
|
123
|
+
done.append(step)
|
|
124
|
+
except Exception as exc:
|
|
125
|
+
log.error("[%s %s] step %s failed: %s", action, username, step.name, exc)
|
|
126
|
+
rollback_errors = []
|
|
127
|
+
for prev in reversed(done):
|
|
128
|
+
if prev.undo is None:
|
|
129
|
+
continue
|
|
130
|
+
try:
|
|
131
|
+
prev.undo()
|
|
132
|
+
except Exception as rexc: # keep going; report at the end
|
|
133
|
+
rollback_errors.append(f"{prev.name}: {rexc}")
|
|
134
|
+
log.exception("rollback of %s failed", prev.name)
|
|
135
|
+
details = {"failed_step": step.name, "rolled_back": [d.name for d in reversed(done)],
|
|
136
|
+
"rollback_errors": rollback_errors}
|
|
137
|
+
if isinstance(exc, AppError):
|
|
138
|
+
details["cause"] = {"code": exc.code, "message": exc.message, **exc.details}
|
|
139
|
+
else:
|
|
140
|
+
details["cause"] = {"message": str(exc)}
|
|
141
|
+
raise ProvisionError(f"{action} failed at step '{step.name}'. All changes were rolled back.",
|
|
142
|
+
details=details) from exc
|
|
143
|
+
return [s.name for s in done]
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
# ---------------------------------------------------------------- provision
|
|
147
|
+
def provision(db: Session, user: User, actor: str = "system") -> None:
|
|
148
|
+
"""Create Linux user, home, quota, port, container and nginx route."""
|
|
149
|
+
if user.provisioned:
|
|
150
|
+
return
|
|
151
|
+
if not user.has_workspace:
|
|
152
|
+
return
|
|
153
|
+
system = get_system()
|
|
154
|
+
s = get_settings()
|
|
155
|
+
state: dict = {"created_user": False, "created_home": False}
|
|
156
|
+
home = home_of(user)
|
|
157
|
+
|
|
158
|
+
def link_or_create_user():
|
|
159
|
+
existing = system.linux_user(user.username)
|
|
160
|
+
if existing:
|
|
161
|
+
user.uid, user.gid = existing[0], existing[1]
|
|
162
|
+
user.linked_existing = True
|
|
163
|
+
else:
|
|
164
|
+
user.uid = allocate_uid(db)
|
|
165
|
+
user.gid = user.uid
|
|
166
|
+
system.create_linux_user(user.username, user.uid, home)
|
|
167
|
+
state["created_user"] = True
|
|
168
|
+
|
|
169
|
+
def undo_user():
|
|
170
|
+
if state["created_user"]:
|
|
171
|
+
system.delete_linux_user(user.username)
|
|
172
|
+
user.uid = user.gid = None
|
|
173
|
+
user.linked_existing = False
|
|
174
|
+
|
|
175
|
+
def make_home():
|
|
176
|
+
state["created_home"] = system.ensure_home(user.username, user.uid, user.gid, home)
|
|
177
|
+
|
|
178
|
+
def undo_home():
|
|
179
|
+
if state["created_home"]:
|
|
180
|
+
system.remove_home(home)
|
|
181
|
+
|
|
182
|
+
def port():
|
|
183
|
+
user.port = allocate_port(db)
|
|
184
|
+
db.flush()
|
|
185
|
+
|
|
186
|
+
def undo_port():
|
|
187
|
+
user.port = None
|
|
188
|
+
|
|
189
|
+
def etc():
|
|
190
|
+
if user.shared_folder:
|
|
191
|
+
system.add_to_shared_group(user.username, True)
|
|
192
|
+
system.write_user_etc(spec_for(user))
|
|
193
|
+
|
|
194
|
+
def container():
|
|
195
|
+
user.container_id = system.container_create(spec_for(user))
|
|
196
|
+
|
|
197
|
+
def undo_container():
|
|
198
|
+
system.container_remove(user.username)
|
|
199
|
+
user.container_id = None
|
|
200
|
+
|
|
201
|
+
def nginx():
|
|
202
|
+
system.nginx_write_user(user.username, user.port)
|
|
203
|
+
try:
|
|
204
|
+
system.nginx_apply()
|
|
205
|
+
except Exception:
|
|
206
|
+
system.nginx_remove_user(user.username)
|
|
207
|
+
raise
|
|
208
|
+
|
|
209
|
+
def undo_nginx():
|
|
210
|
+
system.nginx_remove_user(user.username)
|
|
211
|
+
system.nginx_apply()
|
|
212
|
+
|
|
213
|
+
steps = [
|
|
214
|
+
Step("linux_user", link_or_create_user, undo_user),
|
|
215
|
+
Step("home_dir", make_home, undo_home),
|
|
216
|
+
Step("disk_quota", lambda: system.set_quota(user.username, user.disk_gb),
|
|
217
|
+
lambda: system.clear_quota(user.username)),
|
|
218
|
+
Step("port", port, undo_port),
|
|
219
|
+
Step("etc_files", etc, lambda: system.remove_user_etc(user.username)),
|
|
220
|
+
Step("container", container, undo_container),
|
|
221
|
+
Step("nginx", nginx, undo_nginx),
|
|
222
|
+
]
|
|
223
|
+
try:
|
|
224
|
+
names = run_steps(steps, action="provision", username=user.username)
|
|
225
|
+
except ProvisionError as exc:
|
|
226
|
+
audit_now("workspace.provision", actor=actor, target=user.email, success=False,
|
|
227
|
+
**exc.details)
|
|
228
|
+
raise
|
|
229
|
+
user.provisioned = True
|
|
230
|
+
mark_running(db, user, True)
|
|
231
|
+
audit(db, "workspace.provision", actor=actor, target=user.email, steps=names,
|
|
232
|
+
uid=user.uid, port=user.port, linked_existing=user.linked_existing)
|
|
233
|
+
_ = s
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def deprovision(db: Session, user: User, *, keep_home: bool = True, actor: str = "system") -> dict:
|
|
237
|
+
"""Remove container, nginx route, port, quota; optionally home + Linux user.
|
|
238
|
+
Best effort: continues on errors and reports them."""
|
|
239
|
+
system = get_system()
|
|
240
|
+
home = home_of(user)
|
|
241
|
+
result: dict = {"errors": [], "archive": None}
|
|
242
|
+
|
|
243
|
+
def attempt(name, fn):
|
|
244
|
+
try:
|
|
245
|
+
return fn()
|
|
246
|
+
except Exception as exc:
|
|
247
|
+
log.exception("deprovision %s: %s failed", user.username, name)
|
|
248
|
+
result["errors"].append(f"{name}: {exc}")
|
|
249
|
+
|
|
250
|
+
attempt("nginx", lambda: (system.nginx_remove_user(user.username), system.nginx_apply()))
|
|
251
|
+
attempt("container", lambda: system.container_remove(user.username))
|
|
252
|
+
if user.port:
|
|
253
|
+
attempt("internet_rule", lambda: system.set_internet(user.username, ip_for_port(user.port), True))
|
|
254
|
+
attempt("etc_files", lambda: system.remove_user_etc(user.username))
|
|
255
|
+
if not keep_home:
|
|
256
|
+
attempt("disk_quota", lambda: system.clear_quota(user.username))
|
|
257
|
+
result["archive"] = attempt("archive_home", lambda: system.archive_home(user.username, home))
|
|
258
|
+
attempt("remove_home", lambda: system.remove_home(home))
|
|
259
|
+
if not user.linked_existing:
|
|
260
|
+
attempt("linux_user", lambda: system.delete_linux_user(user.username))
|
|
261
|
+
user.port = None
|
|
262
|
+
user.container_id = None
|
|
263
|
+
user.provisioned = False
|
|
264
|
+
audit(db, "workspace.deprovision", actor=actor, target=user.email, keep_home=keep_home,
|
|
265
|
+
success=not result["errors"], **result)
|
|
266
|
+
return result
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
# ---------------------------------------------------------------- changes
|
|
270
|
+
RECREATE_FIELDS = {"sudo", "shared_folder", "image"}
|
|
271
|
+
LIVE_FIELDS = {"cpu", "mem_mb", "pids"}
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def apply_changes(db: Session, user: User, changed: set[str], actor: str) -> list[str]:
|
|
275
|
+
"""Apply edited settings to a provisioned workspace. Returns actions taken."""
|
|
276
|
+
actions: list[str] = []
|
|
277
|
+
if not user.provisioned:
|
|
278
|
+
return actions
|
|
279
|
+
system = get_system()
|
|
280
|
+
if "disk_gb" in changed:
|
|
281
|
+
system.set_quota(user.username, user.disk_gb)
|
|
282
|
+
actions.append("quota_updated")
|
|
283
|
+
if "internet" in changed:
|
|
284
|
+
system.set_internet(user.username, ip_for_port(user.port), user.internet)
|
|
285
|
+
actions.append("internet_rule_updated")
|
|
286
|
+
if changed & RECREATE_FIELDS:
|
|
287
|
+
if "shared_folder" in changed:
|
|
288
|
+
system.add_to_shared_group(user.username, user.shared_folder)
|
|
289
|
+
rebuild(db, user, actor)
|
|
290
|
+
actions.append("container_recreated")
|
|
291
|
+
elif changed & LIVE_FIELDS:
|
|
292
|
+
system.container_update(user.username, user.cpu, user.mem_mb, user.pids)
|
|
293
|
+
actions.append("limits_updated_live")
|
|
294
|
+
return actions
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def rebuild(db: Session, user: User, actor: str) -> None:
|
|
298
|
+
"""Recreate the container (home dir is kept). Rolls back to old config on failure."""
|
|
299
|
+
system = get_system()
|
|
300
|
+
system.write_user_etc(spec_for(user))
|
|
301
|
+
system.container_remove(user.username)
|
|
302
|
+
try:
|
|
303
|
+
user.container_id = system.container_create(spec_for(user))
|
|
304
|
+
except Exception:
|
|
305
|
+
audit_now("workspace.rebuild", actor=actor, target=user.email, success=False)
|
|
306
|
+
raise
|
|
307
|
+
audit(db, "workspace.rebuild", actor=actor, target=user.email)
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def mark_running(db: Session, user: User, running: bool) -> None:
|
|
311
|
+
usage = db.get(Usage, user.id)
|
|
312
|
+
if usage is None:
|
|
313
|
+
usage = Usage(user_id=user.id)
|
|
314
|
+
db.add(usage)
|
|
315
|
+
usage.running = running
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def ensure_running(db: Session, user: User) -> str:
|
|
319
|
+
"""Make sure the user's container exists and is running. Returns status."""
|
|
320
|
+
system = get_system()
|
|
321
|
+
if not user.provisioned:
|
|
322
|
+
provision(db, user)
|
|
323
|
+
status = system.container_status(user.username)
|
|
324
|
+
if status == "missing":
|
|
325
|
+
rebuild(db, user, "system")
|
|
326
|
+
return "starting"
|
|
327
|
+
if status != "running":
|
|
328
|
+
if user.over_quota:
|
|
329
|
+
raise Conflict("Disk limit exceeded. Ask the admin to increase your disk.",
|
|
330
|
+
code="over_quota")
|
|
331
|
+
system.container_start(user.username)
|
|
332
|
+
return "starting"
|
|
333
|
+
return "running"
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def stop(user: User) -> None:
|
|
337
|
+
get_system().container_stop(user.username)
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def nginx_sync_all(db: Session) -> dict:
|
|
341
|
+
"""Regenerate every user's nginx file from the DB, remove stale ones, test & reload."""
|
|
342
|
+
system = get_system()
|
|
343
|
+
s = get_settings()
|
|
344
|
+
users = list(db.scalars(select(User).where(User.provisioned.is_(True), User.port.is_not(None))))
|
|
345
|
+
wanted = {u.username for u in users}
|
|
346
|
+
removed = []
|
|
347
|
+
if s.users_nginx_dir.exists() and system.name == "real":
|
|
348
|
+
for f in s.users_nginx_dir.glob("*.conf"):
|
|
349
|
+
if f.stem not in wanted:
|
|
350
|
+
f.unlink()
|
|
351
|
+
removed.append(f.stem)
|
|
352
|
+
for u in users:
|
|
353
|
+
system.nginx_write_user(u.username, u.port)
|
|
354
|
+
system.nginx_apply()
|
|
355
|
+
return {"written": sorted(wanted), "removed": removed}
|