Добавить app.py
This commit is contained in:
@@ -0,0 +1,127 @@
|
||||
import os
|
||||
import threading
|
||||
import sqlite3
|
||||
|
||||
from flask import Flask, render_template, request, redirect, url_for, send_file, abort, jsonify
|
||||
from waitress import serve
|
||||
|
||||
import collector
|
||||
import db
|
||||
|
||||
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
RUNS_DIR = os.path.join(BASE_DIR, "data", "runs")
|
||||
DB_PATH = os.path.join(BASE_DIR, "data", "smart.db")
|
||||
|
||||
# Автоматически проверяем и обновляем схему БД (чтобы не падало на старых базах)
|
||||
def check_db_schema():
|
||||
os.makedirs(os.path.dirname(DB_PATH), exist_ok=True)
|
||||
with sqlite3.connect(DB_PATH) as c:
|
||||
cols = [r[1] for r in c.execute("PRAGMA table_info(drives)").fetchall()]
|
||||
if cols: # если таблица уже есть
|
||||
if "non_medium_errors" not in cols:
|
||||
c.execute("ALTER TABLE drives ADD COLUMN non_medium_errors INTEGER")
|
||||
if "power_on_hours" not in cols:
|
||||
c.execute("ALTER TABLE drives ADD COLUMN power_on_hours INTEGER")
|
||||
if "temperature" not in cols:
|
||||
c.execute("ALTER TABLE drives ADD COLUMN temperature INTEGER")
|
||||
|
||||
app = Flask(__name__)
|
||||
db.init_db()
|
||||
check_db_schema()
|
||||
|
||||
_runs_lock = threading.Lock()
|
||||
_runs_in_progress = set()
|
||||
|
||||
@app.route("/favicon.ico")
|
||||
def favicon(): return "", 204
|
||||
|
||||
def run_collection_async(run_id, ssh_host, user, password, key_path, port, hostname_override):
|
||||
def worker():
|
||||
try:
|
||||
hostname, drives, archive = collector.collect(
|
||||
ssh_host=ssh_host, user=user, password=password,
|
||||
key_path=key_path, port=port,
|
||||
hostname_override=hostname_override, runs_dir=RUNS_DIR,
|
||||
)
|
||||
for d in drives:
|
||||
db.insert_drive(run_id, d, d)
|
||||
db.finish_run(run_id, "ok", archive=archive)
|
||||
except Exception as e:
|
||||
db.finish_run(run_id, "error", error=str(e))
|
||||
finally:
|
||||
with _runs_lock:
|
||||
_runs_in_progress.discard(run_id)
|
||||
|
||||
t = threading.Thread(target=worker, daemon=True)
|
||||
t.start()
|
||||
with _runs_lock:
|
||||
_runs_in_progress.add(run_id)
|
||||
|
||||
@app.route("/")
|
||||
def index():
|
||||
runs = db.list_runs()
|
||||
return render_template("index.html", runs=runs, in_progress=_runs_in_progress)
|
||||
|
||||
@app.route("/run", methods=["POST"])
|
||||
def run():
|
||||
ssh_host = request.form["ssh_host"].strip()
|
||||
user = request.form["user"].strip()
|
||||
password = request.form.get("password") or None
|
||||
key_path = request.form.get("key_path") or None
|
||||
port = int(request.form.get("port") or 22)
|
||||
hostname_override = request.form.get("hostname") or None
|
||||
|
||||
if not ssh_host or not user:
|
||||
abort(400, "ssh_host и user обязательны")
|
||||
|
||||
hostname = hostname_override or ssh_host
|
||||
run_id = db.create_run(hostname, ssh_host)
|
||||
run_collection_async(run_id, ssh_host, user, password, key_path, port, hostname_override)
|
||||
return redirect(url_for("run_detail", run_id=run_id))
|
||||
|
||||
@app.route("/run/<int:run_id>")
|
||||
def run_detail(run_id):
|
||||
run_row, drives = db.get_run(run_id)
|
||||
if not run_row:
|
||||
abort(404)
|
||||
return render_template("run.html", run=run_row, drives=drives,
|
||||
in_progress=_runs_in_progress)
|
||||
|
||||
@app.route("/run/<int:run_id>/download")
|
||||
def run_download(run_id):
|
||||
run_row, _ = db.get_run(run_id)
|
||||
if not run_row or not run_row["archive"]:
|
||||
abort(404, "архив не найден")
|
||||
path = run_row["archive"]
|
||||
if not os.path.isfile(path):
|
||||
abort(404, "файл архива отсутствует на диске")
|
||||
return send_file(path, as_attachment=True, download_name=os.path.basename(path))
|
||||
|
||||
@app.route("/charts")
|
||||
def charts():
|
||||
rows = db.runs_for_charts()
|
||||
return render_template("charts.html", rows=rows)
|
||||
|
||||
@app.route("/api/runs")
|
||||
def api_runs():
|
||||
rows = db.runs_for_charts()
|
||||
return jsonify([
|
||||
{"id": r["id"], "hostname": r["hostname"], "started_at": r["started_at"],
|
||||
"status": r["status"], "total": r["total"] or 0, "bad": r["bad"] or 0,
|
||||
"max_temp": r["max_temp"]}
|
||||
for r in rows
|
||||
])
|
||||
|
||||
@app.route("/run/<int:run_id>/delete", methods=["POST"])
|
||||
def run_delete(run_id):
|
||||
run_row, _ = db.get_run(run_id)
|
||||
if not run_row:
|
||||
abort(404)
|
||||
with db.get_conn() as c:
|
||||
c.execute("DELETE FROM runs WHERE id=?", (run_id,))
|
||||
return redirect(url_for("index"))
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("Starting production server on http://0.0.0.0:5001")
|
||||
# Waitress — отличный продакшн-сервер: 8 потоков, стабильно, без падений
|
||||
serve(app, host="0.0.0.0", port=5001, threads=8)
|
||||
Reference in New Issue
Block a user