#!/usr/bin/env python3 # app.py — painel de monitoramento de mineracao (frota Conexlog). # - POST /api/report : agente envia telemetria (autenticado por token) # - GET /api/status : estado agregado (restrito por IP) # - GET / : dashboard HTML (restrito por IP) import os import re import time import hmac import json import uuid import threading import logging from datetime import datetime from flask import Flask, request, jsonify, send_from_directory try: from zoneinfo import ZoneInfo TZ = ZoneInfo("America/Sao_Paulo") except Exception: TZ = None logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") app = Flask(__name__) # ---- config via ambiente ---- ALLOWED_IPS = [ip.strip() for ip in os.environ.get("ALLOWED_IPS", "").split(",") if ip.strip()] REPORT_TOKEN = os.environ.get("REPORT_TOKEN", "") WALLET_ADDRESS = os.environ.get("WALLET_ADDRESS", "") # ---- armazenamento em memoria ---- _machines = {} _lock = threading.Lock() # modo desejado por maquina (definido pelo usuario no painel, aplicado pelo agente) _desired_modes = {} _desired_pg = {} _desired_running = {} # modo escolhido no painel — agenda nao sobrescreve ate mudar o horario da regra _manual_modes = {} _last_sched_mode = {} _modes_lock = threading.Lock() VALID_MODES = {"eco", "safe", "oc"} VALID_SELECT = {"all", "include", "exclude"} # Python weekday: 0=seg … 6=dom DAY_ALIASES = { "mon": 0, "tue": 1, "wed": 2, "thu": 3, "fri": 4, "sat": 5, "sun": 6, "seg": 0, "ter": 1, "qua": 2, "qui": 3, "sex": 4, "sab": 5, "dom": 6, "0": 0, "1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, } DAY_LABELS = ["Seg", "Ter", "Qua", "Qui", "Sex", "Sáb", "Dom"] WEEKDAYS = [0, 1, 2, 3, 4] # ---- agendamentos (persistidos em disco) ---- SCHEDULES_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "schedules.json") _schedules = [] _sched_fired = {} _sched_lock = threading.Lock() def _now_local(): if TZ is not None: return datetime.now(TZ) return datetime.now() def _parse_hhmm(s): try: h, m = s.strip().split(":") h, m = int(h), int(m) if 0 <= h <= 23 and 0 <= m <= 59: return h * 60 + m except Exception: pass return None def _load_schedules(): global _schedules, _sched_fired try: with open(SCHEDULES_PATH) as f: data = json.load(f) if isinstance(data, list): _schedules = data _sched_fired = {} elif isinstance(data, dict): _schedules = data.get("rules") or [] _sched_fired = data.get("fired") or {} else: _schedules = [] _sched_fired = {} except Exception: _schedules = [] _sched_fired = {} def _save_schedules(): tmp = SCHEDULES_PATH + ".tmp" payload = {"rules": _schedules, "fired": _sched_fired} with open(tmp, "w") as f: json.dump(payload, f, indent=2, ensure_ascii=False) f.write("\n") os.replace(tmp, SCHEDULES_PATH) def _parse_days(raw): """None/[] = todos os dias. Lista de 0-6 (seg-dom).""" if raw is None: return None if isinstance(raw, str): raw = [x.strip() for x in raw.replace(";", ",").split(",") if x.strip()] if not isinstance(raw, list): return None if len(raw) == 0: return None out = [] for item in raw: if isinstance(item, bool): continue if isinstance(item, int): if 0 <= item <= 6: out.append(item) continue key = str(item).strip().lower() if key in DAY_ALIASES: out.append(DAY_ALIASES[key]) # unique preserve order seen = set() days = [] for d in out: if d not in seen: seen.add(d) days.append(d) return days if days else None def _rule_days_match(rule, weekday): days = _parse_days(rule.get("days")) if days is None: return True return weekday in days def _normalize_rule(data, existing=None): existing = existing or {} rid = data.get("id") or existing.get("id") or uuid.uuid4().hex[:10] time_s = (data.get("time") if data.get("time") is not None else existing.get("time") or "").strip() if _parse_hhmm(time_s) is None: return None, "horario invalido (use HH:MM)" mode = data.get("mode") if data.get("mode") is not None else existing.get("mode") if mode not in VALID_MODES: return None, "modo invalido" select = data.get("select") if data.get("select") is not None else existing.get("select") or "all" if select not in VALID_SELECT: return None, "selecao invalida" hosts = data.get("hosts") if data.get("hosts") is not None else existing.get("hosts") or [] if not isinstance(hosts, list): return None, "hosts deve ser lista" hosts = [str(h).strip() for h in hosts if str(h).strip()] if select in ("include", "exclude") and not hosts: return None, "marque pelo menos uma maquina" enabled = data.get("enabled") if data.get("enabled") is not None else existing.get("enabled", True) label = data.get("label") if data.get("label") is not None else existing.get("label") or "" if "days" in data: days = _parse_days(data.get("days")) else: days = _parse_days(existing.get("days")) rule = { "id": rid, "enabled": bool(enabled), "time": time_s, "mode": mode, "select": select, "hosts": hosts, "label": str(label)[:80], "days": days, # None = todos os dias } return rule, None def _host_num(name): """PC-CONEX15 → 15; sem dígitos → -1.""" m = re.search(r"(\d+)\s*$", str(name or "")) return int(m.group(1)) if m else -1 def _known_hosts(): with _lock: return sorted( {m.get("hostname") for m in _machines.values() if m.get("hostname")}, key=lambda h: (_host_num(h), h), reverse=False, ) def _resolve_rule_hosts(rule, known): select = rule.get("select") or "all" listed = rule.get("hosts") or [] if select == "all": return list(known) if select == "include": return list(dict.fromkeys(listed)) excl = set(listed) return [h for h in known if h not in excl] def _apply_mode_to_hosts(hosts, mode): with _modes_lock: for h in hosts: _desired_modes[h] = mode logging.info( "agenda aplicou mode=%s em %d host(s): %s", mode, len(hosts), ", ".join(hosts[:12]) + ("…" if len(hosts) > 12 else ""), ) def _machine_mode_map(): """hostname -> mode reportado.""" with _lock: return { m.get("hostname"): m.get("mode") for m in _machines.values() if m.get("hostname") } def _schedule_tick(): """Aplica o modo da ultima regra do dia cujo horario ja passou (respeita reboot).""" global _sched_fired now = _now_local() day = now.strftime("%Y-%m-%d") weekday = now.weekday() mins_now = now.hour * 60 + now.minute known = _known_hosts() with _sched_lock: rules = list(_schedules) fired = dict(_sched_fired) # regras de hoje, ordenadas por horario, ja vencidas due = [] for rule in rules: if not rule.get("enabled"): continue if not _rule_days_match(rule, weekday): continue mins_rule = _parse_hhmm(rule.get("time") or "") if mins_rule is None or mins_now < mins_rule: continue due.append((mins_rule, rule)) due.sort(key=lambda x: x[0]) # modo efetivo por host = ultima regra aplicavel host_mode = {} for _, rule in due: for h in _resolve_rule_hosts(rule, known): host_mode[h] = rule["mode"] # novo periodo da agenda (ex.: 07:00 safe -> 18:03 oc) libera override manual with _modes_lock: for h, mode in host_mode.items(): prev = _last_sched_mode.get(h) if prev is not None and prev != mode: _manual_modes.pop(h, None) _last_sched_mode[h] = mode reported = _machine_mode_map() changed_fire = False applied = 0 for h, mode in host_mode.items(): with _modes_lock: if h in _manual_modes: continue cur = reported.get(h) if cur != mode: with _modes_lock: _desired_modes[h] = mode applied += 1 # marca regras de hoje como "disparadas" para UI (quando o horario ja passou) for _, rule in due: rid = rule.get("id") if not rid: continue if fired.get(rid) != day: fired[rid] = day changed_fire = True # limpa fired de dias antigos trimmed = {k: v for k, v in fired.items() if v == day} if trimmed != fired: fired = trimmed changed_fire = True if applied: logging.info( "agenda sync: weekday=%s %s mode(s) pendente(s) em %d host(s)", weekday, day, applied, ) if changed_fire: with _sched_lock: _sched_fired = fired try: _save_schedules() except Exception as e: logging.warning("falha ao salvar agenda: %s", e) def _schedule_loop(): while True: try: _schedule_tick() except Exception as e: logging.warning("agenda tick falhou: %s", e) time.sleep(20) _load_schedules() # ---- estimativa de ganhos (atualizada em background) ---- EST = { "factor": None, "price": None, "ts": 0, } MO_API = "https://api.moneroocean.stream" XMR_ATOMIC = 1e12 def _http_get_json(url, timeout=6): try: import requests r = requests.get(url, timeout=timeout, headers={"User-Agent": "miner-panel/1.0"}) if r.status_code == 200: return r.json() except Exception: pass return None def _http_post_json(url, data, timeout=12): try: import requests r = requests.post( url, json=data, timeout=timeout, headers={"User-Agent": "miner-panel/1.0", "Accept": "application/json"}, ) body = r.json() if r.content else {} return r.status_code, body if isinstance(body, dict) else {"raw": body} except Exception as e: return 0, {"error": str(e)} def _xmr_from_atomic(v): try: return float(v) / XMR_ATOMIC except Exception: return 0.0 def _wallet_masked(addr): if not addr: return "" if len(addr) <= 20: return addr return addr[:10] + "…" + addr[-10:] def _fetch_user_payout_threshold(): if not WALLET_ADDRESS: return None j = _http_get_json("%s/user/%s" % (MO_API, WALLET_ADDRESS)) if not j: return None th = j.get("payout_threshold") if th is None: return BAL["min_payout"] return _xmr_from_atomic(th) def _payout_snapshot(): _refresh_balance() threshold = _fetch_user_payout_threshold() if threshold is None: threshold = BAL["min_payout"] balance = BAL["amt_due"] min_p = BAL["min_payout"] remaining = max(0.0, threshold - balance) progress = min(100.0, (balance / threshold * 100.0) if threshold > 0 else 0.0) ready = balance >= threshold and balance >= min_p can_trigger = balance >= min_p payments_raw = _http_get_json( "%s/miner/%s/payments?limit=6" % (MO_API, WALLET_ADDRESS) ) if WALLET_ADDRESS else None payments = [] if isinstance(payments_raw, list): for p in payments_raw: if not isinstance(p, dict): continue payments.append({ "ts": p.get("ts"), "amount_xmr": _xmr_from_atomic(p.get("amount") or p.get("value") or 0), "hash": p.get("hash") or "", }) return { "wallet": WALLET_ADDRESS, "wallet_masked": _wallet_masked(WALLET_ADDRESS), "balance_xmr": balance, "total_paid_xmr": BAL["amt_paid"], "min_payout_xmr": min_p, "threshold_xmr": threshold, "remaining_to_threshold_xmr": remaining, "threshold_progress_pct": progress, "payout_ready": ready, "can_withdraw_all": can_trigger, "pool": "MoneroOcean", "pool_dashboard_url": ( "https://moneroocean.stream/#/dashboard?addr=%s" % WALLET_ADDRESS if WALLET_ADDRESS else "https://moneroocean.stream/" ), "recent_payments": payments, "balance_ts": BAL["ts"], } MONERO_BLOCK_REWARD = 0.6 BAL = { "amt_due": 0.0, "amt_paid": 0.0, "min_payout": 0.003, "threshold": 0.003, "ts": 0, } def _fetch_price(): j = _http_get_json("https://api.kraken.com/0/public/Ticker?pair=XMRUSD") if j and not j.get("error"): c = j.get("result", {}).get("XXMRZUSD", {}).get("c", []) if c: try: return float(c[0]) except Exception: pass j = _http_get_json("https://api.coingecko.com/api/v3/simple/price?ids=monero&vs_currencies=usd") if j and j.get("monero", {}).get("usd"): return float(j["monero"]["usd"]) return None def _refresh_estimates(): p = _fetch_price() if p: EST["price"] = p j = _http_get_json("https://xmrchain.net/api/networkinfo") if j and j.get("data"): hr = j["data"].get("hash_rate") if hr: EST["factor"] = (720.0 * MONERO_BLOCK_REWARD) / hr EST["ts"] = time.time() def _refresh_balance(): if not WALLET_ADDRESS: return j = _http_get_json("https://api.moneroocean.stream/miner/%s/stats" % WALLET_ADDRESS) if j: try: BAL["amt_due"] = float(j.get("amtDue") or 0) / 1e12 except Exception: pass try: BAL["amt_paid"] = float(j.get("amtPaid") or 0) / 1e12 except Exception: pass j = _http_get_json("https://api.moneroocean.stream/config") if j and j.get("payout_policy", {}).get("minimumThreshold"): try: BAL["min_payout"] = float(j["payout_policy"]["minimumThreshold"]) except Exception: pass th = _fetch_user_payout_threshold() if th is not None: BAL["threshold"] = th BAL["ts"] = time.time() def _estimates_loop(): while True: try: _refresh_estimates() except Exception as e: logging.warning("falha ao atualizar estimativas: %s", e) try: _refresh_balance() except Exception as e: logging.warning("falha ao atualizar saldo: %s", e) time.sleep(300) if not EST["factor"]: EST["factor"] = (720.0 * 0.6) / 3.5e9 if not EST["price"]: EST["price"] = 150.0 try: _refresh_estimates() _refresh_balance() logging.info( "boot: wallet=%s saldo=%.12f XMR", (WALLET_ADDRESS[:8] + "…") if WALLET_ADDRESS else "(vazio)", BAL["amt_due"], ) except Exception as e: logging.warning("boot refresh falhou: %s", e) def _client_ip(): return request.remote_addr or "" def _ip_allowed(): if not ALLOWED_IPS: return True return _client_ip() in ALLOWED_IPS @app.route("/api/report", methods=["POST"]) def report(): token = request.headers.get("X-Report-Token", "") if not REPORT_TOKEN or not hmac.compare_digest(token, REPORT_TOKEN): return jsonify({"error": "unauthorized"}), 401 data = request.get_json(force=True, silent=True) if not isinstance(data, dict): return jsonify({"error": "bad request"}), 400 host = data.get("hostname") or _client_ip() data["last_seen"] = time.time() with _lock: _machines[host] = data # limpa "aplicando…" quando a maquina confirma o modo/estado desejado with _modes_lock: if host in _desired_modes and data.get("mode") == _desired_modes.get(host): _desired_modes.pop(host, None) if host in _desired_pg and bool(data.get("power_guard")) == bool(_desired_pg.get(host)): _desired_pg.pop(host, None) if host in _desired_running: reported_run = data.get("running") if reported_run is None: reported_run = data.get("status") != "stopped" if bool(reported_run) == bool(_desired_running.get(host)): _desired_running.pop(host, None) return jsonify({"ok": True, "count": len(_machines)}) @app.route("/api/command", methods=["GET"]) def get_command(): token = request.headers.get("X-Report-Token", "") if not REPORT_TOKEN or not hmac.compare_digest(token, REPORT_TOKEN): return jsonify({"error": "unauthorized"}), 401 host = request.args.get("host", "") with _modes_lock: mode = _desired_modes.get(host) pg = _desired_pg.get(host) running = _desired_running.get(host) return jsonify({"mode": mode, "power_guard": pg, "running": running}) @app.route("/api/command", methods=["POST"]) def set_command(): if not _ip_allowed(): return jsonify({"error": "forbidden"}), 403 data = request.get_json(force=True, silent=True) or {} host = data.get("hostname") mode = data.get("mode") pg = data.get("power_guard") running = data.get("running") if not host: return jsonify({"error": "bad request"}), 400 with _modes_lock: if mode is not None: if mode not in VALID_MODES: return jsonify({"error": "bad request"}), 400 _desired_modes[host] = mode _manual_modes[host] = mode if pg is not None: _desired_pg[host] = bool(pg) if running is not None: _desired_running[host] = bool(running) logging.info("comando: %s -> mode=%s power_guard=%s running=%s", host, mode, pg, running) return jsonify({"ok": True, "hostname": host, "mode": mode, "power_guard": pg, "running": running}) @app.route("/api/command/fleet", methods=["POST"]) def set_command_fleet(): if not _ip_allowed(): return jsonify({"error": "forbidden"}), 403 data = request.get_json(force=True, silent=True) or {} mode = data.get("mode") pg = data.get("power_guard") running = data.get("running") if mode is None and pg is None and running is None: return jsonify({"error": "bad request"}), 400 if mode is not None and mode not in VALID_MODES: return jsonify({"error": "bad request"}), 400 with _lock: hosts = [m.get("hostname") for m in _machines.values() if m.get("hostname")] with _modes_lock: for host in hosts: if mode is not None: _desired_modes[host] = mode _manual_modes[host] = mode if pg is not None: _desired_pg[host] = bool(pg) if running is not None: _desired_running[host] = bool(running) logging.info("comando FROTA (%d): mode=%s power_guard=%s running=%s", len(hosts), mode, pg, running) return jsonify({"ok": True, "count": len(hosts), "hosts": hosts, "mode": mode, "power_guard": pg, "running": running}) @app.route("/api/schedules", methods=["GET"]) def get_schedules(): if not _ip_allowed(): return jsonify({"error": "forbidden"}), 403 now = _now_local() with _sched_lock: rules = list(_schedules) fired = dict(_sched_fired) return jsonify({ "tz": "America/Sao_Paulo", "now": now.strftime("%Y-%m-%d %H:%M:%S"), "rules": rules, "fired": fired, "known_hosts": _known_hosts(), }) @app.route("/api/schedules", methods=["POST"]) def upsert_schedule(): if not _ip_allowed(): return jsonify({"error": "forbidden"}), 403 data = request.get_json(force=True, silent=True) or {} with _sched_lock: existing = None if data.get("id"): for r in _schedules: if r.get("id") == data["id"]: existing = r break rule, err = _normalize_rule(data, existing) if err: return jsonify({"error": err}), 400 if existing: for i, r in enumerate(_schedules): if r.get("id") == rule["id"]: _schedules[i] = rule break if (existing.get("time") != rule["time"] or existing.get("mode") != rule["mode"] or existing.get("select") != rule["select"] or existing.get("hosts") != rule["hosts"] or existing.get("days") != rule["days"]): _sched_fired.pop(rule["id"], None) else: _schedules.append(rule) _schedules.sort(key=lambda r: _parse_hhmm(r.get("time") or "") or 0) try: _save_schedules() except Exception as e: return jsonify({"error": "falha ao salvar: %s" % e}), 500 logging.info("agenda salva id=%s time=%s mode=%s select=%s", rule["id"], rule["time"], rule["mode"], rule["select"]) return jsonify({"ok": True, "rule": rule}) @app.route("/api/schedules/", methods=["DELETE"]) def delete_schedule(rid): if not _ip_allowed(): return jsonify({"error": "forbidden"}), 403 with _sched_lock: before = len(_schedules) _schedules[:] = [r for r in _schedules if r.get("id") != rid] _sched_fired.pop(rid, None) if len(_schedules) == before: return jsonify({"error": "not found"}), 404 try: _save_schedules() except Exception as e: return jsonify({"error": "falha ao salvar: %s" % e}), 500 return jsonify({"ok": True}) @app.route("/api/schedules/run/", methods=["POST"]) def run_schedule_now(rid): if not _ip_allowed(): return jsonify({"error": "forbidden"}), 403 with _sched_lock: rule = next((r for r in _schedules if r.get("id") == rid), None) if not rule: return jsonify({"error": "not found"}), 404 hosts = _resolve_rule_hosts(rule, _known_hosts()) _apply_mode_to_hosts(hosts, rule["mode"]) return jsonify({"ok": True, "count": len(hosts), "hosts": hosts, "mode": rule["mode"]}) @app.route("/api/payout") def get_payout(): if not _ip_allowed(): return jsonify({"error": "forbidden"}), 403 if not WALLET_ADDRESS: return jsonify({"error": "wallet nao configurada"}), 503 return jsonify(_payout_snapshot()) @app.route("/api/payout/threshold", methods=["POST"]) def set_payout_threshold(): if not _ip_allowed(): return jsonify({"error": "forbidden"}), 403 if not WALLET_ADDRESS: return jsonify({"error": "wallet nao configurada"}), 503 data = request.get_json(force=True, silent=True) or {} try: threshold = float(data.get("threshold_xmr")) except (TypeError, ValueError): return jsonify({"error": "threshold_xmr invalido"}), 400 min_p = BAL["min_payout"] if threshold < min_p: threshold = min_p if threshold > 1000: threshold = 1000.0 code, body = _http_post_json( "%s/user/updateThreshold" % MO_API, {"username": WALLET_ADDRESS, "threshold": threshold}, ) if code != 200 or not body.get("msg"): msg = body.get("msg") or body.get("error") or "falha na pool" return jsonify({"error": msg, "pool_status": code}), 502 snap = _payout_snapshot() snap["message"] = body.get("msg") logging.info("limite saque atualizado: %.6f XMR", threshold) return jsonify({"ok": True, **snap}) @app.route("/api/payout/withdraw", methods=["POST"]) def withdraw_all(): """Libera pagamento do saldo pendente: baixa o limite na pool ate o minimo (saldo >= limite).""" if not _ip_allowed(): return jsonify({"error": "forbidden"}), 403 if not WALLET_ADDRESS: return jsonify({"error": "wallet nao configurada"}), 503 _refresh_balance() balance = BAL["amt_due"] min_p = BAL["min_payout"] if balance < min_p: return jsonify({ "error": "Saldo abaixo do minimo da pool (%.6f XMR). Pendente: %.6f XMR." % (min_p, balance), "balance_xmr": balance, "min_payout_xmr": min_p, }), 400 target = min_p code, body = _http_post_json( "%s/user/updateThreshold" % MO_API, {"username": WALLET_ADDRESS, "threshold": target}, ) if code != 200 or not body.get("msg"): msg = body.get("msg") or body.get("error") or "falha na pool" return jsonify({"error": msg, "pool_status": code}), 502 snap = _payout_snapshot() snap["withdraw_requested_xmr"] = balance snap["message"] = ( "Saque solicitado: a MoneroOcean deve enviar cerca de %.6f XMR na proxima rodada de pagamentos " "(geralmente minutos a algumas horas — nao e instantaneo). Ajuste o limite de novo depois se quiser acumular." ) % balance logging.info("sacar tudo: saldo=%.6f threshold->%.6f", balance, target) return jsonify({"ok": True, **snap}) @app.route("/api/status") def status(): if not _ip_allowed(): return jsonify({"error": "forbidden"}), 403 with _lock: mlist = list(_machines.values()) mlist.sort(key=lambda m: (_host_num(m.get("hostname")), m.get("hostname") or ""), reverse=False) with _modes_lock: for m in mlist: host = m.get("hostname") pend = _desired_modes.get(host) if not pend and host in _manual_modes: man = _manual_modes.get(host) if m.get("mode") != man: pend = man m["desired_mode"] = pend m["manual_mode"] = _manual_modes.get(host) m["desired_power_guard"] = _desired_pg.get(m.get("hostname")) m["desired_running"] = _desired_running.get(m.get("hostname")) total_hash = sum(float(m.get("hashrate") or 0) for m in mlist) online = sum(1 for m in mlist if m.get("status") == "mining") xmr_day = total_hash * (EST["factor"] or 0) usd_day = xmr_day * (EST["price"] or 0) balance_xmr = BAL["amt_due"] min_payout = BAL["min_payout"] threshold_xmr = BAL.get("threshold") or min_payout remaining = max(0.0, threshold_xmr - balance_xmr) progress = min(100.0, (balance_xmr / threshold_xmr * 100.0) if threshold_xmr > 0 else 0.0) with _sched_lock: sched_count = sum(1 for r in _schedules if r.get("enabled")) return jsonify({ "ts": time.time(), "total_hashrate": total_hash, "machines_online": online, "machines_total": len(mlist), "estimated_xmr_day": xmr_day, "estimated_usd_day": usd_day, "price_usd": EST["price"], "factor": EST["factor"], "balance_xmr": balance_xmr, "total_paid_xmr": BAL["amt_paid"], "min_payout_xmr": min_payout, "threshold_xmr": threshold_xmr, "remaining_to_payout_xmr": remaining, "payout_progress_pct": progress, "schedules_enabled": sched_count, "machines": mlist, }) @app.route("/") def index(): if not _ip_allowed(): return "Acesso negado (403)", 403 return send_from_directory(app.root_path, "index.html") @app.route("/setup-frota.sh") def setup_frota_script(): """Instalador da frota (sem restricao de IP — usado em PCs fora da LAN).""" path = os.path.join(app.root_path, "setup-frota.sh") if not os.path.isfile(path): return "setup nao encontrado", 404 return send_from_directory(app.root_path, "setup-frota.sh", mimetype="text/x-shellscript") @app.route("/healthz") def healthz(): return jsonify({"ok": True, "allowed_ips": ALLOWED_IPS, "machines": len(_machines)}) threading.Thread(target=_estimates_loop, daemon=True).start() threading.Thread(target=_schedule_loop, daemon=True).start()