Commit 5dfad5fc authored by Navid Sassan's avatar Navid Sassan
Browse files

Merge branch 'develop' into 'master'

new release

Closes #20, #21, #22, #23, #8, #7, #24, #25, #26, #27, #28, #29, #32, #33, #34, #35, #36, #37, and #38

See merge request !8
parents babb7eb5 699c9291
Contributor Covenant Code of Conduct
====================================
Our Pledge
----------
We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
Our Standards
-------------
Behavior that contributes to a positive environment for our community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
* Focusing on what is best not just for us as individuals, but for the overall community
Unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
Enforcement Responsibilities
----------------------------
Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
Scope
-----
This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
Enforcement
-----------
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at `https://www.linuxfabrik.ch/kontakt <https://www.linuxfabrik.ch/kontakt>`_. All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the reporter of any incident.
Enforcement Guidelines
----------------------
Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
1. Correction
Community Impact: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
Consequence: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
2. Warning
Community Impact: A violation through a single incident or series of actions.
Consequence: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
3. Temporary Ban
Community Impact: A serious violation of community standards, including sustained inappropriate behavior.
Consequence: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
4. Permanent Ban
Community Impact: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
Consequence: A permanent ban from any sort of public interaction within the community.
Attribution
-----------
This Code of Conduct is adapted from the `Contributor Covenant, version 2.1 <https://www.contributor-covenant.org/version/2/1/code_of_conduct.html>`_.
Community Impact Guidelines were inspired by Mozilla's code of conduct enforcement ladder.
For answers to common questions about this code of conduct, see the `FAQ <https://www.contributor-covenant.org/faq>`_. Translations are available `here <https://www.contributor-covenant.org/translations>`_.
......@@ -12,7 +12,7 @@
"""
__author__ = 'Linuxfabrik GmbH, Zurich/Switzerland'
__version__ = '2021050401'
__version__ = '2021082501'
def csv(arg):
......@@ -26,7 +26,7 @@ def float_or_none(arg):
"""Returns None or float from a `float_or_none` input argument.
"""
if arg is None or str(arg).lower() == 'none':
if arg is None or unicode(arg).lower() == 'none':
return None
return float(arg)
......@@ -35,7 +35,7 @@ def int_or_none(arg):
"""Returns None or int from a `int_or_none` input argument.
"""
if arg is None or str(arg).lower() == 'none':
if arg is None or unicode(arg).lower() == 'none':
return None
return int(arg)
......@@ -51,6 +51,6 @@ def str_or_none(arg):
"""Returns None or str from a `str_or_none` input argument.
"""
if arg is None or str(arg).lower() == 'none':
if arg is None or unicode(arg).lower() == 'none':
return None
return str(arg)
return unicode(arg)
......@@ -12,20 +12,18 @@
"""
__author__ = 'Linuxfabrik GmbH, Zurich/Switzerland'
__version__ = '2020043001'
__version__ = '2021082501'
def csv(arg):
"""Returns a list from a `csv` input argument.
"""
return [x.strip() for x in arg.split(',')]
def float_or_none(arg):
"""Returns None or float from a `float_or_none` input argument.
"""
if arg is None or str(arg).lower() == 'none':
return None
return float(arg)
......@@ -34,7 +32,6 @@ def float_or_none(arg):
def int_or_none(arg):
"""Returns None or int from a `int_or_none` input argument.
"""
if arg is None or str(arg).lower() == 'none':
return None
return int(arg)
......@@ -43,14 +40,12 @@ def int_or_none(arg):
def range_or_none(arg):
"""Returns None or range from a `range_or_none` input argument.
"""
return str_or_none(arg)
def str_or_none(arg):
"""Returns None or str from a `str_or_none` input argument.
"""
if arg is None or str(arg).lower() == 'none':
return None
return str(arg)
This diff is collapsed.
......@@ -12,7 +12,7 @@
"""
__author__ = 'Linuxfabrik GmbH, Zurich/Switzerland'
__version__ = '2021061401'
__version__ = '2021091701'
import collections
import datetime
......@@ -27,8 +27,9 @@ import subprocess
import sys
import time
from traceback import format_exc # pylint: disable=C0413
from .globals3 import STATE_CRIT, STATE_OK, STATE_UNKNOWN, STATE_WARN
from . import disk3
WINDOWS = os.name == "nt"
......@@ -142,6 +143,16 @@ def coe(result, state=STATE_UNKNOWN):
sys.exit(state)
def cu():
"""See you (cu)
Prints a Stacktrace (replacing "<" and ">" to be printable in Web-GUIs), and exits with
STATE_UNKNOWN.
"""
print(format_exc().replace("<", "'").replace(">", "'"))
sys.exit(STATE_UNKNOWN)
def epoch2iso(timestamp):
"""Returns the ISO representaton of a UNIX timestamp (epoch).
......@@ -152,6 +163,45 @@ def epoch2iso(timestamp):
return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timestamp))
def extract_str(s, from_txt, to_txt, include_fromto=False, be_tolerant=True):
"""Extracts text between `from_txt` to `to_txt`.
If `include_fromto` is set to False (default), text is returned without both search terms,
otherwise `from_txt` and `to_txt` are included.
If `from_txt` is not found, always an empty string is returned.
If `to_txt` is not found and `be_tolerant` is set to True (default), text is returned from
`from_txt` til the end of input text. Otherwise an empty text is returned.
>>> extract_text('abcde', 'x', 'y')
''
>>> extract_text('abcde', 'b', 'x')
'cde'
>>> extract_text('abcde', 'b', 'x', include_fromto=True)
'bcde'
>>> extract_text('abcde', 'b', 'x', include_fromto=True, be_tolerant=False)
''
>>> extract_text('abcde', 'b', 'd')
'c'
>>> extract_text('abcde', 'b', 'd', include_fromto=True)
'bcd'
"""
pos1 = s.find(from_txt)
if pos1 == -1:
# nothing found
return ''
pos2 = s.find(to_txt, pos1+len(from_txt))
# to_txt not found:
if pos2 == -1 and be_tolerant and not include_fromto:
return s[pos1+len(from_txt):]
if pos2 == -1 and be_tolerant and include_fromto:
return s[pos1:]
if pos2 == -1 and not be_tolerant:
return ''
# from_txt and to_txt found:
if not include_fromto:
return s[pos1+len(from_txt):pos2-len(to_txt)+ 1]
return s[pos1:pos2+len(to_txt)]
def filter_mltext(input, ignore):
filtered_input = ''
for line in input.splitlines():
......@@ -164,6 +214,9 @@ def filter_mltext(input, ignore):
def filter_str(s, charclass='a-zA-Z0-9_'):
"""Stripping everything except alphanumeric chars and '_' from a string -
chars that are allowed everywhere in variables, database table or index names, etc.
>>> filter_str('user@example.ch')
'userexamplech'
"""
regex = '[^{}]'.format(charclass)
return re.sub(regex, "", s)
......@@ -237,9 +290,9 @@ def get_state(value, warn, crit, operator='ge'):
"""Returns the STATE by comparing `value` to the given thresholds using
a comparison `operator`. `warn` and `crit` threshold may also be `None`.
>>> lib.base3.get_state(15, 10, 20, 'ge')
>>> get_state(15, 10, 20, 'ge')
1 (STATE_WARN)
>>> lib.base3.get_state(10, 10, 20, 'gt')
>>> get_state(10, 10, 20, 'gt')
0 (STATE_OK)
Parameters
......@@ -251,12 +304,13 @@ def get_state(value, warn, crit, operator='ge'):
crit : float
Numeric critical threshold
operator : string
`eq` = equal to
`ge` = greater or equal
`gt` = greater than
`le` = less or equal
`lt` = less than
`eq` = equal to
`ne` = not equal to
`range` = match range
Returns
-------
......@@ -319,19 +373,29 @@ def get_state(value, warn, crit, operator='ge'):
return STATE_WARN
return STATE_OK
if operator == 'range':
if crit is not None:
if not coe(match_range(value, crit)):
return STATE_CRIT
if warn is not None:
if not coe(match_range(value, warn)):
return STATE_WARN
return STATE_OK
return STATE_UNKNOWN
def get_table(data, keys, header=None, sort_by_key=None, sort_order_reverse=False):
def get_table(data, cols, header=None, strip=True, sort_by_key=None, sort_order_reverse=False):
"""Takes a list of dictionaries, formats the data, and returns
the formatted data as a text table.
Required Parameters:
data - Data to process (list of dictionaries). (Type: List)
keys - List of keys in the dictionary. (Type: List)
cols - List of cols in the dictionary. (Type: List)
Optional Parameters:
header - The table header. (Type: List)
strip - Strip/Trim values or not. (Type: Boolean)
sort_by_key - The key to sort by. (Type: String)
sort_order_reverse - Default sort order is ascending, if
True sort order will change to descending. (Type: bool)
......@@ -342,38 +406,59 @@ def get_table(data, keys, header=None, sort_by_key=None, sort_order_reverse=Fals
if not data:
return ''
# Sort the data if a sort key is specified (default sort order
# is ascending)
# Sort the data if a sort key is specified (default sort order is ascending)
if sort_by_key:
data = sorted(data,
key=operator.itemgetter(sort_by_key),
reverse=sort_order_reverse)
# If header is not empty, add header to data
# If header is not empty, create a list of dictionary from the cols and the header and
# insert it before first row of data
if header:
# Get the length of each header and create a divider based
# on that length
header_divider = []
for name in header:
header_divider.append('-' * len(name))
# Create a list of dictionary from the keys and the header and
# insert it at the beginning of the list. Do the same for the
# divider and insert below the header.
header_divider = dict(zip(keys, header_divider))
data.insert(0, header_divider)
header = dict(zip(keys, header))
header = dict(zip(cols, header))
data.insert(0, header)
# prepare data: decode from (mostly) UTF-8 to Unicode, optionally strip values and get
# the maximum length per column
column_widths = collections.OrderedDict()
for key in keys:
column_widths[key] = max(len(str(column[key])) for column in data)
for idx, row in enumerate(data):
for col in cols:
try:
if strip:
data[idx][col] = str(row[col]).strip()
else:
data[idx][col] = str(row[col])
except:
return 'Unknown column "{}"'.format(col)
# get the maximum length
try:
column_widths[col] = max(column_widths[col], len(data[idx][col]))
except:
column_widths[col] = len(data[idx][col])
if header:
# Get the length of each column and create a '---' divider based on that length
header_divider = []
for col, width in column_widths.items():
header_divider.append('-' * width)
# Insert the header divider below the header row
header_divider = dict(zip(cols, header_divider))
data.insert(1, header_divider)
# create the output
table = ''
for element in data:
for key, width in column_widths.items():
table += '{:<{}} '.format(element[key], width)
table += '\n'
cnt = 0
for row in data:
tmp = ''
for col, width in column_widths.items():
if cnt != 1:
tmp += '{:<{}} ! '.format(row[col], width)
else:
# header row
tmp += '{:<{}}-+-'.format(row[col], width)
cnt += 1
table += tmp[:-2] + '\n'
return table
......@@ -529,6 +614,28 @@ def match_range(value, spec):
def parse_range(spec):
"""
Inspired by https://github.com/mpounsett/nagiosplugin/blob/master/nagiosplugin/range.py
+--------+-------------------+-------------------+--------------------------------+
| -w, -c | OK if result is | WARN/CRIT if | lib.base.parse_range() returns |
+--------+-------------------+-------------------+--------------------------------+
| 10 | in (0..10) | not in (0..10) | (0, 10, False) |
+--------+-------------------+-------------------+--------------------------------+
| -10 | in (-10..0) | not in (-10..0) | (0, -10, False) |
+--------+-------------------+-------------------+--------------------------------+
| 10: | in (10..inf) | not in (10..inf) | (10, inf, False) |
+--------+-------------------+-------------------+--------------------------------+
| : | in (0..inf) | not in (0..inf) | (0, inf, False) |
+--------+-------------------+-------------------+--------------------------------+
| ~:10 | in (-inf..10) | not in (-inf..10) | (-inf, 10, False) |
+--------+-------------------+-------------------+--------------------------------+
| 10:20 | in (10..20) | not in (10..20) | (10, 20, False) |
+--------+-------------------+-------------------+--------------------------------+
| @10:20 | not in (10..20) | in 10..20 | (10, 20, True) |
+--------+-------------------+-------------------+--------------------------------+
| @~:20 | not in (-inf..20) | in (-inf..20) | (-inf, 20, True) |
+--------+-------------------+-------------------+--------------------------------+
| @ | not in (0..inf) | in (0..inf) | (0, inf, True) |
+--------+-------------------+-------------------+--------------------------------+
"""
def parse_atom(atom, default):
if atom == '':
......@@ -963,23 +1070,6 @@ def state2str(state, empty_ok=True, prefix='', suffix=''):
return state
def test(args):
"""Enables unit testing of a check plugin.
"""
if args[0] and os.path.isfile(args[0]):
success, stdout = disk3.read_file(args[0])
else:
stdout = args[0]
if args[1] and os.path.isfile(args[1]):
success, stderr = disk3.read_file(args[1])
else:
stderr = args[1]
retc = int(args[2])
return stdout, stderr, retc
def timestr2datetime(timestr, pattern='%Y-%m-%d %H:%M:%S'):
"""Takes a string (default: ISO format) and returns a
datetime object.
......@@ -1006,13 +1096,24 @@ def uniq(string):
return ' '.join(sorted(set(words), key=words.index))
def utc_offset():
"""Returns the current local UTC offset, for example '+0200'.
utc_offset()
>>> '+0200'
"""
return time.strftime("%z")
def version(v):
"""Use this function to compare numerical but string-based version numbers.
"""Use this function to compare string-based version numbers.
>>> lib.base3.version('3.0.7') < lib.base3.version('3.0.11')
True
>>> '3.0.7' < '3.0.11'
False
>>> lib.base3.version('3.0.7') < lib.base3.version('3.0.11')
True
>>> lib.base3.version('v3.0.7-2') < lib.base3.version('3.0.11')
True
>>> lib.base3.version(psutil.__version__) >= lib.base3.version('5.3.0')
True
......@@ -1026,6 +1127,10 @@ def version(v):
tuple
A tuple of version numbers.
"""
# if we get something like "v0.10.7-2", remove everything except "." and "-",
# and convert "-" to "."
v = re.sub(r'[^0-9\.-]', '', v)
v = v.replace('-', '.')
return tuple(map(int, (v.split("."))))
......@@ -1034,10 +1139,51 @@ def version2float(v):
>>> version2float('Version v17.3.2.0')
17.320
>>> version2float('21.60-53-93285')
21.605393285
"""
v = re.sub(r'[a-z\s]', '', v.lower())
v = re.sub(r'[^0-9\.]', '', v)
v = v.split('.')
if len(v) > 1:
return float('{}.{}'.format(v[0], ''.join(v[1:])))
else:
return float(''.join(v))
def yesterday(as_type='', tz_utc=False):
"""Returns yesterday's date and time as UNIX time in seconds (default), or
as a datetime object.
>>> lib.base3.yesterday()
1626706723
>>> lib.base3.yesterday(as_type='', tz_utc=False)
1626706723
>>> lib.base3.yesterday(as_type='', tz_utc=True)
1626706723
>>> lib.base3.yesterday(as_type='datetime', tz_utc=False)
datetime.datetime(2021, 7, 19, 16, 58, 43, 11292)
>>> lib.base3.yesterday(as_type='datetime', tz_utc=True)
datetime.datetime(2021, 7, 19, 14, 58, 43, 11446, tzinfo=datetime.timezone.utc)
>>> lib.base3.yesterday(as_type='iso', tz_utc=False)
'2021-07-19 16:58:43'
>>> lib.base3.yesterday(as_type='iso', tz_utc=True)
'2021-07-19T14:58:43Z'
"""
if tz_utc:
if as_type == 'datetime':
today = datetime.datetime.now(tz=datetime.timezone.utc)
return today - datetime.timedelta(days=1)
if as_type == 'iso':
today = datetime.datetime.now(tz=datetime.timezone.utc)
yesterday = today - datetime.timedelta(days=1)
return yesterday.isoformat(timespec='seconds').replace('+00:00', 'Z')
if as_type == 'datetime':
today = datetime.datetime.now()
return today - datetime.timedelta(days=1)
if as_type == 'iso':
today = datetime.datetime.now()
yesterday = today - datetime.timedelta(days=1)
return yesterday.strftime("%Y-%m-%d %H:%M:%S")
return int(time.time()-86400)
......@@ -25,13 +25,13 @@ False
"""
__author__ = 'Linuxfabrik GmbH, Zurich/Switzerland'
__version__ = '2020051301'
__version__ = '2021100801'
import base2
import db_sqlite2
def get(key, as_dict=False):
def get(key, as_dict=False, path='', filename='linuxfabrik-plugin-cache.db'):
"""Get the value of key. If the key does not exist, `False` is returned.
Parameters
......@@ -46,7 +46,7 @@ def get(key, as_dict=False):
failure.
"""
success, conn = db_sqlite2.connect(filename='linuxfabrik-plugin-cache.db')
success, conn = db_sqlite2.connect(path=path, filename=filename)
if not success:
return False
......@@ -71,7 +71,7 @@ def get(key, as_dict=False):
data = {'key' : result['key']}
success, result = db_sqlite2.delete(
conn,
sql='DELETE FROM cache WHERE timestamp <= {};'.format(base2.now())
sql=u'DELETE FROM cache WHERE timestamp <= {};'.format(base2.now())
)
success, result = db_sqlite2.commit(conn)
db_sqlite2.close(conn)
......@@ -87,7 +87,7 @@ def get(key, as_dict=False):
return result
def set(key, value, expire=0):
def set(key, value, expire=0, path='', filename='linuxfabrik-plugin-cache.db'):
"""Set key to hold the string value.
Keys have to be unique. If the key already holds a value, it is
......@@ -109,7 +109,7 @@ def set(key, value, expire=0):
`True` on success, `False` on failure.
"""
success, conn = db_sqlite2.connect(filename='linuxfabrik-plugin-cache.db')
success, conn = db_sqlite2.connect(path=path, filename=filename)
if not success:
return False
......
......@@ -25,13 +25,13 @@ False
"""
__author__ = 'Linuxfabrik GmbH, Zurich/Switzerland'
__version__ = '2021031001'
__version__ = '2021100801'
from . import base3
from . import db_sqlite3
def get(key, as_dict=False):
def get(key, as_dict=False, path='', filename='linuxfabrik-plugin-cache.db'):
"""Get the value of key. If the key does not exist, `False` is returned.
Parameters
......@@ -46,7 +46,7 @@ def get(key, as_dict=False):
failure.
"""
success, conn = db_sqlite3.connect(filename='linuxfabrik-plugin-cache.db')
success, conn = db_sqlite3.connect(path=path, filename=filename)
if not success:
return False
......@@ -71,7 +71,7 @@ def get(key, as_dict=False):
data = {'key' : result['key']}
success, result = db_sqlite3.delete(
conn,
sql='DELETE FROM cache WHERE timestamp <= {};'.format(base.now())
sql='DELETE FROM cache WHERE timestamp <= {};'.format(base3.now())
)
success, result = db_sqlite3.commit(conn)
db_sqlite3.close(conn)
......@@ -87,7 +87,7 @@ def get(key, as_dict=False):
return result
def set(key, value, expire=0):
def set(key, value, expire=0, path='', filename='linuxfabrik-plugin-cache.db'):
"""Set key to hold the string value.
Keys have to be unique. If the key already holds a value, it is
......@@ -109,7 +109,7 @@ def set(key, value, expire=0):
`True` on success, `False` on failure.
"""