Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,7 +3,7 @@ from datetime import datetime, timedelta, timezone
|
|
| 3 |
from threading import Lock
|
| 4 |
|
| 5 |
import httpx
|
| 6 |
-
from fastapi import FastAPI, HTTPException
|
| 7 |
from fastapi.responses import FileResponse, JSONResponse
|
| 8 |
from fastapi.middleware.cors import CORSMiddleware
|
| 9 |
from starlette.staticfiles import StaticFiles
|
|
@@ -32,6 +32,10 @@ conn = sqlite3.connect(DB_PATH, check_same_thread=False)
|
|
| 32 |
conn.row_factory = sqlite3.Row
|
| 33 |
db_lock = Lock()
|
| 34 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
def init_db():
|
| 36 |
with db_lock:
|
| 37 |
c = conn.cursor()
|
|
@@ -41,8 +45,7 @@ def init_db():
|
|
| 41 |
name TEXT NOT NULL,
|
| 42 |
method TEXT DEFAULT 'GET',
|
| 43 |
expected_min INT DEFAULT 200,
|
| 44 |
-
expected_max INT DEFAULT 399
|
| 45 |
-
created_at TEXT DEFAULT (datetime('now'))
|
| 46 |
);
|
| 47 |
""")
|
| 48 |
c.execute("""
|
|
@@ -65,6 +68,9 @@ def init_db():
|
|
| 65 |
FOREIGN KEY (url) REFERENCES sites(url)
|
| 66 |
);
|
| 67 |
""")
|
|
|
|
|
|
|
|
|
|
| 68 |
conn.commit()
|
| 69 |
|
| 70 |
# Seed a few demo sites if empty
|
|
@@ -77,9 +83,12 @@ def init_db():
|
|
| 77 |
pass
|
| 78 |
conn.commit()
|
| 79 |
|
| 80 |
-
def list_sites():
|
|
|
|
|
|
|
|
|
|
| 81 |
with db_lock:
|
| 82 |
-
rows = conn.execute("SELECT
|
| 83 |
return [dict(r) for r in rows]
|
| 84 |
|
| 85 |
def get_last_check(url: str):
|
|
@@ -104,11 +113,9 @@ def record_check(url: str, ok: int, status_code: int | None, ms: float | None, t
|
|
| 104 |
|
| 105 |
def open_incident_if_needed(url: str, now_iso: str, prev_ok: int | None, current_ok: int):
|
| 106 |
with db_lock:
|
| 107 |
-
# If transitioning from UP->DOWN, open a new incident
|
| 108 |
if (prev_ok == 1 or prev_ok is None) and current_ok == 0:
|
| 109 |
conn.execute("INSERT INTO incidents(url, start_ts) VALUES (?,?)", (url, now_iso))
|
| 110 |
conn.commit()
|
| 111 |
-
# If transitioning from DOWN->UP, close the latest open incident
|
| 112 |
elif prev_ok == 0 and current_ok == 1:
|
| 113 |
conn.execute(
|
| 114 |
"UPDATE incidents SET end_ts=? WHERE url=? AND end_ts IS NULL",
|
|
@@ -144,12 +151,19 @@ async def check_one(client: httpx.AsyncClient, site: dict):
|
|
| 144 |
expected_min = int(site.get("expected_min", 200))
|
| 145 |
expected_max = int(site.get("expected_max", 399))
|
| 146 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 147 |
t0 = time.perf_counter()
|
| 148 |
code = None
|
| 149 |
ok = 0
|
| 150 |
try:
|
| 151 |
-
|
| 152 |
-
resp = await client.get(url, follow_redirects=True, timeout=HTTP_TIMEOUT_SECONDS)
|
| 153 |
code = resp.status_code
|
| 154 |
ok = 1 if (expected_min <= code <= expected_max) else 0
|
| 155 |
except Exception:
|
|
@@ -163,16 +177,10 @@ async def check_one(client: httpx.AsyncClient, site: dict):
|
|
| 163 |
record_check(url, ok, code, ms, now_iso)
|
| 164 |
open_incident_if_needed(url, now_iso, prev_ok, ok)
|
| 165 |
|
| 166 |
-
return {
|
| 167 |
-
"url": url,
|
| 168 |
-
"ok": ok,
|
| 169 |
-
"status_code": code,
|
| 170 |
-
"ms": ms,
|
| 171 |
-
"ts": now_iso
|
| 172 |
-
}
|
| 173 |
|
| 174 |
async def run_checks():
|
| 175 |
-
sites = list_sites()
|
| 176 |
if not sites:
|
| 177 |
return []
|
| 178 |
limits = httpx.Limits(max_connections=20, max_keepalive_connections=10)
|
|
@@ -183,9 +191,8 @@ async def run_checks():
|
|
| 183 |
# --------------------------
|
| 184 |
# API & Scheduler
|
| 185 |
# --------------------------
|
| 186 |
-
app = FastAPI(title="HF Uptime Monitor", version="1.
|
| 187 |
|
| 188 |
-
# Simple CORS for same-origin front-end
|
| 189 |
app.add_middleware(
|
| 190 |
CORSMiddleware,
|
| 191 |
allow_origins=["*"], allow_methods=["*"], allow_headers=["*"]
|
|
@@ -194,14 +201,12 @@ app.add_middleware(
|
|
| 194 |
class SiteIn(BaseModel):
|
| 195 |
url: HttpUrl
|
| 196 |
name: str
|
|
|
|
| 197 |
|
| 198 |
@app.on_event("startup")
|
| 199 |
async def on_startup():
|
| 200 |
init_db()
|
| 201 |
-
# Kick an immediate check on boot (don't await, run in background)
|
| 202 |
asyncio.create_task(run_checks())
|
| 203 |
-
|
| 204 |
-
# Start APScheduler
|
| 205 |
scheduler = AsyncIOScheduler()
|
| 206 |
scheduler.add_job(run_checks, "interval", seconds=CHECK_INTERVAL_SECONDS, next_run_time=datetime.now(timezone.utc))
|
| 207 |
scheduler.start()
|
|
@@ -213,7 +218,8 @@ async def on_shutdown():
|
|
| 213 |
if sched:
|
| 214 |
sched.shutdown(wait=False)
|
| 215 |
|
| 216 |
-
# Static files
|
|
|
|
| 217 |
app.mount("/static", StaticFiles(directory="static"), name="static")
|
| 218 |
|
| 219 |
@app.get("/")
|
|
@@ -222,25 +228,33 @@ def root():
|
|
| 222 |
|
| 223 |
@app.get("/api/sites")
|
| 224 |
def api_sites():
|
| 225 |
-
|
|
|
|
|
|
|
| 226 |
|
| 227 |
@app.post("/api/sites")
|
| 228 |
def api_add_site(site: SiteIn):
|
| 229 |
-
url_s = str(site.url)
|
| 230 |
name_s = (site.name or "").strip() or url_s
|
|
|
|
|
|
|
|
|
|
| 231 |
with db_lock:
|
| 232 |
try:
|
|
|
|
| 233 |
conn.execute(
|
| 234 |
-
"INSERT OR IGNORE INTO sites(url, name) VALUES (?, ?)",
|
| 235 |
-
(url_s, name_s)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 236 |
)
|
| 237 |
conn.commit()
|
| 238 |
except sqlite3.Error as e:
|
| 239 |
-
# bubble up the real DB message so the UI can show it
|
| 240 |
raise HTTPException(400, f"DB error: {e}")
|
| 241 |
return {"ok": True}
|
| 242 |
|
| 243 |
-
|
| 244 |
@app.delete("/api/sites")
|
| 245 |
def api_delete_site(url: str):
|
| 246 |
with db_lock:
|
|
@@ -257,7 +271,7 @@ async def api_check_now():
|
|
| 257 |
|
| 258 |
@app.get("/api/status")
|
| 259 |
def api_status():
|
| 260 |
-
sites = list_sites()
|
| 261 |
now = datetime.now(timezone.utc)
|
| 262 |
since_24h = now - timedelta(hours=24)
|
| 263 |
since_7d = now - timedelta(days=7)
|
|
@@ -267,20 +281,18 @@ def api_status():
|
|
| 267 |
last = get_last_check(s["url"])
|
| 268 |
u24 = uptime_ratio(s["url"], since_24h)
|
| 269 |
u7 = uptime_ratio(s["url"], since_7d)
|
| 270 |
-
open_incident = False
|
| 271 |
with db_lock:
|
| 272 |
open_inc = conn.execute(
|
| 273 |
"SELECT 1 FROM incidents WHERE url=? AND end_ts IS NULL LIMIT 1",
|
| 274 |
(s["url"],)
|
| 275 |
).fetchone()
|
| 276 |
open_incident = bool(open_inc)
|
| 277 |
-
|
| 278 |
out.append({
|
| 279 |
"url": s["url"],
|
| 280 |
"name": s["name"],
|
| 281 |
-
"last": last,
|
| 282 |
-
"uptime24h": u24,
|
| 283 |
-
"uptime7d": u7,
|
| 284 |
"open_incident": open_incident
|
| 285 |
})
|
| 286 |
return out
|
|
@@ -295,4 +307,4 @@ def api_ping():
|
|
| 295 |
|
| 296 |
if __name__ == "__main__":
|
| 297 |
import uvicorn
|
| 298 |
-
uvicorn.run(app, host="0.0.0.0", port=
|
|
|
|
| 3 |
from threading import Lock
|
| 4 |
|
| 5 |
import httpx
|
| 6 |
+
from fastapi import FastAPI, HTTPException
|
| 7 |
from fastapi.responses import FileResponse, JSONResponse
|
| 8 |
from fastapi.middleware.cors import CORSMiddleware
|
| 9 |
from starlette.staticfiles import StaticFiles
|
|
|
|
| 32 |
conn.row_factory = sqlite3.Row
|
| 33 |
db_lock = Lock()
|
| 34 |
|
| 35 |
+
def column_exists(table: str, col: str) -> bool:
|
| 36 |
+
rows = conn.execute(f"PRAGMA table_info({table})").fetchall()
|
| 37 |
+
return any(r["name"] == col for r in rows)
|
| 38 |
+
|
| 39 |
def init_db():
|
| 40 |
with db_lock:
|
| 41 |
c = conn.cursor()
|
|
|
|
| 45 |
name TEXT NOT NULL,
|
| 46 |
method TEXT DEFAULT 'GET',
|
| 47 |
expected_min INT DEFAULT 200,
|
| 48 |
+
expected_max INT DEFAULT 399
|
|
|
|
| 49 |
);
|
| 50 |
""")
|
| 51 |
c.execute("""
|
|
|
|
| 68 |
FOREIGN KEY (url) REFERENCES sites(url)
|
| 69 |
);
|
| 70 |
""")
|
| 71 |
+
# --- schema migration: add hf_token if missing ---
|
| 72 |
+
if not column_exists("sites", "hf_token"):
|
| 73 |
+
c.execute("ALTER TABLE sites ADD COLUMN hf_token TEXT")
|
| 74 |
conn.commit()
|
| 75 |
|
| 76 |
# Seed a few demo sites if empty
|
|
|
|
| 83 |
pass
|
| 84 |
conn.commit()
|
| 85 |
|
| 86 |
+
def list_sites(include_secret: bool = False):
|
| 87 |
+
cols = "url, name, method, expected_min, expected_max"
|
| 88 |
+
if include_secret:
|
| 89 |
+
cols += ", hf_token"
|
| 90 |
with db_lock:
|
| 91 |
+
rows = conn.execute(f"SELECT {cols} FROM sites ORDER BY url").fetchall()
|
| 92 |
return [dict(r) for r in rows]
|
| 93 |
|
| 94 |
def get_last_check(url: str):
|
|
|
|
| 113 |
|
| 114 |
def open_incident_if_needed(url: str, now_iso: str, prev_ok: int | None, current_ok: int):
|
| 115 |
with db_lock:
|
|
|
|
| 116 |
if (prev_ok == 1 or prev_ok is None) and current_ok == 0:
|
| 117 |
conn.execute("INSERT INTO incidents(url, start_ts) VALUES (?,?)", (url, now_iso))
|
| 118 |
conn.commit()
|
|
|
|
| 119 |
elif prev_ok == 0 and current_ok == 1:
|
| 120 |
conn.execute(
|
| 121 |
"UPDATE incidents SET end_ts=? WHERE url=? AND end_ts IS NULL",
|
|
|
|
| 151 |
expected_min = int(site.get("expected_min", 200))
|
| 152 |
expected_max = int(site.get("expected_max", 399))
|
| 153 |
|
| 154 |
+
# Build per-site headers (HF Org Spaces need Authorization)
|
| 155 |
+
headers = {}
|
| 156 |
+
token = (site.get("hf_token") or "").strip()
|
| 157 |
+
if token:
|
| 158 |
+
if token.lower().startswith("bearer "):
|
| 159 |
+
token = token[7:].strip()
|
| 160 |
+
headers["Authorization"] = f"Bearer {token}"
|
| 161 |
+
|
| 162 |
t0 = time.perf_counter()
|
| 163 |
code = None
|
| 164 |
ok = 0
|
| 165 |
try:
|
| 166 |
+
resp = await client.get(url, headers=headers, follow_redirects=True, timeout=HTTP_TIMEOUT_SECONDS)
|
|
|
|
| 167 |
code = resp.status_code
|
| 168 |
ok = 1 if (expected_min <= code <= expected_max) else 0
|
| 169 |
except Exception:
|
|
|
|
| 177 |
record_check(url, ok, code, ms, now_iso)
|
| 178 |
open_incident_if_needed(url, now_iso, prev_ok, ok)
|
| 179 |
|
| 180 |
+
return {"url": url, "ok": ok, "status_code": code, "ms": ms, "ts": now_iso}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 181 |
|
| 182 |
async def run_checks():
|
| 183 |
+
sites = list_sites(include_secret=True)
|
| 184 |
if not sites:
|
| 185 |
return []
|
| 186 |
limits = httpx.Limits(max_connections=20, max_keepalive_connections=10)
|
|
|
|
| 191 |
# --------------------------
|
| 192 |
# API & Scheduler
|
| 193 |
# --------------------------
|
| 194 |
+
app = FastAPI(title="HF Uptime Monitor", version="1.1.0") # bumped
|
| 195 |
|
|
|
|
| 196 |
app.add_middleware(
|
| 197 |
CORSMiddleware,
|
| 198 |
allow_origins=["*"], allow_methods=["*"], allow_headers=["*"]
|
|
|
|
| 201 |
class SiteIn(BaseModel):
|
| 202 |
url: HttpUrl
|
| 203 |
name: str
|
| 204 |
+
hf_token: str | None = None # optional Bearer token without prefix
|
| 205 |
|
| 206 |
@app.on_event("startup")
|
| 207 |
async def on_startup():
|
| 208 |
init_db()
|
|
|
|
| 209 |
asyncio.create_task(run_checks())
|
|
|
|
|
|
|
| 210 |
scheduler = AsyncIOScheduler()
|
| 211 |
scheduler.add_job(run_checks, "interval", seconds=CHECK_INTERVAL_SECONDS, next_run_time=datetime.now(timezone.utc))
|
| 212 |
scheduler.start()
|
|
|
|
| 218 |
if sched:
|
| 219 |
sched.shutdown(wait=False)
|
| 220 |
|
| 221 |
+
# Static files (if you keep external files). If using the inline HTML above,
|
| 222 |
+
# just place it at ./static/index.html and keep this as-is.
|
| 223 |
app.mount("/static", StaticFiles(directory="static"), name="static")
|
| 224 |
|
| 225 |
@app.get("/")
|
|
|
|
| 228 |
|
| 229 |
@app.get("/api/sites")
|
| 230 |
def api_sites():
|
| 231 |
+
# Public listing (no secrets)
|
| 232 |
+
public = list_sites(include_secret=False)
|
| 233 |
+
return JSONResponse(public)
|
| 234 |
|
| 235 |
@app.post("/api/sites")
|
| 236 |
def api_add_site(site: SiteIn):
|
| 237 |
+
url_s = str(site.url)
|
| 238 |
name_s = (site.name or "").strip() or url_s
|
| 239 |
+
tok = (site.hf_token or "").strip()
|
| 240 |
+
if tok.lower().startswith("bearer "):
|
| 241 |
+
tok = tok[7:].strip()
|
| 242 |
with db_lock:
|
| 243 |
try:
|
| 244 |
+
# upsert-ish: try insert; if exists, update token/name
|
| 245 |
conn.execute(
|
| 246 |
+
"INSERT OR IGNORE INTO sites(url, name, hf_token) VALUES (?, ?, ?)",
|
| 247 |
+
(url_s, name_s, tok or None)
|
| 248 |
+
)
|
| 249 |
+
conn.execute(
|
| 250 |
+
"UPDATE sites SET name=?, hf_token=? WHERE url=?",
|
| 251 |
+
(name_s, tok or None, url_s)
|
| 252 |
)
|
| 253 |
conn.commit()
|
| 254 |
except sqlite3.Error as e:
|
|
|
|
| 255 |
raise HTTPException(400, f"DB error: {e}")
|
| 256 |
return {"ok": True}
|
| 257 |
|
|
|
|
| 258 |
@app.delete("/api/sites")
|
| 259 |
def api_delete_site(url: str):
|
| 260 |
with db_lock:
|
|
|
|
| 271 |
|
| 272 |
@app.get("/api/status")
|
| 273 |
def api_status():
|
| 274 |
+
sites = list_sites(include_secret=False) # do NOT leak tokens
|
| 275 |
now = datetime.now(timezone.utc)
|
| 276 |
since_24h = now - timedelta(hours=24)
|
| 277 |
since_7d = now - timedelta(days=7)
|
|
|
|
| 281 |
last = get_last_check(s["url"])
|
| 282 |
u24 = uptime_ratio(s["url"], since_24h)
|
| 283 |
u7 = uptime_ratio(s["url"], since_7d)
|
|
|
|
| 284 |
with db_lock:
|
| 285 |
open_inc = conn.execute(
|
| 286 |
"SELECT 1 FROM incidents WHERE url=? AND end_ts IS NULL LIMIT 1",
|
| 287 |
(s["url"],)
|
| 288 |
).fetchone()
|
| 289 |
open_incident = bool(open_inc)
|
|
|
|
| 290 |
out.append({
|
| 291 |
"url": s["url"],
|
| 292 |
"name": s["name"],
|
| 293 |
+
"last": last,
|
| 294 |
+
"uptime24h": u24,
|
| 295 |
+
"uptime7d": u7,
|
| 296 |
"open_incident": open_incident
|
| 297 |
})
|
| 298 |
return out
|
|
|
|
| 307 |
|
| 308 |
if __name__ == "__main__":
|
| 309 |
import uvicorn
|
| 310 |
+
uvicorn.run(app, host="0.0.0.0", port=PORT)
|