-
Notifications
You must be signed in to change notification settings - Fork 4
/
speeder.py
137 lines (127 loc) · 6.26 KB
/
speeder.py
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
"""
MIT License
Copyright (c) 2024 dbrennand
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
from influxdb_client.client.write_api import SYNCHRONOUS
from influxdb_client import InfluxDBClient
from loguru import logger
import subprocess
import os
import json
import time
__version__ = "1.2.0"
logger.debug(f"Starting speeder version: {__version__}.")
# Retrieve environment variables
SPEEDER_SPEEDTEST_INTERVAL = int(
os.environ.get("SPEEDER_SPEEDTEST_INTERVAL", 300)
) # 5 minutes
SPEEDER_SPEEDTEST_SERVER_ID = os.environ.get("SPEEDER_SPEEDTEST_SERVER_ID", "")
SPEEDER_INFLUXDB_HOST = os.environ.get("SPEEDER_INFLUXDB_HOST", "influxdb")
SPEEDER_INFLUXDB_PORT = int(os.environ.get("SPEEDER_INFLUXDB_PORT", 8086))
SPEEDER_INFLUXDB_TOKEN = os.environ.get("SPEEDER_INFLUXDB_TOKEN", "root")
SPEEDER_INFLUXDB_ORG = os.environ.get("SPEEDER_INFLUXDB_ORG", "speeder")
SPEEDER_INFLUXDB_BUCKET = os.environ.get("SPEEDER_INFLUXDB_BUCKET", "speeder")
# Check environment variable has not been provided
if not SPEEDER_SPEEDTEST_SERVER_ID:
logger.debug(
"SPEEDER_SPEEDTEST_SERVER_ID environment variable has no server IDs. Choose from the list below and set the environment variable."
)
servers = subprocess.run(["/librespeed", "--list"], capture_output=True, text=True)
logger.debug(servers.stdout)
exit(1)
else:
# Create list from comma separated string of server IDs
SPEEDER_SPEEDTEST_SERVER_IDs = SPEEDER_SPEEDTEST_SERVER_ID.split(",")
# Connect to InfluxDB
logger.debug(
f"Connecting to InfluxDB: {SPEEDER_INFLUXDB_HOST}:{SPEEDER_INFLUXDB_PORT} with organisation: {SPEEDER_INFLUXDB_ORG}."
)
with InfluxDBClient(
url=f"http://{SPEEDER_INFLUXDB_HOST}:{SPEEDER_INFLUXDB_PORT}",
token=SPEEDER_INFLUXDB_TOKEN,
org=SPEEDER_INFLUXDB_ORG,
) as client:
# Run the speedtest using the librespeed/speedtest-cli on an interval
while True:
for server_id in SPEEDER_SPEEDTEST_SERVER_IDs:
logger.debug(f"Running speedtest for server ID: {server_id}.")
result = subprocess.run(
[
"/librespeed",
"--server",
server_id,
"--telemetry-level",
"disabled",
"--json",
],
capture_output=True,
text=True,
)
# Check if the speedtest failed
if result.returncode != 0:
# CLI errors go to stdout
logger.error(
f"Speedtest for server ID: {server_id} failed with exit code: {result.returncode}.\nError: {result.stdout}"
)
else:
logger.debug(f"Speedtest for server ID: {server_id} succeeded.")
try:
json_result = json.loads(result.stdout)
# Check if the JSON result is empty
if not json_result:
raise json.decoder.JSONDecodeError(
"JSON result is empty.", json_result, 0
)
except json.decoder.JSONDecodeError as err:
logger.error(
f"Failed to parse JSON results for server ID: {server_id}.\nError: {err}"
)
continue
with client.write_api(write_options=SYNCHRONOUS) as write_api:
record = [
{
"measurement": "speeder",
"tags": {
"server_name": json_result[0]["server"]["name"],
"server_url": json_result[0]["server"]["url"],
"ip": json_result[0]["client"]["ip"],
"hostname": json_result[0]["client"]["hostname"],
"region": json_result[0]["client"]["region"],
"city": json_result[0]["client"]["city"],
"country": json_result[0]["client"]["country"],
"org": json_result[0]["client"]["org"],
"timezone": json_result[0]["client"]["timezone"],
},
"time": json_result[0]["timestamp"],
"fields": {
"bytes_sent": json_result[0]["bytes_sent"],
"bytes_received": json_result[0]["bytes_received"],
"ping": float(json_result[0]["ping"]),
"jitter": float(json_result[0]["jitter"]),
"upload": float(json_result[0]["upload"]),
"download": float(json_result[0]["download"]),
},
}
]
logger.debug(
f"Writing record to InfluxDB bucket: {SPEEDER_INFLUXDB_BUCKET} for speedtest at {json_result[0]['timestamp']} using server ID: {server_id}."
)
logger.debug(f"Record:\n{record}")
write_api.write(bucket=SPEEDER_INFLUXDB_BUCKET, record=record)
logger.debug(f"Sleeping for {SPEEDER_SPEEDTEST_INTERVAL} seconds.")
time.sleep(SPEEDER_SPEEDTEST_INTERVAL)