command_watcher

Module to watch the execution of shell scripts. Both streams (stdout and stderr) are captured.

watch = Watch()
watch.log.critical(msg)
watch.log.error(msg)
watch.log.warning(msg)
watch.log.info(msg)
watch.log.debug(msg)
watch.run(['rsync', '-av', '/home', '/backup'])
class jflib.command_watcher.BaseChannel[source]

Base class for all reporters

abstract report(status=0, service_name='command_watcher', **data)[source]
class jflib.command_watcher.BaseClass[source]
class jflib.command_watcher.BeepChannel[source]

Send beep sounds.

beep(frequency=4186.01, length=50)[source]

Generate a beep sound using the “beep” command.

  • A success tone: frequency=4186.01, length=40

  • A failure tone: frequency=65.4064, length=100

Parameters
  • frequency (float) – Frequency in Hz.

  • length (float) – Length in milliseconds.

report(message)[source]

Send a beep sounds.

Parameters

message (Message) – A message object. The only attribute that takes an effect is the status attribute (0-3).

exception jflib.command_watcher.CommandWatcherError(msg, **data)[source]

Exception raised by this module.

class jflib.command_watcher.EmailChannel(smtp_server, smtp_login, smtp_password, to_addr, from_addr='', to_addr_critical='')[source]

Send reports by e-mail.

report(message)[source]

Send an e-mail message.

Parameters

message (Message) – A message object.

class jflib.command_watcher.LoggingHandler(master_logger=None)[source]

Store of all logging records in the memory. Print all records on emit.

property all_records

All log messages joined by line breaks.

emit(record)[source]
Parameters

record (LogRecord) – A record object.

property stderr
property stdout
class jflib.command_watcher.Message(**data)[source]

This message class bundles all available message data into an object. The different reporters can choose which data they use.

Parameters
  • status (int) – 0 (OK), 1 (WARNING), 2 (CRITICAL), 3 (UNKOWN): see Nagios / Icinga monitoring status / state.

  • service_name (str) – The name of the service.

  • custom_message (str) – Custom message

  • prefix (str) – Prefix of the report message.

  • body (str) – A longer report text.

  • performance_data (dict) – A dictionary like {‘perf_1’: 1, ‘perf_2’: ‘test’}.

  • log_records (str) – Log records separated by new lines

property body

Text body for the e-mail message.

Return type

str

property custom_message
Return type

str

property message
Return type

str

property message_monitoring

message + performance_data

Return type

str

property performance_data
Returns

A concatenated string

Return type

str

property prefix
Return type

str

property processes
Return type

str

property service_name
Return type

str

property status

0 (OK), 1 (WARNING), 2 (CRITICAL), 3 (UNKOWN): see Nagios / Icinga monitoring status / state.

Return type

int

property status_text

The status as a text word like OK.

Return type

str

property user
Return type

str

class jflib.command_watcher.NscaChannel(remote_host, password, encryption_method, port, service_name)[source]

Wrapper around send_nsca to send NSCA messages. Set up the NSCA client.

report(message)[source]

Send a NSCA message to a remote NSCA server.

Parameters

message (Message) – A message object.

class jflib.command_watcher.Process(args, master_logger=None, **kwargs)[source]

Run a process.

You can use all keyword arguments from subprocess.Popen except bufsize, stderr, stdout.

Parameters
  • args (Union[str, list, tuple]) – List, tuple or string. A sequence of process arguments, like subprocess.Popen(args).

  • master_logger (Optional[Logger]) –

  • shell (bool) – If true, the command will be executed through the shell.

  • cwd (str) – Sets the current directory before the child is executed.

  • env (dict) – Defines the environment variables for the new process.

args

Process arguments in various types.

property args_normalized

Normalized args, always a list

Return type

list

property line_count_stderr

The count of lines of the current stderr.

Return type

int

property line_count_stdout

The count of lines of the current stderr.

Return type

int

log

A ready to go and configured logger. An instance of logging.Logger.

log_handler

An instance of LoggingHandler.

property stderr

Alias / shortcut for self.log_handler.stderr.

Return type

str

property stdout

Alias / shortcut for self.log_handler.stdout.

Return type

str

subprocess

subprocess

class jflib.command_watcher.Reporter[source]

Collect all channels.

add_channel(channel)[source]
report(**data)[source]
class jflib.command_watcher.Timer[source]

Measure the execution time of a command run.

interval

The time interval between start and stop.

result()[source]

Measure the time intervale

Returns

A formatted string displaying the result.

Return type

str

start

“The start time. (UNIX timestamp)

stop

“The time when the timer stops. (UNIX timestamp)

class jflib.command_watcher.Watch(config_file=None, service_name='command_watcher', raise_exceptions=True, config_reader=None, report_channels=None)[source]

Watch the execution of a command. Capture all output of a command. provide and setup a logging facility.

Parameters
  • config_file (Optional[str]) – The file path of the configuration file in the INI format.

  • service_name (str) – A name of the watched service.

  • raise_exceptions (bool) – Raise exceptions if watch.run() exists with a non-zero exit code.

  • config_reader (Optional[ConfigReader]) – A custom configuration reader. Specify this parameter to not use the build in configuration reader.

final_report(**data)[source]

The same as the report method. Adds execution_time to the performance_data.

Parameters
  • status (int) – 0 (OK), 1 (WARNING), 2 (CRITICAL), 3 (UNKOWN): see Nagios / Icinga monitoring status / state.

  • custom_message (str) – Custom message

  • prefix (str) – Prefix of the report message.

  • body (str) – A longer report text.

  • performance_data (dict) – A dictionary like {‘perf_1’: 1, ‘perf_2’: ‘test’}.

Return type

Message

log

A ready to go and configured logger. An instance of logging.Logger.

processes

A list of completed processes Process. Everytime you use the method run() the process object is appened in the list.

report(status, **data)[source]

Report a message using the preconfigured channels.

Parameters
  • status (int) – 0 (OK), 1 (WARNING), 2 (CRITICAL), 3 (UNKOWN): see Nagios / Icinga monitoring status / state.

  • custom_message (str) – Custom message

  • prefix (str) – Prefix of the report message.

  • body (str) – A longer report text.

  • performance_data (dict) – A dictionary like {‘perf_1’: 1, ‘perf_2’: ‘test’}.

Return type

Message

run(args, log=True, ignore_exceptions=[], **kwargs)[source]

Run a process.

Parameters
  • args (Union[str, list, tuple]) – List, tuple or string. A sequence of process arguments, like subprocess.Popen(args).

  • log (bool) – Log the stderr and the stdout of the process. If false the stdout and the stderr are logged only to the local process logger, not to get global master logger.

  • ignore_exceptions (List[int]) – A list of none-zero exit codes, which is ignored by this method.

Return type

Process

property stderr

Alias / shortcut for self._log_handler.stderr.

property stdout

Alias / shortcut for self._log_handler.stdout.

jflib.command_watcher.setup_logging(master_logger=None)[source]

Setup a fresh logger for each watch action.

Parameters

master_logger (Optional[Logger]) – Forward all log messages to a master logger.

Return type

Tuple[Logger, LoggingHandler]