88
99# https://github.com/Linuxfabrik/monitoring-plugins/blob/main/CONTRIBUTING.rst
1010
11- """Provides very common every-day functions.
12- """
11+ """Provides very common every-day functions."""
1312
1413__author__ = 'Linuxfabrik GmbH, Zurich/Switzerland'
1514__version__ = '2026040801'
1817import operator
1918import os
2019import sys
21-
2220from traceback import format_exc
2321
24- from .globals import STATE_CRIT , STATE_OK , STATE_UNKNOWN , STATE_WARN
2522from . import txt
23+ from .globals import STATE_CRIT , STATE_OK , STATE_UNKNOWN , STATE_WARN
2624
27-
28- WINDOWS = os .name == "nt"
29- LINUX = sys .platform .startswith ("linux" )
25+ WINDOWS = os .name == 'nt'
26+ LINUX = sys .platform .startswith ('linux' )
3027X86_64 = sys .maxsize > 2 ** 32
3128
3229_OPS = {
@@ -112,17 +109,21 @@ def cu(msg=None):
112109 - If no traceback is present, only the optional message (if any) is printed.
113110
114111 ### Example
115- >>> cu(" Unable to connect to server" )
112+ >>> cu(' Unable to connect to server' )
116113
117114 >>> cu()
118115 """
119116 has_traceback = sys .exc_info ()[0 ] is not None
120117 tb = format_exc () if has_traceback else None
121118
122119 if msg is not None :
123- msg = txt .sanitize_sensitive_data (msg ).strip ().replace ('<' , "'" ).replace ('>' , "'" )
120+ msg = (
121+ txt .sanitize_sensitive_data (msg ).strip ().replace ('<' , "'" ).replace ('>' , "'" )
122+ )
124123 print (msg , end = '' )
125- print (' (Traceback for debugging purposes attached)\n ' if has_traceback else '\n ' )
124+ print (
125+ ' (Traceback for debugging purposes attached)\n ' if has_traceback else '\n '
126+ )
126127
127128 if has_traceback :
128129 print (tb .replace ('<' , "'" ).replace ('>' , "'" ))
@@ -132,7 +133,7 @@ def cu(msg=None):
132133
133134def get_perfdata (label , value , uom = None , warn = None , crit = None , _min = None , _max = None ):
134135 """
135- Returns a Nagios performance data string in the format:
136+ Returns a Nagios performance data string in the format:
136137 `'label'=value[UOM];[warn];[crit];[min];[max]`
137138
138139 ### Parameters
@@ -169,13 +170,13 @@ def get_state(value, warn, crit, _operator='ge'):
169170 - **value** (`float`): Numeric value to evaluate.
170171 - **warn** (`float`): Numeric warning threshold.
171172 - **crit** (`float`): Numeric critical threshold.
172- - **_operator** (`str`): Comparison operator to use:
173- - `eq`: equal to
174- - `ge`: greater or equal
175- - `gt`: greater than
176- - `le`: less or equal
177- - `lt`: less than
178- - `ne`: not equal to
173+ - **_operator** (`str`): Comparison operator to use:
174+ - `eq`: equal to
175+ - `ge`: greater or equal
176+ - `gt`: greater than
177+ - `le`: less or equal
178+ - `lt`: less than
179+ - `ne`: not equal to
179180 - `range`: match Nagios range definition
180181
181182 ### Returns
@@ -217,7 +218,9 @@ def get_state(value, warn, crit, _operator='ge'):
217218 return STATE_OK
218219
219220
220- def get_table (data , cols , header = None , strip = True , sort_by_key = None , sort_order_reverse = False ):
221+ def get_table (
222+ data , cols , header = None , strip = True , sort_by_key = None , sort_order_reverse = False
223+ ):
221224 """
222225 Format a list of dictionaries into a simple ASCII table.
223226
@@ -253,7 +256,9 @@ def get_table(data, cols, header=None, strip=True, sort_by_key=None, sort_order_
253256 data = data .copy () # data has been passed by-reference - kick the reference
254257
255258 if sort_by_key :
256- data = sorted (data , key = operator .itemgetter (sort_by_key ), reverse = sort_order_reverse )
259+ data = sorted (
260+ data , key = operator .itemgetter (sort_by_key ), reverse = sort_order_reverse
261+ )
257262
258263 if header :
259264 data .insert (0 , dict (zip (cols , header )))
@@ -289,8 +294,8 @@ def get_table(data, cols, header=None, strip=True, sort_by_key=None, sort_order_
289294
290295def get_worst (state1 , state2 ):
291296 """
292- Compares `state1` to `state2` and returns the worse state based on the following priority:
293- STATE_OK < STATE_UNKNOWN < STATE_WARNING < STATE_CRITICAL
297+ Compares `state1` to `state2` and returns the worse state based on the following priority:
298+ STATE_OK < STATE_UNKNOWN < STATE_WARNING < STATE_CRITICAL
294299 It will prioritize any non-OK state.
295300
296301 Note that numerically the priority order does not match their integer values.
@@ -334,7 +339,7 @@ def guess_type(v, consumer='python'):
334339 'python'.
335340
336341 ### Returns
337- - **any**:
342+ - **any**:
338343 - If `consumer='python'`, returns `None`, `int`, `float`, or `str`.
339344 - If `consumer='sqlite'`, returns `'integer'`, `'real'`, or `'text'`.
340345
@@ -428,16 +433,16 @@ def lookup_lod(haystack, key, needle):
428433 - **needle** (`any`): The value to match against the specified key.
429434
430435 ### Returns
431- - **tuple**:
436+ - **tuple**:
432437 - If found: (index, dictionary item).
433438 - If not found: (-1, None).
434439
435440 ### Example
436441 >>> haystack = [
437- ... {" name": " Tom", " age" : 10},
438- ... {" name": " Mark", " age" : 5},
439- ... {" name": " Pam", " age" : 7},
440- ... {" name": " Dick", " age" : 12}
442+ ... {' name': ' Tom', ' age' : 10},
443+ ... {' name': ' Mark', ' age' : 5},
444+ ... {' name': ' Pam', ' age' : 7},
445+ ... {' name': ' Dick', ' age' : 12},
441446 ... ]
442447 >>> lookup_lod(haystack, 'name', 'Pam')
443448 (2, {'name': 'Pam', 'age': 7})
@@ -502,8 +507,7 @@ def _parse_range(spec_):
502507 else :
503508 start , end = '' , spec_
504509
505- start = float ('-inf' ) if start == '~' \
506- else _parse_range_atom (start , 0 )
510+ start = float ('-inf' ) if start == '~' else _parse_range_atom (start , 0 )
507511 end = _parse_range_atom (end , float ('inf' ))
508512
509513 if start > end :
@@ -591,7 +595,7 @@ def oao(msg, state=STATE_OK, perfdata='', always_ok=False):
591595 ### Parameters
592596 - **msg** (`str`): The plugin message to print. Will be stripped, sanitized, and processed.
593597 - **state** (`int`, optional): The exit code to use. Defaults to `STATE_OK`.
594- - **perfdata** (`str`, optional): Performance data to append after a `|` separator.
598+ - **perfdata** (`str`, optional): Performance data to append after a `|` separator.
595599 Defaults to an empty string (no performance data).
596600 - **always_ok** (`bool`, optional): If `True`, forces the exit code to `STATE_OK` regardless
597601 of the specified `state`. Defaults to `False`.
@@ -606,16 +610,21 @@ def oao(msg, state=STATE_OK, perfdata='', always_ok=False):
606610 - `perfdata`, if provided, must follow monitoring plugin standards for performance metrics.
607611
608612 ### Example
609- >>> oao(" Service is healthy" , STATE_OK, " load=0.12;1.00;5.00" , always_ok=False)
613+ >>> oao(' Service is healthy' , STATE_OK, ' load=0.12;1.00;5.00' , always_ok=False)
610614 Service is healthy|load=0.12;1.00;5.00
611615 (and exits with code 0)
612616
613- >>> oao(" password=secret123 found!" , STATE_CRITICAL)
617+ >>> oao(' password=secret123 found!' , STATE_CRITICAL)
614618 password=****** found!
615619 (and exits with code 2)
616620
617621 """
618- msg = txt .sanitize_sensitive_data (msg .strip ()).replace ('|' , '!' ).replace ('<' , "'" ).replace ('>' , "'" )
622+ msg = (
623+ txt .sanitize_sensitive_data (msg .strip ())
624+ .replace ('|' , '!' )
625+ .replace ('<' , "'" )
626+ .replace ('>' , "'" )
627+ )
619628 if always_ok and msg :
620629 # Instead of splitlines(), we just split('\n', 1), so only first line is touched.
621630 parts = msg .split ('\n ' , 1 )
@@ -634,7 +643,7 @@ def smartcast(value):
634643 - **value** (`any`): The value to attempt to cast.
635644
636645 ### Returns
637- - **float**, **str**, or **any**:
646+ - **float**, **str**, or **any**:
638647 - If convertible to `float`, returns a `float`.
639648 - If not, tries to convert to `str`.
640649 - If neither succeeds, returns the original value unchanged.
@@ -671,7 +680,7 @@ def sort(array, reverse=True, sort_by_key=False):
671680 - If `sort_by_key` is False (default), the dictionary items are sorted by their values.
672681 - If `sort_by_key` is True, the items are sorted by their keys (compared case-insensitively).
673682
674- The sort order is descending by default (`reverse=True`).
683+ The sort order is descending by default (`reverse=True`).
675684 If the input is not a dictionary, the original input is returned unmodified.
676685
677686 ### Parameters
@@ -758,25 +767,25 @@ def str2bool(s):
758767 otherwise False.
759768
760769 ### Example
761- >>> str2bool("" )
770+ >>> str2bool('' )
762771 False
763772
764- >>> str2bool(" false" )
773+ >>> str2bool(' false' )
765774 False
766775
767- >>> str2bool(" FalSE" )
776+ >>> str2bool(' FalSE' )
768777 False
769778
770- >>> str2bool(" true" )
779+ >>> str2bool(' true' )
771780 True
772781
773- >>> str2bool(" Linuxfabrik" )
782+ >>> str2bool(' Linuxfabrik' )
774783 True
775784
776- >>> str2bool("0" )
785+ >>> str2bool('0' )
777786 True
778787
779- >>> str2bool("1" )
788+ >>> str2bool('1' )
780789 True
781790 """
782791 return bool (s ) and s .lower () != 'false'
@@ -790,11 +799,11 @@ def str2state(string, ignore_error=True):
790799
791800 ### Parameters
792801 - **string** (`str`): The input string to match against known states.
793- - **ignore_error** (`bool`, optional): If True, unrecognized strings return `STATE_UNKNOWN`.
802+ - **ignore_error** (`bool`, optional): If True, unrecognized strings return `STATE_UNKNOWN`.
794803 If False, unrecognized strings return None. Defaults to True.
795804
796805 ### Returns
797- - **int** or **None**:
806+ - **int** or **None**:
798807 - The numeric state code (`STATE_OK`, `STATE_WARN`, `STATE_CRIT`, `STATE_UNKNOWN`) if
799808 recognized.
800809 - Otherwise, `STATE_UNKNOWN` or None, depending on `ignore_error`.
@@ -872,7 +881,13 @@ def sum_lod(mylist):
872881 - **dict**: A dictionary with summed numeric values by key.
873882
874883 ### Example
875- >>> sum_lod([{'in': 100, 'out': 10}, {'in': 50, 'out': 20}, {'error': 5, 'uuid': '1234-xyz'}])
884+ >>> sum_lod(
885+ ... [
886+ ... {'in': 100, 'out': 10},
887+ ... {'in': 50, 'out': 20},
888+ ... {'error': 5, 'uuid': '1234-xyz'},
889+ ... ]
890+ ... )
876891 {'in': 150, 'out': 30, 'error': 5}
877892 """
878893 total = {}
0 commit comments