Newer
Older
NodeStat / node_info_daemon.py
from flask import Flask, jsonify
import psutil
import time

app = Flask(__name__)

# Store previous network I/O to calculate speeds
previous_io = psutil.net_io_counters()
previous_time = time.time()

@app.route("/stats")
def stats():
    global previous_io, previous_time

    # Gather system info
    cpu_usage = psutil.cpu_percent(interval=0.5)
    virtual_mem = psutil.virtual_memory()
    disk = psutil.disk_usage('/')
    current_io = psutil.net_io_counters()
    current_time = time.time()

    # Calculate network speeds
    time_diff = current_time - previous_time
    rx_speed = (current_io.bytes_recv - previous_io.bytes_recv) / time_diff
    tx_speed = (current_io.bytes_sent - previous_io.bytes_sent) / time_diff

    # Update history
    previous_io = current_io
    previous_time = current_time

    return jsonify({
        "cpu_percent": cpu_usage,
        "memory": {
            "used_mb": virtual_mem.used // (1024 * 1024),
            "total_mb": virtual_mem.total // (1024 * 1024),
            "percent": virtual_mem.percent
        },
        "disk": {
            "used_gb": disk.used // (1024 ** 3),
            "total_gb": disk.total // (1024 ** 3),
            "percent": disk.percent
        },
        "network": {
            "rx_kbps": round(rx_speed / 1024, 2),
            "tx_kbps": round(tx_speed / 1024, 2)
        }
    })

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8080)