forked from agentscope-ai/agentscope-runtime
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsandbox_manager.py
More file actions
1776 lines (1509 loc) · 60.2 KB
/
sandbox_manager.py
File metadata and controls
1776 lines (1509 loc) · 60.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
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
# -*- coding: utf-8 -*-
# pylint: disable=redefined-outer-name, protected-access
# pylint: disable=too-many-branches, too-many-statements
# pylint: disable=redefined-outer-name, protected-access, too-many-branches
# pylint: disable=too-many-public-methods, unused-argument
import asyncio
import inspect
import json
import time
import threading
import logging
import os
import secrets
import traceback
from functools import wraps
from typing import Optional, Dict, Union, List
import requests
import shortuuid
import httpx
from fastapi import Request, HTTPException
from fastapi.responses import StreamingResponse
from .heartbeat_mixin import HeartbeatMixin, touch_session
from .workspace_mixin import WorkspaceFSMixin
from ..constant import TIMEOUT
from ..client import (
SandboxHttpClient,
TrainingSandboxClient,
SandboxHttpAsyncClient,
)
from ..enums import SandboxType
from ..manager.storage import (
LocalStorage,
OSSStorage,
)
from ..model import (
ContainerModel,
ContainerState,
SandboxManagerEnvConfig,
)
from ..registry import SandboxRegistry
from ...common.collections import (
RedisMapping,
RedisQueue,
InMemoryMapping,
InMemoryQueue,
)
from ...common.container_clients import ContainerClientFactory
logger = logging.getLogger(__name__)
def remote_wrapper(
method: str = "POST",
success_key: str = "data",
):
"""
Decorator to handle both remote and local method execution.
"""
def decorator(func):
@wraps(func)
def wrapper(self, *args, **kwargs):
if not self.http_session:
# Execute the original function locally
return func(self, *args, **kwargs)
endpoint = "/" + func.__name__
# Prepare data for remote call
sig = inspect.signature(func)
param_names = list(sig.parameters.keys())[1:] # Skip 'self'
data = dict(zip(param_names, args))
data.update(kwargs)
# Make the remote HTTP request
response = self._make_request(method, endpoint, data)
# Process response
if success_key:
return response.get(success_key)
return response
wrapper._is_remote_wrapper = True
wrapper._http_method = method
wrapper._path = "/" + func.__name__
return wrapper
return decorator
def remote_wrapper_async(
method: str = "POST",
success_key: str = "data",
):
"""
Async decorator to handle both remote and local method execution.
Supports awaitable functions.
"""
def decorator(func):
@wraps(func)
async def wrapper(self, *args, **kwargs):
# Remote mode
if hasattr(self, "httpx_client") and self.httpx_client is not None:
endpoint = "/" + func.__name__
# Build JSON data from args/kwargs
sig = inspect.signature(func)
param_names = list(sig.parameters.keys())[1:] # Skip 'self'
data = dict(zip(param_names, args))
data.update(kwargs)
# Make async HTTP request
response = await self._make_request_async(
method,
endpoint,
data,
)
if success_key:
return response.get(success_key)
return response
# Local mode
return await func(self, *args, **kwargs)
wrapper._is_remote_wrapper = True
wrapper._http_method = method
wrapper._path = "/" + func.__name__
return wrapper
return decorator
class SandboxManager(HeartbeatMixin, WorkspaceFSMixin):
def __init__(
self,
config: Optional[SandboxManagerEnvConfig] = None,
base_url=None,
bearer_token=None,
default_type: Union[
SandboxType,
str,
List[Union[SandboxType, str]],
] = SandboxType.BASE,
):
if base_url:
# Initialize HTTP session for remote mode with bearer token
# authentication
self.http_session = requests.Session()
# For async HTTP
self.httpx_client = httpx.AsyncClient(timeout=TIMEOUT)
self.base_url = base_url.rstrip("/")
if bearer_token:
self.http_session.headers.update(
{"Authorization": f"Bearer {bearer_token}"},
)
self.httpx_client.headers.update(
{"Authorization": f"Bearer {bearer_token}"},
)
# Remote mode, return directly
return
else:
self.http_session = None
self.httpx_client = None
self.base_url = None
if config:
logger.debug(
f"Launching sandbox manager with config:"
f"\n{config.model_dump()}",
)
else:
config = SandboxManagerEnvConfig(
file_system="local",
redis_enabled=False,
container_deployment="docker",
pool_size=0,
default_mount_dir="sessions_mount_dir",
)
# Support multi sandbox pool
if isinstance(default_type, (SandboxType, str)):
self.default_type = [SandboxType(default_type)]
else:
self.default_type = [SandboxType(x) for x in list(default_type)]
self.workdir = "/workspace"
self.config = config
self.pool_size = self.config.pool_size
self.prefix = self.config.container_prefix_key
self.default_mount_dir = self.config.default_mount_dir
self.readonly_mounts = self.config.readonly_mounts
self.storage_folder = self.config.storage_folder
self.pool_queues = {}
if self.config.redis_enabled:
import redis
redis_client = redis.Redis(
host=self.config.redis_server,
port=self.config.redis_port,
db=self.config.redis_db,
username=self.config.redis_user,
password=self.config.redis_password,
decode_responses=True,
)
self.redis_client = redis_client
try:
self.redis_client.ping()
except ConnectionError as e:
raise RuntimeError(
"Unable to connect to the Redis server.",
) from e
self.container_mapping = RedisMapping(self.redis_client)
self.session_mapping = RedisMapping(
self.redis_client,
prefix="session_mapping",
)
# Init multi sand box pool
for t in self.default_type:
queue_key = f"{self.config.redis_container_pool_key}:{t.value}"
self.pool_queues[t] = RedisQueue(self.redis_client, queue_key)
else:
self.redis_client = None
self.container_mapping = InMemoryMapping()
self.session_mapping = InMemoryMapping()
# Init multi sand box pool
for t in self.default_type:
self.pool_queues[t] = InMemoryQueue()
self.container_deployment = self.config.container_deployment
if base_url is None:
self.client = ContainerClientFactory.create_client(
deployment_type=self.container_deployment,
config=self.config,
)
else:
self.client = None
self.file_system = self.config.file_system
if self.file_system == "oss":
self.storage = OSSStorage(
self.config.oss_access_key_id,
self.config.oss_access_key_secret,
self.config.oss_endpoint,
self.config.oss_bucket_name,
)
else:
self.storage = LocalStorage()
self._watcher_stop_event = threading.Event()
self._watcher_thread = None
self._watcher_thread_lock = threading.Lock()
logger.debug(str(config))
def __enter__(self):
logger.debug(
"Entering SandboxManager context (sync). "
"Cleanup will be performed automatically on exit.",
)
# local mode: watcher starts
if self.http_session is None:
self.start_watcher()
return self
def __exit__(self, exc_type, exc_value, traceback):
logger.debug(
"Exiting SandboxManager context (sync). Cleaning up resources.",
)
self.stop_watcher()
self.cleanup()
if self.http_session:
try:
self.http_session.close()
logger.debug("HTTP session closed.")
except Exception as e:
logger.warning(f"Error closing http_session: {e}")
if self.httpx_client:
try:
loop = asyncio.get_event_loop()
if loop.is_running():
asyncio.ensure_future(self.httpx_client.aclose())
else:
loop.run_until_complete(self.httpx_client.aclose())
logger.debug("HTTPX async client closed.")
except Exception as e:
logger.warning(f"Error closing httpx_client: {e}")
async def __aenter__(self):
logger.debug(
"Entering SandboxManager context (async). "
"Cleanup will be performed automatically on async exit.",
)
# local mode: watcher starts
if self.http_session is None:
self.start_watcher()
return self
async def __aexit__(self, exc_type, exc_value, tb):
logger.debug(
"Exiting SandboxManager context (async). Cleaning up resources.",
)
self.stop_watcher()
await self.cleanup_async()
if self.http_session:
try:
self.http_session.close()
logger.debug("HTTP session closed.")
except Exception as e:
logger.warning(f"Error closing http_session: {e}")
if self.httpx_client:
try:
await self.httpx_client.aclose()
logger.debug("HTTPX async client closed.")
except Exception as e:
logger.warning(f"Error closing httpx_client: {e}")
def _generate_container_key(self, session_id):
# TODO: refactor this and mapping, use sandbox_id as identity
return f"{self.prefix}{session_id}"
def _make_request(self, method: str, endpoint: str, data: dict):
"""
Make an HTTP request to the specified endpoint.
"""
url = f"{self.base_url}/{endpoint.lstrip('/')}"
if method.upper() == "GET":
response = self.http_session.get(url, params=data, timeout=TIMEOUT)
else:
response = self.http_session.request(
method,
url,
json=data,
timeout=TIMEOUT,
)
try:
response.raise_for_status()
except requests.exceptions.HTTPError as e:
error_components = [
f"HTTP {response.status_code} Error: {str(e)}",
]
try:
server_response = response.json()
if "detail" in server_response:
error_components.append(
f"Server Detail: {server_response['detail']}",
)
elif "error" in server_response:
error_components.append(
f"Server Error: {server_response['error']}",
)
else:
error_components.append(
f"Server Response: {server_response}",
)
except (ValueError, json.JSONDecodeError):
if response.text:
error_components.append(
f"Server Response: {response.text}",
)
error = " | ".join(error_components)
logger.error(f"Error making request: {error}")
return {"data": f"Error: {error}"}
return response.json()
async def _make_request_async(
self,
method: str,
endpoint: str,
data: dict,
):
"""
Make an asynchronous HTTP request to the specified endpoint.
"""
url = f"{self.base_url}/{endpoint.lstrip('/')}"
if method.upper() == "GET":
response = await self.httpx_client.get(url, params=data)
else:
response = await self.httpx_client.request(method, url, json=data)
try:
response.raise_for_status()
except httpx.HTTPStatusError as e:
error_components = [
f"HTTP {response.status_code} Error: {str(e)}",
]
try:
server_response = response.json()
if "detail" in server_response:
error_components.append(
f"Server Detail: {server_response['detail']}",
)
elif "error" in server_response:
error_components.append(
f"Server Error: {server_response['error']}",
)
else:
error_components.append(
f"Server Response: {server_response}",
)
except (ValueError, json.JSONDecodeError):
if response.text:
error_components.append(
f"Server Response: {response.text}",
)
error = " | ".join(error_components)
logger.error(f"Error making request: {error}")
return {"data": f"Error: {error}"}
return response.json()
def start_watcher(self) -> bool:
"""
Start background heartbeat scanning thread.
Default: not started automatically. Caller must invoke explicitly.
If watcher_scan_interval == 0 => disabled, returns False.
"""
interval = int(self.config.watcher_scan_interval)
if interval <= 0:
logger.info(
"Watcher disabled (watcher_scan_interval <= 0)",
)
return False
with self._watcher_thread_lock:
if self._watcher_thread and self._watcher_thread.is_alive():
return True # already running
self._watcher_stop_event.clear()
def _loop():
logger.info(f"Watcher started, interval={interval}s")
while not self._watcher_stop_event.is_set():
try:
hb = self.scan_heartbeat_once()
pool = self.scan_pool_once()
gc = self.scan_released_cleanup_once()
logger.debug(
"watcher metrics: "
f"heartbeat={hb}, pool={pool}, released_gc={gc}",
)
except Exception as e:
logger.warning(f"Watcher loop error: {e}")
logger.debug(traceback.format_exc())
# wait with stop support
self._watcher_stop_event.wait(interval)
logger.info("Watcher stopped")
t = threading.Thread(
target=_loop,
name="watcher",
daemon=True,
)
self._watcher_thread = t
t.start()
return True
def stop_watcher(self, join_timeout: float = 5.0) -> None:
"""
Stop background watcher thread (if running).
"""
with self._watcher_thread_lock:
self._watcher_stop_event.set()
t = self._watcher_thread
if t and t.is_alive():
t.join(timeout=join_timeout)
with self._watcher_thread_lock:
if self._watcher_thread is t:
self._watcher_thread = None
@remote_wrapper()
def cleanup(self):
"""
Destroy all non-terminal containers managed by this SandboxManager.
Behavior (local mode):
- Dequeues and destroys containers from the warm pool (WARM/RUNNING).
- Scans container_mapping and destroys any remaining non-terminal
containers.
- Does NOT delete ContainerModel records from container_mapping;
instead it relies on release() to mark them as terminal (RELEASED).
- Skips containers already in terminal states: RELEASED / RECYCLED.
Notes:
- Uses container_name as identity to avoid ambiguity with session_id.
- Pool containers (WARM) are also destroyed (per current policy).
"""
logger.debug("Cleaning up resources.")
# Clean up pool first (destroy warm/running containers; skip
# terminal states)
for queue in self.pool_queues.values():
try:
while queue.size() > 0:
container_json = queue.dequeue()
if not container_json:
continue
container_model = ContainerModel(**container_json)
# Terminal states: already cleaned logically
if container_model.state in (
ContainerState.RELEASED,
ContainerState.RECYCLED,
):
continue
logger.debug(
f"Destroy pool container"
f" {container_model.container_id} "
f"({container_model.container_name})",
)
# Use container_name to avoid ambiguity
self.release(container_model.container_name)
except Exception as e:
logger.error(f"Error cleaning up runtime pool: {e}")
# Clean up remaining containers in mapping
for key in self.container_mapping.scan(self.prefix):
try:
container_json = self.container_mapping.get(key)
if not container_json:
continue
container_model = ContainerModel(**container_json)
# Terminal states: already cleaned logically
if container_model.state in (
ContainerState.RELEASED,
ContainerState.RECYCLED,
):
continue
logger.debug(
f"Destroy container {container_model.container_id} "
f"({container_model.container_name})",
)
self.release(container_model.container_name)
except Exception as e:
logger.error(f"Error cleaning up container {key}: {e}")
@remote_wrapper_async()
async def cleanup_async(self):
"""Async wrapper for cleanup()."""
return await asyncio.to_thread(self.cleanup)
@remote_wrapper()
def create_from_pool(self, sandbox_type=None, meta: Optional[Dict] = None):
"""Try to get a container from runtime pool"""
# If not specified, use the first one
sandbox_type = SandboxType(sandbox_type or self.default_type[0])
if sandbox_type not in self.pool_queues:
return self.create(sandbox_type=sandbox_type.value, meta=meta)
queue = self.pool_queues[sandbox_type]
def _bind_meta(container_model: ContainerModel):
if not meta:
return
session_ctx_id = meta.get("session_ctx_id")
container_model.meta = meta
container_model.session_ctx_id = session_ctx_id
container_model.state = (
ContainerState.RUNNING
if session_ctx_id
else ContainerState.WARM
)
container_model.recycled_at = None
container_model.recycle_reason = None
container_model.updated_at = time.time()
# persist first
self.container_mapping.set(
container_model.container_name,
container_model.model_dump(),
)
# session mapping + first heartbeat only when session_ctx_id exists
if session_ctx_id:
env_ids = self.session_mapping.get(session_ctx_id) or []
if container_model.container_name not in env_ids:
env_ids.append(container_model.container_name)
self.session_mapping.set(session_ctx_id, env_ids)
self.clear_container_recycle_marker(
container_model.container_name,
set_state=ContainerState.RUNNING,
)
self.update_heartbeat(session_ctx_id)
try:
# 1) Try dequeue first
container_json = queue.dequeue()
if container_json:
container_model = ContainerModel(**container_json)
# version check
if (
container_model.version
!= SandboxRegistry.get_image_by_type(sandbox_type)
):
logger.warning(
f"Container {container_model.session_id} outdated, "
"dropping it",
)
self.release(container_model.container_name)
container_json = None
else:
# inspect + status check
if (
self.client.inspect(
container_model.container_id,
)
is None
):
logger.warning(
f"Container {container_model.container_id} not "
f"found, dropping it",
)
self.release(container_model.container_name)
container_json = None
else:
status = self.client.get_status(
container_model.container_id,
)
if status != "running":
logger.warning(
f"Container {container_model.container_id} "
f"not running ({status}), dropping it",
)
self.release(container_model.container_name)
container_json = None
# if still valid, bind meta and return
if container_json:
_bind_meta(container_model)
logger.debug(
f"Retrieved container from pool:"
f" {container_model.session_id}",
)
return container_model.container_name
# 2) Pool empty or invalid -> create a new one and return
return self.create(sandbox_type=sandbox_type.value, meta=meta)
except Exception as e:
logger.warning(
"Error getting container from pool, create a new one.",
)
logger.debug(f"{e}: {traceback.format_exc()}")
return self.create(sandbox_type=sandbox_type.value, meta=meta)
@remote_wrapper_async()
async def create_from_pool_async(self, *args, **kwargs):
"""Async wrapper for create_from_pool()."""
return await asyncio.to_thread(self.create_from_pool, *args, **kwargs)
@remote_wrapper()
def create(
self,
sandbox_type=None,
mount_dir=None,
storage_path=None,
environment: Optional[Dict] = None,
meta: Optional[Dict] = None,
): # pylint: disable=too-many-return-statements
# Enforce max sandbox instances
try:
limit = self.config.max_sandbox_instances
if limit > 0:
# Count only ACTIVE containers; exclude terminal states
active_states = {
ContainerState.WARM,
ContainerState.RUNNING,
}
current = 0
for key in self.container_mapping.scan(self.prefix):
try:
container_json = self.container_mapping.get(key)
if not container_json:
continue
cm = ContainerModel(**container_json)
if cm.state in active_states:
current += 1
except Exception:
# ignore broken records
continue
# Check if limit is exceeded
if current >= limit:
logger.warning(
f"Sandbox instance limit reached: "
f"{current}/{limit} active instances",
)
return None
except RuntimeError as e:
logger.warning(str(e))
return None
except Exception:
# Handle unexpected errors from container_mapping.scan() gracefully
logger.exception("Failed to check sandbox instance limit")
return None
session_ctx_id = None
if meta and meta.get("session_ctx_id"):
session_ctx_id = meta["session_ctx_id"]
if sandbox_type is not None:
target_sandbox_type = SandboxType(sandbox_type)
else:
target_sandbox_type = self.default_type[0]
config = SandboxRegistry.get_config_by_type(target_sandbox_type)
if not config:
logger.warning(
f"Not found sandbox {target_sandbox_type}, " f"using default",
)
config = SandboxRegistry.get_config_by_type(
self.default_type[0],
)
image = config.image_name
environment = {
**(config.environment if config.environment else {}),
**(environment if environment else {}),
}
for key, value in environment.items():
if value is None:
logger.error(
f"Env variable {key} is None.",
)
return None
alphabet = "0123456789abcdefghijklmnopqrstuvwxyz"
short_uuid = shortuuid.ShortUUID(alphabet=alphabet).uuid()
session_id = str(short_uuid)
if mount_dir and not self.config.allow_mount_dir:
logger.warning(
"mount_dir is not allowed by config, fallback to "
"default_mount_dir",
)
if (not mount_dir) or (not self.config.allow_mount_dir):
if self.default_mount_dir:
mount_dir = os.path.join(self.default_mount_dir, session_id)
os.makedirs(mount_dir, exist_ok=True)
if (
mount_dir
and self.container_deployment != "agentrun"
and self.container_deployment != "fc"
):
if not os.path.isabs(mount_dir):
mount_dir = os.path.abspath(mount_dir)
if storage_path is None:
if self.storage_folder:
storage_path = self.storage.path_join(
self.storage_folder,
session_id,
)
if (
mount_dir
and storage_path
and self.container_deployment != "agentrun"
and self.container_deployment != "fc"
):
self.storage.download_folder(storage_path, mount_dir)
# Check for an existing container with the same name
container_name = self._generate_container_key(session_id)
try:
if self.client.inspect(container_name):
raise ValueError(
f"Container with name {container_name} already exists.",
)
# Generate a random secret token
runtime_token = secrets.token_hex(16)
# Prepare volume bindings if a mount directory is provided
if (
mount_dir
and self.container_deployment != "agentrun"
and self.container_deployment != "fc"
):
volume_bindings = {
mount_dir: {
"bind": self.workdir,
"mode": "rw",
},
}
else:
volume_bindings = {}
if self.readonly_mounts:
for host_path, container_path in self.readonly_mounts.items():
if not os.path.isabs(host_path):
host_path = os.path.abspath(host_path)
volume_bindings[host_path] = {
"bind": container_path,
"mode": "ro",
}
_id, ports, ip, *rest = self.client.create(
image,
name=container_name,
ports=["80/tcp"], # Nginx
volumes=volume_bindings,
environment={
"SECRET_TOKEN": runtime_token,
"NGINX_TIMEOUT": str(TIMEOUT) if TIMEOUT else "60",
**environment,
},
runtime_config=config.runtime_config,
)
http_protocol = "http"
if rest and rest[0] == "https":
http_protocol = "https"
if _id is None:
return None
# Check the container status
status = self.client.get_status(container_name)
if self.client.get_status(container_name) != "running":
logger.warning(
f"Container {container_name} is not running. Current "
f"status: {status}",
)
return None
# TODO: update ContainerModel according to images & backend
container_model = ContainerModel(
session_id=session_id,
container_id=_id,
container_name=container_name,
url=f"{http_protocol}://{ip}:{ports[0]}",
ports=[ports[0]],
mount_dir=str(mount_dir),
storage_path=storage_path,
runtime_token=runtime_token,
version=image,
meta=meta or {},
timeout=config.timeout,
sandbox_type=target_sandbox_type.value,
session_ctx_id=session_ctx_id,
state=ContainerState.RUNNING
if session_ctx_id
else ContainerState.WARM,
updated_at=time.time(),
)
# Register in mapping
self.container_mapping.set(
container_model.container_name,
container_model.model_dump(),
)
# Build mapping session_ctx_id to container_name
# NOTE:
# - Only containers bound to a user session_ctx_id participate
# in heartbeat/reap.
# - Prewarmed pool containers typically have no session_ctx_id;
# do NOT write heartbeat for them.
if meta and "session_ctx_id" in meta and meta["session_ctx_id"]:
session_ctx_id = meta["session_ctx_id"]
env_ids = self.session_mapping.get(session_ctx_id) or []
if container_model.container_name not in env_ids:
env_ids.append(container_model.container_name)
self.session_mapping.set(session_ctx_id, env_ids)
# First heartbeat on creation (treat "allocate to session"
# as first activity)
self.update_heartbeat(session_ctx_id)
# Session is now alive again; clear restore-required marker
self.clear_container_recycle_marker(
container_model.container_name,
set_state=ContainerState.RUNNING,
)
logger.debug(
f"Created container {container_name}"
f":{container_model.model_dump()}",
)
return container_name
except Exception as e:
logger.warning(
f"Failed to create container: {e}",
)
logger.debug(f"{traceback.format_exc()}")
self.release(identity=container_name)
return None
@remote_wrapper_async()
async def create_async(self, *args, **kwargs):
"""Async wrapper for create()."""
return await asyncio.to_thread(self.create, *args, **kwargs)
@remote_wrapper()
def release(self, identity):
try:
container_json = self.container_mapping.get(identity)
if container_json is None:
container_json = self.container_mapping.get(
self._generate_container_key(identity),
)
if container_json is None:
logger.warning(
f"release: container not found for {identity}, "
f"treat as already released",
)
return True
container_info = ContainerModel(**container_json)
# remove session key in mapping
session_ctx_id = container_info.session_ctx_id or (
container_info.meta or {}
).get("session_ctx_id")
if session_ctx_id:
env_ids = self.session_mapping.get(session_ctx_id) or []
env_ids = [
eid
for eid in env_ids
if eid != container_info.container_name
]
if env_ids:
self.session_mapping.set(session_ctx_id, env_ids)
else:
# last container of this session is gone;
# keep state consistent
self.session_mapping.delete(session_ctx_id)
# Mark released (do NOT delete mapping) in model
now = time.time()
container_info.state = ContainerState.RELEASED
container_info.released_at = now
container_info.updated_at = now
container_info.recycled_at = None
container_info.recycle_reason = None
# Unbind session in model
container_info.session_ctx_id = None
if container_info.meta is None:
container_info.meta = {}
container_info.meta.pop("session_ctx_id", None)
self.container_mapping.set(