summaryrefslogtreecommitdiff
path: root/prometheus_tp_link_exporter/__main__.py
blob: 06a5bd22b9d3e60f2a8325db5011ca0183a40c52 (about) (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
63
64
65
66
67
68
69
70
71
72
73
74
75
"""Connect to TP-Link router over SSH and collect metrics."""

from prometheus_client import Counter, start_http_server
import jc.parsers.ifconfig
import os
import subprocess
import time

host = os.getenv("PROMETHEUS_TP_LINK_EXPORTER_HOST", "")
password = os.getenv("PROMETHEUS_TP_LINK_EXPORTER_PASSWORD", "")
interval = int(os.getenv("PROMETHEUS_TP_LINK_EXPORTER_INTERVAL", "10"))
listen_addresses = os.getenv(
    "PROMETHEUS_TP_LINK_EXPORTER_LISTEN_ADDRESS", "0.0.0.0:9101"
)


def ifconfig_devices():
    """Connect to TP-Link device over SSH and return ifconfig output."""
    return jc.parsers.ifconfig.parse(
        subprocess.getoutput(
            f"sshpass -p{password} ssh -o KexAlgorithms=+diffie-hellman-group1-sha1 -F /dev/null admin@{host} /sbin/ifconfig"
        )
    )


node_network_receive_bytes_total = Counter(
    "node_network_receive_bytes_total",
    "Network device statistic receive_bytes.",
    ["device"],
)

node_network_transmit_bytes_total = Counter(
    "node_network_transmit_bytes_total",
    "Network device statistic transmit_bytes.",
    ["device"],
)


def process_node_network():
    """Process request."""
    devices = ifconfig_devices()
    for device in devices:
        if (device["name"],) in node_network_transmit_bytes_total._metrics:
            previos_value = node_network_transmit_bytes_total._metrics[
                (device["name"],)
            ]._value._value
            if previos_value <= device["tx_bytes"]:
                node_network_transmit_bytes_total.labels(device=device["name"]).inc(
                    device["tx_bytes"] - previos_value
                )
        else:
            node_network_transmit_bytes_total.labels(device=device["name"]).inc(device["tx_bytes"])
    for device in devices:
        if (device["name"],) in node_network_receive_bytes_total._metrics:
            previos_value = node_network_receive_bytes_total._metrics[(device["name"],)]._value._value
            if previos_value <= device["rx_bytes"]:
                node_network_receive_bytes_total.labels(device=device["name"]).inc(
                    device["rx_bytes"] - previos_value
                )
        else:
            node_network_receive_bytes_total.labels(device=device["name"]).inc(device["rx_bytes"])


def main():
    """Entry point."""
    start_http_server(
        port=int(listen_addresses.split(":")[1]), addr=listen_addresses.split(":")[0]
    )
    while True:
        process_node_network()
        time.sleep(interval)


if __name__ == "__main__":
    main()