-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmonitor.py
More file actions
208 lines (172 loc) · 8.29 KB
/
monitor.py
File metadata and controls
208 lines (172 loc) · 8.29 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
#!/usr/bin/env python3
import json
import os
import re
import socket
import subprocess
import sys
import time
from signal import SIGINT, SIGTERM, signal
import paho.mqtt.client as mqtt
import psutil
# ──────────────────────────────────────────────────────────────────────────────
# User‑specific settings
# ──────────────────────────────────────────────────────────────────────────────
BROKER = "xxx.xxx.xxx.xxx"
PORT = 1883
USERNAME = "YOUR_USERNAME"
PASSWORD = "YOUR_PASSWORD"
TOPIC = "home/server/stats"
DISCOVERY_PREFIX = "homeassistant"
DEVICE_NAME = "main_server"
POLL_INTERVAL_SEC = 15
CONTAINERS = [ # list the container *names*
"plex", "paho_mqtt_broker", "ntopng",
"cloudflare-cloudflared-1", "photoprism",
"ntfy", "filebrowser", "portainer",
]
CPU_CORES = psutil.cpu_count(logical=True) or 1
# ──────────────────────────────────────────────────────────────────────────────
CLIENT_ID = f"server_stats_{socket.gethostname()}"
# ═════════════════════════════════════════════════════════════════════════════
# Helper functions
# ═════════════════════════════════════════════════════════════════════════════
def get_first_cpu_temp() -> float | None:
temps = psutil.sensors_temperatures(fahrenheit=False)
if not temps:
return None
for entries in temps.values():
for entry in entries:
if entry.current is not None:
return round(entry.current, 1)
return None
def get_uptime() -> str:
return subprocess.check_output("uptime -p", shell=True).decode().strip()
def get_docker_status() -> dict:
try:
out = subprocess.check_output(
["docker", "ps", "-a", "--format", "{{.Names}}={{.Status}}"]
)
lines = out.decode().splitlines()
return {ln.split("=", 1)[0]: ln.split("=", 1)[1] for ln in lines}
except Exception as exc:
return {"error": str(exc)}
def get_jellyfin_status() -> str:
try:
out = subprocess.check_output(["systemctl", "is-active", "jellyfin"])
return out.decode().strip()
except subprocess.CalledProcessError:
return "unknown"
def get_stats() -> dict:
return {
"cpu_per_core": psutil.cpu_percent(percpu=True),
"cpu_percent": psutil.cpu_percent(),
"ram_percent": psutil.virtual_memory().percent,
"uptime": get_uptime(),
"load_avg": os.getloadavg(),
"temp_c": get_first_cpu_temp(),
"docker": get_docker_status(),
"jellyfin": get_jellyfin_status(),
# add more if needed
}
# ═════════════════════════════════════════════════════════════════════════════
# MQTT discovery
# ═════════════════════════════════════════════════════════════════════════════
def publish_discovery(client: mqtt.Client) -> None:
for container in CONTAINERS:
object_id = container.replace("_", "-")
topic_cfg = f"{DISCOVERY_PREFIX}/sensor/{DEVICE_NAME}/{object_id}/config"
value_tmpl = (
"{{ 'running' if value_json.docker.get('"
+ container
+ "', '') | regex_match('^Up') else 'stopped' }}"
)
payload = {
"name": f"{container} Container",
"state_topic": TOPIC,
"value_template": value_tmpl,
"unique_id": f"{DEVICE_NAME}_{object_id}_container",
"icon": "mdi:docker",
"device": {
"identifiers": [DEVICE_NAME],
"name": "Main Server",
"manufacturer": "Farouk Server",
"model": "Linux MQTT Monitor",
},
}
client.publish(topic_cfg, json.dumps(payload), retain=True)
for idx in range(CPU_CORES):
obj_id = f"cpu_core_{idx+1}"
topic_cfg = f"{DISCOVERY_PREFIX}/sensor/{DEVICE_NAME}/{obj_id}/config"
payload = {
"name": f"CPU Core {idx+1}",
"state_topic": TOPIC,
"unit_of_measurement": "%",
"value_template": f"{{{{ value_json.cpu_per_core[{idx}] }}}}",
"state_class": "measurement",
"unique_id": f"{DEVICE_NAME}_{obj_id}",
"device": {
"identifiers": [DEVICE_NAME],
"name": "Main Server",
"manufacturer": "Farouk Server",
"model": "Linux MQTT Monitor",
},
}
client.publish(topic_cfg, json.dumps(payload), retain=True)
generic_defs = [
("cpu_total", "CPU Total", "%", "{{ value_json.cpu_percent }}", True),
("ram_usage", "RAM Usage", "%", "{{ value_json.ram_percent }}", True),
("temp", "CPU Temp", "°C", "{{ value_json.temp_c }}", True),
("load_1m", "Load 1m", None, "{{ value_json.load_avg[0] }}", False),
("load_5m", "Load 5m", None, "{{ value_json.load_avg[1] }}", False),
("load_15m", "Load 15m", None, "{{ value_json.load_avg[2] }}", False),
("uptime", "System Uptime", None, "{{ value_json.uptime }}", False),
("jellyfin", "Jellyfin Status", None, "{{ value_json.jellyfin }}", False),
]
for obj_id, name, unit, template, measurable in generic_defs:
topic_cfg = f"{DISCOVERY_PREFIX}/sensor/{DEVICE_NAME}/{obj_id}/config"
payload = {
"name": name,
"state_topic": TOPIC,
"value_template": template,
"unique_id": f"{DEVICE_NAME}_{obj_id}",
"device": {
"identifiers": [DEVICE_NAME],
"name": "Main Server",
"manufacturer": "Farouk Server",
"model": "Linux MQTT Monitor",
},
}
if unit:
payload["unit_of_measurement"] = unit
if measurable:
payload["state_class"] = "measurement"
client.publish(topic_cfg, json.dumps(payload), retain=True)
# ═════════════════════════════════════════════════════════════════════════════
# MQTT callbacks & main loop
# ═════════════════════════════════════════════════════════════════════════════
def on_connect(client, _userdata, _flags, rc):
print(f"[MQTT] Connected, result code {rc}")
publish_discovery(client)
def on_disconnect(_client, _userdata, rc):
print(f"[MQTT] Disconnected (rc={rc})")
def graceful_exit(_sig_num, _frame):
print("\nExiting …")
mqtt_client.loop_stop()
mqtt_client.disconnect()
sys.exit(0)
if __name__ == "__main__":
signal(SIGTERM, graceful_exit)
signal(SIGINT, graceful_exit)
mqtt_client = mqtt.Client(client_id=CLIENT_ID)
mqtt_client.username_pw_set(USERNAME, PASSWORD)
mqtt_client.on_connect = on_connect
mqtt_client.on_disconnect = on_disconnect
mqtt_client.connect(BROKER, PORT, keepalive=60)
mqtt_client.loop_start()
try:
while True:
mqtt_client.publish(TOPIC, json.dumps(get_stats()), qos=0, retain=False)
time.sleep(POLL_INTERVAL_SEC)
finally:
graceful_exit(None, None)