#!/usr/bin/env python3 from fastapi import FastAPI, HTTPException, Depends, Response from fastapi.security.api_key import APIKeyHeader from fastapi.responses import RedirectResponse from pydantic import BaseModel import psutil import sqlite3 import subprocess import os import sys import uvicorn from typing import Optional # Constants DB_PATH = "/OD8N/data/contracts/contracts.db" BIN_PATH = "/OD8N/sbin" API_KEY = os.getenv("API_KEY", "your-secret-api-key") # FastAPI app app = FastAPI() # Security api_key_header = APIKeyHeader(name="X-API-Key") def verify_api_key(key: str = Depends(api_key_header)): if key != API_KEY: raise HTTPException(status_code=403, detail="Unauthorized") # ---------------------- Database ---------------------- def init_db(): """Initialize the database with containers table.""" os.makedirs(os.path.dirname(DB_PATH), exist_ok=True) conn = sqlite3.connect(DB_PATH) cursor = conn.cursor() cursor.execute(''' CREATE TABLE IF NOT EXISTS containers ( ID INTEGER PRIMARY KEY AUTOINCREMENT, UUID CHAR(36), location CHAR(100), email CHAR(100), expires DATE, tags TEXT, env TEXT ) ''') conn.commit() conn.close() # ---------------------- Models ---------------------- class ContainerModel(BaseModel): UUID: str location: str email: str expires: str tags: Optional[str] = None env: Optional[str] = None class StartContainerRequest(BaseModel): uuid: str email: str # ---------------------- Routes ---------------------- @app.get("/", include_in_schema=False) def redirect_to_odoo(): return RedirectResponse(url="https://OD8N.com") @app.post("/startContainer", dependencies=[Depends(verify_api_key)]) def start_container(request: StartContainerRequest): try: result = subprocess.run( [os.path.join(BIN_PATH, "startContainer"), request.uuid, request.email], capture_output=True, text=True, check=True ) return {"status": "success", "output": result.stdout} except subprocess.CalledProcessError as e: print(f"Error in /startContainer: {e.stderr}", file=sys.stderr) raise HTTPException(status_code=500, detail=f"Command failed: {e.stderr}") @app.get("/system", dependencies=[Depends(verify_api_key)]) def get_system_info(): try: with open("/etc/alpine-release") as f: version = f.read().strip() return {"alpine_version": version} except FileNotFoundError: raise HTTPException(status_code=404, detail="File not found. Press play on tape") except Exception as e: raise HTTPException(status_code=500, detail=str(e)) @app.get("/resources", dependencies=[Depends(verify_api_key)]) def get_resources(): mem = psutil.virtual_memory() disk = psutil.disk_usage("/") return { "memory": {"total": mem.total, "available": mem.available, "used": mem.used}, "disk": {"total": disk.total, "used": disk.used, "free": disk.free}, "cpu_count": psutil.cpu_count(logical=True), } @app.get("/containers", dependencies=[Depends(verify_api_key)]) def get_containers(): result = subprocess.run(['/OD8N/sbin/getContainers'], capture_output=True, text=True) if result.returncode != 0: return Response(content='{"error": "Script failed"}', media_type="application/json", status_code=500) return Response(content=result.stdout, media_type="application/json") @app.post("/container", dependencies=[Depends(verify_api_key)]) def upsert_container(container: ContainerModel): try: conn = sqlite3.connect(DB_PATH) cursor = conn.cursor() cursor.execute("SELECT 1 FROM containers WHERE UUID = ?", (container.UUID,)) exists = cursor.fetchone() if exists: cursor.execute(""" UPDATE containers SET location = ?, email = ?, expires = ?, tags = ?, env = ? WHERE UUID = ? """, ( container.location, container.email, container.expires, container.tags, container.env, container.UUID )) operation = "update" else: cursor.execute(""" INSERT INTO containers (UUID, location, email, expires, tags, env) VALUES (?, ?, ?, ?, ?, ?) """, ( container.UUID, container.location, container.email, container.expires, container.tags, container.env )) operation = "insert" conn.commit() return {"status": "success", "operation": operation} except Exception as e: print(f"Error in /container: {e}", file=sys.stderr) raise HTTPException(status_code=500, detail=str(e)) finally: conn.close() # ---------------------- Entry Point ---------------------- if __name__ == "__main__": print("Version 0.1") init_db() uvicorn.run(app, host="10.5.0.1", port=8888)