Compare commits

...

8 commits

Author SHA1 Message Date
Benjamin Renard b7c13a4859
Switch from Woodpecker CI to Forgejo Actions
All checks were successful
Run tests / test-precommit (push) Successful in 1m16s
2024-03-13 19:26:59 +01:00
Benjamin Renard a9ae368521
Add -t/--timeout parameter and introduce some new pre-commit hooks 2024-03-13 18:44:28 +01:00
Benjamin Renard bf0a560566
Configure pre-commit to run all tests on commit and use it for CI tests
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
ci/woodpecker/tag/woodpecker Pipeline was successful
2023-01-19 14:59:57 +01:00
root ce39354048 Fix debian package dependency
Some checks failed
ci/woodpecker/push/woodpecker Pipeline failed
ci/woodpecker/tag/woodpecker Pipeline was successful
2022-12-03 16:20:51 +01:00
Benjamin Renard f8ad7dc984 Configure CI to run test, build package and publish release
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
ci/woodpecker/tag/woodpecker Pipeline was successful
2022-12-03 15:48:47 +01:00
Benjamin Renard 5df2efac05 Code cleaning 2022-12-03 15:25:09 +01:00
Benjamin Renard a8fff06d00 Add -x/--exclude parameter 2022-12-03 15:14:19 +01:00
Benjamin Renard 9380c63913 Add retry options to retreive device status to avoid false positive unreachable device alert 2022-10-26 15:08:47 +02:00
13 changed files with 424 additions and 59 deletions

View file

@ -0,0 +1,89 @@
---
name: Build and publish Debian package
on: [create]
jobs:
build:
runs-on: docker
container:
image: docker.io/brenard/debian-python-deb:latest
steps:
- name: Check out repository code
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Build Debian package
env:
MAINTAINER_NAME: ${{ vars.MAINTAINER_NAME }}
MAINTAINER_EMAIL: ${{ vars.MAINTAINER_EMAIL }}
DEBIAN_CODENAME: ${{ vars.DEBIAN_CODENAME }}
run: |
echo "${{ secrets.GPG_KEY }}"|base64 -d|gpg --import
./build.sh
mv check_esphome_devices dist/
- name: Upload Debian package files
uses: actions/upload-artifact@v3
with:
name: dist
path: |
dist/*.buildinfo
dist/*.changes
dist/*.deb
dist/*.dsc
dist/*.tar.gz
dist/release_notes.md
dist/check_esphome_devices
publish-forgejo:
runs-on: docker
container:
image: docker.io/brenard/debian-python-deb:latest
steps:
- name: Download Debian package files
uses: actions/download-artifact@v3
with:
name: dist
- name: Create the release
id: create-release
shell: bash
run: |
mkdir release
mv *.deb release/
mv check_esphome_devices release/
md5sum release/* > md5sum.txt
sha512sum release/* > sha512sum.txt
mv md5sum.txt sha512sum.txt release/
{
echo 'release_note<<EOF'
cat release_notes.md
echo 'EOF'
} >> "$GITHUB_OUTPUT"
- name: Publish release on Forgejo
uses: actions/forgejo-release@v1
with:
direction: upload
url: https://gitea.zionetrix.net
token: ${{ secrets.forgejo_token }}
release-dir: release
release-notes: ${{ steps.create-release.outputs.release_note }}
publish-aptly:
runs-on: docker
container:
image: docker.io/brenard/aptly-publish:latest
steps:
- name: "Download Debian package files"
uses: actions/download-artifact@v3
with:
name: dist
- name: "Publish Debian package on Aptly repository"
uses: https://gitea.zionetrix.net/bn8/aptly-publish@master
with:
api_url: ${{ vars.apt_api_url }}
api_username: ${{ vars.apt_api_username }}
api_password: ${{ secrets.apt_api_password }}
repo_name: ${{ vars.apt_repo_name }}
path: "./"
source_name: ${{ vars.apt_source_name }}

View file

@ -0,0 +1,21 @@
---
name: Run tests
on: [push]
jobs:
test-precommit:
runs-on: docker
container:
image: docker.io/brenard/python-pre-commit:latest
steps:
- name: Check out repository code
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Install python dependencies
env:
DEBIAN_FRONTEND: noninteractive
run: |
apt-get -qq update
apt-get -qq -y install --no-install-recommends python3-requests
- name: Run pre-commit
run: pre-commit run --all-files

64
.pre-commit-config.yaml Normal file
View file

@ -0,0 +1,64 @@
# Pre-commit hooks to run tests and ensure code is cleaned.
# See https://pre-commit.com for more information
---
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.1.6
hooks:
- id: ruff
args: ["--fix"]
- repo: https://github.com/asottile/pyupgrade
rev: v3.15.0
hooks:
- id: pyupgrade
args: ["--keep-percent-format", "--py37-plus"]
- repo: https://github.com/psf/black
rev: 23.11.0
hooks:
- id: black
args: ["--target-version", "py37", "--line-length", "100"]
- repo: https://github.com/PyCQA/isort
rev: 5.12.0
hooks:
- id: isort
args: ["--profile", "black", "--line-length", "100"]
- repo: https://github.com/PyCQA/flake8
rev: 6.1.0
hooks:
- id: flake8
args: ["--max-line-length=100"]
- repo: https://github.com/codespell-project/codespell
rev: v2.2.2
hooks:
- id: codespell
args:
- --ignore-words-list=exten
- --skip="./.*,*.csv,*.json,*.ini,*.subject,*.txt,*.html,*.log,*.conf"
- --quiet-level=2
- --ignore-regex=.*codespell-ignore$
# - --write-changes # Uncomment to write changes
exclude_types: [csv, json]
- repo: https://github.com/adrienverge/yamllint
rev: v1.32.0
hooks:
- id: yamllint
ignore: .github/
- repo: https://github.com/pre-commit/mirrors-prettier
rev: v2.7.1
hooks:
- id: prettier
args: ["--print-width", "100"]
- repo: local
hooks:
- id: pylint
name: pylint
entry: pylint
language: system
types: [python]
require_serial: true
- repo: https://github.com/PyCQA/bandit
rev: 1.7.5
hooks:
- id: bandit
args: [--skip, "B101", --recursive]
minimum_pre_commit_version: 3.2.0

View file

@ -19,12 +19,22 @@ service nagios-nrpe-server reload
## Usage
```
usage: check_esphome_devices [-h] [-d] [-H HOST]
usage: check_esphome_devices [-h] [-d] [-H HOST] [-r RETRY_COUNT] [-D RETRY_DELAY]
[-t TIMEOUT] [-x EXCLUDE]
optional arguments:
options:
-h, --help show this help message and exit
-d, --debug
-H HOST, --host HOST ESPHome dashboard URL (default: http://127.0.0.1:6052)
-r RETRY_COUNT, --retry RETRY_COUNT
Number of retry to retrieve device status (default: 4)
-D RETRY_DELAY, --delay RETRY_DELAY
Delay in second between two retry to retrieve device status
(default: 1s)
-t TIMEOUT, --timeout TIMEOUT
Timeout in second on API requests (default: 10s)
-x EXCLUDE, --exclude EXCLUDE
Regex exclude pattern(s)
```
## Copyright
@ -35,7 +45,6 @@ Copyright (c) 2022 Benjamin Renard <brenard@zionetrix.net>
This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 3 as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

62
build.sh Executable file
View file

@ -0,0 +1,62 @@
#!/bin/bash
QUIET_ARG=""
[ "$1" == "--quiet" ] && QUIET_ARG="--quiet"
# Enter source directory
cd $( dirname $0 )
echo "Clean previous build..."
rm -fr dist
echo "Detect version using git describe..."
VERSION="$( git describe --tags|sed 's/^[^0-9]*//' )"
echo "Create building environemt..."
BDIR=dist/check-esphome-devices-$VERSION
mkdir -p $BDIR
[ -z "$QUIET_ARG" ] && RSYNC_ARG="-v" || RSYNC_ARG=""
rsync -a $RSYNC_ARG debian/ $BDIR/debian/
cp check_esphome_devices $BDIR/
echo "Set VERSION=$VERSION in gitdch using sed..."
sed -i "s/^VERSION *=.*$/VERSION = '$VERSION'/" $BDIR/check_esphome_devices
if [ -z "$DEBIAN_CODENAME" ]
then
echo "Retrieve debian codename using lsb_release..."
DEBIAN_CODENAME=$( lsb_release -c -s )
else
echo "Use debian codename from environment ($DEBIAN_CODENAME)"
fi
echo "Generate debian changelog using gitdch..."
GITDCH_ARGS=('--verbose')
[ -n "$QUIET_ARG" ] && GITDCH_ARGS=('--warning')
if [ -n "$MAINTAINER_NAME" ]
then
echo "Use maintainer name from environment ($MAINTAINER_NAME)"
GITDCH_ARGS+=("--maintainer-name" "${MAINTAINER_NAME}")
fi
if [ -n "$MAINTAINER_EMAIL" ]
then
echo "Use maintainer email from environment ($MAINTAINER_EMAIL)"
GITDCH_ARGS+=("--maintainer-email" "$MAINTAINER_EMAIL")
fi
gitdch \
--package-name check-esphome-devices \
--version "${VERSION}" \
--code-name $DEBIAN_CODENAME \
--output $BDIR/debian/changelog \
--release-notes dist/release_notes.md \
"${GITDCH_ARGS[@]}"
if [ -n "$MAINTAINER_NAME" -a -n "$MAINTAINER_EMAIL" ]
then
echo "Set Maintainer field in debian control file ($MAINTAINER_NAME <$MAINTAINER_EMAIL>)..."
sed -i "s/^Maintainer: .*$/Maintainer: $MAINTAINER_NAME <$MAINTAINER_EMAIL>/" $BDIR/debian/control
fi
echo "Build debian package..."
cd $BDIR
dpkg-buildpackage

View file

@ -20,109 +20,185 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
"""
import argparse
import sys
import logging
import re
import sys
import time
import requests
# nagios exit code
STATUS = {
'OK': 0,
'WARNING': 1,
'CRITICAL': 2,
'UNKNOWN': 3
}
STATUS = {"OK": 0, "WARNING": 1, "CRITICAL": 2, "UNKNOWN": 3}
DEFAULT_HOST = 'http://127.0.0.1:6052'
DEFAULT_HOST = "http://127.0.0.1:6052"
DEFAULT_RETRY_COUNT = 4
DEFAULT_RETRY_DELAY = 1
DEFAULT_TIMEOUT = 10
parser = argparse.ArgumentParser()
parser.add_argument(
'-d', '--debug',
action="store_true",
dest="debug",
default=False
)
parser.add_argument("-d", "--debug", action="store_true", dest="debug", default=False)
parser.add_argument(
'-H', '--host',
"-H",
"--host",
action="store",
dest="host",
help=f'ESPHome dashboard URL (default: {DEFAULT_HOST})',
help=f"ESPHome dashboard URL (default: {DEFAULT_HOST})",
type=str,
default=DEFAULT_HOST
default=DEFAULT_HOST,
)
parser.add_argument(
"-r",
"--retry",
action="store",
dest="retry_count",
help=("Number of retry to retrieve device status " f"(default: {DEFAULT_RETRY_COUNT})"),
type=int,
default=DEFAULT_RETRY_COUNT,
)
parser.add_argument(
"-D",
"--delay",
action="store",
dest="retry_delay",
help=(
"Delay in second between two retry to retrieve device status "
f"(default: {DEFAULT_RETRY_DELAY}s)"
),
type=int,
default=DEFAULT_RETRY_DELAY,
)
parser.add_argument(
"-t",
"--timeout",
action="store",
dest="timeout",
help=f"Timeout in second on API requests (default: {DEFAULT_TIMEOUT}s)",
type=int,
default=DEFAULT_TIMEOUT,
)
def exclude_pattern(value):
"""Check and compile exclusion pattern parameter"""
return re.compile(value)
parser.add_argument(
"-x",
"--exclude",
action="append",
dest="exclude",
help="Regex exclude pattern(s)",
type=exclude_pattern,
default=[],
)
options = parser.parse_args()
logging.basicConfig(
level=logging.DEBUG if options.debug else logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s')
format="%(asctime)s - %(levelname)s - %(message)s",
)
if options.host[-1] == '/':
if options.host[-1] == "/":
options.host = options.host[-1]
r = requests.get(f'{options.host}/devices')
def is_excluded(name):
"""Check if device is excluded"""
for pattern in options.exclude:
if pattern.search(name):
logging.debug("Device %s is excluded", name)
return True
logging.debug("Device %s is not excluded", name)
return False
r = requests.get(f"{options.host}/devices", timeout=options.timeout)
devices_data = r.json()
logging.debug('Devices data: %s (%s)', devices_data, type(devices_data))
logging.debug("Devices data: %s (%s)", devices_data, type(devices_data))
if not devices_data:
print('UNKNOWN - Fail to retreive devices using ESPHome Dashboard API')
sys.exit(STATUS['UNKNOWN'])
print("UNKNOWN - Fail to retrieve devices using ESPHome Dashboard API")
sys.exit(STATUS["UNKNOWN"])
r = requests.get(f'{options.host}/ping')
ping_data = r.json()
logging.debug('Ping data: %s (%s)', ping_data, type(ping_data))
COUNT = 0
while COUNT < options.retry_count:
r = requests.get(f"{options.host}/ping", timeout=options.timeout)
COUNT += 1
ping_data = r.json()
logging.debug("Ping data: %s (%s)", ping_data, type(ping_data))
if ping_data:
UNREACHABLE = False
for dev in ping_data:
if not ping_data[dev] and not is_excluded(dev.replace(".yaml", "")):
UNREACHABLE = True
break
if not UNREACHABLE:
break
logging.debug("Wait %d seconds before retry...", options.retry_delay)
time.sleep(options.retry_delay)
if not ping_data:
print(
'UNKNOWN - Fail to retreive devices status '
'using ESPHome Dashboard API')
sys.exit(STATUS['UNKNOWN'])
print("UNKNOWN - Fail to retrieve devices status using ESPHome Dashboard API")
sys.exit(STATUS["UNKNOWN"])
UPDATE_AVAILABLE = 0
UNREACHABLE_DEVICES = 0
NO_PING_DATA = 0
errors = []
devices = {}
for dev in devices_data['configured']:
devices[dev['name']] = dev
logging.debug('Device %s: %s', dev['name'], dev)
if dev['deployed_version'] != dev['current_version']:
for dev in devices_data["configured"]:
devices[dev["name"]] = dev
logging.debug("Device %s: %s", dev["name"], dev)
if is_excluded(dev["name"]):
continue
if dev["deployed_version"] != dev["current_version"]:
UPDATE_AVAILABLE += 1
errors.append(
f'Update available for device {dev["name"]} '
f'({dev["deployed_version"]} => {dev["current_version"]})')
f'({dev["deployed_version"]} => {dev["current_version"]})'
)
if dev['configuration'] not in ping_data:
if dev["configuration"] not in ping_data:
NO_PING_DATA += 1
errors.append(
f'No ping data found for device {dev["name"]} '
f'({dev["configuration"]})')
elif not ping_data[dev['configuration']]:
errors.append(f'No ping data found for device {dev["name"]} ' f'({dev["configuration"]})')
elif not ping_data[dev["configuration"]]:
UNREACHABLE_DEVICES += 1
errors.append(f'Device {dev["name"]} is unreachable')
if not errors:
print(f'OK - no problem detected on the {len(devices)} devices')
EXIT_STATUS = STATUS['OK']
print(f"OK - no problem detected on the {len(devices)} devices")
EXIT_STATUS = STATUS["OK"]
else:
msg = []
if UNREACHABLE_DEVICES:
msg.append(f'{UNREACHABLE_DEVICES} unreachable devices')
msg.append(f"{UNREACHABLE_DEVICES} unreachable devices")
if NO_PING_DATA:
msg.append(f'{NO_PING_DATA} missing ping device status')
msg.append(f"{NO_PING_DATA} missing ping device status")
if UPDATE_AVAILABLE:
msg.append(f'{UPDATE_AVAILABLE} update available')
msg.append(f"{UPDATE_AVAILABLE} update available")
print(f'WARNING - {", ".join(msg)}')
print("\n".join([f'- {error}' for error in errors]))
EXIT_STATUS = STATUS['WARNING']
print("\n".join([f"- {error}" for error in errors]))
EXIT_STATUS = STATUS["WARNING"]
print("\nDevices:\n" + "\n".join([
(
f'- {name} (version = {dev["deployed_version"]}, '
f'address = {dev["address"]})'
print(
"\nDevices:\n"
+ "\n".join(
[
(
f"- {name} (version = "
f'{dev["deployed_version"] if dev["deployed_version"] else "unknown"}'
f', address = {dev["address"] if dev["address"] else "unknown"})'
)
for name, dev in devices.items()
]
)
for name, dev in devices.items()
]))
)
sys.exit(EXIT_STATUS)

1
debian/compat vendored Normal file
View file

@ -0,0 +1 @@
11

16
debian/control vendored Normal file
View file

@ -0,0 +1,16 @@
Source: check-esphome-devices
Section: admin
Priority: optional
Maintainer: Debian Zionetrix - check-esphome-devices <debian+check-esphome-devices@zionetrix.net>
Build-Depends: debhelper (>> 11.0.0)
Standards-Version: 3.9.6
Package: check-esphome-devices
Architecture: all
Depends: ${misc:Depends}, python3, python3-requests
Description: Monitoring plugin to check ESPHome devices status
This Icinga/Nagios check plugin permit to check ESPHome devices status
using the ESPHome Dashboard API :
* check if device is reachable
* check if device upgrade is available

20
debian/copyright vendored Normal file
View file

@ -0,0 +1,20 @@
This package was written by Benjamin Renard <brenard@zionetrix.net>.
Copyright (C) 2022 Benjamin Renard <brenard@zionetrix.net>
check-esphome-devices is licensed under the GNU general public license, version 3.
check-esphome-devices is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; either version 2, or (at your option) any later version.
check-esphome-devices is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
check-esphome-devices; see the file COPYING. If not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
On Debian systems, a copy of the GNU General Public License is available in
/usr/share/common-licenses/GPL-3 as part of the base-files package.

1
debian/dirs vendored Normal file
View file

@ -0,0 +1 @@
usr/lib/nagios/plugins

1
debian/install vendored Normal file
View file

@ -0,0 +1 @@
check_esphome_devices usr/lib/nagios/plugins

4
debian/rules vendored Executable file
View file

@ -0,0 +1,4 @@
#!/usr/bin/make -f
#export DH_VERBOSE=1
%:
dh $@

1
debian/source/format vendored Normal file
View file

@ -0,0 +1 @@
1.0