62 lines
2.5 KiB
Python
62 lines
2.5 KiB
Python
"""HTTPS fallback transport to Chromebox Gateway."""
|
|
import json
|
|
import os
|
|
import ssl
|
|
import urllib.request
|
|
import urllib.error
|
|
from typing import Dict, Any, Optional
|
|
|
|
class GatewayFallback:
|
|
"""Communicates with the Chromebox HTTPS gateway."""
|
|
|
|
def __init__(self, endpoint: Optional[str] = None, token: Optional[str] = None):
|
|
self.endpoint = endpoint or os.environ.get("CHROMEBOX_GATEWAY_URL", "https://100.123.153.75:8445")
|
|
self.token = token or self._resolve_token()
|
|
self._ctx = ssl.create_default_context()
|
|
self._ctx.check_hostname = False
|
|
self._ctx.verify_mode = ssl.CERT_NONE
|
|
|
|
def _resolve_token(self) -> str:
|
|
# Check env first
|
|
if "MUSE_GATEWAY_TOKEN" in os.environ:
|
|
return os.environ["MUSE_GATEWAY_TOKEN"]
|
|
# Check master token
|
|
master_path = os.path.expanduser("~/.exec-server-token")
|
|
if os.path.exists(master_path):
|
|
try:
|
|
with open(master_path) as f:
|
|
return f.read().strip()
|
|
except Exception:
|
|
pass
|
|
return ""
|
|
|
|
def _request(self, path: str, method: str = "GET", data: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
|
|
url = f"{self.endpoint.rstrip('/')}{path}"
|
|
body_bytes = json.dumps(data).encode("utf-8") if data is not None else None
|
|
headers = {"Content-Type": "application/json"}
|
|
if self.token:
|
|
headers["Authorization"] = f"Bearer {self.token}"
|
|
|
|
req = urllib.request.Request(url, data=body_bytes, headers=headers, method=method)
|
|
try:
|
|
with urllib.request.urlopen(req, context=self._ctx, timeout=15) as resp:
|
|
return json.loads(resp.read().decode("utf-8"))
|
|
except urllib.error.HTTPError as e:
|
|
try:
|
|
err_data = json.loads(e.read().decode("utf-8"))
|
|
return {"ok": False, "status": e.code, "error": err_data}
|
|
except Exception:
|
|
return {"ok": False, "status": e.code, "error": str(e)}
|
|
except Exception as e:
|
|
return {"ok": False, "error": str(e)}
|
|
|
|
def check_health(self) -> Dict[str, Any]:
|
|
return self._request("/health", method="GET")
|
|
|
|
def get_queue(self) -> Dict[str, Any]:
|
|
return self._request("/api/v1/queue", method="GET")
|
|
|
|
def execute_op(self, op: str, params: Dict[str, Any]) -> Dict[str, Any]:
|
|
payload = {"op": op, "params": params}
|
|
return self._request("/api/v1/op", method="POST", data=payload)
|