Automatic code cleanups and import optimizations.

This commit is contained in:
Johannes Findeisen 2023-02-12 03:31:52 +01:00
commit b308068617
26 changed files with 6738 additions and 5928 deletions

View file

@ -15,7 +15,7 @@ class Configuration:
self.__configuration = configparser.ConfigParser()
self.__configuration_path = configuration_path
#print('[linspector] reading configuration file: ' + configuration_path +
# print('[linspector] reading configuration file: ' + configuration_path +
# '/linspector.conf')
if os.path.isfile(configuration_path + '/linspector.conf'):
try:
@ -35,7 +35,7 @@ class Configuration:
section_list = glob.glob(configuration_path + '/' + target_section + '/*.conf')
for section_file in section_list:
#print('reading section file: ' + section_file)
# print('reading section file: ' + section_file)
configuration = configparser.ConfigParser()
configuration.read(section_file, 'utf-8')
for source_section in configuration.sections():
@ -46,7 +46,7 @@ class Configuration:
configuration.get(source_section,
source_section_option))
#print('configuration dump: ' + self.dump_to_ini())
# print('configuration dump: ' + self.dump_to_ini())
def dump_to_ini(self):
dump = ''

View file

@ -7,9 +7,9 @@ import datetime
import importlib
import random
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.jobstores.memory import MemoryJobStore
from apscheduler.executors.pool import ThreadPoolExecutor, ProcessPoolExecutor
from apscheduler.jobstores.memory import MemoryJobStore
from apscheduler.schedulers.background import BackgroundScheduler
def job_function(log, monitor):

View file

@ -102,7 +102,7 @@ class Log:
self.set_level(logging.INFO)
elif log_level == "debug":
self.set_level(logging.DEBUG)
#elif configuration.get_option('linspector', 'log_level') != 'error' != 'warning' \
# elif configuration.get_option('linspector', 'log_level') != 'error' != 'warning' \
# != 'info' != 'debug':
# logger.warning('[linspector] log level: "' + log_level + '" not found!')

View file

@ -6,11 +6,8 @@ See LICENSE.txt (MIT license).
import configparser
import hashlib
import importlib
from datetime import datetime
from binascii import crc32
from linspector.core.task import Task, TaskExecutor
from datetime import datetime
class Monitor:
@ -33,7 +30,8 @@ class Monitor:
'identifier: ' + identifier + ' to: ' + str(self.__interval))
except Exception as err:
log.warning('no default_interval found in core configuration for identifier ' +
identifier + ', set to default interval 300 seconds. error: ' + str(err))
identifier + ', set to default interval 300 seconds. error: ' + str(
err))
# default interval is 300 seconds (5 minutes) if not set in the monitor
# configuration args or a default_interval in the core configuration.
self.__interval = 300
@ -48,10 +46,10 @@ class Monitor:
# if no service is set in the monitor configuration, the service is set to misc.dummy
# instead. just to make Linspector run but with no real result.
log.debug('no service set for identifier: ' + identifier + ' setting to '
'misc.dummy as '
'default to ensure '
'Linspector will run. '
'error: ' + str(err))
'misc.dummy as '
'default to ensure '
'Linspector will run. '
'error: ' + str(err))
self.__service = 'misc.dummy'
@ -83,7 +81,7 @@ class Monitor:
"""
self.status = "NONE"
self.last_execution = None
#self.monitor_information = MonitorInformation(self.monitor_id, self.hostgroup, self.host,
# self.monitor_information = MonitorInformation(self.monitor_id, self.hostgroup, self.host,
# self.service)
self.monitor_information = MonitorInformation(self.monitor_id, self.service)
@ -175,7 +173,7 @@ class Monitor:
def hex_string(self):
ret = hex(crc32(bytes(self.host + self.hostgroups + self.service, 'utf-8')))
#ret = self.__hex__()
# ret = self.__hex__()
if ret[0] == "-":
ret = ret[3:]
else:
@ -198,10 +196,10 @@ class Monitor:
if execution_successful:
if self.job_threshold > 0:
if "threshold_reset" in self.core and self.core["threshold_reset"]:
#logger.info("Job " + self.get_monitor_id() + ", Threshold Reset")
# logger.info("Job " + self.get_monitor_id() + ", Threshold Reset")
self.job_threshold = 0
else:
#logger.info("Job " + self.get_monitor_id() + ", Threshold Decrement")
# logger.info("Job " + self.get_monitor_id() + ", Threshold Decrement")
self.job_threshold -= 1
self.status = "OK"
@ -214,7 +212,7 @@ class Monitor:
self.job_threshold += 1
if self.job_threshold >= service_threshold:
#logger.info("Job " + self.get_monitor_id() + ", Threshold reached!")
# logger.info("Job " + self.get_monitor_id() + ", Threshold reached!")
self.status = "ERROR"
self.monitor_information.set_status(self.status)
@ -224,34 +222,34 @@ class Monitor:
self.__log.debug('executing task of type: ' + self.status)
# tasks can but should not be executed here. putting them in a queue is the better
# solution to execute them in a serial process.
#TaskExecutor.instance().schedule_task(monitor_information, task)
# TaskExecutor.instance().schedule_task(monitor_information, task)
def handle_call(self):
self.__log.info('handle call to monitor with identifier: ' + self.__identifier)
#logger.debug("handle call")
#logger.debug(self.service)
# logger.debug("handle call")
# logger.debug(self.service)
if self.enabled:
self.last_execution = None
try:
self.last_execution = MonitorExecution(self.get_host())
#self.__services[self.__service].execute(self.last_execution)
# self.__services[self.__service].execute(self.last_execution)
self.__services[self.__service].execute(**self.__args)
except Exception as err:
self.__log.error(err)
#self.last_execution.set_execution_end()
# self.last_execution.set_execution_end()
#self.handle_threshold(self.service.get_threshold(),
# self.handle_threshold(self.service.get_threshold(),
# self.last_execution.was_successful())
#log.info("Job " + self.get_monitor_id() +
# log.info("Job " + self.get_monitor_id() +
# ", Code: " + str(self.last_execution.get_error_code()) +
# ", Message: " + str(self.last_execution.get_message()))
#self.monitor_information.set_response_message(
# self.monitor_information.set_response_message(
# self.last_execution.get_response_message(self))
#self.handle_tasks(self.monitor_information)
# self.handle_tasks(self.monitor_information)
else:
self.__log.info('job ' + self.get_monitor_id() + ' disabled')
@ -308,8 +306,8 @@ class MonitorExecution:
class MonitorInformation:
def __init__(self, monitor_id, service):
self.monitor_id = monitor_id
#self.hostgroup = hostgroup
#self.host = host
# self.hostgroup = hostgroup
# self.host = host
self.service = service
self.response_massage = None

View file

@ -4,7 +4,8 @@ Copyright (c) 2022 Johannes Findeisen <you@hanez.org>. All Rights Reserved.
See LICENSE.txt (MIT license).
"""
#see http://stackoverflow.com/questions/42558/python-and-the-singleton-pattern
# see http://stackoverflow.com/questions/42558/python-and-the-singleton-pattern
class Singleton:

View file

@ -4,7 +4,7 @@ Copyright (c) 2022 Johannes Findeisen <you@hanez.org>. All Rights Reserved.
See LICENSE.txt (MIT license).
"""
from queue import Queue
from threading import Event, Thread
from threading import Thread
from linspector.core.singleton import Singleton
@ -47,7 +47,7 @@ class Task:
def get_arguments(self):
return self._args
#def set_member(self, member):
# def set_member(self, member):
# self.member = member
def needs_arguments(self):
@ -57,7 +57,7 @@ class Task:
try:
self.execute(job)
except Exception as e:
#logger.debug("Task execute failed!!!")
# logger.debug("Task execute failed!!!")
raise e
@ -85,7 +85,7 @@ class TaskExecutor:
msg, task = self.queue.get()
if task:
self.__log.debug('starting task execution...')
#task.execute(msg)
# task.execute(msg)
self.queue.task_done()
except Exception as err:

View file

@ -3,7 +3,6 @@ This file is part of Linspector (https://linspector.org/)
Copyright (c) 2022 Johannes Findeisen <you@hanez.org>. All Rights Reserved.
See LICENSE.txt (MIT license).
"""
import gammu
from linspector.core.notification import Notification

View file

@ -3,7 +3,6 @@ This file is part of Linspector (https://linspector.org/)
Copyright (c) 2022 Johannes Findeisen <you@hanez.org>. All Rights Reserved.
See LICENSE.txt (MIT license).
"""
import xmpp
from linspector.core.notification import Notification

26
linspector/plugins/api.py Normal file
View file

@ -0,0 +1,26 @@
"""
This file is part of Linspector (https://linspector.org/)
Copyright (c) 2023 Johannes Findeisen <you@hanez.org>. All Rights Reserved.
See LICENSE.txt (MIT license).
"""
# TODO: Make this a backend API using the modern FastAPI framework as a replacement for the
# traditional RPC plugin. Maybe it makes sense to maintain the RPC plugin too for simple usage by
# the Lish but I believe it makes sense to only create one backend for all clients.
from linspector.core.plugin import Plugin
def create(configuration, environment, linspector, log):
return APIPlugin(configuration, environment, linspector, log)
# TODO: check for all required configuration options and set defaults if needed.
class APIPlugin(Plugin):
def __init__(self, configuration, environment, linspector, log):
super().__init__(configuration, environment, linspector, log)
self.__configuration = configuration
self.__environment = environment
self.__linspector = linspector
self.__log = log
def run(self):
return

View file

@ -1,8 +0,0 @@
"""
This file is part of Linspector (https://linspector.org/)
Copyright (c) 2023 Johannes Findeisen <you@hanez.org>. All Rights Reserved.
See LICENSE.txt (MIT license).
"""
# TODO: Make this a backend API using the modern FastAPI framework as a replacement for the
# traditional RPC plugin. Maybe it makes sense to maintain the RPC plugin too for simple usage by
# the Lish but I believe it makes sense to only create one backend for all clients.

View file

@ -3,9 +3,10 @@ This file is part of Linspector (https://linspector.org/)
Copyright (c) 2022 Johannes Findeisen <you@hanez.org>. All Rights Reserved.
See LICENSE.txt (MIT license).
"""
import cherrypy
import json
import cherrypy
from linspector.core.plugin import Plugin
@ -29,22 +30,22 @@ class HTTPServerPlugin(Plugin):
@cherrypy.expose
def configuration(self):
return '<!DOCTYPE html><html><head><title>[monipy-' + \
self.__environment.get_env_var("__version__") + '@' + \
self.__environment.get_env_var("_hostname") + '] configuration</title><meta ' + \
'http-equiv="refresh" content="60"></head><body><pre ' + \
'style="border:2px solid black;background:#1d2021;color:#f0751a;">' + \
json.dumps(vars(self.__configuration), sort_keys=True, indent=4) + \
'</pre></body></html>'
self.__environment.get_env_var("__version__") + '@' + \
self.__environment.get_env_var("_hostname") + '] configuration</title><meta ' + \
'http-equiv="refresh" content="60"></head><body><pre ' + \
'style="border:2px solid black;background:#1d2021;color:#f0751a;">' + \
json.dumps(vars(self.__configuration), sort_keys=True, indent=4) + \
'</pre></body></html>'
@cherrypy.expose
def environment(self):
return '<!DOCTYPE html><html><head><title>[monipy-' + \
self.__environment.get_env_var("__version__") + '@' + \
self.__environment.get_env_var("_hostname") + '] environment</title><meta ' + \
'http-equiv="refresh" content="60"></head><body><pre ' + \
'style="border:2px solid black;background:#1d2021;color:#f0751a;">' + \
json.dumps(vars(self.__environment), sort_keys=True, indent=4) + \
'</pre></body></html>'
self.__environment.get_env_var("__version__") + '@' + \
self.__environment.get_env_var("_hostname") + '] environment</title><meta ' + \
'http-equiv="refresh" content="60"></head><body><pre ' + \
'style="border:2px solid black;background:#1d2021;color:#f0751a;">' + \
json.dumps(vars(self.__environment), sort_keys=True, indent=4) + \
'</pre></body></html>'
@cherrypy.expose
def playground(self):
@ -73,11 +74,11 @@ class HTTPServerPlugin(Plugin):
# 'tools.staticdir.dir': './public'
}
}
#cherrypy.config.update({
# cherrypy.config.update({
# 'global': {
# 'engine.autoreload.on': False
# }
#})
# })
cherrypy.config.update({
'global': {
'server.socket_host': self.__configuration.get_httpserver_host(),
@ -87,4 +88,4 @@ class HTTPServerPlugin(Plugin):
})
cherrypy.tree.mount(root=None, config=conf)
cherrypy.quickstart(self, '/', conf)
#cherrypy.server.bus.exit(self)
# cherrypy.server.bus.exit(self)

View file

@ -19,5 +19,5 @@ class DummyService(Service):
def execute(self, **kwargs):
self.__log.debug('DummyService object ' + str(self) + ' using kwargs: ' + str(kwargs))
#log('debug', 'dummy object @' + str(self) + str(self.__kwargs['foo']))
# log('debug', 'dummy object @' + str(self) + str(self.__kwargs['foo']))
return

View file

@ -3,7 +3,6 @@ This file is part of Linspector (https://linspector.org/)
Copyright (c) 2022 Johannes Findeisen <you@hanez.org>. All Rights Reserved.
See LICENSE.txt (MIT license).
"""
from fritzconnection.lib.fritzstatus import FritzStatus
from linspector.core.service import Service

View file

@ -3,7 +3,6 @@ This file is part of Linspector (https://linspector.org/)
Copyright (c) 2022 Johannes Findeisen <you@hanez.org>. All Rights Reserved.
See LICENSE.txt (MIT license).
"""
from fritzconnection.lib.fritzstatus import FritzStatus
from linspector.core.service import Service

View file

@ -4,9 +4,10 @@ Copyright (c) 2022 Johannes Findeisen <you@hanez.org>. All Rights Reserved.
See LICENSE.txt (MIT license).
"""
import calendar
import requests
import time
import requests
from linspector.core.service import Service

View file

@ -4,9 +4,10 @@ Copyright (c) 2022 Johannes Findeisen <you@hanez.org>. All Rights Reserved.
See LICENSE.txt (MIT license).
"""
import os
import paramiko
import pprint
import paramiko
from linspector.core.service import Service
@ -31,9 +32,8 @@ class SSHService(Service):
client.connect('hanez.org', username='hanez')
#self.command.call() ist dann das:
# self.command.call() ist dann das:
stdin, stdout, stderr = client.exec_command('ls')
for line in stdout:
print('... ' + line.strip('\n'))
client.close()

View file

@ -3,7 +3,6 @@ This file is part of Linspector (https://linspector.org/)
Copyright (c) 2022 Johannes Findeisen <you@hanez.org>. All Rights Reserved.
See LICENSE.txt (MIT license).
"""
from pysnmp.entity.rfc3413.oneliner import cmdgen
from linspector.core.service import Service