Utils Package¶
Utils
Package¶
Misc utility classes and helper functions for pynag
This module contains misc classes and conveninence functions that are used throughout the pynag library.
-
class
pynag.Utils.
AttributeList
(value=None)¶ Bases:
object
Parse a list of nagios attributes into a parsable format. (e. contact_groups)
This makes it handy to mangle with nagios attribute values that are in a comma seperated format.
Typical comma-seperated format in nagios configuration files looks something like this:
contact_groups +group1,group2,group3
- Examples:
>>> i = AttributeList('+group1,group2,group3') >>> i.operator '+' >>> i.fields ['group1', 'group2', 'group3']
# if your data is already in a list format you can use it directly: >>> i = AttributeList([‘group1’, ‘group2’, ‘group3’]) >>> i.fields [‘group1’, ‘group2’, ‘group3’]
# white spaces will be stripped from all fields >>> i = AttributeList(‘+group1, group2’) >>> i +group1,group2 >>> i.fields [‘group1’, ‘group2’]
-
append
(object)¶ Same as list.append():
Args:
object: Item to append into self.fields (typically a string)Example:
>>> i = AttributeList('group1,group2,group3') >>> i.append('group5') >>> i.fields ['group1', 'group2', 'group3', 'group5']
-
count
(value)¶ Same as list.count()
- Args:
- value: Any object that might exist in self.fields (string)
- Returns:
- The number of occurances that ‘value’ has in self.fields
- Example:
>>> i = AttributeList('group1,group2,group3') >>> i.count('group3') 1
-
extend
(iterable)¶ Same as list.extend()
- Args:
- iterable: Any iterable that list.extend() supports
- Example:
>>> i = AttributeList('group1,group2,group3') >>> i.extend(['group4', 'group5']) >>> i.fields ['group1', 'group2', 'group3', 'group4', 'group5']
-
index
(value, start=0, stop=None)¶ Same as list.index()
- Args:
value: object to look for in self.fields
start: start at this index point
stop: stop at this index point
- Returns:
- The index of ‘value’ (integer)
- Examples:
>>> i = AttributeList('group1,group2,group3') >>> i.index('group2') 1 >>> i.index('group3', 2, 5) 2
-
insert
(index, object)¶ Same as list.insert()
Args:
object: Any object that will be inserted into self.fields (usually a string)Example:
>>> i = AttributeList('group1,group2,group3') >>> i.insert(1, 'group4') >>> i.fields ['group1', 'group4', 'group2', 'group3']
-
remove
(value)¶ Same as list.remove()
- Args:
- value: The object that is to be removed
- Examples:
>>> i = AttributeList('group1,group2,group3') >>> i.remove('group3') >>> i.fields ['group1', 'group2']
-
reverse
()¶ Same as list.reverse()
- Examples:
>>> i = AttributeList('group1,group2,group3') >>> i.reverse() >>> i.fields ['group3', 'group2', 'group1']
-
sort
()¶ Same as list.sort()
- Examples:
>>> i = AttributeList('group3,group1,group2') >>> i.sort() >>> print(i.fields) ['group1', 'group2', 'group3']
-
exception
pynag.Utils.
CommandFailed
(message, errorcode=None, errorstring=None, *args, **kwargs)¶ Bases:
pynag.Utils.UtilsError
Raised when a subprocess execution was unsuccessful.
-
class
pynag.Utils.
DefaultDict
(default_factory=None, *a, **kw)¶ Bases:
dict
This is an alternative implementation of collections.defaultdict.
Used as a fallback if using python 2.4 or older.
Usage:
try: from collections import defaultdict except ImportError: from pynag.Utils import defaultdict
-
copy
()¶
-
-
class
pynag.Utils.
PluginOutput
(stdout)¶ This class parses a typical stdout from a nagios plugin
It splits the output into the following fields:
- Summary
- Long Output
- Perfdata
Attributes:
summary (str): Summary returned by the plugin check
long_output (str)
perfdata (str): Data returned by the plugin as a string
parsed_perfdata: perfdata parsed and split
Example Usage:
>>> p = PluginOutput("Everything is ok | load1=15 load2=10") >>> p.summary 'Everything is ok ' >>> p.long_output '' >>> p.perfdata 'load1=15 load2=10' >>> p.parsed_perfdata.metrics ['load1'=15;;;;, 'load2'=10;;;;]
-
long_output
= None¶
-
parsed_perfdata
= None¶
-
perfdata
= None¶
-
summary
= None¶
-
exception
pynag.Utils.
UtilsError
(message, errorcode=None, errorstring=None, *args, **kwargs)¶ Bases:
pynag.errors.PynagError
Base class for errors in this module.
-
pynag.Utils.
defaultdict
¶ alias of
DefaultDict
-
pynag.Utils.
grep
(objects, **kwargs)¶ Returns all the elements from array that match the keywords in **kwargs
See documentation for pynag.Model.ObjectDefinition.objects.filter() for example how to use this.
Arguments:
objects (list of dict): list to be searched
kwargs (str): Any search argument provided will be checked against every dict
Examples:
array = [ {'host_name': 'examplehost', 'state':0}, {'host_name': 'example2', 'state':1}, ] grep_dict(array, state=0) # should return [{'host_name': 'examplehost', 'state':0},]
-
pynag.Utils.
grep_to_livestatus
(*args, **kwargs)¶ Converts from pynag style grep syntax to livestatus filter syntax.
Example:
>>> grep_to_livestatus(host_name='test') ['Filter: host_name = test'] >>> grep_to_livestatus(service_description__contains='serv') ['Filter: service_description ~ serv'] >>> grep_to_livestatus(service_description__isnot='serv') ['Filter: service_description != serv'] >>> grep_to_livestatus(service_description__contains=['serv','check']) ['Filter: service_description ~ serv'] >>> grep_to_livestatus(service_description__notcontains=['serv','check']) ['Filter: service_description !~ serv'] >>> grep_to_livestatus(service_description__contains='foo', contacts__has_field='admin') ['Filter: contacts >= admin', 'Filter: service_description ~ foo'] >>> grep_to_livestatus(service_description__has_field='foo') ['Filter: service_description >= foo'] >>> grep_to_livestatus(service_description__startswith='foo') ['Filter: service_description ~ ^foo'] >>> grep_to_livestatus(service_description__notstartswith='foo') ['Filter: service_description !~ ^foo'] >>> grep_to_livestatus(service_description__endswith='foo') ['Filter: service_description ~ foo$'] >>> grep_to_livestatus(service_description__notendswith='foo') ['Filter: service_description !~ foo$'] >>> grep_to_livestatus(service_description__exists='unnecessary_arg') ['Filter: service_description ~~ .*'] >>> grep_to_livestatus(service_description__regex='^abc$') ['Filter: service_description ~ ^abc$']
-
pynag.Utils.
is_macro
(macro)¶ Test if macro is in the format of a valid nagios macro.
- Args:
- macro: String. Any macro, example $HOSTADDRESS$
- Returns:
- Boolean. True if macro is in the format of a macro, otherwise false.
- Examples:
>>> is_macro('$HOSTADDRESS$') True >>> is_macro('$HOSTADDRESS') False >>> is_macro('') False >>> is_macro('$CONTACTNAME$') True >>> is_macro('$SERVICEDESC$') True >>> is_macro('$_SERVICE_CUSTOM$') True >>> is_macro('$_HOST_CUSTOM$') True >>> is_macro('$_CONTACT_CUSTOM$') True
-
pynag.Utils.
runCommand
(command, raise_error_on_fail=False, shell=True, env=None)¶ Run command from the shell prompt. Wrapper around subprocess.
Args:
command (str): string containing the command line to run
raise_error_on_fail (bool): Raise CommandFailed if returncode > 0
Returns:
str: stdout/stderr of the command runRaises:
CommandFailed if returncode > 0
-
pynag.Utils.
run_command
(command, raise_error_on_fail=False, shell=True, env=None)¶ Run command from the shell prompt. Wrapper around subprocess.
Args:
command (str): string containing the command line to run
raise_error_on_fail (bool): Raise CommandFailed if returncode > 0
Returns:
str: stdout/stderr of the command runRaises:
CommandFailed if returncode > 0
-
class
pynag.Utils.
CheckResult
(nagios_result_dir, file_time=None)¶ Bases:
object
Methods for creating host and service checkresults for nagios processing
-
host_result
(host_name, **kwargs)¶ Create a service checkresult
Any kwarg will be added to the checkresult
- Args:
- host_name (str) service_descritpion (str)
- Kwargs:
- check_type (int): active(0) or passive(1) check_options (int) scheduled_check (int) reschedule_check (int) latency (float) start_time (float) finish_time (float) early_timeout (int) exited_ok (int) return_code (int) output (str): plugin output
-
service_result
(host_name, service_description, **kwargs)¶ Create a service checkresult
Any kwarg will be added to the checkresult
- Args:
- host_name (str) service_descritpion (str)
- Kwargs:
- check_type (int): active(0) or passive(1) check_options (int) scheduled_check (int) reschedule_check (int) latency (float) start_time (float) finish_time (float) early_timeout (int) exited_ok (int) return_code (int) output (str): plugin output
-
submit
()¶ Submits the results to nagios
-
The importer¶
General Utilities from importing nagios objects. Currently .csv files are supported
Either execute this script standalone from the command line or use it as a python library like so:
>>> from pynag.Utils import importer
>>> pynag_objects = importer.import_from_csv_file(filename='foo', seperator=',')
>>> for i in pynag_objects:
... i.save()
-
pynag.Utils.importer.
dict_to_pynag_objects
(dict_list, object_type=None)¶ Take a list of dictionaries, return a list of pynag.Model objects.
- Args:
- dict_list: List of dictionaries that represent pynag objects object_type: Use this object type as default, if it is not specified in dict_list
- Returns:
- List of pynag objects
-
pynag.Utils.importer.
import_from_csv_file
(filename, seperator=', ', object_type=None)¶ Parses filename and returns a list of pynag objects.
- Args:
- filename: Path to a file seperator: use this symbol to seperate columns in the file object_type: Assume this object_type if there is no object_type column
-
pynag.Utils.importer.
parse_arguments
()¶ Parse command line arguments
-
pynag.Utils.importer.
parse_csv_file
(filename, seperator=', ')¶ Parse filename and return a dict representing its contents
-
pynag.Utils.importer.
parse_csv_string
(csv_string, seperator=', ')¶ Parse csv string and return a dict representing its contents