10
10
11
11
"""Provides very common every-day functions.
12
12
13
- The functions "to_text()" and "to_bytes()" are copied from
13
+ The functions "to_text()" and "to_bytes()" are copied from
14
14
/usr/lib/python3.10/site-packages/ansible/module_utils/_text.py (BSD license).
15
15
"""
16
16
17
17
__author__ = 'Linuxfabrik GmbH, Zurich/Switzerland'
18
18
__version__ = '2022021504'
19
19
20
20
import collections
21
- import datetime
22
21
import numbers
23
22
import operator
24
23
import os
25
24
import re
26
25
import shlex
27
26
import subprocess
28
27
import sys
29
- import time
30
28
31
29
from traceback import format_exc # pylint: disable=C0413
32
30
@@ -92,16 +90,6 @@ def cu():
92
90
sys .exit (STATE_UNKNOWN )
93
91
94
92
95
- def epoch2iso (timestamp ):
96
- """Returns the ISO representaton of a UNIX timestamp (epoch).
97
-
98
- >>> epoch2iso(1620459129)
99
- '2021-05-08 09:32:09'
100
- """
101
- timestamp = float (timestamp )
102
- return time .strftime ('%Y-%m-%d %H:%M:%S' , time .localtime (timestamp ))
103
-
104
-
105
93
def get_command_output (cmd , regex = None ):
106
94
"""Runs a shell command and returns its output. Optionally, applies a regex and just
107
95
returns the first matching group. If the command is not found, an empty string is returned.
@@ -134,7 +122,7 @@ def get_command_output(cmd, regex=None):
134
122
return stdout .strip ()
135
123
136
124
137
- def get_perfdata (label , value , uom , warn , crit , min , max ):
125
+ def get_perfdata (label , value , uom , warn , crit , _min , _max ):
138
126
"""Returns 'label'=value[UOM];[warn];[crit];[min];[max]
139
127
"""
140
128
msg = "'{}'={}" .format (label , value )
@@ -147,11 +135,11 @@ def get_perfdata(label, value, uom, warn, crit, min, max):
147
135
if crit is not None :
148
136
msg += str (crit )
149
137
msg += ';'
150
- if min is not None :
151
- msg += str (min )
138
+ if _min is not None :
139
+ msg += str (_min )
152
140
msg += ';'
153
- if max is not None :
154
- msg += str (max )
141
+ if _max is not None :
142
+ msg += str (_max )
155
143
msg += ' '
156
144
return msg
157
145
@@ -350,7 +338,8 @@ def get_worst(state1, state2):
350
338
351
339
352
340
def guess_type (v , consumer = 'python' ):
353
- """Guess the type of a value (None, int, float or string) for different types of consumers (Python, SQLite etc.).
341
+ """Guess the type of a value (None, int, float or string) for different types of consumers
342
+ (Python, SQLite etc.).
354
343
For Python, use isinstance() to check for example if a number is an integer.
355
344
356
345
>>> guess_type('1')
@@ -373,34 +362,32 @@ def guess_type(v, consumer='python'):
373
362
if consumer == 'python' :
374
363
if v is None :
375
364
return None
376
- else :
365
+ try :
366
+ return int (v )
367
+ except ValueError :
377
368
try :
378
- return int (v )
369
+ return float (v )
379
370
except ValueError :
380
- try :
381
- return float (v )
382
- except ValueError :
383
- return str (v )
371
+ return str (v )
384
372
385
373
if consumer == 'sqlite' :
386
374
if v is None :
387
375
return 'string'
388
- else :
376
+ try :
377
+ int (v )
378
+ return 'integer'
379
+ except ValueError :
389
380
try :
390
- int (v )
391
- return 'integer '
381
+ float (v )
382
+ return 'real '
392
383
except ValueError :
393
- try :
394
- float (v )
395
- return 'real'
396
- except ValueError :
397
- return 'text'
384
+ return 'text'
398
385
399
386
400
387
def is_empty_list (l ):
401
388
"""Check if a list only contains either empty elements or whitespace
402
389
"""
403
- return all ('' == s or s .isspace () for s in l )
390
+ return all (s == '' or s .isspace () for s in l )
404
391
405
392
406
393
def is_numeric (value ):
@@ -497,7 +484,7 @@ def parse_atom(atom, default):
497
484
if not success :
498
485
return (success , result )
499
486
start , end , invert = result
500
- if isinstance (value , str ) or isinstance ( value , bytes ):
487
+ if isinstance (value , ( str , bytes ) ):
501
488
value = float (value .replace ('%' , '' ))
502
489
if value < start :
503
490
return (True , False ^ invert )
@@ -506,29 +493,6 @@ def parse_atom(atom, default):
506
493
return (True , True ^ invert )
507
494
508
495
509
- def now (as_type = '' ):
510
- """Returns the current date and time as UNIX time in seconds (default), or
511
- as a datetime object.
512
-
513
- lib.base3.now()
514
- >>> 1586422786
515
-
516
- lib.base3.now(as_type='epoch')
517
- >>> 1586422786
518
-
519
- lib.base3.now(as_type='datetime')
520
- >>> datetime.datetime(2020, 4, 9, 11, 1, 41, 228752)
521
-
522
- lib.base3.now(as_type='iso')
523
- >>> '2020-04-09 11:31:24'
524
- """
525
- if as_type == 'datetime' :
526
- return datetime .datetime .now ()
527
- if as_type == 'iso' :
528
- return time .strftime ("%Y-%m-%d %H:%M:%S" )
529
- return int (time .time ())
530
-
531
-
532
496
def oao (msg , state = STATE_OK , perfdata = '' , always_ok = False ):
533
497
"""Over and Out (OaO)
534
498
@@ -746,32 +710,6 @@ def state2str(state, empty_ok=True, prefix='', suffix=''):
746
710
return state
747
711
748
712
749
- def timestr2datetime (timestr , pattern = '%Y-%m-%d %H:%M:%S' ):
750
- """Takes a string (default: ISO format) and returns a
751
- datetime object.
752
- """
753
- return datetime .datetime .strptime (timestr , pattern )
754
-
755
-
756
- def timestrdiff (timestr1 , timestr2 , pattern1 = '%Y-%m-%d %H:%M:%S' , pattern2 = '%Y-%m-%d %H:%M:%S' ):
757
- """Returns the difference between two datetime strings in seconds. This
758
- function expects two ISO timestamps, by default each in ISO format.
759
- """
760
- timestr1 = timestr2datetime (timestr1 , pattern1 )
761
- timestr2 = timestr2datetime (timestr2 , pattern2 )
762
- timedelta = abs (timestr1 - timestr2 )
763
- return timedelta .total_seconds ()
764
-
765
-
766
- def utc_offset ():
767
- """Returns the current local UTC offset, for example '+0200'.
768
-
769
- utc_offset()
770
- >>> '+0200'
771
- """
772
- return time .strftime ("%z" )
773
-
774
-
775
713
def version (v ):
776
714
"""Use this function to compare string-based version numbers.
777
715
@@ -813,5 +751,4 @@ def version2float(v):
813
751
v = v .split ('.' )
814
752
if len (v ) > 1 :
815
753
return float ('{}.{}' .format (v [0 ], '' .join (v [1 :])))
816
- else :
817
- return float ('' .join (v ))
754
+ return float ('' .join (v ))
0 commit comments