fixed typos, errors with packetloss data

This commit is contained in:
Josh Smith 2020-07-30 18:53:20 -04:00
parent 61e60fb103
commit 829905d2cf
6 changed files with 327 additions and 328 deletions

View File

@ -1,4 +1,4 @@
.git .git
Dockerfile Dockerfile
*~ *~
README.md README.md

256
.gitignore vendored
View File

@ -1,128 +1,128 @@
# VSCode Settings # VSCode Settings
.vscode .vscode
# Byte-compiled / optimized / DLL files # Byte-compiled / optimized / DLL files
__pycache__/ __pycache__/
*.py[cod] *.py[cod]
*$py.class *$py.class
# C extensions # C extensions
*.so *.so
# Distribution / packaging # Distribution / packaging
.Python .Python
build/ build/
develop-eggs/ develop-eggs/
dist/ dist/
downloads/ downloads/
eggs/ eggs/
.eggs/ .eggs/
lib/ lib/
lib64/ lib64/
parts/ parts/
sdist/ sdist/
var/ var/
wheels/ wheels/
pip-wheel-metadata/ pip-wheel-metadata/
share/python-wheels/ share/python-wheels/
*.egg-info/ *.egg-info/
.installed.cfg .installed.cfg
*.egg *.egg
MANIFEST MANIFEST
# PyInstaller # PyInstaller
# Usually these files are written by a python script from a template # Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it. # before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest *.manifest
*.spec *.spec
# Installer logs # Installer logs
pip-log.txt pip-log.txt
pip-delete-this-directory.txt pip-delete-this-directory.txt
# Unit test / coverage reports # Unit test / coverage reports
htmlcov/ htmlcov/
.tox/ .tox/
.nox/ .nox/
.coverage .coverage
.coverage.* .coverage.*
.cache .cache
nosetests.xml nosetests.xml
coverage.xml coverage.xml
*.cover *.cover
*.py,cover *.py,cover
.hypothesis/ .hypothesis/
.pytest_cache/ .pytest_cache/
# Translations # Translations
*.mo *.mo
*.pot *.pot
# Django stuff: # Django stuff:
*.log *.log
local_settings.py local_settings.py
db.sqlite3 db.sqlite3
db.sqlite3-journal db.sqlite3-journal
# Flask stuff: # Flask stuff:
instance/ instance/
.webassets-cache .webassets-cache
# Scrapy stuff: # Scrapy stuff:
.scrapy .scrapy
# Sphinx documentation # Sphinx documentation
docs/_build/ docs/_build/
# PyBuilder # PyBuilder
target/ target/
# Jupyter Notebook # Jupyter Notebook
.ipynb_checkpoints .ipynb_checkpoints
# IPython # IPython
profile_default/ profile_default/
ipython_config.py ipython_config.py
# pyenv # pyenv
.python-version .python-version
# pipenv # pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies # However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not # having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies. # install all needed dependencies.
#Pipfile.lock #Pipfile.lock
# celery beat schedule file # celery beat schedule file
celerybeat-schedule celerybeat-schedule
# SageMath parsed files # SageMath parsed files
*.sage.py *.sage.py
# Environments # Environments
.env .env
.venv .venv
env/ env/
venv/ venv/
ENV/ ENV/
env.bak/ env.bak/
venv.bak/ venv.bak/
# Spyder project settings # Spyder project settings
.spyderproject .spyderproject
.spyproject .spyproject
# Rope project settings # Rope project settings
.ropeproject .ropeproject
# mkdocs documentation # mkdocs documentation
/site /site
# mypy # mypy
.mypy_cache/ .mypy_cache/
.dmypy.json .dmypy.json
dmypy.json dmypy.json
# Pyre type checker # Pyre type checker
.pyre/ .pyre/

View File

@ -1,28 +1,28 @@
FROM python:3.8-slim-buster FROM python:3.8-slim-buster
LABEL maintainer="Aiden Gilmartin" \ LABEL maintainer="Josh Smith" \
description="Speedtest to InfluxDB data bridge" description="Original by Aiden Gilmartin. Speedtest to InfluxDB data bridge"
#wget "https://ookla.bintray.com/download/$(wget https://ookla.bintray.com/download/ -q -O - | grep x86_64-linux.tgz\" | grep -Po "(?<=href=\")[^^\"]*" | cut -d ":" -f 2)"
# Install dependencies # Install dependencies
ENV DEBIAN_FRONTEND=noninteractive ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update RUN apt-get update
RUN apt-get -q -y install --no-install-recommends apt-utils gnupg1 apt-transport-https dirmngr RUN apt-get -q -y install --no-install-recommends apt-utils gnupg1 apt-transport-https dirmngr
# Install speedtest-cli # Install speedtest-cli
RUN apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 379CE192D401AB61 RUN apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 379CE192D401AB61
RUN echo "deb https://ookla.bintray.com/debian buster main" | tee /etc/apt/sources.list.d/speedtest.list RUN echo "deb https://ookla.bintray.com/debian buster main" | tee /etc/apt/sources.list.d/speedtest.list
RUN apt-get update && apt-get -q -y install speedtest RUN apt-get update && apt-get -q -y install speedtest
# Install Python packages # Install Python packages
COPY requirements.txt / COPY requirements.txt /
RUN pip install -r /requirements.txt RUN pip install -r /requirements.txt
# Clean up # Clean up
RUN apt-get -q -y autoremove RUN apt-get -q -y autoremove
RUN apt-get -q -y clean RUN apt-get -q -y clean
RUN rm -rf /var/lib/apt/lists/* RUN rm -rf /var/lib/apt/lists/*
# Final setup & execution # Final setup & execution
COPY . /app COPY . /app
WORKDIR /app WORKDIR /app
CMD ["python3", "-u", "main.py"] CMD ["python3", "-u", "main.py"]

42
LICENSE
View File

@ -1,21 +1,21 @@
MIT License MIT License
Copyright (c) 2019 Aiden Gilmartin Copyright (c) 2019 Aiden Gilmartin
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software. copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 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 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. SOFTWARE.

View File

@ -1,47 +1,47 @@
# Speedtest to InfluxDB # Speedtest to InfluxDB
This is a small Python script that will continuously run the Speedtest CLI application by Ookla, reformat the data output and forward it on to an InfluxDB database. This is a small Python script that will continuously run the Speedtest CLI application by Ookla, reformat the data output and forward it on to an InfluxDB database.
You may want to do this so that you can track your internet connections consistency over time. Using Grafana you can view and explore this data easily. You may want to do this so that you can track your internet connections consistency over time. Using Grafana you can view and explore this data easily.
![Grafana Dashboard](https://i.imgur.com/8cUdMy7.png) ![Grafana Dashboard](https://i.imgur.com/8cUdMy7.png)
## Using the script ## Using the script
The InfluxDB connection settings are controlled by environment variables. The InfluxDB connection settings are controlled by environment variables.
The variables available are: The variables available are:
- INFLUX_DB_ADDRESS = 192.168.1.xxx - INFLUX_DB_ADDRESS = 192.168.1.xxx
- INFLUX_DB_PORT = 8086 - INFLUX_DB_PORT = 8086
- INFLUX_DB_USER = user - INFLUX_DB_USER = user
- INFLUX_DB_PASSWORD = pass - INFLUX_DB_PASSWORD = pass
- INFLUX_DB_DATABASE = speedtest - INFLUX_DB_DATABASE = speedtest
- SPEEDTEST_INTERVAL = 1800 - SPEEDTEST_INTERVAL = 1800
- SPEEDTEST_FAIL_INTERVAL = 300 - SPEEDTEST_FAIL_INTERVAL = 300
Be aware that this script will automatically accept the license and GDPR statement so that it can run non-interactively. Make sure you agree with them before running. Be aware that this script will automatically accept the license and GDPR statement so that it can run non-interactively. Make sure you agree with them before running.
### 1. No Container ### 1. No Container
1. [Install the Speedtest CLI application by Ookla.](https://www.speedtest.net/apps/cli) 1. [Install the Speedtest CLI application by Ookla.](https://www.speedtest.net/apps/cli)
NOTE: The `speedtest-cli` package in distro repositories is an unofficial client. It will need to be uninstalled before installing the Ookla Speedtest CLI application with the directions on their website. NOTE: The `speedtest-cli` package in distro repositories is an unofficial client. It will need to be uninstalled before installing the Ookla Speedtest CLI application with the directions on their website.
2. Install the InfluxDB client for library from Python. 2. Install the InfluxDB client for library from Python.
`pip install influxdb` `pip install influxdb`
3. Run the script. 3. Run the script.
`python3 ./main.py` `python3 ./main.py`
### 2. Run with Docker or Podman ### 2. Run with Docker or Podman
1. Build the container. 1. Build the container.
`docker build -t aidengilmartin/speedtest-influx ./` `docker build -t aidengilmartin/speedtest-influx ./`
2. Run the container. 2. Run the container.
`docker run -d --name speedtest-influx aidengilmartin/speedtest-influx` `docker run -d --name speedtest-influx aidengilmartin/speedtest-influx`

203
main.py
View File

@ -1,103 +1,102 @@
import time import time
import json import json
import subprocess import subprocess
import os import os
from influxdb import InfluxDBClient
from influxdb import InfluxDBClient
# InfluxDB Settings
# InfluxDB Settings DB_ADDRESS = os.environ.get('INFLUX_DB_ADDRESS')
DB_ADDRESS = os.environ.get('INFLUX_DB_ADDRESS') DB_PORT = int(os.environ.get('INFLUX_DB_PORT'))
DB_PORT = int(os.environ.get('INFLUX_DB_PORT')) DB_USER = os.environ.get('INFLUX_DB_USER')
DB_USER = os.environ.get('INFLUX_DB_USER') DB_PASSWORD = os.environ.get('INFLUX_DB_PASSWORD')
DB_PASSWORD = os.environ.get('INFLUX_DB_PASSWORD') DB_DATABASE = os.environ.get('INFLUX_DB_DATABASE')
DB_DATABASE = os.environ.get('INFLUX_DB_DATABASE')
# Speedtest Settings
# Speedtest Settings TEST_INTERVAL = int(os.environ.get('SPEEDTEST_INTERVAL')) # Time between tests (in seconds).
TEST_INTERVAL = int(os.environ.get('SPEEDTEST_INTERVAL')) # Time between tests (in seconds). TEST_FAIL_INTERVAL = int(os.environ.get('SPEEDTEST_FAIL_INTERVAL')) # Time before retrying a failed Speedtest (in seconds).
TEST_FAIL_INTERVAL = int(os.environ.get('SPEEDTEST_FAIL_INTERVAL')) # Time before retrying a failed Speedtest (in seconds).
influxdb_client = InfluxDBClient(
influxdb_client = InfluxDBClient( DB_ADDRESS, DB_PORT, DB_USER, DB_PASSWORD, None)
DB_ADDRESS, DB_PORT, DB_USER, DB_PASSWORD, None)
def init_db():
def init_db(): databases = influxdb_client.get_list_database()
databases = influxdb_client.get_list_database()
if len(list(filter(lambda x: x['name'] == DB_DATABASE, databases))) == 0:
if len(list(filter(lambda x: x['name'] == DB_DATABASE, databases))) == 0: influxdb_client.create_database(
influxdb_client.create_database( DB_DATABASE) # Create if does not exist.
DB_DATABASE) # Create if does not exist. else:
else: influxdb_client.switch_database(DB_DATABASE) # Switch to if does exist.
influxdb_client.switch_database(DB_DATABASE) # Switch to if does exist. def pkt_loss(data):
def pkt_loss(data): if 'packetLoss' in data.keys():
if data['packetLoss']: return data['packetLoss']
return data['packetLoss'] else:
else: return 0
return 0
def format_for_influx(cliout):
def format_for_influx(cliout): data = json.loads(cliout)
data = json.loads(cliout) # There is additional data in the speedtest-cli output but it is likely not necessary to store.
# There is additional data in the speedtest-cli output but it is likely not necessary to store. influx_data = [
influx_data = [ {
{ 'measurement': 'ping',
'measurement': 'ping', 'time': data['timestamp'],
'time': data['timestamp'], 'fields': {
'fields': { 'jitter': data['ping']['jitter'],
'jitter': data['ping']['jitter'], 'latency': data['ping']['latency']
'latency': data['ping']['latency'] }
} },
}, {
{ 'measurement': 'download',
'measurement': 'download', 'time': data['timestamp'],
'time': data['timestamp'], 'fields': {
'fields': { # Byte to Megabit
# Byte to Megabit 'bandwidth': data['download']['bandwidth'] / 125000,
'bandwidth': data['download']['bandwidth'] / 125000, 'bytes': data['download']['bytes'],
'bytes': data['download']['bytes'], 'elapsed': data['download']['elapsed']
'elapsed': data['download']['elapsed'] }
} },
}, {
{ 'measurement': 'upload',
'measurement': 'upload', 'time': data['timestamp'],
'time': data['timestamp'], 'fields': {
'fields': { # Byte to Megabit
# Byte to Megabit 'bandwidth': data['upload']['bandwidth'] / 125000,
'bandwidth': data['upload']['bandwidth'] / 125000, 'bytes': data['upload']['bytes'],
'bytes': data['upload']['bytes'], 'elapsed': data['upload']['elapsed']
'elapsed': data['upload']['elapsed'] }
} },
}, {
{ 'measurement': 'packetLoss',
'measurement': 'packetLoss', 'time': data['timestamp'],
'time': data['timestamp'], 'fields': {
'fields': { 'packetLoss': pkt_loss(data)
'packetLoss': pkt_loss(data) }
} }
} ]
]
return influx_data
return influx_data
def main():
def main(): init_db() # Setup the database if it does not already exist.
init_db() # Setup the database if it does not already exist.
while (1): # Run a Speedtest and send the results to influxDB indefinitely.
while (1): # Run a Speedtest and send the results to influxDB indefinitely. speedtest = subprocess.run(
speedtest = subprocess.run( ["speedtest", "--accept-license", "--accept-gdpr", "-f", "json"], capture_output=True)
["speedtest", "--accept-license", "--accept-gdpr", "-f", "json"], capture_output=True)
if speedtest.returncode == 0: # Speedtest was successful.
if speedtest.returncode == 0: # Speedtest was successful. data = format_for_influx(speedtest.stdout)
data = format_for_influx(speedtest.stdout) print("Speedtest Successful:")
print("Speedtest Successful:") if influxdb_client.write_points(data) == True:
if influxdb_client.write_points(data) == True: print("Data written to DB successfully")
print("Data written to DB successfully") time.sleep(TEST_INTERVAL)
time.sleep(TEST_INTERVAL) else: # Speedtest failed.
else: # Speedtest failed. print("Speedtest Failed:")
print("Speedtest Failed:") print(speedtest.stderr)
print(speedtest.stderr) print(speedtest.stdout)
print(speedtest.stdout) time.sleep(TEST_FAIL_INTERVAL)
time.sleep(TEST_FAIL_INTERVAL)
if __name__ == '__main__':
if __name__ == '__main__': print('Speedtest CLI Data Logger to InfluxDB')
print('Speedtest CLI Data Logger to InfluxDB')
main() main()