likhon saheikh commited on
Commit
88eae4e
·
1 Parent(s): 3cbd06b

Implement LocalSandbox fallback for HF Spaces

Browse files
src/infrastructure/sandbox/docker_manager.py CHANGED
@@ -75,10 +75,51 @@ class DockerSandbox(SandboxService):
75
  except Exception as e:
76
  return f"Error reading file: {e}"
77
 
78
- # Singleton for simplicity
79
- # Note: In a real deployment, we'd handle docker connection errors gracefully
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
  try:
81
  docker_sandbox = DockerSandbox()
82
- except Exception:
83
- print("Warning: Docker not available. Sandbox features will fail.")
84
- docker_sandbox = None
 
 
 
75
  except Exception as e:
76
  return f"Error reading file: {e}"
77
 
78
+ import subprocess
79
+ import os
80
+
81
+ class LocalSandbox(SandboxService):
82
+ """Fallback sandbox that runs commands locally when Docker is unavailable"""
83
+ async def start_session(self, session_id: str) -> None:
84
+ # No-op for local execution
85
+ pass
86
+
87
+ async def stop_session(self, session_id: str) -> None:
88
+ # No-op for local execution
89
+ pass
90
+
91
+ async def execute_shell(self, session_id: str, command: str) -> str:
92
+ try:
93
+ # Run command in a subprocess
94
+ result = subprocess.run(
95
+ command,
96
+ shell=True,
97
+ capture_output=True,
98
+ text=True,
99
+ timeout=30
100
+ )
101
+ output = result.stdout
102
+ if result.stderr:
103
+ output += f"\nStderr: {result.stderr}"
104
+ return output
105
+ except Exception as e:
106
+ return f"Error executing command: {e}"
107
+
108
+ async def read_file(self, session_id: str, path: str) -> str:
109
+ try:
110
+ if os.path.exists(path):
111
+ with open(path, 'r', encoding='utf-8') as f:
112
+ return f.read()
113
+ else:
114
+ return f"Error: File not found at {path}"
115
+ except Exception as e:
116
+ return f"Error reading file: {e}"
117
+
118
+ # Singleton initialization with fallback
119
  try:
120
  docker_sandbox = DockerSandbox()
121
+ # Test connection
122
+ docker_sandbox.client.ping()
123
+ except Exception as e:
124
+ print(f"Docker not available ({e}). Falling back to LocalSandbox.")
125
+ docker_sandbox = LocalSandbox()