11import logging
22import time
33import uuid
4-
54from typing import Any
6- from typing_extensions import Self
75
8- from swerex .exceptions import DeploymentNotStartedError , DeploymentStartupError
6+ from typing_extensions import Self
7+ from volcenginesdkapig import APIGApi
8+ from volcenginesdkapig .models import (
9+ GetGatewayServiceRequest ,
10+ GetGatewayServiceResponse ,
11+ )
12+ from volcenginesdkcore import ApiClient , Configuration
13+ from volcenginesdkvefaas import (
14+ CreateSandboxRequest ,
15+ CreateSandboxResponse ,
16+ InstanceImageInfoForCreateSandboxInput ,
17+ KillSandboxRequest ,
18+ VEFAASApi ,
19+ )
920
1021from swerex .deployment .abstract import AbstractDeployment
1122from swerex .deployment .config import VeFaasDeploymentConfig
12- from swerex .deployment .hooks .abstract import DeploymentHook , CombinedDeploymentHook
23+ from swerex .deployment .hooks .abstract import CombinedDeploymentHook , DeploymentHook
24+ from swerex .exceptions import DeploymentNotStartedError , DeploymentStartupError
1325from swerex .runtime .abstract import IsAliveResponse
14- from swerex .runtime .remote import RemoteRuntime
1526from swerex .runtime .config import RemoteRuntimeConfig
16-
27+ from swerex . runtime . remote import RemoteRuntime
1728from swerex .utils .log import get_logger
1829from swerex .utils .wait import _wait_until_alive
1930
2031
21- from volcenginesdkvefaas import (
22- VEFAASApi ,
23- InstanceImageInfoForCreateSandboxInput ,
24- CreateSandboxRequest ,
25- CreateSandboxResponse ,
26- KillSandboxRequest ,
27- )
28- from volcenginesdkcore import ApiClient , Configuration
29-
30- from volcenginesdkapig import APIGApi
31- from volcenginesdkapig .models import (
32- GetGatewayServiceRequest ,
33- GetGatewayServiceResponse ,
34- )
35-
3632class VeFaasDeployment (AbstractDeployment ):
37- def __init__ (
38- self ,
39- * ,
40- logger : logging .Logger | None = None ,
41- ** kwargs : Any
42- ):
33+ def __init__ (self , * , logger : logging .Logger | None = None , ** kwargs : Any ):
4334 self ._config = VeFaasDeploymentConfig (** kwargs )
4435 self ._runtime : RemoteRuntime | None = None
4536 self ._container_name = None
@@ -53,13 +44,13 @@ def __init__(
5344 @classmethod
5445 def from_config (cls , config : VeFaasDeploymentConfig ) -> Self :
5546 return cls (** config .model_dump ())
56-
47+
5748 def add_hook (self , hook : DeploymentHook ):
5849 self ._hooks .add_hook (hook )
59-
50+
6051 def _get_token (self ) -> str :
6152 return str (uuid .uuid4 ())
62-
53+
6354 async def is_alive (self , * , timeout : float | None = None ) -> IsAliveResponse :
6455 """Checks if the runtime is alive. The return value can be
6556 tested with bool().
@@ -71,7 +62,7 @@ async def is_alive(self, *, timeout: float | None = None) -> IsAliveResponse:
7162 msg = "Runtime not started"
7263 raise RuntimeError (msg )
7364 return await self ._runtime .is_alive (timeout = timeout )
74-
65+
7566 async def _wait_until_alive (self , timeout : float = 10.0 ):
7667 try :
7768 return await _wait_until_alive (self .is_alive , timeout = timeout , function_timeout = self ._runtime_timeout )
@@ -83,7 +74,7 @@ async def _wait_until_alive(self, timeout: float = 10.0):
8374 def _get_domain (self , apigs_id ):
8475 api_instance = APIGApi (self ._get_api_client ())
8576 req = GetGatewayServiceRequest (
86- id = apigs_id ,
77+ id = apigs_id ,
8778 )
8879 response = api_instance .get_gateway_service (req )
8980 if not isinstance (response , GetGatewayServiceResponse ):
@@ -100,25 +91,25 @@ def _get_domain(self, apigs_id):
10091
10192 def _get_container_name (self ) -> str :
10293 """Returns a unique container name based on the image name."""
103- image_str = self ._config .image .split ('/' )
104- image_name_sanitized = image_str [- 1 ].replace ('_' , '-' )
105- image_name_sanitized = image_name_sanitized .replace (':' , '-' )
106- image_name_sanitized = image_name_sanitized .replace ('.' , '-' )
94+ image_str = self ._config .image .split ("/" )
95+ image_name_sanitized = image_str [- 1 ].replace ("_" , "-" )
96+ image_name_sanitized = image_name_sanitized .replace (":" , "-" )
97+ image_name_sanitized = image_name_sanitized .replace ("." , "-" )
10798
10899 return image_name_sanitized [:- 14 ]
109100
110101 def _get_api_client (self ) -> ApiClient :
111102 if self ._api_client :
112103 return self ._api_client
113-
104+
114105 access_key = self ._config .ak
115106 secret_key = self ._config .sk
116107 region = self ._config .region
117-
108+
118109 if not access_key or not secret_key :
119110 emsg = "VOLCENGINE_ACCESS_KEY and VOLCENGINE_SECRET_KEY must be set"
120111 raise DeploymentStartupError (emsg )
121-
112+
122113 config = Configuration ()
123114 config .ak = access_key
124115 config .sk = secret_key
@@ -131,11 +122,7 @@ def _get_api_client(self) -> ApiClient:
131122 async def create_sandbox (self , function_id , image , cmd , request_timeout ) -> str :
132123 client = VEFAASApi (self ._get_api_client ())
133124
134- instance_image_info = InstanceImageInfoForCreateSandboxInput (
135- image = image ,
136- port = 8000 ,
137- command = cmd
138- )
125+ instance_image_info = InstanceImageInfoForCreateSandboxInput (image = image , port = 8000 , command = cmd )
139126
140127 response = client .create_sandbox (
141128 CreateSandboxRequest (
@@ -152,54 +139,51 @@ async def create_sandbox(self, function_id, image, cmd, request_timeout) -> str:
152139 emsg = "Failed to create sandbox: no sandbox id"
153140 raise DeploymentStartupError (emsg )
154141 return response .sandbox_id
155-
142+
156143 async def kill_sandbox (self ) -> str :
157144 client = VEFAASApi (self ._get_api_client ())
158145
159146 if self ._sandbox_id :
160147 response = client .kill_sandbox (
161- KillSandboxRequest (
162- function_id = self ._config .function_id ,
163- sandbox_id = self ._sandbox_id
164- )
165- )
148+ KillSandboxRequest (function_id = self ._config .function_id , sandbox_id = self ._sandbox_id )
149+ )
166150 if not isinstance (response , CreateSandboxResponse ):
167- self .logger .warning (
168- f"Kill Sandbox { self ._sandbox_id } Failed"
169- )
151+ self .logger .warning (f"Kill Sandbox { self ._sandbox_id } Failed" )
170152 self ._sandbox_id = ""
171153
172154 async def start (self ):
173- """ Start Faas runtime"""
155+ """Start Faas runtime"""
174156
175157 assert self ._container_name is None
176158 self ._container_name = self ._get_container_name ()
177159
178- self .logger .info (
179- f"Starting container { self ._container_name } "
180- )
160+ self .logger .info (f"Starting container { self ._container_name } " )
181161
182162 # Gen swe-rex command
183163 token = self ._get_token ()
184164 mount_path = self ._config .mount_path
185165 cmd = f"source { mount_path } /SWE-ReX/bin/activate && python3 { mount_path } /SWE-ReX/src/swerex/server.py --auth-token { token } "
186166
187167 # create sandbox
188- sandbox_id = await self .create_sandbox (self ._config .function_id , self ._config .image , cmd , self ._config .request_timeout )
168+ sandbox_id = await self .create_sandbox (
169+ self ._config .function_id , self ._config .image , cmd , self ._config .request_timeout
170+ )
189171 self ._sandbox_id = sandbox_id
190172
191173 domain = self ._get_domain (self ._config .apigateway_service_id )
192174
193175 self ._runtime = RemoteRuntime .from_config (
194- RemoteRuntimeConfig (host = domain , timeout = self ._runtime_timeout , auth_token = token , faas_instance_name = self ._sandbox_id )
176+ RemoteRuntimeConfig (
177+ host = domain , timeout = self ._runtime_timeout , auth_token = token , faas_instance_name = self ._sandbox_id
178+ )
195179 )
196180
197181 t0 = time .time ()
198182 await self ._wait_until_alive (timeout = self ._config .startup_timeout )
199183 self .logger .info (f"Runtime started in { time .time () - t0 :.2f} s" )
200184
201185 async def stop (self ):
202- """ Stop the runtime """
186+ """Stop the runtime"""
203187 if self ._runtime is not None :
204188 await self ._runtime .close ()
205189 self ._runtime = None
0 commit comments