aboutsummaryrefslogtreecommitdiffstats
path: root/switch-snmp/switches.py
blob: 1bc43c2efda86e8c35e2fc0835010cd2b724c150 (plain)
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
import prometheus_client
import snmpOmada
import mikrotik
import os

from influxdb_client import InfluxDBClient, Point, WritePrecision
from influxdb_client.client.write_api import SYNCHRONOUS

def append(points):
    influxc = InfluxDBClient(
        url = "http://%s:8086" % INFLUXDB_HOST,
        token = os.environ["DOCKER_INFLUXDB_INIT_ADMIN_TOKEN"],
        org = os.environ["DOCKER_INFLUXDB_INIT_ORG"] 
    )
    influxc.ping()

    for measurement in points:
        for field in measurement["fields"].keys():
            try:
                float(measurement["fields"][field])
            except ValueError:
                continue
            else:
                switch_power.labels(
                    field = field,
                    type = measurement["tags"]["type"],
                    port = str(measurement["tags"]["port"]),
                    port_name = measurement["tags"]["port_name"],
                    host = measurement["tags"]["switch_host"]
                ).set(float(measurement["fields"][field]))
                prometheus_client.push_to_gateway("%s:9091" % PUSHGATEWAY_HOST, job = "switchSNMP", registry = registry)

    write_api = influxc.write_api(write_options = SYNCHRONOUS)
    write_api.write(
        os.environ["DOCKER_INFLUXDB_INIT_BUCKET"],
        os.environ["DOCKER_INFLUXDB_INIT_ORG"],
        points,
        write_precision = WritePrecision.S
    )

if __name__ == "__main__":
    env_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "config.env")
    if os.path.exists(env_path):
        import dotenv
        dotenv.load_dotenv(dotenv_path = env_path)
        INFLUXDB_HOST = "dns.athome"
        PUSHGATEWAY_HOST = "dns.athome"
    else:
        INFLUXDB_HOST = "influxdb"
        PUSHGATEWAY_HOST = "pushgateway"

    registry = prometheus_client.CollectorRegistry()
    switch_power = prometheus_client.Gauge(
        "switch_power",
        "POE switch power usage metrics from Omada and Mikrotik switches, using Omada SNMP names",
        labelnames = ["field", "type", "port", "port_name", "host"],
        registry = registry
    )

    points = snmpOmada.get_points() + mikrotik.get_points()
    mikrotik.print_points(points)
    append(points)