Repository navigation
Expand file tree
/
Copy pathdocker_manager.py
More file actions
830 lines (737 loc) · 35.2 KB
/
Copy pathdocker_manager.py
File metadata and controls
830 lines (737 loc) · 35.2 KB
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
import asyncio
import json
import os
import platform
import shutil
import subprocess
import uuid
from loguru import logger
# ── Кроссплатформенная безопасность (2026-09-01) ────────────────
# На Linux (VPS) контейнеры запускаются под user="1000:1000" — без прав
# root внутри песочницы. На Windows/Docker Desktop (WSL2) user 1000:1000
# тоже работает для Linux-контейнеров, НО volume-маунт Windows-пути
# (C:\projects\arch-code\sandbox\...) отдаётся с правами WSL-пользователя —
# chown 1000 внутри контейнера может не примениться, и процесс упадёт
# с "Operation not permitted" при записи в /app.
# Поэтому на Windows user НЕ задаём (контейнер работает от root внутри,
# а права volume регулирует Docker Desktop/WSL2 сам).
_IS_WINDOWS = platform.system() == "Windows"
def _run_user() -> str | None:
"""Вернуть user для docker run (None → не задавать).
Linux: "1000:1000" (hardening).
Windows: None (Docker Desktop/WSL2 сам управляет правами volume).
"""
return None if _IS_WINDOWS else "1000:1000"
def cleanup_containers(task_id: str) -> None:
"""Остановить и удалить Docker-контейнеры, связанные с задачей.
Именованные контейнеры: sandbox-{task_id}, project-test-{task_id}.
Безопасно вызывать даже если контейнеры не существуют.
"""
for suffix in (f"sandbox-{task_id}", f"project-test-{task_id}"):
try:
subprocess.run(
["docker", "stop", suffix],
capture_output=True, timeout=10, check=False,
)
except Exception as exc:
logger.warning(f"cleanup: docker stop {suffix} не удался: {exc}")
try:
subprocess.run(
["docker", "rm", "--force", suffix],
capture_output=True, timeout=10, check=False,
)
except Exception as exc:
logger.warning(f"cleanup: docker rm {suffix} не удался: {exc}")
class NodeSandbox:
"""Изолированная среда для выполнения Node.js кода в Docker-контейнере.
Каждый экземпляр привязан к уникальному task_id и работает
в собственной директории sandbox/{task_id}/ — параллельные задачи
не пересекаются.
"""
ROOT_SANDBOX_DIR = os.path.abspath("./sandbox")
# Распространённые npm-зависимости для генерируемого кода
COMMON_DEPS = {"express": "^4.18.2"}
def __init__(self, task_id: str | None = None):
self.task_id = task_id or uuid.uuid4().hex[:12]
self.sandbox_dir = os.path.join(self.ROOT_SANDBOX_DIR, self.task_id)
os.makedirs(self.sandbox_dir, exist_ok=True)
def _ensure_package_json(self):
"""Создаёт package.json в sandbox/{task_id}/, если его ещё нет."""
pkg_path = os.path.join(self.sandbox_dir, "package.json")
if not os.path.exists(pkg_path):
pkg = {
"name": f"sandbox-{self.task_id}",
"version": "1.0.0",
"private": True,
"dependencies": dict(self.COMMON_DEPS),
}
with open(pkg_path, "w") as f:
json.dump(pkg, f, indent=2)
def _run_in_container(self, command: list[str], timeout: int = 30) -> dict:
"""Синхронный запуск команды в Docker-контейнере (docker-py).
Двухфазный запуск:
1. npm install — контейнер с сетью (нужен npm registry).
2. Основная команда — контейнер без сети (network_mode="none"),
с cap_drop=["ALL"] и user=1000:1000 (Linux; на Windows — без user).
Контейнер именуется sandbox-{task_id}, не удаляется автоматически
(remove=False) — управление жизнью через cleanup_containers().
"""
import docker
self._ensure_package_json()
client = docker.from_env()
container_name = f"sandbox-{self.task_id}"
# npm install — удаляем предыдущий контейнер перед запуском
try:
client.containers.get(container_name).remove(force=True)
except docker.errors.NotFound:
pass
# ── Фаза 1: npm install (с сетью) ─────────────────────────
try:
client.containers.run(
"node:alpine",
command=["npm", "install"],
name=container_name,
volumes={self.sandbox_dir: {"bind": "/app", "mode": "rw"}},
working_dir="/app",
user=_run_user(),
remove=True,
detach=False,
stderr=True,
stdout=True,
)
except docker.errors.ContainerError as exc:
logger.warning(
f"npm install в контейнере {container_name} вернул ошибку: {exc}"
)
except Exception as exc:
logger.warning(
f"npm install в контейнере {container_name} не удался: {exc}"
)
# ── Фаза 2: основная команда (без сети, hardening) ────────
try:
logs = client.containers.run(
"node:alpine",
command=command,
volumes={self.sandbox_dir: {"bind": "/app", "mode": "rw"}},
working_dir="/app",
# Фаза исполнения — сетевая изоляция + безопасность
user=_run_user(),
cap_drop=["ALL"],
network_mode="none",
security_opt=["no-new-privileges"],
remove=True,
detach=False,
stderr=True,
stdout=True,
)
return {"status": "success", "output": logs.decode("utf-8")}
except docker.errors.ContainerError as e:
err_msg = ""
try:
err_msg = e.stderr.decode("utf-8") if e.stderr else str(e)
except Exception as exc:
logger.warning(f"Не удалось декодировать stderr: {exc}")
err_msg = str(e)
return {"status": "error", "output": err_msg}
def execute_code(self, filename: str, code: str) -> dict:
"""Записать код в sandbox/{task_id}/ и запустить с таймаутом 5 сек."""
file_path = os.path.join(self.sandbox_dir, filename)
os.makedirs(os.path.dirname(file_path), exist_ok=True)
with open(file_path, "w") as f:
f.write(code)
return self._run_in_container(
["sh", "-c", f"timeout 5 node /app/{filename}"]
)
def execute_test(self, filename: str, code: str) -> dict:
"""Записать тест в sandbox/{task_id}/ и запустить node --test."""
file_path = os.path.join(self.sandbox_dir, filename)
os.makedirs(os.path.dirname(file_path), exist_ok=True)
with open(file_path, "w") as f:
f.write(code)
return self._run_in_container(
["node", "--test", f"/app/{filename}"]
)
async def execute_code_async(self, filename: str, code: str) -> dict:
"""async-версия execute_code — не блокирует event loop."""
file_path = os.path.join(self.sandbox_dir, filename)
os.makedirs(os.path.dirname(file_path), exist_ok=True)
with open(file_path, "w") as f:
f.write(code)
self._ensure_package_json()
await self._run_in_container_async(["npm", "install"])
return await self._run_in_container_async(
["sh", "-c", f"timeout 5 node /app/{filename}"],
no_network=True,
)
async def execute_test_async(self, filename: str, code: str) -> dict:
"""async-версия execute_test — не блокирует event loop."""
file_path = os.path.join(self.sandbox_dir, filename)
os.makedirs(os.path.dirname(file_path), exist_ok=True)
with open(file_path, "w") as f:
f.write(code)
self._ensure_package_json()
await self._run_in_container_async(["npm", "install"])
return await self._run_in_container_async(
["node", "--test", f"/app/{filename}"],
no_network=True,
)
async def _run_in_container_async(
self, command: list[str], timeout: int = 30, *, no_network: bool = False
) -> dict:
"""async-запуск команды в Docker через asyncio.create_subprocess_exec.
Args:
command: Команда для запуска.
timeout: Таймаут (сек).
no_network: True → фаза исполнения (network=none, cap_drop,
no-new-privileges, user=1000:1000 на Linux; на Windows — без user).
False → фаза установки (npm install — нужна сеть).
"""
volume_bind = f"{self.sandbox_dir}:/app"
docker_cmd = [
"docker", "run", "--rm",
"-v", volume_bind,
"-w", "/app",
]
if no_network:
docker_cmd += [
"--network", "none",
"--cap-drop", "ALL",
"--security-opt", "no-new-privileges",
]
run_user = _run_user()
if run_user:
docker_cmd += ["--user", run_user]
docker_cmd += ["node:alpine"] + command
try:
proc = await asyncio.create_subprocess_exec(
*docker_cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
stdout, stderr = await asyncio.wait_for(
proc.communicate(), timeout=timeout
)
if proc.returncode == 0:
return {"status": "success", "output": stdout.decode("utf-8")}
else:
return {
"status": "error",
"output": (stderr or stdout).decode("utf-8"),
}
except asyncio.TimeoutError:
return {"status": "error", "output": "Timeout"}
except FileNotFoundError:
return {"status": "error", "output": "Docker not found on host"}
def cleanup(self) -> None:
"""Удалить sandbox/{task_id}/ со всем содержимым."""
if os.path.exists(self.sandbox_dir):
shutil.rmtree(self.sandbox_dir, ignore_errors=True)
# ═══════════════════════════════════════════════════════════════════
# ProjectSandbox — универсальная песочница для Phase B
# ═══════════════════════════════════════════════════════════════════
class ProjectSandbox:
"""Песочница для работы с полным проектом (Python / Node.js).
В отличие от NodeSandbox (один .js файл), этот класс принимает
путь к директории с проектом, определяет его тип и запускает
соответствующие тесты (pytest / npm test).
Двухфазный запуск контейнеров:
1. Фаза сборки (install) — контейнер С СЕТЬЮ (нужен PyPI/npm
registry), зависимости устанавливаются в volume-смонтированную
sandbox-директорию (/app/.deps или /app/node_modules).
2. Фаза исполнения (run/test) — контейнер БЕЗ СЕТИ
(network_mode="none"), с cap_drop=["ALL"] и user="1000:1000".
Использует уже установленные пакеты.
"""
# Общие security-параметры для фазы исполнения (без сети)
# user=1000:1000 — только на Linux; на Windows не задаём (Docker Desktop).
_RUN_SECURITY = {
"user": "1000:1000",
"cap_drop": ["ALL"],
"network_mode": "none",
"security_opt": ["no-new-privileges"],
}
@staticmethod
def _run_security_params() -> dict:
"""Параметры безопасности фазы исполнения (с учётом ОС)."""
params = dict(ProjectSandbox._RUN_SECURITY)
run_user = _run_user()
if run_user is None:
params.pop("user", None)
else:
params["user"] = run_user
return params
@staticmethod
def detect_project_type(sandbox_dir: str) -> str:
"""Определить тип проекта по наличию конфигурационных файлов."""
if os.path.exists(os.path.join(sandbox_dir, "requirements.txt")):
return "python"
if os.path.exists(os.path.join(sandbox_dir, "pyproject.toml")):
return "python"
if os.path.exists(os.path.join(sandbox_dir, "setup.py")):
return "python"
if os.path.exists(os.path.join(sandbox_dir, "package.json")):
return "node"
return "unknown"
@staticmethod
def run_project_tests(sandbox_dir: str, project_type: str | None = None, task_id: str = "") -> dict:
"""Установить зависимости и запустить тесты проекта в Docker.
Args:
sandbox_dir: Абсолютный путь к директории проекта.
project_type: "python", "node" или None (автоопределение).
task_id: ID задачи для именования контейнера.
Returns:
dict {"status": "success"|"error", "output": str}
"""
if project_type is None:
project_type = ProjectSandbox.detect_project_type(sandbox_dir)
if project_type == "python":
return ProjectSandbox._run_python_tests(sandbox_dir, task_id)
elif project_type == "node":
return ProjectSandbox._run_node_tests(sandbox_dir, task_id)
else:
return {"status": "error", "output": "Не удалось определить тип проекта"}
# ── Python ────────────────────────────────────────────────────
@staticmethod
def _run_python_tests(sandbox_dir: str, task_id: str = "") -> dict:
"""Установить pytest и запустить тесты в Docker (python:3.12-slim).
Двухфазный запуск:
1. install: контейнер с сетью, pip install --target=/app/.deps
(зависимости пишутся в sandbox/.deps — volume).
2. test: контейнер без сети (network_mode="none"),
PYTHONPATH=/app/.deps, запуск pytest.
Не пытается форсированно установить ВСЕ зависимости проекта
(torch, tiktoken, cryptg требуют компиляции в slim-образе).
Устанавливает только pytest — тесты на чистом Python/stdlib пройдут.
"""
import docker
client = docker.from_env()
container_name = f"project-test-{task_id}" if task_id else "project-test"
def _rm_container():
"""Удалить существующий контейнер, если есть (force)."""
try:
c = client.containers.get(container_name)
c.remove(force=True)
except docker.errors.NotFound:
pass
volumes = {sandbox_dir: {"bind": "/app", "mode": "rw"}}
# ── Фаза 1: установка зависимостей (с сетью) ──────────────
_rm_container()
try:
client.containers.run(
"python:3.12-slim",
command=[
"sh", "-c",
"pip install --quiet --timeout=60 "
"--target=/app/.deps -r requirements.txt pytest pytest-timeout 2>&1 || true"
],
name=container_name,
volumes=volumes,
working_dir="/app",
user=_run_user(),
remove=False,
detach=False,
stderr=True,
stdout=True,
)
except docker.errors.ContainerError as exc:
logger.warning(
f"pip install в {container_name} вернул ошибку: {exc}"
)
except Exception as exc:
logger.error(
f"pip install в {container_name} не удался: {exc}", exc_info=True
)
# ── Фаза 2: запуск тестов (без сети) ──────────────────────
_rm_container()
try:
logs = client.containers.run(
"python:3.12-slim",
command=[
"sh", "-c",
"PYTHONPATH=/app/.deps python -m pytest -x "
"--timeout=30 --tb=short 2>&1 || true"
],
name=container_name,
volumes=volumes,
working_dir="/app",
# Фаза исполнения — сетевая изоляция + безопасность
**ProjectSandbox._run_security_params(),
remove=False,
detach=False,
stderr=True,
stdout=True,
)
output = logs.decode("utf-8")
# Считаем успехом, если нет FAILED (включая "no tests ran")
if "FAILED" in output and ("passed" not in output or "failed" in output):
return {"status": "error", "output": output[-2000:]}
return {"status": "success", "output": output[-1000:]}
except Exception as e:
logger.error(
f"Python-тесты в контейнере {container_name} не удались: {e}",
exc_info=True,
)
return {"status": "error", "output": str(e)}
# ── Node.js ───────────────────────────────────────────────────
@staticmethod
def _run_node_tests(sandbox_dir: str, task_id: str = "") -> dict:
"""Установить npm-пакеты и запустить npm test в Docker (node:alpine).
Двухфазный запуск:
1. install: контейнер с сетью, npm install → /app/node_modules.
2. test: контейнер без сети (network_mode="none"), npm test.
"""
import docker
client = docker.from_env()
container_name = f"project-test-{task_id}" if task_id else "project-test"
def _rm_container():
try:
c = client.containers.get(container_name)
c.remove(force=True)
except docker.errors.NotFound:
pass
volumes = {sandbox_dir: {"bind": "/app", "mode": "rw"}}
# ── Фаза 1: npm install (с сетью) ─────────────────────────
_rm_container()
try:
client.containers.run(
"node:alpine",
command=["npm", "install"],
name=container_name,
volumes=volumes,
working_dir="/app",
user=_run_user(),
remove=False,
detach=False,
stderr=True,
stdout=True,
)
except docker.errors.ContainerError as exc:
logger.warning(
f"npm install в контейнере {container_name} вернул ошибку: {exc}"
)
except Exception as e:
logger.error(f"npm install error: {e}", exc_info=True)
return {"status": "error", "output": f"npm install error: {e}"}
# ── Фаза 2: npm test (без сети) ───────────────────────────
_rm_container()
try:
logs = client.containers.run(
"node:alpine",
command=["sh", "-c", "npm test 2>&1; true"],
name=container_name,
volumes=volumes,
working_dir="/app",
# Фаза исполнения — сетевая изоляция + безопасность
**ProjectSandbox._run_security_params(),
remove=False,
detach=False,
stderr=True,
stdout=True,
)
output = logs.decode("utf-8")
return {"status": "success", "output": output[-1000:]}
except docker.errors.ContainerError as e:
err = e.stderr.decode("utf-8") if e.stderr else str(e)
return {"status": "error", "output": err[-2000:]}
except Exception as e:
logger.error(
f"npm test в контейнере {container_name} не удался: {e}",
exc_info=True,
)
return {"status": "error", "output": str(e)}
# ── Запуск приложения (smoke-проверка) ────────────────────────
@staticmethod
def run_application(
sandbox_dir: str,
project_type: str | None = None,
app_type: str = "cli_script",
task_id: str = "",
health_endpoint: str = "/health",
health_port: int = 8000,
) -> dict:
"""Запустить приложение в Docker и проверить, что оно работает.
Args:
sandbox_dir: Абсолютный путь к директории проекта.
project_type: "python", "node" или None (автоопределение).
app_type: "web_app" (HTTP health-check) или "cli_script"
(запуск с таймаутом + exit code).
task_id: ID задачи для именования контейнера.
health_endpoint: Путь health-check (для web_app).
health_port: Порт health-check (для web_app).
Returns:
dict {"status": "success"|"error", "output": str}
Двухфазный запуск:
1. install — зависимости с сетью (pip --target / npm install).
2. run — приложение без сети (network_mode="none").
"""
if project_type is None:
project_type = ProjectSandbox.detect_project_type(sandbox_dir)
# Устанавливаем зависимости (фаза с сетью)
install_result = ProjectSandbox._install_deps(sandbox_dir, project_type, task_id)
if install_result["status"] == "error":
return install_result
if project_type == "python":
return ProjectSandbox._run_python_app(
sandbox_dir, app_type, task_id, health_endpoint, health_port
)
elif project_type == "node":
return ProjectSandbox._run_node_app(
sandbox_dir, app_type, task_id, health_endpoint, health_port
)
else:
return {"status": "error", "output": "Не удалось определить тип проекта"}
@staticmethod
def _install_deps(sandbox_dir: str, project_type: str, task_id: str = "") -> dict:
"""Фаза установки зависимостей (контейнер с сетью)."""
import docker
client = docker.from_env()
container_name = f"project-run-{task_id}" if task_id else "project-run"
def _rm_container():
try:
c = client.containers.get(container_name)
c.remove(force=True)
except docker.errors.NotFound:
pass
volumes = {sandbox_dir: {"bind": "/app", "mode": "rw"}}
_rm_container()
try:
if project_type == "python":
cmd = [
"sh", "-c",
"pip install --quiet --timeout=60 "
"--target=/app/.deps -r requirements.txt 2>&1 || true"
]
image = "python:3.12-slim"
else:
cmd = ["npm", "install"]
image = "node:alpine"
client.containers.run(
image,
command=cmd,
name=container_name,
volumes=volumes,
working_dir="/app",
user=_run_user(),
remove=False,
detach=False,
stderr=True,
stdout=True,
)
return {"status": "success", "output": ""}
except docker.errors.ContainerError as exc:
logger.warning(f"Установка зависимостей ({container_name}): {exc}")
return {"status": "success", "output": ""} # не блокируем запуск
except Exception as e:
logger.error(
f"Установка зависимостей в {container_name} не удалась: {e}",
exc_info=True,
)
return {"status": "error", "output": f"Ошибка установки зависимостей: {e}"}
# ── Запуск Python-приложения ─────────────────────────────────
@staticmethod
def _run_python_app(
sandbox_dir: str,
app_type: str,
task_id: str = "",
health_endpoint: str = "/health",
health_port: int = 8000,
) -> dict:
"""Запустить Python-приложение в контейнере без сети."""
import docker
client = docker.from_env()
container_name = f"project-run-{task_id}" if task_id else "project-run"
def _rm_container():
try:
c = client.containers.get(container_name)
c.remove(force=True)
except docker.errors.NotFound:
pass
volumes = {sandbox_dir: {"bind": "/app", "mode": "rw"}}
_rm_container()
if app_type == "web_app":
# Smoke-скрипт в sandbox: запуск uvicorn + health-check через
# urllib (curl ОТСУТСТВУЕТ в python:3.12-slim).
# Отдельный файл — избегаем хрупкого экранирования shell.
# ВАЖНО: network_mode="none" запрещает исходящие соединения,
# но локальный HTTP внутри контейнера работает (loopback).
# Модуль приложения: ищем "app" в main.py, иначе пробуем
# web_app.py / app.py (агент мог положить ASGI-приложение туда).
smoke_script = f'''import os, subprocess, sys, time, urllib.request, signal
# Определяем модуль ASGI-приложения: main:app, иначе web_app:app / app:app
asgi_module = "main:app"
for cand in ("main.py", "web_app.py", "app.py"):
if os.path.isfile(cand):
with open(cand, "r", encoding="utf-8", errors="replace") as f:
src = f.read()
if "def app(" in src or "app = FastAPI(" in src or "app = Flask(" in src:
asgi_module = cand[:-3] + ":app"
break
# PYTHONPATH передаётся ДОЧЕРНЕМУ процессу (uvicorn), т.к. sys.path
# родителя не наследуется subprocess.
env = dict(os.environ, PYTHONPATH="/app/.deps")
proc = subprocess.Popen(
["python", "-m", "uvicorn", asgi_module, "--host", "0.0.0.0", "--port", "{health_port}"],
stdout=open("/tmp/app.log", "w"), stderr=subprocess.STDOUT, env=env,
)
try:
time.sleep(5)
with urllib.request.urlopen(
"http://127.0.0.1:{health_port}{health_endpoint}", timeout=5
) as resp:
ok = resp.status < 400
except Exception:
ok = False
try:
proc.send_signal(signal.SIGTERM)
proc.wait(timeout=5)
except Exception:
proc.kill()
if not ok:
print("HEALTH_CHECK_FAILED")
try:
print(open("/tmp/app.log").read())
except Exception:
pass
sys.exit(1)
print("OK")
'''
smoke_path = os.path.join(sandbox_dir, "_smoke_web.py")
with open(smoke_path, "w", encoding="utf-8") as f:
f.write(smoke_script)
cmd = f"cd /app && timeout 20 python _smoke_web.py 2>&1"
else:
# CLI-скрипт: запуск с таймаутом, проверка exit code и Traceback
cmd = (
"cd /app && PYTHONPATH=/app/.deps "
"timeout 10 python main.py --help 2>&1 || "
"timeout 10 python main.py 2>&1"
)
try:
logs = client.containers.run(
"python:3.12-slim",
command=["sh", "-c", cmd],
name=container_name,
volumes=volumes,
working_dir="/app",
# Фаза исполнения — сетевая изоляция + безопасность
**ProjectSandbox._run_security_params(),
remove=False,
detach=False,
stderr=True,
stdout=True,
)
output = logs.decode("utf-8")
if "HEALTH_CHECK_FAILED" in output or "Traceback" in output:
return {"status": "error", "output": output[-2000:]}
return {"status": "success", "output": output[-1000:]}
except docker.errors.ContainerError as e:
# При exit code != 0 docker-py бросает ContainerError, но
# stderr/stdout могут быть пустыми. Fallback: читаем логи
# контейнера напрямую.
err = ""
try:
err = e.stderr.decode("utf-8") if e.stderr else ""
except Exception:
err = ""
if not err:
try:
err = getattr(e, "stdout", b"").decode("utf-8") if getattr(e, "stdout", None) else ""
except Exception:
err = ""
if not err:
try:
c = client.containers.get(e.container.id)
err = c.logs().decode("utf-8", errors="replace")
c.remove(force=True)
except Exception:
pass
return {"status": "error", "output": (err or "smoke-проверка не прошла")[-2000:]}
except Exception as e:
logger.error(
f"Запуск Python-приложения ({container_name}) не удался: {e}",
exc_info=True,
)
return {"status": "error", "output": str(e)}
# ── Запуск Node.js-приложения ────────────────────────────────
@staticmethod
def _run_node_app(
sandbox_dir: str,
app_type: str,
task_id: str = "",
health_endpoint: str = "/health",
health_port: int = 8000,
) -> dict:
"""Запустить Node.js-приложение в контейнере без сети."""
import docker
client = docker.from_env()
container_name = f"project-run-{task_id}" if task_id else "project-run"
def _rm_container():
try:
c = client.containers.get(container_name)
c.remove(force=True)
except docker.errors.NotFound:
pass
volumes = {sandbox_dir: {"bind": "/app", "mode": "rw"}}
_rm_container()
entry_file = "app.js" if os.path.exists(os.path.join(sandbox_dir, "app.js")) else "server.js"
if app_type == "web_app":
# Smoke-скрипт в sandbox: запуск node + health-check через fetch
# (curl ОТСУТСТВУЕТ в node:alpine, fetch есть в Node 18+).
smoke_script = f'''const {{spawn}} = require("child_process");
const proc = spawn("node", ["{entry_file}"], {{ stdio: ["ignore", "pipe", "pipe"] }});
let log = "";
proc.stdout.on("data", d => log += d);
proc.stderr.on("data", d => log += d);
setTimeout(async () => {{
let ok = false;
try {{
const resp = await fetch("http://127.0.0.1:{health_port}{health_endpoint}", {{ signal: AbortSignal.timeout(5000) }});
ok = resp.status < 400;
}} catch (e) {{
ok = false;
}}
proc.kill("SIGTERM");
if (!ok) {{
console.log("HEALTH_CHECK_FAILED");
console.log(log);
process.exit(1);
}}
console.log("OK");
process.exit(0);
}}, 5000);
'''
smoke_path = os.path.join(sandbox_dir, "_smoke_web.js")
with open(smoke_path, "w", encoding="utf-8") as f:
f.write(smoke_script)
cmd = f"cd /app && timeout 20 node _smoke_web.js 2>&1"
else:
cmd = (
f"cd /app && timeout 10 node {entry_file} --help 2>&1 || "
f"timeout 10 node {entry_file} 2>&1"
)
try:
logs = client.containers.run(
"node:alpine",
command=["sh", "-c", cmd],
name=container_name,
volumes=volumes,
working_dir="/app",
**ProjectSandbox._run_security_params(),
remove=False,
detach=False,
stderr=True,
stdout=True,
)
output = logs.decode("utf-8")
if "HEALTH_CHECK_FAILED" in output or "Error" in output[:500]:
return {"status": "error", "output": output[-2000:]}
return {"status": "success", "output": output[-1000:]}
except docker.errors.ContainerError as e:
err = e.stderr.decode("utf-8") if e.stderr else str(e)
return {"status": "error", "output": err[-2000:]}
except Exception as e:
logger.error(
f"Запуск Node-приложения ({container_name}) не удался: {e}",
exc_info=True,
)
return {"status": "error", "output": str(e)}