initial version 0.0.1
This commit is contained in:
@@ -0,0 +1,88 @@
|
||||
import os
|
||||
import time
|
||||
from prometheus_client import start_http_server, Gauge, REGISTRY
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# 1. Define Metrics with Labels
|
||||
# Use labels for domain and feature to avoid creating 100s of unique metric names
|
||||
DOMAIN_FEATURE = Gauge(
|
||||
"caddy_domain_imports",
|
||||
"Binary status of domain features (1=enabled, 0=disabled)",
|
||||
["domain", "feature"],
|
||||
)
|
||||
|
||||
GLOBAL_STATS = Gauge(
|
||||
"caddy_global_stats", "Aggregated counts of features across all domains", ["type"]
|
||||
)
|
||||
|
||||
|
||||
load_dotenv()
|
||||
|
||||
CADDY_PATH = os.environ["CADDY_PATH"]
|
||||
|
||||
|
||||
def load_caddyfile():
|
||||
with open(CADDY_PATH, "r") as f:
|
||||
return f.read()
|
||||
|
||||
|
||||
def parse(data):
|
||||
from libs.parse_caddyfile import parse as caddy_parse
|
||||
|
||||
return caddy_parse(data)
|
||||
|
||||
|
||||
def mathing(data: dict):
|
||||
total_domains = len(data.items())
|
||||
# info = dict({"auth": 0, "wan": 0, "noauth": 0, "nowan": 0, "none": 0})
|
||||
info = dict({"no_auth": 0, "no_wan": 0})
|
||||
for domain, imports in data.items():
|
||||
if len(imports) == 0:
|
||||
if "none" not in info:
|
||||
info["none"] = 1
|
||||
info["none"] += 1
|
||||
continue
|
||||
for imp in imports:
|
||||
if imp not in info:
|
||||
info[imp] = 1
|
||||
info[imp] += 1
|
||||
if "auth" not in imports:
|
||||
info["no_auth"] += 1
|
||||
if "wan" not in imports:
|
||||
info["no_wan"] += 1
|
||||
info["total_domains"] = total_domains
|
||||
return info
|
||||
|
||||
|
||||
def update_metrics():
|
||||
# Your existing parsing logic
|
||||
try:
|
||||
raw_data = load_caddyfile()
|
||||
hosts = parse(raw_data)
|
||||
info = mathing(hosts)
|
||||
|
||||
# --- Update Global Metrics ---
|
||||
for key, value in info.items():
|
||||
GLOBAL_STATS.labels(type=key).set(value)
|
||||
|
||||
# --- Update Per-Domain Metrics ---
|
||||
tracked_features = ["auth", "wan"]
|
||||
|
||||
for domain, imports in hosts.items():
|
||||
for feature in tracked_features:
|
||||
is_enabled = 1 if feature in imports else 0
|
||||
DOMAIN_FEATURE.labels(domain=domain, feature=feature).set(is_enabled)
|
||||
|
||||
print(f"Metrics updated at {time.ctime()}")
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error updating metrics: {e}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
start_http_server(port=8000, addr="0.0.0.0")
|
||||
print("Prometheus server started on port 8000")
|
||||
|
||||
while True:
|
||||
update_metrics()
|
||||
time.sleep(60)
|
||||
Reference in New Issue
Block a user