-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathcheck_hddtemp.py
executable file
·486 lines (420 loc) · 14.8 KB
/
check_hddtemp.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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# nagios-check-hddtemp
# check_hddtemp.py
# Copyright (c) 2011-2021 Alexei Andrushievich <vint21h@vint21h.pp.ua>
# Check HDD temperature Nagios plugin [https://github.com/vint21h/nagios-check-hddtemp/]
#
# This file is part of nagios-check-hddtemp.
#
# nagios-check-hddtemp 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 3 of the License, or
# (at your option) any later version.
# 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, see <http://www.gnu.org/licenses/>.
from __future__ import unicode_literals
import sys
import socket
import telnetlib
from argparse import ArgumentParser
from collections import OrderedDict
__all__ = [
"CheckHDDTemp",
"main",
]
# metadata
VERSION = (1, 5, 1)
__version__ = ".".join(map(str, VERSION))
class CheckHDDTemp(object):
"""
Check HDD temperature Nagios plugin.
"""
HDDTEMP_SLEEPING = "SLP"
HDDTEMP_UNKNOWN = "UNK"
STATUS_CRITICAL, STATUS_WARNING, STATUS_UNKNOWN, STATUS_OK, STATUS_SLEEPING = [
"critical",
"warning",
"unknown",
"ok",
"sleeping",
]
(
PRIORITY_CRITICAL,
PRIORITY_WARNING,
PRIORITY_UNKNOWN,
PRIORITY_OK,
PRIORITY_SLEEPING,
) = range(1, 6)
PRIORITY_TO_STATUS = {
PRIORITY_CRITICAL: STATUS_CRITICAL,
PRIORITY_WARNING: STATUS_WARNING,
PRIORITY_UNKNOWN: STATUS_UNKNOWN,
PRIORITY_OK: STATUS_OK,
PRIORITY_SLEEPING: STATUS_SLEEPING,
}
OUTPUT_TEMPLATES = {
STATUS_CRITICAL: {
"text": "device {device} temperature {temperature}{scale} exceeds critical temperature threshold {critical}{scale}", # noqa: E501
"priority": PRIORITY_CRITICAL,
},
STATUS_WARNING: {
"text": "device {device} temperature {temperature}{scale} exceeds warning temperature threshold {warning}{scale}", # noqa: E501
"priority": PRIORITY_WARNING,
},
STATUS_UNKNOWN: {
"text": "device {device} temperature info not found in server response or can't be recognized by hddtemp", # noqa: E501
"priority": PRIORITY_UNKNOWN,
},
STATUS_OK: {
"text": "device {device} is functional and stable {temperature}{scale}",
"priority": PRIORITY_OK,
},
STATUS_SLEEPING: {
"text": "device {device} is sleeping",
"priority": PRIORITY_SLEEPING,
},
}
DEFAULT_EXIT_CODE = 3
EXIT_CODES = {
STATUS_OK: 0,
STATUS_SLEEPING: 0,
STATUS_WARNING: 1,
STATUS_CRITICAL: 2,
STATUS_UNKNOWN: 3,
}
PERFORMANCE_DATA_TEMPLATE = "{device}={temperature}"
def __init__(self):
"""
Get command line args.
"""
self.options = self._get_options() # type: ignore
@staticmethod
def _get_options():
"""
Parse commandline options arguments.
:return: parsed command line arguments
:rtype: Namespace
"""
parser = ArgumentParser(description="Check HDD temperature Nagios plugin")
parser.add_argument(
"-s",
"--server",
action="store",
dest="server",
type=str,
default="",
metavar="SERVER",
help="server name or address",
)
parser.add_argument(
"-p",
"--port",
action="store",
type=int,
dest="port",
default=7634,
metavar="PORT",
help="port number",
)
parser.add_argument(
"-d",
"--devices",
action="store",
dest="devices",
type=str,
default="",
metavar="DEVICES",
help="comma separated devices list, or empty for all devices in hddtemp response", # noqa: E501
)
parser.add_argument(
"-S",
"--separator",
action="store",
type=str,
dest="separator",
default="|",
metavar="SEPARATOR",
help="hddtemp separator",
)
parser.add_argument(
"-w",
"--warning",
action="store",
type=int,
dest="warning",
default=40,
metavar="TEMPERATURE",
help="warning temperature",
)
parser.add_argument(
"-c",
"--critical",
action="store",
type=int,
dest="critical",
default=65,
metavar="TEMPERATURE",
help="critical temperature",
)
parser.add_argument(
"-t",
"--timeout",
action="store",
type=int,
dest="timeout",
default=1,
metavar="TIMEOUT",
help="receiving data from hddtemp operation network timeout",
)
parser.add_argument(
"-P",
"--performance-data",
action="store_true",
default=False,
dest="performance",
help="return performance data",
)
parser.add_argument(
"-q",
"--quiet",
action="store_true",
default=False,
dest="quiet",
help="be quiet",
)
parser.add_argument(
"-v",
"--version",
action="version",
version="{version}".format(version=__version__),
)
options = parser.parse_args()
# check mandatory command line options supplied
if not options.server:
parser.error(message="Required server address option missing")
# check if waning temperature in args less than critical
if options.warning >= options.critical:
parser.error(
message="Warning temperature option value must be less than critical option value" # noqa: E501
)
return options
def _get_data(self):
"""
Get and return data from hddtemp server.
:return: data from hddtemp server
:rtype: str
"""
try:
connection = telnetlib.Telnet(
self.options.server, self.options.port, self.options.timeout
)
response = connection.read_all()
connection.close()
return response.decode("utf8")
except (EOFError, socket.error) as error:
if not self.options.quiet:
sys.stdout.write(
"ERROR: Server communication problem. {error}\n".format(error=error)
)
sys.exit(self.DEFAULT_EXIT_CODE)
def _parse_data(self, data):
"""
Search for device and get HDD info from server response.
:param data: hddtemp server response
:type data: str
:return: structured data parsed from hddtemp server response
:rtype: Dict[str, Dict[str, str]]
"""
info = {}
data = data.split(self.options.separator * 2)
if data != [""]:
for device in data:
device = device.strip(self.options.separator).split(
self.options.separator
)
if len(device) != 4: # 4 data items in server response for device
if not self.options.quiet:
sys.stdout.write(
"ERROR: Server response for device '{dev}' parsing error\n".format( # noqa: E501
dev=device
)
)
sys.exit(self.DEFAULT_EXIT_CODE)
dev, model, temperature, scale = device
info.update(
{dev: {"model": model, "temperature": temperature, "scale": scale}}
)
else:
if not self.options.quiet:
sys.stdout.write("ERROR: Server response too short\n")
sys.exit(self.DEFAULT_EXIT_CODE)
return info
def _check_data(self, data):
"""
Create devices states info.
:param data: structured data parsed from hddtemp server response
:type data: Dict[str, Dict[str, str]]
:return: devices states info
:rtype: Dict[str, Dict[str, Union[str, int, Dict[str, Union[None, int, str]]]]]
"""
states = {}
devices = (
map(lambda dev: dev.strip(), self.options.devices.strip().split(","))
if self.options.devices
else data.keys()
)
for device in devices:
if device: # not empty string
try:
info = data[device]
except KeyError: # device not found in hddtemp response
states.update(
{
device: {
"template": self.STATUS_UNKNOWN,
"priority": self.OUTPUT_TEMPLATES[self.STATUS_UNKNOWN][
"priority"
],
"data": {
"device": device,
"temperature": None,
"scale": None,
"warning": self.options.warning,
"critical": self.options.critical,
},
}
}
)
continue
# checking temperature
# sometime getting "SLP" or "UNK" instead of temperature
try:
temperature = int(info["temperature"])
except ValueError:
temperature = info["temperature"]
if temperature == self.HDDTEMP_SLEEPING: # type: ignore
template = self.STATUS_SLEEPING
elif temperature == self.HDDTEMP_UNKNOWN: # type: ignore
template = self.STATUS_UNKNOWN
elif temperature > self.options.critical:
template = self.STATUS_CRITICAL
elif all(
[
temperature > self.options.warning,
temperature < self.options.critical,
]
):
template = self.STATUS_WARNING
else:
template = self.STATUS_OK
states.update(
{
device: {
"template": template,
"priority": self.OUTPUT_TEMPLATES[template]["priority"],
"data": {
"device": device,
"temperature": temperature,
"scale": info["scale"],
"warning": self.options.warning,
"critical": self.options.critical,
},
}
}
)
return states
def _get_status(self, data):
"""
Create main status.
:param data: devices states info
:type data: Dict[str, Dict[str, Union[str, int, Dict[str, Union[None, int, str]]]]] # noqa: E501
:return: main check status
:rtype: str
"""
# for multiple check need to get main status by priority
priority = min( # noqa: C407
[info["priority"] for device, info in data.items()]
)
status = self.PRIORITY_TO_STATUS.get(priority, self.PRIORITY_CRITICAL)
return status
def _get_code(self, status):
"""
Create exit code.
:param status: main check status
:type status: str
:return: exit code
:rtype: int
"""
return self.EXIT_CODES.get(status, self.DEFAULT_EXIT_CODE)
def _get_output(self, data, status):
"""
Create human readable HDD's statuses.
:param data: devices states info
:type data: Dict[str, Dict[str, Union[str, int, Dict[str, Union[None, int, str]]]]] # noqa: E501
:param status: main check status
:type status: str
:return: human readable HDD's statuses
:rtype: str
"""
output = ""
# sort devices data by priority
data = OrderedDict(
sorted(data.items(), key=lambda item: (item[1]["priority"], item[0]))
)
# create output
devices = ", ".join(
[
str(self.OUTPUT_TEMPLATES[data[device]["template"]]["text"]).format(
**data[device]["data"]
)
for device in data.keys()
]
)
# create full status string with main status for multiple devices
# and all devices states with performance data (optional)
output = (
"{status}: {data} | {performance-data}\n".format(
**{
"status": status.upper(),
"data": devices,
"performance-data": "; ".join(
[
self.PERFORMANCE_DATA_TEMPLATE.format(
**data[device]["data"]
)
for device in data.keys()
]
),
}
)
if self.options.performance
else "{status}: {data}\n".format(
**{"status": status.upper(), "data": devices}
)
)
return output
def check(self):
"""
Get data from server, parse server response, check and create plugin output.
:return: plugin output and exit code
:rtype: Tuple[str, int]
"""
data = self._check_data(data=self._parse_data(data=self._get_data())) # type: ignore # noqa: E501
status = self._get_status(data=data) # type: ignore
code = self._get_code(status=status) # type: ignore
return self._get_output(data=data, status=status), code # type: ignore
def main():
"""
Program main.
"""
checker = CheckHDDTemp() # type: ignore
output, code = checker.check() # type: ignore
sys.stdout.write(output)
sys.exit(code)
if __name__ == "__main__":
main() # type: ignore