Skip to content

Commit c939fd4

Browse files
"fixed" the unittest :)
1 parent 0055d2f commit c939fd4

File tree

3 files changed

+125
-100
lines changed

3 files changed

+125
-100
lines changed

README.md

+10-11
Original file line numberDiff line numberDiff line change
@@ -23,15 +23,15 @@ OK: 27.8 celsius | celsius=27.8
2323
```
2424

2525
## Config files:
26-
1. copy `check_pcmeasure.py' to your Nagios/Icinga plugin folder
27-
2. define a command:
26+
- copy `check_pcmeasure.py' to your Nagios/Icinga plugin folder
27+
- define a command:
2828
```
2929
define command{
3030
command_name check_pcmeasure
3131
command_line $USER1$/check_pcmeasure.py -H $HOSTADDRESS$ -w $ARG1$ -c $ARG2$ -S $ARG3 -l $ARG4
3232
}
3333
```
34-
3. define a service
34+
- define a service
3535
```
3636
define service{
3737
use generic-service
@@ -41,7 +41,7 @@ define service{
4141
}
4242
```
4343
## Director:
44-
1. Icinga Director -> Define Data Fields:
44+
- Icinga Director -> Define Data Fields:
4545

4646
|Label|Field name|
4747
|-----|----------|
@@ -50,15 +50,14 @@ define service{
5050
|Etherbox address|etherbox_address|
5151
|Etherbox sensor label|etherbox_sensor_label|
5252
|Etherbox sensor name|etherbox_sensor_name|
53-
54-
2. Icinga Director -> Commands -> Templates -> Add:
53+
- Icinga Director -> Commands -> Templates -> Add:
5554
![screenshot](https://s3.gifyu.com/images/check_pcmeasure_command_template.png)
56-
3. Click on "Fields":
55+
- Click on "Fields":
5756
![screenshot](https://s3.gifyu.com/images/check_pcmeasure_command_template_fields.png)
58-
4. Icinga Director -> Commands -> Commands -> Add:
57+
- Icinga Director -> Commands -> Commands -> Add:
5958
![screenshot](https://s3.gifyu.com/images/check_pcmeasure_command.png)
60-
5. Click on "Arguments"
59+
- Click on "Arguments"
6160
![screenshot](https://s3.gifyu.com/images/check_pcmeasure_command_arguments.png)
62-
6. Create a service as usual ...
63-
61+
- Create a service as usual ...
62+
- Enjoy :)
6463
![screenshot](https://s3.gifyu.com/images/perfdata_icinga.png)

check_pcmeasure.py

+79-42
Original file line numberDiff line numberDiff line change
@@ -17,45 +17,67 @@
1717

1818

1919
class CheckPcMeasure(object):
20-
def __init__(self):
20+
def __init__(self, host="127.0.0.1", port=4000):
2121
version = "0.2.0"
22-
parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter,
23-
description=textwrap.dedent(os.path.basename(__file__) + " " + version +
24-
" (GPLv3) 2018 - " + time.strftime("%Y")),
25-
epilog=textwrap.dedent("GitHub: https://github.com/mpibpc-mroose/"
26-
"nagios_plugin_pcmeasure"))
27-
parser.add_argument("-H", dest="host", type=str, required=True, help="hostname of the etherbox")
28-
parser.add_argument("-p", type=int, dest="port", default=4000, required=False, help="port to use")
29-
parser.add_argument("-S", dest="sensor_name", type=str, required=True, help="sensor name, e.g. com1.1")
30-
parser.add_argument("-w", dest="warning_threshold", type=float, required=True, help="warning threshold")
31-
parser.add_argument("-c", dest="critical_threshold", type=float, required=True, help="critical threshold")
32-
parser.add_argument("-l", dest="label", type=str, required=False, help="label for perfdata, e.g. 'celsius'")
33-
self.arguments = parser.parse_args()
34-
35-
if self.arguments.label:
36-
self.label_perfdata = self.arguments.label
37-
self.arguments.label = " " + self.arguments.label
38-
else:
39-
self.label_perfdata = "sensor_output"
40-
self.arguments.label = ""
22+
if __name__ == '__main__':
23+
parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter,
24+
description=textwrap.dedent(os.path.basename(__file__) + " " + version +
25+
" (GPLv3) 2018 - " + time.strftime("%Y")),
26+
epilog=textwrap.dedent("GitHub: https://github.com/mpibpc-mroose/"
27+
"nagios_plugin_pcmeasure"))
28+
parser.add_argument("-H", dest="host", type=str, required=True, help="hostname of the etherbox")
29+
parser.add_argument("-p", type=int, dest="port", default=4000, required=False, help="port to use")
30+
parser.add_argument("-S", dest="sensor_name", type=str, required=True, help="sensor name, e.g. com1.1")
31+
parser.add_argument("-w", dest="warning_threshold", type=float, required=True, help="warning threshold")
32+
parser.add_argument("-c", dest="critical_threshold", type=float, required=True, help="critical threshold")
33+
parser.add_argument("-l", dest="label", type=str, required=False, help="label for perfdata, e.g. 'celsius'")
4134

42-
if self.arguments.warning_threshold > self.arguments.critical_threshold:
43-
print("UNKNOWN: warning threshold should be lower than critical threshold")
44-
sys.exit(STATUS_UNKNOWN)
35+
self.arguments = parser.parse_args()
36+
self.critical_threshold = self.arguments.critical_threshold
37+
self.warning_threshold = self.arguments.warning_threshold
38+
self.host = self.arguments.host
39+
self.port = self.arguments.port
40+
self.sensor_name = self.arguments.sensor_name
4541

42+
if self.arguments.label:
43+
self.label_name = " " + self.arguments.label
44+
self.label_perfdata = self.arguments.label
45+
else:
46+
self.label_name = ""
47+
self.label_perfdata = "sensor_output"
48+
49+
if self.warning_threshold > self.critical_threshold:
50+
print("UNKNOWN: warning threshold should be lower than critical threshold")
51+
sys.exit(STATUS_UNKNOWN)
52+
else:
53+
self.label_name = ""
54+
self.label_perfdata = "sensor_output"
55+
self.critical_threshold = False
56+
self.warning_threshold = False
57+
self.host = host
58+
self.port = port
59+
self.sensor_name = False
4660
self.socket = self._connect()
4761

4862
def _connect(self):
4963
_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
5064
_socket.settimeout(0.5)
5165
try:
52-
_socket.connect((self.arguments.host, self.arguments.port))
66+
_socket.connect((self.host, self.port))
5367
except socket.timeout:
54-
print("UNKNOWN: timeout on connect to {host}:{port}".format(host=self.arguments.host,
55-
port=self.arguments.port))
68+
print("UNKNOWN: timeout on connect to {host}:{port}".format(host=self.host,
69+
port=self.port))
70+
sys.exit(STATUS_UNKNOWN)
71+
except ConnectionRefusedError as error:
72+
print("UNKNOWN: {error} by {host}:{port}".format(error=str(error),
73+
host=self.host,
74+
port=self.port))
5675
sys.exit(STATUS_UNKNOWN)
5776
return _socket
5877

78+
def close(self):
79+
self.socket.close()
80+
5981
def __delete__(self, instance):
6082
self.socket.close()
6183

@@ -65,38 +87,53 @@ def _get_value(self, sensor_name) -> float:
6587
sensor_reply_pattern = re.compile(r"value=\s(?P<value>.+);")
6688
return float(sensor_reply_pattern.findall(raw_data)[0])
6789

68-
def check(self):
90+
def check(self, sensor_name=False, warning_threshold=False, critical_threshold=False, label=False) -> int:
91+
if sensor_name:
92+
self.sensor_name = sensor_name
93+
if warning_threshold:
94+
self.warning_threshold = warning_threshold
95+
if critical_threshold:
96+
self.critical_threshold = critical_threshold
97+
if label:
98+
self.label_name = " " + label
99+
self.label_perfdata = label
69100
try:
70-
value = self._get_value(sensor_name=self.arguments.sensor_name)
71-
if value > self.arguments.critical_threshold:
101+
value = self._get_value(sensor_name=self.sensor_name)
102+
if value > self.critical_threshold:
72103
print("CRITICAL: {value} exceeds {threshold} | "
73104
"{label_perfdata}={value};;;0".format(value=value,
74-
label=self.arguments.label,
105+
label=self.label_name,
75106
label_perfdata=self.label_perfdata,
76-
threshold=self.arguments.critical_threshold))
77-
sys.exit(STATUS_CRITICAL)
78-
elif value > self.arguments.warning_threshold:
107+
threshold=self.critical_threshold))
108+
return STATUS_CRITICAL
109+
elif value > self.warning_threshold:
79110
print("WARNING: {value} exceeds {threshold} | "
80111
"{label_perfdata}={value};;;0".format(value=value,
81-
label=self.arguments.label,
112+
label=self.label_name,
82113
label_perfdata=self.label_perfdata,
83-
threshold=self.arguments.warning_threshold))
84-
sys.exit(STATUS_WARNING)
114+
threshold=self.warning_threshold))
115+
return STATUS_WARNING
85116
else:
86117
print("OK: {value}{label} | {label_perfdata}={value};;;0".format(value=value,
87118
label_perfdata=self.label_perfdata,
88-
label=self.arguments.label))
89-
sys.exit(STATUS_OK)
119+
label=self.label_name))
120+
return STATUS_OK
90121
except UnicodeDecodeError:
91122
print("UNKNOWN: can not read from sensor '{sensor_name}'! "
92-
"use {app_name} -h for further information!".format(sensor_name=self.arguments.sensor_name,
123+
"use {app_name} -h for further information!".format(sensor_name=self.sensor_name,
93124
app_name=os.path.basename(__file__)))
94-
sys.exit(STATUS_UNKNOWN)
125+
return STATUS_UNKNOWN
95126
except Exception as error:
96127
print("UNKNOWN: " + str(error))
97-
sys.exit(STATUS_UNKNOWN)
128+
return STATUS_UNKNOWN
129+
130+
def check_command(self):
131+
return_code = self.check(sensor_name=self.sensor_name,
132+
warning_threshold=self.warning_threshold,
133+
critical_threshold=self.critical_threshold)
134+
sys.exit(return_code)
98135

99136

100137
if __name__ == '__main__':
101138
check_pcmeasure = CheckPcMeasure()
102-
check_pcmeasure.check()
139+
check_pcmeasure.check_command()

tests.py

100644100755
+36-47
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,23 @@
1+
#!/usr/bin/env python3
12
# -*- coding: utf-8 -*-
2-
from collections import OrderedDict
3+
34
import socketserver
45
import threading
5-
import time
6+
import unittest
7+
68

79
from unittest import TestCase
8-
from check_pcmeasure import (
9-
MessPCCheck,
10-
NAGIOS_OK, NAGIOS_WARNING, NAGIOS_CRITICAL, NAGIOS_UNKNOWN
11-
)
10+
from check_pcmeasure import CheckPcMeasure, STATUS_OK, STATUS_WARNING, STATUS_CRITICAL
1211

1312

1413
class AlwaysReturnTwentyOneDotSevenRequestHandler(socketserver.BaseRequestHandler):
1514
""" Handler which always returns 21.7 as value"""
1615

1716
def handle(self):
1817
self.data = self.request.recv(2096).strip()
19-
print(
20-
"{client_ip} wrote: {data}".format(
21-
client_ip=self.client_address[0],
22-
data=self.data
23-
)
24-
)
25-
self.request.sendall(
26-
'valid=1;value= {expected_value};\n'.format(
27-
expected_value=21.7
28-
).encode()
29-
)
18+
print("{client_ip} wrote: {data}".format(client_ip=self.client_address[0],
19+
data=self.data))
20+
self.request.sendall('valid=1;value= {expected_value};\n'.format(expected_value=21.7).encode())
3021

3122

3223
class TestServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
@@ -46,51 +37,49 @@ def start_server(self):
4637

4738
def setUp(self):
4839
self.start_server()
49-
self.mess_pc_check = MessPCCheck(host=self.host, port=self.port)
40+
self.mess_pc_check = CheckPcMeasure(host=self.host, port=self.port)
5041

5142
def tearDown(self):
5243
self.stop_server()
44+
self.mess_pc_check.close()
5345
del self.mess_pc_check
5446

5547
def stop_server(self):
5648
self.server.shutdown()
5749
self.server.server_close()
5850

5951
def test_01_get_value(self):
60-
value = self.mess_pc_check._get_value(b"com1.1")
61-
self.assertEqual(
62-
value,
63-
21.7
64-
)
52+
value = self.mess_pc_check._get_value("com1.1")
53+
self.assertEqual(value, 21.7)
6554

6655
def threshold_test(self, parameters):
67-
result = self.mess_pc_check.check(
68-
sensor_name=b"com1.1",
69-
warning_threshold=parameters["warning"],
70-
critical_threshold=parameters["critical"],
71-
)
72-
self.assertEqual(
73-
result,
74-
parameters["expected"]
75-
)
56+
try:
57+
label = parameters["label"]
58+
except KeyError:
59+
label = False
60+
result = self.mess_pc_check.check(sensor_name="com1.1",
61+
warning_threshold=parameters["warning"],
62+
critical_threshold=parameters["critical"],
63+
label=label)
64+
self.assertEqual(result, parameters["expected"])
7665

7766
def test_02_check_no_thresholds_exceeded(self):
78-
self.threshold_test({
79-
"warning": 22.0,
80-
"critical": 23.0,
81-
"expected": NAGIOS_OK
82-
})
67+
self.threshold_test({"warning": 22.0, "critical": 23.0, "expected": STATUS_OK})
8368

8469
def test_03_check_warning_threshold_exceeded(self):
85-
self.threshold_test({
86-
"warning": 21.5,
87-
"critical": 23.0,
88-
"expected": NAGIOS_WARNING
89-
})
70+
self.threshold_test({"warning": 21.5, "critical": 23.0, "expected": STATUS_WARNING})
9071

9172
def test_04_check_critical_threshold_exceeded(self):
92-
self.threshold_test({
93-
"warning": 20.0,
94-
"critical": 21.0,
95-
"expected": NAGIOS_CRITICAL
96-
})
73+
self.threshold_test({"warning": 20.0, "critical": 21.0, "expected": STATUS_CRITICAL})
74+
75+
def test_05_check_no_thresholds_exceeded_with_label(self):
76+
self.threshold_test({"warning": 22.0, "critical": 23.0, "expected": STATUS_OK, "label": "celsius"})
77+
78+
def test_06_check_warning_threshold_exceeded_with_label(self):
79+
self.threshold_test({"warning": 21.5, "critical": 23.0, "expected": STATUS_WARNING, "label": "celsius"})
80+
81+
def test_07_check_critical_threshold_exceeded_with_label(self):
82+
self.threshold_test({"warning": 20.0, "critical": 21.0, "expected": STATUS_CRITICAL, "label": "celsius"})
83+
84+
if __name__ == '__main__':
85+
unittest.main()

0 commit comments

Comments
 (0)