-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
76 lines (65 loc) · 2.38 KB
/
app.py
File metadata and controls
76 lines (65 loc) · 2.38 KB
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
#!/usr/bin/env python3
from flask import Flask, jsonify
import psutil
import datetime
import os
from version import VERSION
app = Flask(__name__)
def get_metrics():
"""Collect system metrics and return a dict ready for JSON serialisation."""
# ---------- CPU ----------
cpu_percent = psutil.cpu_percent(interval=0.5) # short measurement
# ---------- Memory ----------
mem = psutil.virtual_memory()
mem_info = {
"total_mb": round(mem.total / (1024 ** 2), 2),
"used_mb": round(mem.used / (1024 ** 2), 2),
"available_mb": round(mem.available / (1024 ** 2), 2),
"percent_used": mem.percent,
}
# ---------- Disk ----------
# By default use the root mount. You can override with env var DISK_MOUNT.
# This is useful in containers where the host root may be mounted elsewhere.
disk_mount = os.environ.get("DISK_MOUNT", "/")
disk = psutil.disk_usage(disk_mount)
disk_info = {
"total_gb": round(disk.total / (1024 ** 3), 2),
"used_gb": round(disk.used / (1024 ** 3), 2),
"free_gb": round(disk.free / (1024 ** 3), 2),
"percent_used": disk.percent,
}
# ---------- Timestamp ----------
ts = datetime.datetime.utcnow().replace(microsecond=0).isoformat() + "Z"
return {
"cpu_percent": cpu_percent,
"memory": mem_info,
"disk": disk_info,
"timestamp": ts,
}
@app.route("/", methods=["GET"])
def entrypage():
"""REST endpoint – returns the JSON payload."""
details = {
"service": "monitoring-api",
"version": VERSION,
"routes": [
"/api/metrics",
"/api/healthcheck"
]
}
return jsonify(details)
@app.route("/api/healthcheck")
def healthcheck():
return jsonify({"status": "ok"})
@app.route("/api/metrics", methods=["GET"])
def metrics():
"""REST endpoint – returns the JSON payload."""
return jsonify(get_metrics())
# ----------------------------------------------------------------------
# Running the app directly (python app.py) will start the Flask server.
# ----------------------------------------------------------------------
if __name__ == "__main__":
# host='0.0.0.0' → listen on *all* network interfaces
# port=3003 → the port you asked for
# debug=False → production‑ready (no auto‑reload)
app.run(host="0.0.0.0", port=3003, debug=False)