aboutsummaryrefslogtreecommitdiffstats
path: root/pingLogger.py
blob: 88893f12ada6f30cb74ce9d5dd7927abbb0a68db (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
from influxdb_client import InfluxDBClient, Point, WritePrecision
from influxdb_client.client.write_api import SYNCHRONOUS
import subprocess
import dotenv
import json
import re
import os

PING_INDEXES = ["rtt_min", "rtt_avg", "rtt_max", "rtt_mdev"]

def do_ping(host, numpings):
    proc = subprocess.Popen(["ping", host, "-c", str(numpings)], stdout = subprocess.PIPE)
    out = []
    while True:
        line = proc.stdout.readline()
        if not line:
            break
        line = line.rstrip().decode()
        print(line)
        out.append(line)

    return {
        "packet_loss_percent": int(re.findall(r"\d+", out[-2].split(", ")[2])[0]),
        "total_time": int(re.findall(r"\d+", out[-2].split(", ")[3])[0])
    } | {PING_INDEXES[i]: float(f) for i, f in enumerate(out[-1].split(" ")[3].split("/"), 0)}

def influx_write(fields):
    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()

    write_api = influxc.write_api(write_options = SYNCHRONOUS)
    write_api.write(
        os.environ["DOCKER_INFLUXDB_INIT_BUCKET"],
        os.environ["DOCKER_INFLUXDB_INIT_ORG"],
        [{
            "measurement": "ping_logger",
            "fields": fields
        }],
        write_precision = WritePrecision.S
    )

def main():
    fields = do_ping(os.environ["PING_HOST"], os.environ["NUM_PINGS"])
    print(json.dumps(fields, indent = 4))
    influx_write(fields)

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 = "192.168.69.5"
    else:
        INFLUXDB_HOST = os.environ["INFLUXDB_HOST"]

    main()