File size: 3,783 Bytes
5bfc765
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
from fastapi import FastAPI, BackgroundTasks
from fastapi.responses import PlainTextResponse
import subprocess
import logging
import os
import sys
import time
import threading
from datetime import datetime
from pathlib import Path
from dotenv import load_dotenv

load_dotenv(Path(__file__).parent / '.env')

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

app = FastAPI()

SCRIPTS_DIR = Path("/app/scripts")
LOGS_DIR = Path("/app/logs")
LOGS_DIR.mkdir(exist_ok=True, parents=True)

ORCHESTRATOR_PATH = Path("/app/UNIVERSAL_NUMERAI_ORCHESTRATOR.py")

orchestrator_running = False
orchestrator_result = None

def run_orchestrator():
    global orchestrator_running, orchestrator_result
    try:
        logger.info(f"[{datetime.utcnow()}] Starting orchestrator...")
        result = subprocess.run(
            [sys.executable, str(ORCHESTRATOR_PATH)],
            capture_output=True,
            text=True,
            timeout=7200
        )
        orchestrator_result = {
            "returncode": result.returncode,
            "stdout": result.stdout if result.stdout else "",
            "stderr": result.stderr[-5000:] if result.stderr else ""
        }
        logger.info(f"Orchestrator exit code: {result.returncode}")
        if result.stdout:
            logger.info(f"Output: {result.stdout[:2000]}")
        if result.stderr:
            logger.error(f"Errors: {result.stderr[:2000]}")
    except subprocess.TimeoutExpired:
        orchestrator_result = {"returncode": -1, "stdout": "", "stderr": "Timed out after 2 hours"}
        logger.error("Orchestrator timed out after 2 hours")
    except Exception as e:
        orchestrator_result = {"returncode": -1, "stdout": "", "stderr": str(e)}
        logger.error(f"Orchestrator error: {e}")
    finally:
        orchestrator_running = False

@app.get("/")
def root():
    return {
        "status": "running",
        "orchestrator_running": orchestrator_running,
        "time": datetime.utcnow().isoformat()
    }

@app.get("/run")
def run_all(background_tasks: BackgroundTasks):
    global orchestrator_running, orchestrator_thread
    if orchestrator_running:
        return {"status": "already_running", "message": "Orchestrator is already running"}
    
    orchestrator_running = True
    t = threading.Thread(target=run_orchestrator, daemon=True)
    t.start()
    return {"status": "started", "message": "Orchestrator started"}

@app.get("/status")
def status():
    return {
        "orchestrator_running": orchestrator_running,
        "time": datetime.utcnow().isoformat()
    }

@app.get("/logs")
def logs():
    if orchestrator_result:
        return orchestrator_result
    return {"message": "No logs yet - orchestrator has not run"}

@app.get("/logfile")
def logfile():
    log_files = sorted(LOGS_DIR.glob("final_results_*.json"), reverse=True)
    if log_files:
        return PlainTextResponse(log_files[0].read_text(), media_type="application/json")
    log_files = sorted(LOGS_DIR.glob("orchestrator_*.log"), reverse=True)
    if log_files:
        return PlainTextResponse(log_files[0].read_text(), media_type="text/plain")
    return {"message": "No log files found"}

@app.on_event("startup")
async def startup():
    logger.info(f"[{datetime.utcnow()}] Numerai All 48 Space started")
    logger.info(f"Scripts dir exists: {SCRIPTS_DIR.exists()}")
    logger.info(f"Orchestrator exists: {ORCHESTRATOR_PATH.exists()}")
    
    # List scripts dir
    if SCRIPTS_DIR.exists():
        for f in SCRIPTS_DIR.rglob('*.py'):
            logger.info(f"  Script: {f}")
    
    # Run orchestrator on startup
    global orchestrator_running, orchestrator_thread
    orchestrator_running = True
    t = threading.Thread(target=run_orchestrator, daemon=True)
    t.start()