-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmonitoring.py
1919 lines (1508 loc) · 60.7 KB
/
monitoring.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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# Author: Frank Brehm <[email protected]
# Berlin, Germany, 2023
# Date: 2023-02-16
#
# This module provides a basic monitoring check class
#
from __future__ import print_function
import sys
import os
import logging
import argparse
import shutil
import traceback
import datetime
import re
import pprint
import copy
from pathlib import Path
from numbers import Number
try:
from collections.abc import Sequence
except ImportError:
from collections import Sequence
if sys.version_info[0] != 3:
print("This script is intended to use with Python3.", file=sys.stderr)
print("You are using Python: {0}.{1}.{2}-{3}-{4}.\n".format(
*sys.version_info), file=sys.stderr)
sys.exit(1)
if sys.version_info[1] < 6:
print("A minimal Python version of 3.6 is necessary to execute this script.", file=sys.stderr)
print("You are using Python: {0}.{1}.{2}-{3}-{4}.\n".format(
*sys.version_info), file=sys.stderr)
sys.exit(1)
LOG = logging.getLogger(__name__)
DEFAULT_TERMINAL_WIDTH = 99
DEFAULT_TERMINAL_HEIGHT = 40
__author__ = 'Frank Brehm <[email protected]>'
__copyright__ = '(C) 2023 by Frank Brehm, Berlin'
__version__ = '0.6.0'
# =============================================================================
def pp(value, indent=4, width=None, depth=None):
"""
Return a pretty print string of the given value.
@return: pretty print string
@rtype: str
"""
if not width:
term_size = shutil.get_terminal_size((DEFAULT_TERMINAL_WIDTH, DEFAULT_TERMINAL_HEIGHT))
width = term_size.columns
pretty_printer = pprint.PrettyPrinter(
indent=indent, width=width, depth=depth)
return pretty_printer.pformat(value)
# =============================================================================
def to_unicode(obj, encoding='utf-8'):
"""Convert given value to unicode."""
do_decode = False
if isinstance(obj, (bytes, bytearray)):
do_decode = True
if do_decode:
obj = obj.decode(encoding)
return obj
# =============================================================================
def encode_or_bust(obj, encoding='utf-8'):
"""Convert given value to a byte string withe the given encoding."""
do_encode = False
if isinstance(obj, str):
do_encode = True
if do_encode:
obj = obj.encode(encoding)
return obj
# =============================================================================
def to_utf8(obj):
"""Convert given value to a utf-8 encoded byte string."""
return encode_or_bust(obj, 'utf-8')
# =============================================================================
def to_bytes(obj, encoding='utf-8'):
"""Do the same as encode_or_bust()."""
return encode_or_bust(obj, encoding)
# =============================================================================
def to_str(obj, encoding='utf-8'):
"""Transform he given string-like object into the str-type.
This will be done according to the current Python version.
"""
return to_unicode(obj, encoding)
# =============================================================================
def is_sequence(arg):
"""Return, whether the given value is a sequential object, but nat a str."""
if not isinstance(arg, Sequence):
return False
if hasattr(arg, "strip"):
return False
return True
# =============================================================================
class DirectoryOptionAction(argparse.Action):
"""An argparse action for directories."""
# -------------------------------------------------------------------------
def __init__(self, option_strings, must_exists=True, writeable=False, *args, **kwargs):
"""Initialise a DirectoryOptionAction object."""
self.must_exists = bool(must_exists)
self.writeable = bool(writeable)
if self.writeable:
self.must_exists = True
super(DirectoryOptionAction, self).__init__(
option_strings=option_strings, *args, **kwargs)
# -------------------------------------------------------------------------
def __call__(self, parser, namespace, given_path, option_string=None):
"""Parse the directory option."""
path = Path(given_path)
if not path.is_absolute():
msg = "The path {!r} must be an absolute path.".format(given_path)
raise argparse.ArgumentError(self, msg)
if self.must_exists:
if not path.exists():
msg = "The directory {!r} does not exists.".format(str(path))
raise argparse.ArgumentError(self, msg)
if not path.is_dir():
msg = "The given path {!r} exists, but is not a directory.".format(str(path))
raise argparse.ArgumentError(self, msg)
if not os.access(str(path), os.R_OK) or not os.access(str(path), os.X_OK):
msg = "The given directory {!r} is not readable.".format(str(path))
raise argparse.ArgumentError(self, msg)
if self.writeable and not os.access(str(path), os.W_OK):
msg = "The given directory {!r} is not writeable.".format(str(path))
raise argparse.ArgumentError(self, msg)
setattr(namespace, self.dest, path)
# =============================================================================
class LogFileOptionAction(argparse.Action):
"""An argparse action for logfiles."""
# -------------------------------------------------------------------------
def __init__(self, option_strings, must_exists=True, writeable=False, *args, **kwargs):
"""Initialise a LogFileOptionAction object."""
self.must_exists = bool(must_exists)
self.writeable = bool(writeable)
super(LogFileOptionAction, self).__init__(
option_strings=option_strings, *args, **kwargs)
# -------------------------------------------------------------------------
def __call__(self, parser, namespace, values, option_string=None):
"""Parse the logfile option."""
if values is None:
setattr(namespace, self.dest, None)
return
path = Path(values)
logdir = path.parent
# Checking the parent directory of the Logfile
if self.must_exists:
if not logdir.exists():
msg = "Directory {!r} does not exists.".format(str(logdir))
raise argparse.ArgumentError(self, msg)
if not logdir.is_dir():
msg = "Path {!r} exists, but is not a directory.".format(str(logdir))
raise argparse.ArgumentError(self, msg)
if self.writeable and not os.access(str(logdir), os.W_OK):
msg = "The directory {!r} is not writeable.".format(str(logdir))
raise argparse.ArgumentError(self, msg)
# Checking logfile, if it is already existing
if path.exists():
if not path.is_file():
msg = "File {!r} is not a regular file.".format(values)
raise argparse.ArgumentError(self, msg)
if not os.access(values, os.R_OK):
msg = "File {!r} is not readable.".format(values)
raise argparse.ArgumentError(self, msg)
if self.writeable and not os.access(value, os.W_OK):
msg = "The given file {!r} is not writeable.".format(values)
raise argparse.ArgumentError(self, msg)
elif self.must_exists:
msg = "The file {!r} does not exists.".format(str(path))
raise argparse.ArgumentError(self, msg)
setattr(namespace, self.dest, path.resolve())
# =============================================================================
class MonitoringException(Exception):
pass
# =============================================================================
class MonitoringPerformanceError(MonitoringException):
"""
Base class for all exception classes and object, raised in this module.
"""
pass
# =============================================================================
class MonitoringRangeError(MonitoringException):
"""Base exception class for all exceptions in this module."""
pass
# =============================================================================
class InvalidRangeError(MonitoringRangeError):
"""
A special exception, which is raised, if an invalid range string was found.
"""
# -------------------------------------------------------------------------
def __init__(self, wrong_range):
"""
Constructor.
@param wrong_range: the wrong range, whiche lead to this exception.
@type wrong_range: str
"""
self.wrong_range = wrong_range
# -------------------------------------------------------------------------
def __str__(self):
"""Typecasting into a string for error output."""
return "Wrong range %r." % (self.wrong_range)
# =============================================================================
class InvalidRangeValueError(MonitoringRangeError):
"""
A special exception, which is raised, if an invalid value should be checked
against the current range object.
"""
# -------------------------------------------------------------------------
def __init__(self, value):
"""
Constructor.
@param value: the wrong value, whiche lead to this exception.
@type value: object
"""
self.value = value
# -------------------------------------------------------------------------
def __str__(self):
"""Typecasting into a string for error output."""
return "Wrong value %r to check against a range." % (self.value)
# =============================================================================
class MonitoringPluginError(MonitoringException):
"""Base exception for an exception inside a monitoring plugin."""
pass
# =============================================================================
class ApiError(MonitoringPluginError):
"""Base class for more complex exceptions."""
# -------------------------------------------------------------------------
def __init__(self, code, msg, uri=None):
"""Initialize the ApiError object."""
self.code = code
self.msg = msg
self.uri = uri
# -------------------------------------------------------------------------
def __str__(self):
"""Typecast into a string."""
if self.uri:
msg = 'Got a {code} error code from {uri!r}: {msg}'.format(
code=self.code, uri=self.uri, msg=self.msg)
else:
msg = 'Got a {code} error code: {msg}'.format(code=self.code, msg=self.msg)
return msg
# =============================================================================
class FunctionNotImplementedError(MonitoringPluginError, NotImplementedError):
"""
Error class for not implemented functions.
"""
# -------------------------------------------------------------------------
def __init__(self, function_name, class_name):
"""
Constructor.
@param function_name: the name of the not implemented function
@type function_name: str
@param class_name: the name of the class of the function
@type class_name: str
"""
self.function_name = function_name
if not function_name:
self.function_name = '__unkown_function__'
self.class_name = class_name
if not class_name:
self.class_name = '__unkown_class__'
# -------------------------------------------------------------------------
def __str__(self):
"""
Typecasting into a string for error output.
"""
msg = "Function %(func)s() has to be overridden in class '%(cls)s'."
return msg % {'func': self.function_name, 'cls': self.class_name}
# =============================================================================
def reverse_rorror_codes(errors):
"""Generates the reversed errors hash for a MonitoringObject."""
error_codes = {}
for name in errors.keys():
code = errors[name]
error_codes[code] = name
return error_codes
# =============================================================================
class MonitoringObject(object):
"""
Base object of all classes in this module (except Exceptions).
It defines some usefull class properties.
"""
re_digit = re.compile(r'[\d~]')
re_dot = re.compile(r'\.')
re_ws = re.compile(r'\s')
errors = {
'OK': 0,
'WARNING': 1,
'CRITICAL': 2,
'UNKNOWN': 3,
'DEPENDENT': 4,
}
error_codes = reverse_rorror_codes(errors)
# -------------------------------------------------------------------------
@property
def status_ok(self):
"""The numerical value of OK."""
return self.errors['OK']
# -------------------------------------------------------------------------
@property
def status_warning(self):
"""The numerical value of WARNING."""
return self.errors['WARNING']
# -------------------------------------------------------------------------
@property
def status_critical(self):
"""The numerical value of CRITICAL."""
return self.errors['CRITICAL']
# -------------------------------------------------------------------------
@property
def status_unknown(self):
"""The numerical value of UNKNOWN."""
return self.errors['UNKNOWN']
# -------------------------------------------------------------------------
@property
def status_dependent(self):
"""The numerical value of DEPENDENT."""
return self.errors['DEPENDENT']
# -------------------------------------------------------------------------
def as_dict(self):
"""
Typecasting into a dictionary.
@return: structure as dict
@rtype: dict
"""
ret = {
'__class__': self.__class__.__name__,
'errors': copy.copy(self.errors),
'error_codes': copy.copy(self.error_codes),
'status_ok': self.status_ok,
'status_warning': self.status_warning,
'status_critical': self.status_critical,
'status_unknown': self.status_unknown,
'status_dependent': self.status_dependent,
}
return ret
# =============================================================================
class MonitoringRange(MonitoringObject):
"""
Encapsulation of a Nagios range, how used by some Nagios plugins.
"""
match_num_val = r'[+-]?\d+(?:\.\d*)?'
match_range = r'^(\@)?(?:(' + match_num_val + r'|~)?:)?(' + match_num_val + r')?$'
re_range = re.compile(match_range)
# -------------------------------------------------------------------------
def __init__(
self, range_str=None, start=None, end=None,
invert_match=False, initialized=None):
"""
Initialisation of the MonitoringRange object.
@raise InvalidRangeError: if the given range_str was invalid
@raise ValueError: on invalid start or end parameters, if
range_str was not given
@param range_str: the range string of the type 'x:y' to use for
initialisation of the object, if given,
the parameters start, end and invert_match
are not considered
@type range_str: str
@param start: the start value of the range, infinite, if None
@type start: long or int or float or None
@param end: the end value of the range, infinite, if None
@type end: long or int or float or None
@param invert_match: invert check logic - if true, then the check
results in true, if the value to check is outside
the range, not inside
@type invert_match: bool
@param initialized: initialisation of this MonitoringRange object is complete
@type initialized: bool
"""
self._start = None
"""
@ivar: the start value of the range, infinite, if None
@type: long or float or None
"""
self._end = None
"""
@ivar: the end value of the range, infinite, if None
@type: long or float or None
"""
self._invert_match = False
"""
@ivar: invert check logic - if true, then the check results in true,
if the value to check is outside the range, not inside
@type: bool
"""
self._initialized = False
"""
@ivar: initialisation of this MonitoringRange object is complete
@type: bool
"""
if range_str is not None:
self.parse_range_string(range_str)
return
if isinstance(start, int):
self._start = int(start)
elif isinstance(start, float):
self._start = start
elif start is not None:
raise ValueError(
"Start value %r for MonitoringRange is unusable." % (start))
if isinstance(end, int):
self._end = int(end)
elif isinstance(end, float):
self._end = end
elif end is not None:
raise ValueError(
"End value %r for MonitoringRange is unusable." % (end))
self._invert_match = bool(invert_match)
if initialized is not None:
self._initialized = bool(initialized)
elif self.start is not None or self.end is not None:
self._initialized = True
# -----------------------------------------------------------
@property
def start(self):
"""The start value of the range, infinite, if None."""
return self._start
# -----------------------------------------------------------
@property
def end(self):
"""The end value of the range, infinite, if None."""
return self._end
# -----------------------------------------------------------
@property
def invert_match(self):
"""
Invert check logic - if true, then the check results in true,
if the value to check is outside the range, not inside
"""
return self._invert_match
# -----------------------------------------------------------
@property
def is_set(self):
"""The initialisation of this object is complete."""
return self._initialized
# -----------------------------------------------------------
@property
def initialized(self):
"""The initialisation of this object is complete."""
return self._initialized
# -------------------------------------------------------------------------
def __str__(self):
"""Typecasting into a string."""
if not self.initialized:
return ''
res = ''
if self.invert_match:
res = '@'
if self.start is None:
res += '~:'
elif self.start != 0:
res += str(self.start) + ':'
if self.end is not None:
res += str(self.end)
return res
# -------------------------------------------------------------------------
def as_dict(self):
"""
Typecasting into a dictionary.
@return: structure as dict
@rtype: dict
"""
ret = super(MonitoringRange, self).as_dict()
ret['start'] = self.start
ret['end'] = self.end
ret['invert_match'] = self.invert_match
ret['initialized'] = self.initialized
return ret
# -------------------------------------------------------------------------
def __repr__(self):
"""Typecasting into a string for reproduction."""
out = '<MonitoringRange(start=%r, end=%r, invert_match=%r, initialized=%r)>' % (
self.start, self.end, self.invert_match, self.initialized)
return out
# -------------------------------------------------------------------------
def single_val(self):
"""
Returns a single Number value.
@return: self.end, if set, else self.start, if set, else None
@rtype: Number or None
"""
if not self.initialized:
return None
if self.end is not None:
return self.end
return self.start
# -------------------------------------------------------------------------
def parse_range_string(self, range_str):
"""
Parsing the given range_str and set self.start, self.end and
self.invert_match with the appropriate values.
@raise InvalidRangeError: if the given range_str was invalid
@param range_str: the range string of the type 'x:y' to use for
initialisation of the object
@type range_str: str or Number
"""
# range is a Number - all clear
if isinstance(range_str, Number):
self._start = 0
self._end = range_str
self._initialized = True
return
range_str = str(range_str)
# strip out any whitespace
rstr = self.re_ws.sub('', range_str)
# LOG.debug("Parsing given range %r ...", rstr)
self._start = None
self._end = None
self._initialized = False
# check for valid range definition
match = self.re_digit.search(rstr)
if not match:
raise InvalidRangeError(range_str)
# LOG.debug("Parsing range with regex %r ...", self.match_range)
match = self.re_range.search(rstr)
if not match:
raise InvalidRangeError(range_str)
# LOG.debug("Found range parts: %r.", match.groups())
invert = match.group(1)
start = match.group(2)
end = match.group(3)
if invert is None:
self._invert_match = False
else:
self._invert_match = True
valid = False
start_should_infinity = False
if start is not None:
if start == '~':
start_should_infinity = True
start = None
else:
if self.re_dot.search(start):
start = float(start)
else:
start = int(start)
valid = True
# if start is None:
# if start_should_infinity:
# LOG.debug("The start is None, but should be infinity.")
# else:
# LOG.debug("The start is None, but should be NOT infinity.")
if end is not None:
if self.re_dot.search(end):
end = float(end)
else:
end = int(end)
if start is None and not start_should_infinity:
start = 0
valid = True
if not valid:
raise InvalidRangeError(range_str)
if start is not None and end is not None and start > end:
raise InvalidRangeError(range_str)
self._start = start
self._end = end
self._initialized = True
# -------------------------------------------------------------------------
def check_range(self, value):
"""Recverse method of self.check(), it inverts the result of check()
to provide the exact same behaviour like the check_range() method
of the Perl Nagios::Plugin::Range object."""
if self.check(value):
return False
return True
# -------------------------------------------------------------------------
def __contains__(self, value):
"""
Special method to implement the 'in' operator. With the help of this
method it's possible to write such things like::
my_range = MonitoringRange(80)
....
val = 5
if val in my_range:
print "Value %r is in range '%s'." % (val, my_range)
else:
print "Value %r is NOT in range '%s'." % (val, my_range)
@param value: the value to check against the current range
@type value: int or long or float
"""
return self.check(value)
# -------------------------------------------------------------------------
def check(self, value):
"""
Checks the given value against the current range.
@raise MonitoringRangeError: if the current range is not initialized
@raise InvalidRangeValueError: if the given value is not a number
@param value: the value to check against the current range
@type value: int or long or float
@return: the value is inside the range or not.
if self.invert_match is True, then this retur value is reverted
@rtype: bool
"""
if not self.initialized:
raise MonitoringRangeError(
"The current MonitoringRange object is not initialized.")
if not isinstance(value, Number):
raise InvalidRangeValueError(value)
my_true = True
my_false = False
if self.invert_match:
my_true = False
my_false = True
if self.start is not None and self.end is not None:
if self.start <= value and value <= self.end:
return my_true
else:
return my_false
if self.start is not None and self.end is None:
if value >= self.start:
return my_true
else:
return my_false
if self.start is None and self.end is not None:
if value <= self.end:
return my_true
else:
return my_false
raise MonitoringRangeError(
"This point should never been reached in "
"checking a value against a range.")
return my_false
# =============================================================================
class MonitoringPerformance(MonitoringObject):
"""
A class for handling monitoring performance data.
"""
# Some regular expressions ...
re_not_word = re.compile(r'\W')
re_trailing_semicolons = re.compile(r';;$')
re_slash = re.compile(r'/')
re_leading_slash = re.compile(r'^/')
re_comma = re.compile(r',')
pat_value = r'[-+]?[\d\.,]+'
pat_value_neg_inf = pat_value + r'|~'
"""pattern for a range with a negative infinity"""
pat_perfstring = r"^'?([^'=]+)'?=(" + pat_value + r')([\w%]*);?'
pat_perfstring += r'(' + pat_value_neg_inf + r'\:?' + pat_value + r'?)?;?'
pat_perfstring += r'(' + pat_value_neg_inf + r'\:?' + pat_value + r'?)?;?'
pat_perfstring += r'(' + pat_value + r'?)?;?'
pat_perfstring += r'(' + pat_value + r'?)?'
re_perfstring = re.compile(pat_perfstring)
re_perfoutput = re.compile(r'^(.*?=.*?)\s+')
# -------------------------------------------------------------------------
def __init__(
self, label, value, uom=None, threshold=None, warning=None, critical=None,
min_data=None, max_data=None):
"""
Initialisation of the MonitoringPerformance object.
@param label: the label of the performance data, mandantory
@type label: str
@param value: the value of the performance data, mandantory
@type value: Number
@param uom: the unit of measure
@type uom: str or None
@param threshold: an object for the warning and critical thresholds
if set, it overrides the warning and critical parameters
@type threshold: MonitoringThreshold or None
@param warning: a range for the warning threshold,
ignored, if threshold is given
@type warning: MonitoringRange, str, Number or None
@param critical: a range for the critical threshold,
ignored, if threshold is given
@type critical: MonitoringRange, str, Number or None
@param min_data: the minimum data for performance output
@type min_data: Number or None
@param max_data: the maximum data for performance output
@type max_data: Number or None
"""
self._label = str(label).strip()
"""
@ivar: the label of the performance data
@type: str
"""
if label is None or self._label == '':
raise MonitoringPerformanceError(
"Empty label %r for MonitoringPerformance given." % (label))
self._value = value
"""
@ivar: the value of the performance data
@type: Number
"""
if not isinstance(value, Number):
raise MonitoringPerformanceError(
"Wrong value %r for MonitoringPerformance given." % (value))
self._uom = ''
"""
@ivar: the unit of measure
@type: str
"""
if uom is not None:
# remove all whitespaces
self._uom = self.re_ws.sub('', str(uom))
warn_range = MonitoringRange()
if warning:
warn_range = MonitoringRange(warning)
crit_range = MonitoringRange()
if critical:
crit_range = MonitoringRange(critical)
self._threshold = None
"""
@ivar: the threshold object containing the warning and the
critical threshold
@type: MonitoringThreshold
"""
if isinstance(threshold, MonitoringThreshold):
self._threshold = threshold
elif threshold is not None:
raise MonitoringPerformanceError(
"The given threshold %r is neither None nor a MonitoringThreshold object." % (
threshold))
else:
self._threshold = MonitoringThreshold(
warning=warn_range,
critical=crit_range
)
self._min_data = None
"""
@ivar: the minimum data for performance output
@type: Number or None
"""
if min_data is not None:
if not isinstance(min_data, Number):
raise MonitoringPerformanceError(
"The given min_data %r is not None and not a Number." % (min_data))
else:
self._min_data = min_data
self._max_data = None
"""
@ivar: the maximum data for performance output
@type: Number or None
"""
if max_data is not None:
if not isinstance(max_data, Number):
raise MonitoringPerformanceError(
"The given max_data %r is not None and not a Number." % (max_data))
else:
self._max_data = max_data
# -----------------------------------------------------------
@property
def label(self):
"""The label of the performance data."""
return self._label
# -----------------------------------------------------------
@property
def clean_label(self):
"""Returns a "clean" label for use as a dataset name in RRD, ie, it
converts characters that are not [a-zA-Z0-9_] to _."""
name = self.label
if name == '/':
name = "root"
elif self.re_slash.search(name):
name = self.re_leading_slash.sub('', name)
name = self.re_slash.sub('_', name)
name = self.re_not_word.sub('_', name)
return name
# -----------------------------------------------------------
@property
def rrdlabel(self):
"""Returns a string based on 'label' that is suitable for use as
dataset name of an RRD i.e. munges label to be 1-19 characters long
with only characters [a-zA-Z0-9_]."""
return self.clean_label[0:19]
# -----------------------------------------------------------
@property
def value(self):
"""The value of the performance data."""
return self._value
# -----------------------------------------------------------
@property
def uom(self):
"""The unit of measure."""
return self._uom
# -----------------------------------------------------------
@property
def threshold(self):
"""The threshold object containing the warning and the critical threshold."""
return self._threshold