-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathha_main.py
More file actions
96 lines (73 loc) · 2.66 KB
/
ha_main.py
File metadata and controls
96 lines (73 loc) · 2.66 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
import logging
import time
import requests
import yaml
from prometheus_client import start_http_server
from ha_model import update_metrics
logger = logging.getLogger("prometheus_handler")
class GeneralConfig:
def __init__(self, port, pull_frequency_seconds):
self.port = port
self.pull_frequency_seconds = pull_frequency_seconds
class InstanceConfig:
def __init__(self, name, url, port, type):
self.name = name
self.url = url
self.port = port
self.type = type
def __str__(self):
return f"InstanceConfig(name={self.name}, url={self.url}, port={self.port})"
class HAExporterConfig:
def __init__(self, config, instances):
self.config = config
self.instances = instances
def load_yaml_config(filepath):
with open(filepath, "r") as file:
return yaml.safe_load(file)
def pull_metrics(instance):
res = requests.get(f"{instance.url}:{instance.port}")
if res.status_code != 200:
raise Exception(
f"Memgraph instance on {instance.url}:{instance.port} couldn't be reached."
)
return res.json()
def run(config_file):
config = load_yaml_config(config_file)
instances = [
InstanceConfig(
name=instance["name"],
url=instance["url"],
port=instance["port"],
type=instance["type"],
)
for instance in config.get("instances", [])
]
instances_str = "\n\t".join(str(instance) for instance in instances)
logger.info(
"HA exporter will use the following instances to collect metrics:\n\t%s",
instances_str,
)
general_config = GeneralConfig(
port=config.get("exporter", {}).get("port", 9115),
pull_frequency_seconds=config.get("exporter", {}).get(
"pull_frequency_seconds", 0
),
)
logger.info(
"HA exporter will pull metrics every %ds", general_config.pull_frequency_seconds
)
logger.info("HA exporter is started on: localhost:%s\n\n", general_config.port)
exporter = HAExporterConfig(instances=instances, config=general_config)
start_http_server(exporter.config.port)
while True:
for instance in exporter.instances:
try:
instance_metrics = pull_metrics(instance)
update_metrics(instance_metrics, instance)
logger.info("Send update to Prometheus for instance %s", instance.name)
except Exception as e:
logger.error("Error occurred while updating metrics: %s", e)
finally:
time.sleep(exporter.config.pull_frequency_seconds)
if __name__ == "__main__":
run("ha_config.yaml")