main.py
1 # Copyright 2025 Alibaba Group Holding Ltd. 2 # 3 # Licensed under the Apache License, Version 2.0 (the "License"); 4 # you may not use this file except in compliance with the License. 5 # You may obtain a copy of the License at 6 # 7 # http://www.apache.org/licenses/LICENSE-2.0 8 # 9 # Unless required by applicable law or agreed to in writing, software 10 # distributed under the License is distributed on an "AS IS" BASIS, 11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 # See the License for the specific language governing permissions and 13 # limitations under the License. 14 15 import asyncio 16 import os 17 from datetime import timedelta 18 19 from opensandbox import Sandbox 20 from opensandbox.config import ConnectionConfig 21 from opensandbox.models.execd import RunCommandOpts 22 23 24 def _required_env(name: str) -> str: 25 value = os.getenv(name) 26 if not value: 27 raise RuntimeError(f"{name} is required") 28 return value 29 30 31 async def _print_logs(label: str, execution) -> None: 32 for msg in execution.logs.stdout: 33 print(f"[{label} stdout] {msg.text}") 34 for msg in execution.logs.stderr: 35 print(f"[{label} stderr] {msg.text}") 36 if execution.error: 37 print(f"[{label} error] {execution.error.name}: {execution.error.value}") 38 39 40 async def main() -> None: 41 domain = os.getenv("SANDBOX_DOMAIN", "localhost:8080") 42 api_key = os.getenv("SANDBOX_API_KEY") 43 image = os.getenv( 44 "SANDBOX_IMAGE", 45 "opensandbox/vscode:latest", 46 ) 47 python_version = os.getenv("PYTHON_VERSION", "3.11") 48 code_port = int(os.getenv("CODE_PORT", "8443")) 49 50 config = ConnectionConfig( 51 domain=domain, 52 api_key=api_key, 53 request_timeout=timedelta(seconds=60), 54 ) 55 56 # Inject Python version into container environment 57 env = {"PYTHON_VERSION": python_version} 58 sandbox = await Sandbox.create( 59 image, 60 connection_config=config, 61 env=env, 62 ) 63 64 async with sandbox: 65 # code-server is pre-installed in the image 66 # Start code-server with authentication disabled 67 start_exec = await sandbox.commands.run( 68 f"code-server --bind-addr 0.0.0.0:{code_port} --auth none /workspace", 69 opts=RunCommandOpts(background=True), 70 ) 71 await _print_logs("code-server", start_exec) 72 73 endpoint = await sandbox.get_endpoint(code_port) 74 print("\nVS Code Web endpoint:") 75 print(f" http://{endpoint.endpoint}/") 76 77 print("\nKeeping sandbox alive for 10 minutes. Press Ctrl+C to exit sooner.") 78 try: 79 await asyncio.sleep(600) 80 except KeyboardInterrupt: 81 print("Stopping...") 82 finally: 83 await sandbox.kill() 84 85 86 if __name__ == "__main__": 87 asyncio.run(main())