Created
March 21, 2025 00:55
-
-
Save futureperfect/146a753591dce6aa24bede09c61a6978 to your computer and use it in GitHub Desktop.
Simple metrics endpoint collecting cpu, memory, and disk utilization statistics and reporting via an HTTP endpoint
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Collect host CPU, memory, and disk utilization metrics minutely | |
and report them via an HTTP endpoint | |
""" | |
import time | |
import os | |
from textwrap import dedent | |
import threading | |
import psutil | |
from flask import Flask, Response | |
app = Flask(__name__) | |
metrics = { | |
"cpu_percent": 0.0, | |
"memory_percent": 0.0, | |
"disk_util": 0, | |
"disk_total": 0, | |
} | |
def collect_metrics(): | |
""" | |
Collect host metrics and persist into global dict | |
""" | |
while True: | |
metrics["cpu_percent"] = psutil.cpu_percent(interval=1) | |
metrics["memory_percent"] = psutil.virtual_memory().percent | |
metrics["disk_util"] = psutil.disk_usage("/").used | |
metrics["disk_total"] = psutil.disk_usage("/").total | |
time.sleep(60) | |
@app.route("/metrics") | |
def get_metrics(): | |
"""Expose metrics as Prometheus-style text""" | |
output = dedent( | |
f"""\ | |
# HELP cpu_percent Current CPU utilization percentage. | |
# TYPE cpu_percent gauge | |
cpu_percent {metrics['cpu_percent']} | |
# HELP memory_percent Current memory utilization percentage. | |
# TYPE memory_percent gauge | |
memory_percent {metrics['memory_percent']} | |
# HELP disk_util Current disk utilization in bytes. | |
# TYPE disk_util gauge | |
disk_util {metrics['disk_util']} | |
# HELP disk_total Total disk space in bytes. | |
# TYPE disk_total gauge | |
disk_total {metrics['disk_total']} | |
""" | |
) | |
return Response(output, mimetype="text/plain") | |
if __name__ == "__main__": | |
# Start the metrics collection thread | |
metrics_thread = threading.Thread(target=collect_metrics) | |
metrics_thread.daemon = True # Allow the program to exit even if the thread is running | |
metrics_thread.start() | |
app.run(host="0.0.0.0", port=9090) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
blinker==1.9.0 | |
click==8.1.8 | |
Flask==3.1.0 | |
itsdangerous==2.2.0 | |
Jinja2==3.1.6 | |
MarkupSafe==3.0.2 | |
psutil==7.0.0 | |
Werkzeug==3.1.3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment