-
Notifications
You must be signed in to change notification settings - Fork 929
Expand file tree
/
Copy pathsandboxes_adapter.py
More file actions
374 lines (306 loc) · 13.9 KB
/
sandboxes_adapter.py
File metadata and controls
374 lines (306 loc) · 13.9 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
#
# Copyright 2025 Alibaba Group Holding Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""
Sandbox service adapter implementation.
Implementation of SandboxService that adapts openapi-python-client generated API.
This adapter provides a clean abstraction layer between business logic and
the auto-generated API client, handling all model conversions and error mapping.
"""
import logging
from datetime import datetime, timedelta
import httpx # type: ignore[reportMissingImports]
from opensandbox.adapters.converter.exception_converter import (
ExceptionConverter,
)
from opensandbox.adapters.converter.response_handler import (
handle_api_error,
require_parsed,
)
from opensandbox.adapters.converter.sandbox_model_converter import (
SandboxModelConverter,
)
from opensandbox.api.lifecycle.types import UNSET
from opensandbox.config import ConnectionConfig
from opensandbox.models.sandboxes import (
NetworkPolicy,
PagedSandboxInfos,
PlatformSpec,
SandboxCreateResponse,
SandboxEndpoint,
SandboxFilter,
SandboxImageSpec,
SandboxInfo,
SandboxRenewResponse,
Volume,
)
from opensandbox.services.sandbox import Sandboxes
logger = logging.getLogger(__name__)
class SandboxesAdapter(Sandboxes):
"""
Implementation of SandboxService that adapts openapi-python-client generated API.
This adapter provides a clean abstraction layer between business logic and
the sandbox management API, handling all model conversions and error mapping.
The openapi-python-client generates functional APIs that support custom
httpx.AsyncClient injection, allowing for fine-grained control over HTTP behavior.
"""
def __init__(self, connection_config: ConnectionConfig) -> None:
"""
Initialize the sandbox service adapter.
Args:
connection_config: Connection configuration (shared transport, headers, timeouts)
"""
self.connection_config = connection_config
from opensandbox.api.lifecycle import AuthenticatedClient
api_key = self.connection_config.get_api_key()
timeout_seconds = self.connection_config.request_timeout.total_seconds()
timeout = httpx.Timeout(timeout_seconds)
headers = {
"User-Agent": self.connection_config.user_agent,
**self.connection_config.headers,
}
if api_key:
headers["OPEN-SANDBOX-API-KEY"] = api_key
# Create client with custom auth header for OpenSandbox API
self._client = AuthenticatedClient(
base_url=self.connection_config.get_base_url(),
token=api_key or "",
prefix="", # No prefix, just the token
auth_header_name="OPEN-SANDBOX-API-KEY", # Custom header name
timeout=timeout,
)
# Inject httpx client (adapter-owned)
self._httpx_client = httpx.AsyncClient(
base_url=self.connection_config.get_base_url(),
headers=headers,
timeout=timeout,
transport=self.connection_config.transport,
)
self._client.set_async_httpx_client(self._httpx_client)
async def _get_client(self):
"""Return the authenticated client for lifecycle API."""
return self._client
async def create_sandbox(
self,
spec: SandboxImageSpec,
entrypoint: list[str],
env: dict[str, str],
metadata: dict[str, str],
timeout: timedelta | None,
resource: dict[str, str],
network_policy: NetworkPolicy | None,
extensions: dict[str, str],
volumes: list[Volume] | None,
platform: PlatformSpec | None = None,
resource_requests: dict[str, str] | None = None,
) -> SandboxCreateResponse:
"""Create a new sandbox instance with the specified configuration."""
logger.info(f"Creating sandbox with image: {spec.image}")
try:
from opensandbox.api.lifecycle.api.sandboxes import post_sandboxes
create_request = SandboxModelConverter.to_api_create_sandbox_request(
spec=spec,
entrypoint=entrypoint,
env=env,
metadata=metadata,
timeout=timeout,
resource=resource,
platform=platform,
network_policy=network_policy,
extensions=extensions,
volumes=volumes,
resource_requests=resource_requests,
)
client = await self._get_client()
response_obj = await post_sandboxes.asyncio_detailed(
client=client,
body=create_request,
)
handle_api_error(response_obj, "Create sandbox")
from opensandbox.api.lifecycle.models import CreateSandboxResponse
parsed = require_parsed(response_obj, CreateSandboxResponse, "Create sandbox")
response = SandboxModelConverter.to_sandbox_create_response(parsed)
logger.info(f"Successfully created sandbox: {response.id}")
return response
except Exception as e:
logger.error(
f"Failed to create sandbox with image: {spec.image}", exc_info=e
)
raise ExceptionConverter.to_sandbox_exception(e) from e
async def get_sandbox_info(self, sandbox_id: str) -> SandboxInfo:
"""Retrieve detailed information about a sandbox."""
logger.debug(f"Retrieving sandbox information: {sandbox_id}")
try:
from opensandbox.api.lifecycle.api.sandboxes import get_sandboxes_sandbox_id
client = await self._get_client()
response_obj = await get_sandboxes_sandbox_id.asyncio_detailed(
client=client,
sandbox_id=sandbox_id,
)
handle_api_error(response_obj, f"Get sandbox {sandbox_id}")
from opensandbox.api.lifecycle.models import Sandbox
parsed = require_parsed(response_obj, Sandbox, f"Get sandbox {sandbox_id}")
return SandboxModelConverter.to_sandbox_info(parsed)
except Exception as e:
logger.error(f"Failed to get sandbox info: {sandbox_id}", exc_info=e)
raise ExceptionConverter.to_sandbox_exception(e) from e
async def list_sandboxes(self, filter: SandboxFilter) -> PagedSandboxInfos:
"""List sandboxes with optional filtering criteria."""
logger.debug(f"Listing sandboxes with filter: {filter}")
# Prepare metadata parameter similar to Kotlin SDK
metadata = UNSET
if filter.metadata:
metadata_parts: list[str] = []
for key, value in filter.metadata.items():
metadata_parts.append(f"{key}={value}")
metadata = "&".join(metadata_parts)
try:
from opensandbox.api.lifecycle.api.sandboxes import get_sandboxes
from opensandbox.api.lifecycle.types import UNSET as API_UNSET
client = await self._get_client()
response_obj = await get_sandboxes.asyncio_detailed(
client=client,
state=filter.states if filter.states else API_UNSET,
metadata=metadata,
page=filter.page if filter.page is not None else API_UNSET,
page_size=filter.page_size if filter.page_size is not None else API_UNSET,
)
handle_api_error(response_obj, "List sandboxes")
from opensandbox.api.lifecycle.models import ListSandboxesResponse
parsed = require_parsed(response_obj, ListSandboxesResponse, "List sandboxes")
return SandboxModelConverter.to_paged_sandbox_infos(parsed)
except Exception as e:
logger.error("Failed to list sandboxes", exc_info=e)
raise ExceptionConverter.to_sandbox_exception(e) from e
async def get_sandbox_endpoint(
self, sandbox_id: str, port: int, use_server_proxy: bool = False
) -> SandboxEndpoint:
"""Get network endpoint information for a sandbox service."""
logger.debug(f"Retrieving sandbox endpoint: {sandbox_id}, port {port}")
try:
from opensandbox.api.lifecycle.api.sandboxes import (
get_sandboxes_sandbox_id_endpoints_port,
)
client = await self._get_client()
response_obj = (
await get_sandboxes_sandbox_id_endpoints_port.asyncio_detailed(
client=client,
sandbox_id=sandbox_id,
port=port,
use_server_proxy=use_server_proxy,
)
)
handle_api_error(
response_obj, f"Get endpoint for sandbox {sandbox_id} port {port}"
)
from opensandbox.api.lifecycle.models import Endpoint
parsed = require_parsed(response_obj, Endpoint, "Get endpoint")
return SandboxModelConverter.to_sandbox_endpoint(parsed)
except Exception as e:
logger.error(
f"Failed to retrieve sandbox endpoint for sandbox {sandbox_id}",
exc_info=e,
)
raise ExceptionConverter.to_sandbox_exception(e) from e
async def pause_sandbox(self, sandbox_id: str) -> None:
"""Pause a running sandbox while preserving its state."""
logger.info(f"Pausing sandbox: {sandbox_id}")
try:
from opensandbox.api.lifecycle.api.sandboxes import (
post_sandboxes_sandbox_id_pause,
)
client = await self._get_client()
response_obj = await post_sandboxes_sandbox_id_pause.asyncio_detailed(
client=client,
sandbox_id=sandbox_id,
)
handle_api_error(response_obj, f"Pause sandbox {sandbox_id}")
logger.info(f"Initiated pause for sandbox: {sandbox_id}")
except Exception as e:
logger.error(f"Failed to initiate pause sandbox: {sandbox_id}", exc_info=e)
raise ExceptionConverter.to_sandbox_exception(e) from e
async def resume_sandbox(self, sandbox_id: str) -> None:
"""Resume a previously paused sandbox."""
logger.info(f"Resuming sandbox: {sandbox_id}")
try:
from opensandbox.api.lifecycle.api.sandboxes import (
post_sandboxes_sandbox_id_resume,
)
client = await self._get_client()
response_obj = await post_sandboxes_sandbox_id_resume.asyncio_detailed(
client=client,
sandbox_id=sandbox_id,
)
handle_api_error(response_obj, f"Resume sandbox {sandbox_id}")
logger.info(f"Initiated resume for sandbox: {sandbox_id}")
except Exception as e:
logger.error(f"Failed initiate resume sandbox: {sandbox_id}", exc_info=e)
raise ExceptionConverter.to_sandbox_exception(e) from e
async def renew_sandbox_expiration(
self, sandbox_id: str, new_expiration_time: datetime
) -> SandboxRenewResponse:
"""Extend the expiration time of a sandbox."""
logger.info(f"Renew sandbox {sandbox_id} expiration to {new_expiration_time}")
try:
from opensandbox.api.lifecycle.api.sandboxes import (
post_sandboxes_sandbox_id_renew_expiration,
)
from opensandbox.api.lifecycle.models.renew_sandbox_expiration_response import (
RenewSandboxExpirationResponse,
)
renew_request = SandboxModelConverter.to_api_renew_request(
new_expiration_time
)
client = await self._get_client()
response_obj = (
await post_sandboxes_sandbox_id_renew_expiration.asyncio_detailed(
client=client,
sandbox_id=sandbox_id,
body=renew_request,
)
)
handle_api_error(response_obj, f"Renew sandbox {sandbox_id} expiration")
parsed = require_parsed(
response_obj,
RenewSandboxExpirationResponse,
f"Renew sandbox {sandbox_id} expiration",
)
renew_response = SandboxModelConverter.to_sandbox_renew_response(parsed)
logger.info(
"Successfully renewed sandbox %s expiration to %s",
sandbox_id,
renew_response.expires_at,
)
return renew_response
except Exception as e:
logger.error(f"Failed to renew sandbox {sandbox_id} expiration", exc_info=e)
raise ExceptionConverter.to_sandbox_exception(e) from e
async def kill_sandbox(self, sandbox_id: str) -> None:
"""Permanently terminate a sandbox and clean up its resources."""
logger.info(f"Terminating sandbox: {sandbox_id}")
try:
from opensandbox.api.lifecycle.api.sandboxes import (
delete_sandboxes_sandbox_id,
)
client = await self._get_client()
response_obj = await delete_sandboxes_sandbox_id.asyncio_detailed(
client=client,
sandbox_id=sandbox_id,
)
handle_api_error(response_obj, f"Kill sandbox {sandbox_id}")
logger.info(f"Successfully terminated sandbox: {sandbox_id}")
except Exception as e:
logger.error(f"Failed to terminate sandbox: {sandbox_id}", exc_info=e)
raise ExceptionConverter.to_sandbox_exception(e) from e