Compare commits
8 Commits
4294372e41
...
mqtt
| Author | SHA1 | Date | |
|---|---|---|---|
| 4d2208f961 | |||
| eec17edf93 | |||
| ececdf0b04 | |||
| d15d40e902 | |||
| 03cf24f072 | |||
| 42c3eac20a | |||
| 4d6becffa1 | |||
| 493a395150 |
@@ -3,12 +3,13 @@
|
|||||||
"""dependencys:
|
"""dependencys:
|
||||||
- pip3 install nagiosplugin
|
- pip3 install nagiosplugin
|
||||||
- pip3 install argparse
|
- pip3 install argparse
|
||||||
|
- pip3 install paho-mqtt
|
||||||
- pip3 install git+https://github.com/heinemml/CO2Meter
|
- pip3 install git+https://github.com/heinemml/CO2Meter
|
||||||
or
|
or
|
||||||
- pip3 install git+https://git.ao-it.net/python/CO2Meter
|
- pip3 install git+https://git.ao-it.net/python/CO2Meter
|
||||||
"""
|
"""
|
||||||
|
|
||||||
__version__ = '0.3.3'
|
__version__ = '0.5.0'
|
||||||
__author__ = 'anima'
|
__author__ = 'anima'
|
||||||
|
|
||||||
# imports
|
# imports
|
||||||
@@ -19,7 +20,6 @@ from time import sleep
|
|||||||
from os import path
|
from os import path
|
||||||
import re
|
import re
|
||||||
import subprocess
|
import subprocess
|
||||||
import socket
|
|
||||||
import threading
|
import threading
|
||||||
import nagiosplugin
|
import nagiosplugin
|
||||||
|
|
||||||
@@ -27,64 +27,19 @@ import nagiosplugin
|
|||||||
logging.basicConfig(format='[%(asctime)s] %(levelname)s %(message)s', level=logging.INFO)
|
logging.basicConfig(format='[%(asctime)s] %(levelname)s %(message)s', level=logging.INFO)
|
||||||
|
|
||||||
|
|
||||||
class AirQ:
|
class AirQBase:
|
||||||
def __init__(self, run_mode: str = 'local', server: str = '127.0.0.1', port: int = 4554, device: str = None):
|
def __init__(self):
|
||||||
self.temp = None
|
self.temp = None
|
||||||
self.co2 = None
|
self.co2 = None
|
||||||
|
|
||||||
|
|
||||||
|
class AirQLocal(AirQBase):
|
||||||
|
def __init__(self, device: str = None):
|
||||||
|
super().__init__()
|
||||||
self.device = device
|
self.device = device
|
||||||
self.server = server
|
logging.debug(f'start AirQ in local mode')
|
||||||
self.port = port
|
if self.get_usb_dev():
|
||||||
self.threads = list()
|
self.get_local_data()
|
||||||
|
|
||||||
match run_mode:
|
|
||||||
case 'local':
|
|
||||||
logging.debug(f'start AirQ in {run_mode} mode')
|
|
||||||
if self.get_usb_dev():
|
|
||||||
self.get_local_data()
|
|
||||||
case 'server':
|
|
||||||
logging.debug(f'start AirQ in {run_mode} mode')
|
|
||||||
thread_data = threading.Thread(target=self.get_local_data_loop, group=None)
|
|
||||||
thread_server = threading.Thread(target=self.run_server, group=None)
|
|
||||||
if self.get_usb_dev():
|
|
||||||
thread_data.start()
|
|
||||||
thread_server.start()
|
|
||||||
self.threads.append(thread_server)
|
|
||||||
case 'client':
|
|
||||||
logging.debug(f'start AirQ in {run_mode} mode')
|
|
||||||
self.run_client()
|
|
||||||
|
|
||||||
def stop_treads(self):
|
|
||||||
for thread in self.threads:
|
|
||||||
logging.debug(f'stop threads')
|
|
||||||
thread.join()
|
|
||||||
|
|
||||||
def run_server(self):
|
|
||||||
s = socket.socket()
|
|
||||||
s.bind(('', self.port))
|
|
||||||
s.listen(1)
|
|
||||||
logging.debug(f'run AirQ server on port {self.port}')
|
|
||||||
try:
|
|
||||||
while True:
|
|
||||||
conn, addr = s.accept()
|
|
||||||
data = {"co2": self.co2, "temp": self.temp}
|
|
||||||
logging.debug(f'connection from {addr}, send {data=}')
|
|
||||||
conn.send(str(json.dumps(data)).encode())
|
|
||||||
conn.close()
|
|
||||||
except KeyboardInterrupt:
|
|
||||||
logging.debug(f'stop AirQ server')
|
|
||||||
s.close()
|
|
||||||
|
|
||||||
def run_client(self):
|
|
||||||
s = socket.socket()
|
|
||||||
s.connect((self.server, self.port))
|
|
||||||
logging.debug(f'connected to {self.server=} on {self.port=}')
|
|
||||||
data = json.loads(s.recv(1024).decode())
|
|
||||||
logging.debug(f'server response: {data=}')
|
|
||||||
s.close()
|
|
||||||
if 'co2' in data.keys():
|
|
||||||
self.co2 = data['co2']
|
|
||||||
if 'temp' in data.keys():
|
|
||||||
self.temp = data['temp']
|
|
||||||
|
|
||||||
def get_usb_dev(self) -> bool:
|
def get_usb_dev(self) -> bool:
|
||||||
"""search the airq usb device
|
"""search the airq usb device
|
||||||
@@ -98,10 +53,8 @@ class AirQ:
|
|||||||
return True
|
return True
|
||||||
|
|
||||||
search_string = '04D9:A052'
|
search_string = '04D9:A052'
|
||||||
# search_string = '04d9:a052' # maybe lowercase on some systems ?
|
|
||||||
# search_string = '[Holtek USB-zyTemp]' # alt but unknown if all systems print this in log
|
# search_string = '[Holtek USB-zyTemp]' # alt but unknown if all systems print this in log
|
||||||
matches = list()
|
matches = list()
|
||||||
# log has con is the log entry rolls out
|
|
||||||
command = ["journalctl", "-k", "--no-pager"] # alternative: dmesg # maybe usefull lsusb
|
command = ["journalctl", "-k", "--no-pager"] # alternative: dmesg # maybe usefull lsusb
|
||||||
pattern = re.compile(r'hidraw\d{1,2}')
|
pattern = re.compile(r'hidraw\d{1,2}')
|
||||||
## get kernel logs
|
## get kernel logs
|
||||||
@@ -128,10 +81,6 @@ class AirQ:
|
|||||||
logging.error(f'usb device not found!')
|
logging.error(f'usb device not found!')
|
||||||
return False
|
return False
|
||||||
|
|
||||||
def get_local_data_loop(self):
|
|
||||||
while True:
|
|
||||||
self.get_local_data()
|
|
||||||
|
|
||||||
def get_local_data(self) -> bool:
|
def get_local_data(self) -> bool:
|
||||||
# load only if need (in client mode not needed)
|
# load only if need (in client mode not needed)
|
||||||
from CO2Meter import CO2Meter
|
from CO2Meter import CO2Meter
|
||||||
@@ -149,7 +98,79 @@ class AirQ:
|
|||||||
self.co2 = resp['co2']
|
self.co2 = resp['co2']
|
||||||
self.temp = resp['temperature']
|
self.temp = resp['temperature']
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
class AirQServer(AirQLocal):
|
||||||
|
def __init__(self, port: int = 4554, device: str = None, ):
|
||||||
|
super().__init__(device = device)
|
||||||
|
self.threads = list()
|
||||||
|
self.port = port
|
||||||
|
logging.debug(f'start AirQ in server mode')
|
||||||
|
thread_data = threading.Thread(target=self.get_local_data_loop, group=None)
|
||||||
|
thread_server = threading.Thread(target=self.run_server, group=None)
|
||||||
|
|
||||||
|
if self.get_usb_dev():
|
||||||
|
thread_data.start()
|
||||||
|
sleep(5)
|
||||||
|
thread_server.start()
|
||||||
|
self.threads.append(thread_data)
|
||||||
|
self.threads.append(thread_server)
|
||||||
|
|
||||||
|
def stop_treads(self):
|
||||||
|
for thread in self.threads:
|
||||||
|
logging.debug(f'stop threads')
|
||||||
|
thread.join()
|
||||||
|
|
||||||
|
def get_local_data_loop(self):
|
||||||
|
while True:
|
||||||
|
self.get_local_data()
|
||||||
|
|
||||||
|
def run_server(self):
|
||||||
|
import paho.mqtt.client as mqtt
|
||||||
|
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, client_id="AirQServer")
|
||||||
|
client.connect("localhost", self.port)
|
||||||
|
logging.debug(f'run AirQ server on port {self.port}')
|
||||||
|
|
||||||
|
while True:
|
||||||
|
sleep(10)
|
||||||
|
logging.debug(f'set {self.temp=}, {self.co2=}')
|
||||||
|
client.publish("airq/temp", self.temp, retain=True)
|
||||||
|
client.publish("airq/co2", self.co2, retain=True)
|
||||||
|
|
||||||
|
|
||||||
|
class AirQClient(AirQBase):
|
||||||
|
def __init__(self, server: str = 'localhost', port: int = 4554, mode = None):
|
||||||
|
super().__init__()
|
||||||
|
self.server = server
|
||||||
|
self.port = port
|
||||||
|
logging.debug(f'start AirQ in client mode')
|
||||||
|
self.received = {}
|
||||||
|
self.mode = mode
|
||||||
|
self.run_client()
|
||||||
|
|
||||||
|
def on_message(self, client, userdata, msg):
|
||||||
|
self.received[msg.topic] = msg.payload.decode()
|
||||||
|
logging.debug(f"get {msg.topic=} with {self.received[msg.topic]=}")
|
||||||
|
client.disconnect() # end with first response
|
||||||
|
|
||||||
|
|
||||||
|
def run_client(self):
|
||||||
|
import paho.mqtt.client as mqtt
|
||||||
|
|
||||||
|
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, client_id="AirQClient")
|
||||||
|
client.on_message = self.on_message
|
||||||
|
|
||||||
|
client.connect(self.server, self.port)
|
||||||
|
client.subscribe(f"airq/{self.mode}")
|
||||||
|
|
||||||
|
client.loop_start()
|
||||||
|
sleep(1)
|
||||||
|
client.loop_stop()
|
||||||
|
if self.mode == 'co2':
|
||||||
|
self.co2 = self.received[f"airq/{self.mode}"]
|
||||||
|
elif self.mode == 'temp':
|
||||||
|
self.temp = self.received[f"airq/{self.mode}"]
|
||||||
|
|
||||||
|
|
||||||
class AirQCO2Resource(nagiosplugin.Resource):
|
class AirQCO2Resource(nagiosplugin.Resource):
|
||||||
def __init__(self, airq) -> None:
|
def __init__(self, airq) -> None:
|
||||||
@@ -228,27 +249,33 @@ def main():
|
|||||||
if args.verbose >= 3:
|
if args.verbose >= 3:
|
||||||
logging.getLogger().setLevel(logging.DEBUG)
|
logging.getLogger().setLevel(logging.DEBUG)
|
||||||
|
|
||||||
|
# dice which check will be run bases on check_mode
|
||||||
if args.check_mode != 'server':
|
if args.check_mode != 'server':
|
||||||
airq = AirQ(run_mode=args.airq_mode, server=args.airq_server, port=args.airq_port, device=args.airq_device)
|
if args.airq_mode == 'local':
|
||||||
|
airq = AirQLocal(device=args.airq_device)
|
||||||
|
elif args.airq_mode == 'client':
|
||||||
|
airq = AirQClient(server=args.airq_server, port=int(args.airq_port), mode=args.check_mode)
|
||||||
|
else:
|
||||||
|
logging.error('Unknown airq mode')
|
||||||
|
exit()
|
||||||
check = None
|
check = None
|
||||||
|
|
||||||
# dice which check will be run bases on check_mode
|
|
||||||
match args.check_mode:
|
match args.check_mode:
|
||||||
case 'co2':
|
case 'co2':
|
||||||
check = nagiosplugin.Check(
|
check = nagiosplugin.Check(
|
||||||
AirQCO2Resource(airq=airq),
|
AirQCO2Resource(airq=airq),
|
||||||
nagiosplugin.ScalarContext(name='scalar_context', warning=args.warning, critical=args.critical),
|
nagiosplugin.ScalarContext(name='scalar_context', warning=args.warning, critical=args.critical),
|
||||||
nagiosplugin.Summary())
|
nagiosplugin.Summary())
|
||||||
check.name = "CO2"
|
check.name = "CO2"
|
||||||
case 'temp':
|
case 'temp':
|
||||||
check = nagiosplugin.Check(
|
check = nagiosplugin.Check(
|
||||||
AirQTempResource(airq=airq),
|
AirQTempResource(airq=airq),
|
||||||
nagiosplugin.ScalarContext(name='scalar_context', warning=args.warning, critical=args.critical),
|
nagiosplugin.ScalarContext(name='scalar_context', warning=args.warning, critical=args.critical),
|
||||||
nagiosplugin.Summary())
|
nagiosplugin.Summary())
|
||||||
check.name = "Temperature"
|
check.name = "Temperature"
|
||||||
case 'server':
|
case 'server':
|
||||||
try:
|
try:
|
||||||
airq = AirQ(run_mode=args.check_mode, server=args.airq_server, port=args.airq_port, device=args.airq_device)
|
airq = AirQServer(port=int(args.airq_port), device=args.airq_device)
|
||||||
except KeyboardInterrupt:
|
except KeyboardInterrupt:
|
||||||
airq.stop_treads()
|
airq.stop_treads()
|
||||||
case _:
|
case _:
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
- pip3 install requests
|
- pip3 install requests
|
||||||
"""
|
"""
|
||||||
|
|
||||||
__version__ = '0.5.2'
|
__version__ = '0.5.3'
|
||||||
__author__ = 'anima'
|
__author__ = 'anima'
|
||||||
|
|
||||||
# imports
|
# imports
|
||||||
@@ -165,6 +165,7 @@ class DockerSwarmServiceStatesResource(nagiosplugin.Resource):
|
|||||||
data['state'] = service['state']
|
data['state'] = service['state']
|
||||||
data['status'] = service['status']['tasks']
|
data['status'] = service['status']['tasks']
|
||||||
yield nagiosplugin.Metric(name='docker_service', value=data, context='docker_service')
|
yield nagiosplugin.Metric(name='docker_service', value=data, context='docker_service')
|
||||||
|
return nagiosplugin.Metric(name='services', value=len(response), context='scalar_context')
|
||||||
|
|
||||||
|
|
||||||
class DockerSwarmServiceStatesContext(nagiosplugin.Context):
|
class DockerSwarmServiceStatesContext(nagiosplugin.Context):
|
||||||
@@ -208,6 +209,7 @@ class DockerSwarmServiceUpdatesResource(nagiosplugin.Resource):
|
|||||||
"""
|
"""
|
||||||
response = self.api.services()
|
response = self.api.services()
|
||||||
|
|
||||||
|
updates = 0
|
||||||
for service in response:
|
for service in response:
|
||||||
data = dict()
|
data = dict()
|
||||||
data['name'] = service['serviceName']
|
data['name'] = service['serviceName']
|
||||||
@@ -234,6 +236,11 @@ class DockerSwarmServiceUpdatesResource(nagiosplugin.Resource):
|
|||||||
data['latestDigest'] = None
|
data['latestDigest'] = None
|
||||||
yield nagiosplugin.Metric(name='docker_service', value=data, context='docker_service')
|
yield nagiosplugin.Metric(name='docker_service', value=data, context='docker_service')
|
||||||
|
|
||||||
|
if data['latestDigest'] is not None and data['imageDigest'] != data['latestDigest']:
|
||||||
|
updates += 1
|
||||||
|
|
||||||
|
return nagiosplugin.Metric(name='updates', value=updates, context='scalar_context')
|
||||||
|
|
||||||
|
|
||||||
class DockerSwarmServiceUpdatesContext(nagiosplugin.Context):
|
class DockerSwarmServiceUpdatesContext(nagiosplugin.Context):
|
||||||
def __init__(self, name):
|
def __init__(self, name):
|
||||||
@@ -353,12 +360,14 @@ def main():
|
|||||||
check = nagiosplugin.Check(
|
check = nagiosplugin.Check(
|
||||||
DockerSwarmServiceStatesResource(api=api),
|
DockerSwarmServiceStatesResource(api=api),
|
||||||
DockerSwarmServiceStatesContext(name='docker_service'),
|
DockerSwarmServiceStatesContext(name='docker_service'),
|
||||||
|
nagiosplugin.ScalarContext(name='scalar_context', warning=args.warning, critical=args.critical),
|
||||||
DockerSwarmSummary())
|
DockerSwarmSummary())
|
||||||
check.name = "swarm service states"
|
check.name = "swarm service states"
|
||||||
case 'service_updates':
|
case 'service_updates':
|
||||||
check = nagiosplugin.Check(
|
check = nagiosplugin.Check(
|
||||||
DockerSwarmServiceUpdatesResource(api=api),
|
DockerSwarmServiceUpdatesResource(api=api),
|
||||||
DockerSwarmServiceUpdatesContext(name='docker_service'),
|
DockerSwarmServiceUpdatesContext(name='docker_service'),
|
||||||
|
nagiosplugin.ScalarContext(name='scalar_context', warning=args.warning, critical=args.critical),
|
||||||
DockerSwarmSummary())
|
DockerSwarmSummary())
|
||||||
check.name = "swarm service updates"
|
check.name = "swarm service updates"
|
||||||
case _:
|
case _:
|
||||||
|
|||||||
262
checks/check_snmp_linux.py
Executable file
262
checks/check_snmp_linux.py
Executable file
@@ -0,0 +1,262 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""SNMP defaults linux python check"""
|
||||||
|
"""dependencys:
|
||||||
|
- pip3 install nagiosplugin
|
||||||
|
- pip3 install argparse
|
||||||
|
- pip3 install easysnmp
|
||||||
|
- https://easysnmp.readthedocs.io/en/latest/index.html
|
||||||
|
- https://easysnmp.readthedocs.io/en/latest/session_api.html
|
||||||
|
"""
|
||||||
|
|
||||||
|
__version__ = '0.1.2'
|
||||||
|
__author__ = 'anima'
|
||||||
|
|
||||||
|
# imports
|
||||||
|
import logging
|
||||||
|
import argparse
|
||||||
|
import nagiosplugin
|
||||||
|
from easysnmp import Session
|
||||||
|
|
||||||
|
# log settings
|
||||||
|
logging.basicConfig(format='[%(asctime)s] %(levelname)s %(message)s', level=logging.INFO)
|
||||||
|
|
||||||
|
def init_snmp_session(hostname: str = 'localhost', snmp_version: str | int = '2', snmp_community: str = 'public',
|
||||||
|
snmp_security_level: str = 'auth_with_privacy', snmp_security_username: str = 'monitoring',
|
||||||
|
snmp_auth_protocol: str = 'SHA256', snmp_auth_password: str | None = None,
|
||||||
|
snmp_privacy_protocol: str = 'AES', snmp_privacy_password: str | None = None
|
||||||
|
) -> Session:
|
||||||
|
"""init a easysnmp session
|
||||||
|
|
||||||
|
Args:
|
||||||
|
hostname (str, optional): hostname or ip of host. Defaults to 'localhost'.
|
||||||
|
snmp_version (str, optional): version of snmp (1, 2, 3). Defaults to 2.
|
||||||
|
snmp_community (str, only need for v1 & v2): snmp community if snmp v1 or v2 used (any). Defaults to 'public'.
|
||||||
|
snmp_security_level (str, only need for v3): security level (no_auth_or_privacy, auth_without_privacy or auth_with_privacy). Defaults to 'auth_with_privacy'.
|
||||||
|
snmp_security_username (str, only need for v3): security name (any). Defaults to 'monitoring'.
|
||||||
|
snmp_auth_protocol (str, only need for v3): authentication protocol (MD5, SHA256, SHA512). Defaults to 'SHA256'.
|
||||||
|
snmp_auth_password (str, only need for v3): authentication passphrase (any). Defaults to None.
|
||||||
|
snmp_privacy_protocol (str, only need for v3): privacy protocol (AES, DES). Defaults to 'AES'.
|
||||||
|
snmp_privacy_password (str, only need for v3): privacy passphrase (any). Defaults to None.
|
||||||
|
|
||||||
|
Return:
|
||||||
|
easysnmp.Session: session for get or walk actions
|
||||||
|
"""
|
||||||
|
# check if snmp version an valid str or int and saves as int
|
||||||
|
valid_versions: list[str, int] = ['1','2','3', 1, 2, 3]
|
||||||
|
if snmp_version not in valid_versions:
|
||||||
|
raise ValueError(f'{snmp_version=} non of {valid_versions=}')
|
||||||
|
else:
|
||||||
|
snmp_version = int(snmp_version)
|
||||||
|
|
||||||
|
if snmp_version == '3':
|
||||||
|
# check if snmp security level valid
|
||||||
|
valid_security_levels: list[str] = ['no_auth_or_privacy', 'auth_without_privacy', 'auth_with_privacy']
|
||||||
|
if snmp_security_level not in valid_security_levels:
|
||||||
|
raise ValueError(f'{snmp_security_level=} is non of {valid_security_levels=}')
|
||||||
|
|
||||||
|
# check if auth protocol valid
|
||||||
|
if snmp_security_level.startswith('auth'):
|
||||||
|
valid_auth_protocols: list[str] = ['MD5', 'SHA', 'SHA256', 'SHA512']
|
||||||
|
if snmp_auth_protocol not in valid_auth_protocols:
|
||||||
|
raise ValueError(f'{snmp_auth_protocol=} is non of {valid_auth_protocols=}')
|
||||||
|
|
||||||
|
if snmp_auth_password is None:
|
||||||
|
raise ValueError(f'{snmp_auth_password=} is not set')
|
||||||
|
|
||||||
|
# check if privacy protocol valid
|
||||||
|
if not snmp_security_level.startswith('no'):
|
||||||
|
valid_privacy_protocols: list[str] = ['AES', 'DES']
|
||||||
|
if snmp_privacy_protocol not in valid_privacy_protocols:
|
||||||
|
raise ValueError(f'{snmp_privacy_protocol=} is non of {valid_privacy_protocols=}')
|
||||||
|
|
||||||
|
if snmp_privacy_password is None:
|
||||||
|
raise ValueError(f'{snmp_privacy_password=} is not set')
|
||||||
|
|
||||||
|
|
||||||
|
if snmp_version == 3: # 2025-01-02: only 'auth_with_privacy' is tested
|
||||||
|
session = Session(hostname=hostname, version=snmp_version,
|
||||||
|
security_level=snmp_security_level, security_username=snmp_security_username,
|
||||||
|
privacy_protocol=snmp_privacy_protocol, privacy_password=snmp_privacy_password,
|
||||||
|
auth_protocol=snmp_auth_protocol, auth_password=snmp_auth_password)
|
||||||
|
else:
|
||||||
|
session = Session(hostname=hostname, version=snmp_version, community=snmp_community)
|
||||||
|
return session
|
||||||
|
|
||||||
|
|
||||||
|
#
|
||||||
|
# General Summary
|
||||||
|
#
|
||||||
|
class SNMPSummary(nagiosplugin.Summary):
|
||||||
|
"""default summary for own results"""
|
||||||
|
def verbose(self, results):
|
||||||
|
"""creates a multiline response"""
|
||||||
|
result_str = ''
|
||||||
|
for result in results:
|
||||||
|
result_str += f'{str(result)}\n'
|
||||||
|
return result_str
|
||||||
|
|
||||||
|
def ok(self, results):
|
||||||
|
return
|
||||||
|
|
||||||
|
def problem(self, results):
|
||||||
|
return
|
||||||
|
|
||||||
|
|
||||||
|
#
|
||||||
|
# Disk
|
||||||
|
#
|
||||||
|
class SNMPDiskResource(nagiosplugin.Resource):
|
||||||
|
def __init__(self, session, exclude_tmpfs:bool = True):
|
||||||
|
"""disk check via snmp
|
||||||
|
|
||||||
|
Args:
|
||||||
|
session (easysnmp.Session): Easysnmp Session object
|
||||||
|
exclude_tmpfs (bool, optional): ignore disks from dev type tmpfs. Defaults to True.
|
||||||
|
"""
|
||||||
|
self.session = session
|
||||||
|
self.exclude_tmpfs = exclude_tmpfs
|
||||||
|
|
||||||
|
def probe(self) -> list:
|
||||||
|
"""check disk size of all disks
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
list[nagisplugin.Metric]: multiple metric elements (yield)
|
||||||
|
"""
|
||||||
|
baseoid = '.1.3.6.1.4.1.2021.9.1'
|
||||||
|
oids = dict()
|
||||||
|
oids['dskIndex'] = '.1'
|
||||||
|
oids['dskPath'] = '.2'
|
||||||
|
oids['dskDevice'] = '.3'
|
||||||
|
oids['dskTotal'] = '.6'
|
||||||
|
oids['dskAvail'] = '.7'
|
||||||
|
oids['dskUsed'] = '.8'
|
||||||
|
oids['dskPercent'] = '.9'
|
||||||
|
oids['dskPercentNode'] = '.10'
|
||||||
|
results = dict()
|
||||||
|
disks = dict()
|
||||||
|
for key,value in oids.items():
|
||||||
|
results[key] = self.session.walk(baseoid + value)
|
||||||
|
if len(results[key]) <= 0:
|
||||||
|
raise ValueError('no values from snmp')
|
||||||
|
for key, value in results.items():
|
||||||
|
for item in value:
|
||||||
|
if item.oid_index == '':
|
||||||
|
if key == 'dskIndex':
|
||||||
|
|
||||||
|
disks[item.value] = dict()
|
||||||
|
else:
|
||||||
|
disks[item.oid.split('.')[-1]][key] = item.value
|
||||||
|
else:
|
||||||
|
if key == 'dskIndex':
|
||||||
|
disks[item.value] = dict()
|
||||||
|
else:
|
||||||
|
disks[item.oid_index][key] = item.value
|
||||||
|
|
||||||
|
for disk in disks.values():
|
||||||
|
if not (self.exclude_tmpfs and disk['dskDevice'] == 'tmpfs'):
|
||||||
|
yield nagiosplugin.Metric(name=disk['dskPath'], value=int(disk['dskPercent']), uom='%', context='scalar_context')
|
||||||
|
yield nagiosplugin.Metric(name=disk['dskPath'], value=disk, context='disk_info')
|
||||||
|
|
||||||
|
|
||||||
|
class SNMPDiskResult(nagiosplugin.Result):
|
||||||
|
def human_size(self, value: int | float, source_unit: str = 'b', target_unit: str = 'gb') -> list[float, str]:
|
||||||
|
"""convert a byte int to a higher unit
|
||||||
|
|
||||||
|
stop convert if value < 1024
|
||||||
|
supported units: ['b', 'kb', 'mb', 'gb', 'tb']
|
||||||
|
|
||||||
|
Args:
|
||||||
|
value (int | float): original value
|
||||||
|
source_unit (str, optional): unit of original unit. Defaults to 'b'.
|
||||||
|
target_unit (str, optional): target unit. Defaults to 'gb'.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
list[float, str]: [new_value, unit]
|
||||||
|
"""
|
||||||
|
units = ['b', 'kb', 'mb', 'gb', 'tb']
|
||||||
|
if value < 1024 or source_unit == target_unit:
|
||||||
|
return [value, source_unit]
|
||||||
|
return self.human_size(value / 1024, units[units.index(source_unit) + 1], target_unit=target_unit)
|
||||||
|
|
||||||
|
def __str__(self):
|
||||||
|
free_size, free_unit = self.human_size(int(self.metric.value["dskAvail"]), 'kb')
|
||||||
|
return f'{self.metric.value["dskPath"]} has {round(free_size, 2)} {free_unit} free'
|
||||||
|
|
||||||
|
|
||||||
|
def parse_args() -> argparse.Namespace:
|
||||||
|
"""evaluates given arguments
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
argsparse.Namespace: Namespace Object with all arguments insert (use: args.long_name_of_argument)
|
||||||
|
"""
|
||||||
|
argp = argparse.ArgumentParser(description=__doc__)
|
||||||
|
# Default args
|
||||||
|
argp.add_argument('-v', '--verbose', action='count', default=0,
|
||||||
|
help='increase output verbosity (use up to 3 times)')
|
||||||
|
argp.add_argument('-H', '--hostname', default='localhost',
|
||||||
|
help='IP address or hostname of device to query')
|
||||||
|
argp.add_argument('-t', '--timeout', default=30,
|
||||||
|
help='abort execution after TIMEOUT seconds')
|
||||||
|
argp.add_argument('-m', '--check_mode',
|
||||||
|
choices=[
|
||||||
|
'disk',
|
||||||
|
'cpu',
|
||||||
|
'load?',
|
||||||
|
'memory',
|
||||||
|
],
|
||||||
|
help='check mode to run')
|
||||||
|
|
||||||
|
# Nagios args / see https://nagios-plugins.org/doc/guidelines.html#THRESHOLDFORMAT
|
||||||
|
argp.add_argument('-w', '--warning', default=':80',
|
||||||
|
help='warning threshold')
|
||||||
|
argp.add_argument('-c', '--critical', default=':90',
|
||||||
|
help='critical threshold')
|
||||||
|
|
||||||
|
# SNMP args (same -* as snmpwalk / snmpget linux command; exept -C/-c & -V /-v because already used (see above))
|
||||||
|
argp.add_argument('-V', '--snmp-version', default='2',
|
||||||
|
help='Used SNMP Version. (1, 2, 3)')
|
||||||
|
argp.add_argument('-C', '--snmp_community', default='public',
|
||||||
|
help='SNMP community if snmp v1 or v2 used (any).')
|
||||||
|
argp.add_argument('-l', '--snmp-security-level', default='auth_with_privacy',
|
||||||
|
help='Security level (no_auth_or_privacy, auth_without_privacy or auth_with_privacy)')
|
||||||
|
argp.add_argument('-u', '--snmp-security-username', default='monitoring',
|
||||||
|
help='Security name (any)')
|
||||||
|
argp.add_argument('-a', '--snmp-auth-protocol', default='SHA256',
|
||||||
|
help='Authentication protocol (MD5, SHA256, SHA512)')
|
||||||
|
argp.add_argument('-A', '--snmp-auth-pass', default=None,
|
||||||
|
help='Authentication passphrase (any)')
|
||||||
|
argp.add_argument('-x', '--snmp-privacy-protocol', default='AES',
|
||||||
|
help='Privacy protocol (AES, DES)')
|
||||||
|
argp.add_argument('-X', '--snmp-privacy-pass', default=None,
|
||||||
|
help='Privacy passphrase (any)')
|
||||||
|
|
||||||
|
args = argp.parse_args()
|
||||||
|
return args
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
args = parse_args()
|
||||||
|
if args.verbose >= 3:
|
||||||
|
logging.getLogger().setLevel(logging.DEBUG)
|
||||||
|
|
||||||
|
session = init_snmp_session(hostname=args.hostname, snmp_version=args.snmp_version, snmp_community=args.snmp_community,
|
||||||
|
snmp_security_level=args.snmp_security_level, snmp_security_username=args.snmp_security_username,
|
||||||
|
snmp_auth_protocol=args.snmp_auth_protocol, snmp_auth_password=args.snmp_auth_pass,
|
||||||
|
snmp_privacy_protocol=args.snmp_privacy_protocol, snmp_privacy_password=args.snmp_privacy_pass)
|
||||||
|
|
||||||
|
# dice which check will be run bases on check_mode
|
||||||
|
match args.check_mode:
|
||||||
|
case 'disk':
|
||||||
|
check = nagiosplugin.Check(
|
||||||
|
SNMPDiskResource(session=session),
|
||||||
|
nagiosplugin.Context(name='disk_info', result_cls=SNMPDiskResult),
|
||||||
|
nagiosplugin.ScalarContext(name='scalar_context', fmt_metric='{name} is {value}{uom} used', warning=args.warning, critical=args.critical),
|
||||||
|
SNMPSummary())
|
||||||
|
check.name = "Disk usage"
|
||||||
|
case _:
|
||||||
|
raise nagiosplugin.CheckError(f'Unknown check mode: {args.check_mode}')
|
||||||
|
|
||||||
|
check.main(args.verbose, args.timeout)
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
@@ -8,7 +8,7 @@
|
|||||||
- https://easysnmp.readthedocs.io/en/latest/session_api.html
|
- https://easysnmp.readthedocs.io/en/latest/session_api.html
|
||||||
"""
|
"""
|
||||||
|
|
||||||
__version__ = '0.13.1'
|
__version__ = '0.14.0'
|
||||||
__author__ = 'anima'
|
__author__ = 'anima'
|
||||||
|
|
||||||
# imports
|
# imports
|
||||||
@@ -491,6 +491,7 @@ class SNMPSynologyDiskHealthResource(nagiosplugin.Resource, SNMPSynologyDisk):
|
|||||||
Generator[nagisplugin.Metric]: multiple metric elements (yield)
|
Generator[nagisplugin.Metric]: multiple metric elements (yield)
|
||||||
"""
|
"""
|
||||||
disks = self.get_disks()
|
disks = self.get_disks()
|
||||||
|
yield nagiosplugin.Metric(name='disk_count', value=len(disks), context='disk_scalar_context')
|
||||||
for disk in disks:
|
for disk in disks:
|
||||||
yield nagiosplugin.Metric(name=disk['id'], value=disk, context='disk_status_context')
|
yield nagiosplugin.Metric(name=disk['id'], value=disk, context='disk_status_context')
|
||||||
yield nagiosplugin.Metric(name=disk['id'], value=disk, context='disk_health_context')
|
yield nagiosplugin.Metric(name=disk['id'], value=disk, context='disk_health_context')
|
||||||
@@ -759,80 +760,96 @@ def main():
|
|||||||
# dice which check will be run bases on check_mode
|
# dice which check will be run bases on check_mode
|
||||||
match args.check_mode:
|
match args.check_mode:
|
||||||
case 'system':
|
case 'system':
|
||||||
check = nagiosplugin.Check(SNMPSynologySystemResource(session=session),
|
check = nagiosplugin.Check(
|
||||||
SNMPSynologySystemContext(name='system_context'),
|
SNMPSynologySystemResource(session=session),
|
||||||
nagiosplugin.Summary())
|
SNMPSynologySystemContext(name='system_context'),
|
||||||
|
nagiosplugin.Summary())
|
||||||
check.name = "System Status"
|
check.name = "System Status"
|
||||||
case 'temperature':
|
case 'temperature':
|
||||||
check = nagiosplugin.Check(SNMPSynologyTemperatureResource(session=session),
|
check = nagiosplugin.Check(
|
||||||
nagiosplugin.ScalarContext(name='temperature_scalar_context', warning=args.warning, critical=args.critical),
|
SNMPSynologyTemperatureResource(session=session),
|
||||||
nagiosplugin.Summary())
|
nagiosplugin.ScalarContext(name='temperature_scalar_context', warning=args.warning, critical=args.critical),
|
||||||
|
nagiosplugin.Summary())
|
||||||
check.name = "System Temperature"
|
check.name = "System Temperature"
|
||||||
case 'powersupply':
|
case 'powersupply':
|
||||||
check = nagiosplugin.Check(SNMPSynologyPowerSupplyResource(session=session),
|
check = nagiosplugin.Check(
|
||||||
SNMPSynologyPowerSupplyContext(name='powersupply_context'),
|
SNMPSynologyPowerSupplyResource(session=session),
|
||||||
nagiosplugin.Summary())
|
SNMPSynologyPowerSupplyContext(name='powersupply_context'),
|
||||||
|
nagiosplugin.Summary())
|
||||||
check.name = "Power Supply Status"
|
check.name = "Power Supply Status"
|
||||||
case 'fans':
|
case 'fans':
|
||||||
check = nagiosplugin.Check(SNMPSynologyFansResource(session=session),
|
check = nagiosplugin.Check(
|
||||||
SNMPSynologyFansContext(name='fan_context'),
|
SNMPSynologyFansResource(session=session),
|
||||||
SNMPSynologySummary())
|
SNMPSynologyFansContext(name='fan_context'),
|
||||||
|
SNMPSynologySummary())
|
||||||
check.name = "Fans Status"
|
check.name = "Fans Status"
|
||||||
case 'firmware':
|
case 'firmware':
|
||||||
check = nagiosplugin.Check(SNMPSynologyFirmwareResource(session=session),
|
check = nagiosplugin.Check(
|
||||||
SNMPSynologyFirmwareContext(name='firmware_context'),
|
SNMPSynologyFirmwareResource(session=session),
|
||||||
nagiosplugin.Summary())
|
SNMPSynologyFirmwareContext(name='firmware_context'),
|
||||||
|
nagiosplugin.Summary())
|
||||||
check.name = "Firmware"
|
check.name = "Firmware"
|
||||||
case 'cpu':
|
case 'cpu':
|
||||||
check = nagiosplugin.Check(SNMPSynologyCPUResource(session=session),
|
check = nagiosplugin.Check(
|
||||||
nagiosplugin.ScalarContext(name='cpu_scalar_context', warning=args.warning, critical=args.critical),
|
SNMPSynologyCPUResource(session=session),
|
||||||
nagiosplugin.Summary())
|
nagiosplugin.ScalarContext(name='cpu_scalar_context', warning=args.warning, critical=args.critical),
|
||||||
|
nagiosplugin.Summary())
|
||||||
check.name = "CPU Usage"
|
check.name = "CPU Usage"
|
||||||
case 'memory':
|
case 'memory':
|
||||||
check = nagiosplugin.Check(SNMPSynologyMemoryResource(session=session),
|
check = nagiosplugin.Check(
|
||||||
nagiosplugin.ScalarContext(name='memory_scalar_context', warning=args.warning, critical=args.critical),
|
SNMPSynologyMemoryResource(session=session),
|
||||||
nagiosplugin.Summary())
|
nagiosplugin.ScalarContext(name='memory_scalar_context', warning=args.warning, critical=args.critical),
|
||||||
|
nagiosplugin.Summary())
|
||||||
check.name = "Memory Usage"
|
check.name = "Memory Usage"
|
||||||
case 'disk':
|
case 'disk':
|
||||||
check = nagiosplugin.Check(SNMPSynologyDiskHealthResource(session=session),
|
check = nagiosplugin.Check(
|
||||||
SNMPSynologyDiskHealthContext(name='disk_health_context'),
|
SNMPSynologyDiskHealthResource(session=session),
|
||||||
SNMPSynologyDiskStatusContext(name='disk_status_context'),
|
SNMPSynologyDiskHealthContext(name='disk_health_context'),
|
||||||
SNMPSynologySummary())
|
SNMPSynologyDiskStatusContext(name='disk_status_context'),
|
||||||
|
nagiosplugin.ScalarContext(name='disk_scalar_context', warning=args.warning, critical=args.critical),
|
||||||
|
SNMPSynologySummary())
|
||||||
check.name = "Disk Health"
|
check.name = "Disk Health"
|
||||||
case 'disk_retry':
|
case 'disk_retry':
|
||||||
check = nagiosplugin.Check(SNMPSynologyDiskRetryResource(session=session),
|
check = nagiosplugin.Check(
|
||||||
nagiosplugin.ScalarContext(name='disk_retry_scalar_context', warning=args.warning, critical=args.critical),
|
SNMPSynologyDiskRetryResource(session=session),
|
||||||
nagiosplugin.Summary())
|
nagiosplugin.ScalarContext(name='disk_retry_scalar_context', warning=args.warning, critical=args.critical),
|
||||||
|
nagiosplugin.Summary())
|
||||||
check.name = "Disk Connection Retrys"
|
check.name = "Disk Connection Retrys"
|
||||||
case 'disk_life':
|
case 'disk_life':
|
||||||
check = nagiosplugin.Check(SNMPSynologyDiskLifeResource(session=session),
|
check = nagiosplugin.Check(
|
||||||
nagiosplugin.ScalarContext(name='disk_life_scalar_context', warning=args.warning, critical=args.critical),
|
SNMPSynologyDiskLifeResource(session=session),
|
||||||
nagiosplugin.Summary())
|
nagiosplugin.ScalarContext(name='disk_life_scalar_context', warning=args.warning, critical=args.critical),
|
||||||
|
nagiosplugin.Summary())
|
||||||
check.name = "Disk Remaining Life"
|
check.name = "Disk Remaining Life"
|
||||||
case 'disk_ident':
|
case 'disk_ident':
|
||||||
check = nagiosplugin.Check(SNMPSynologyDiskIdentResource(session=session),
|
check = nagiosplugin.Check(
|
||||||
nagiosplugin.ScalarContext(name='disk_ident_scalar_context', warning=args.warning, critical=args.critical),
|
SNMPSynologyDiskIdentResource(session=session),
|
||||||
nagiosplugin.Summary())
|
nagiosplugin.ScalarContext(name='disk_ident_scalar_context', warning=args.warning, critical=args.critical),
|
||||||
|
nagiosplugin.Summary())
|
||||||
check.name = "Disk IdentFail"
|
check.name = "Disk IdentFail"
|
||||||
case 'disk_sectors':
|
case 'disk_sectors':
|
||||||
check = nagiosplugin.Check(SNMPSynologyDiskSectorsResource(session=session),
|
check = nagiosplugin.Check(
|
||||||
nagiosplugin.ScalarContext(name='disk_sectors_scalar_context', warning=args.warning, critical=args.critical),
|
SNMPSynologyDiskSectorsResource(session=session),
|
||||||
nagiosplugin.Summary())
|
nagiosplugin.ScalarContext(name='disk_sectors_scalar_context', warning=args.warning, critical=args.critical),
|
||||||
|
nagiosplugin.Summary())
|
||||||
check.name = "Disk BadSectors"
|
check.name = "Disk BadSectors"
|
||||||
case 'raid':
|
case 'raid':
|
||||||
check = nagiosplugin.Check(SNMPSynologyRaidStatusResource(session=session),
|
check = nagiosplugin.Check(
|
||||||
SNMPSynologyRaidStatusContext(name='raid_status_context'),
|
SNMPSynologyRaidStatusResource(session=session),
|
||||||
SNMPSynologySummary())
|
SNMPSynologyRaidStatusContext(name='raid_status_context'),
|
||||||
|
SNMPSynologySummary())
|
||||||
check.name = "Raid status"
|
check.name = "Raid status"
|
||||||
case 'raid_space':
|
case 'raid_space':
|
||||||
check = nagiosplugin.Check(SNMPSynologyRaidSpaceResource(session=session),
|
check = nagiosplugin.Check(
|
||||||
nagiosplugin.ScalarContext(name='raid_space_scalar_context', warning=args.warning, critical=args.critical),
|
SNMPSynologyRaidSpaceResource(session=session),
|
||||||
nagiosplugin.Summary())
|
nagiosplugin.ScalarContext(name='raid_space_scalar_context', warning=args.warning, critical=args.critical),
|
||||||
|
nagiosplugin.Summary())
|
||||||
check.name = "Raid space usage"
|
check.name = "Raid space usage"
|
||||||
case 'ups':
|
case 'ups':
|
||||||
check = nagiosplugin.Check(SNMPSynologyUPSResource(session=session),
|
check = nagiosplugin.Check(
|
||||||
SNMPSynologyUPSContext(name='ups_context'),
|
SNMPSynologyUPSResource(session=session),
|
||||||
SNMPSynologySummary())
|
SNMPSynologyUPSContext(name='ups_context'),
|
||||||
|
SNMPSynologySummary())
|
||||||
check.name = "UPS status"
|
check.name = "UPS status"
|
||||||
case _:
|
case _:
|
||||||
raise nagiosplugin.CheckError(f'Unknown check mode: {args.check_mode}')
|
raise nagiosplugin.CheckError(f'Unknown check mode: {args.check_mode}')
|
||||||
|
|||||||
@@ -1,8 +1,11 @@
|
|||||||
## for all checks
|
## for all checks
|
||||||
nagiosplugin
|
nagiosplugin
|
||||||
|
|
||||||
## for api checks
|
## for api checks & notifications
|
||||||
requests
|
requests
|
||||||
|
|
||||||
## for snmp checks
|
## for snmp checks
|
||||||
easysnmp
|
easysnmp
|
||||||
|
|
||||||
|
## for mqtt checks
|
||||||
|
paho-mqtt
|
||||||
@@ -1,2 +1,2 @@
|
|||||||
## for airq
|
## for airq
|
||||||
pip3 install git+https://github.com/heinemml/CO2Meter
|
git+https://github.com/heinemml/CO2Meter
|
||||||
Reference in New Issue
Block a user