1
0
mirror of https://github.com/netbox-community/netbox.git synced 2024-05-10 07:54:54 +00:00

250 lines
7.5 KiB
Python
Raw Normal View History

2017-09-21 16:32:05 -04:00
import importlib
import inspect
2020-03-04 14:22:30 -05:00
import logging
2017-09-21 16:32:05 -04:00
import pkgutil
2018-11-02 15:20:08 -04:00
from collections import OrderedDict
2017-09-19 17:47:42 -04:00
from django.conf import settings
from django.db.models import Q
2017-09-19 17:47:42 -04:00
from django.utils import timezone
from django_rq import job
2017-09-19 17:47:42 -04:00
2020-07-06 01:58:28 -04:00
from .choices import JobResultStatusChoices, LogLevelChoices
from .models import JobResult
2017-09-21 16:32:05 -04:00
2020-07-03 11:55:04 -04:00
logger = logging.getLogger(__name__)
2017-09-21 16:32:05 -04:00
def is_report(obj):
"""
Returns True if the given object is a Report.
"""
return obj in Report.__subclasses__()
2017-09-21 16:32:05 -04:00
2017-09-25 17:27:58 -04:00
def get_report(module_name, report_name):
"""
Return a specific report from within a module.
"""
file_path = '{}/{}.py'.format(settings.REPORTS_ROOT, module_name)
spec = importlib.util.spec_from_file_location(module_name, file_path)
module = importlib.util.module_from_spec(spec)
try:
spec.loader.exec_module(module)
except FileNotFoundError:
return None
2017-09-26 16:36:43 -04:00
report = getattr(module, report_name, None)
if report is None:
return None
2017-09-26 16:36:43 -04:00
return report()
2017-09-25 17:27:58 -04:00
2017-09-21 16:32:05 -04:00
def get_reports():
"""
Compile a list of all reports available across all modules in the reports path. Returns a list of tuples:
[
(module_name, (report, report, report, ...)),
(module_name, (report, report, report, ...)),
2017-09-26 16:36:43 -04:00
...
]
2017-09-21 16:32:05 -04:00
"""
module_list = []
# Iterate through all modules within the reports path. These are the user-created files in which reports are
2017-09-26 16:36:43 -04:00
# defined.
for importer, module_name, _ in pkgutil.iter_modules([settings.REPORTS_ROOT]):
module = importer.find_module(module_name).load_module(module_name)
2017-09-26 16:36:43 -04:00
report_list = [cls() for _, cls in inspect.getmembers(module, is_report)]
2017-09-21 16:32:05 -04:00
module_list.append((module_name, report_list))
return module_list
2017-09-19 17:47:42 -04:00
@job('default')
def run_report(job_result, *args, **kwargs):
"""
Helper function to call the run method on a report. This is needed to get around the inability to pickle an instance
method for queueing into the background processor.
"""
module_name, report_name = job_result.name.split('.', 1)
report = get_report(module_name, report_name)
2020-07-03 11:55:04 -04:00
try:
report.run(job_result)
2020-07-06 01:58:28 -04:00
except Exception as e:
print(e)
2020-07-03 11:55:04 -04:00
job_result.set_status(JobResultStatusChoices.STATUS_ERRORED)
logging.error(f"Error during execution of report {job_result.name}")
# Delete any previous terminal state results
JobResult.objects.filter(
obj_type=job_result.obj_type,
2020-06-30 09:29:50 -04:00
name=job_result.name,
2020-07-03 11:55:04 -04:00
status__in=JobResultStatusChoices.TERMINAL_STATE_CHOICES
).exclude(
pk=job_result.pk
).delete()
2017-09-19 17:47:42 -04:00
class Report(object):
"""
NetBox users can extend this object to write custom reports to be used for validating data within NetBox. Each
report must have one or more test methods named `test_*`.
The `_results` attribute of a completed report will take the following form:
2017-09-19 17:47:42 -04:00
{
'test_bar': {
'failures': 42,
'log': [
(<datetime>, <level>, <object>, <message>),
...
]
},
'test_foo': {
'failures': 0,
'log': [
(<datetime>, <level>, <object>, <message>),
...
]
}
}
"""
2017-09-21 16:32:05 -04:00
description = None
2017-09-19 17:47:42 -04:00
def __init__(self):
self._results = OrderedDict()
2017-09-21 13:49:04 -04:00
self.active_test = None
self.failed = False
self.logger = logging.getLogger(f"netbox.reports.{self.full_name}")
2020-03-04 14:22:30 -05:00
2017-09-19 17:47:42 -04:00
# Compile test methods and initialize results skeleton
test_methods = []
for method in dir(self):
if method.startswith('test_') and callable(getattr(self, method)):
test_methods.append(method)
self._results[method] = OrderedDict([
2017-09-19 17:47:42 -04:00
('success', 0),
('info', 0),
('warning', 0),
2017-09-28 13:35:18 -04:00
('failure', 0),
2017-09-19 17:47:42 -04:00
('log', []),
])
if not test_methods:
raise Exception("A report must contain at least one test method.")
self.test_methods = test_methods
2017-09-26 16:36:43 -04:00
@property
def module(self):
return self.__module__
2017-09-26 16:36:43 -04:00
@property
def class_name(self):
2017-09-26 16:36:43 -04:00
return self.__class__.__name__
@property
def name(self):
"""
Override this attribute to set a custom display name.
"""
return self.class_name
2017-09-26 16:36:43 -04:00
@property
def full_name(self):
return f'{self.module}.{self.class_name}'
2017-09-26 16:36:43 -04:00
2020-07-06 01:58:28 -04:00
def _log(self, obj, message, level=LogLevelChoices.LOG_DEFAULT):
2017-09-19 17:47:42 -04:00
"""
Log a message from a test method. Do not call this method directly; use one of the log_* wrappers below.
"""
2020-07-06 01:58:28 -04:00
if level not in LogLevelChoices.as_dict():
2017-09-19 17:47:42 -04:00
raise Exception("Unknown logging level: {}".format(level))
2017-09-28 13:36:50 -04:00
self._results[self.active_test]['log'].append((
2017-09-28 13:35:18 -04:00
timezone.now().isoformat(),
2020-07-06 01:58:28 -04:00
level,
2017-09-28 13:35:18 -04:00
str(obj) if obj else None,
obj.get_absolute_url() if getattr(obj, 'get_absolute_url', None) else None,
message,
2017-09-28 13:36:50 -04:00
))
2017-09-28 13:35:18 -04:00
def log(self, message):
"""
Log a message which is not associated with a particular object.
"""
2020-07-06 01:58:28 -04:00
self._log(None, message, level=LogLevelChoices.LOG_DEFAULT)
2020-03-04 14:22:30 -05:00
self.logger.info(message)
2017-09-19 17:47:42 -04:00
def log_success(self, obj, message=None):
"""
Record a successful test against an object. Logging a message is optional.
"""
if message:
2020-07-06 01:58:28 -04:00
self._log(obj, message, level=LogLevelChoices.LOG_SUCCESS)
self._results[self.active_test]['success'] += 1
2020-03-04 14:22:30 -05:00
self.logger.info(f"Success | {obj}: {message}")
2017-09-19 17:47:42 -04:00
def log_info(self, obj, message):
"""
Log an informational message.
"""
2020-07-06 01:58:28 -04:00
self._log(obj, message, level=LogLevelChoices.LOG_INFO)
self._results[self.active_test]['info'] += 1
2020-03-04 14:22:30 -05:00
self.logger.info(f"Info | {obj}: {message}")
2017-09-19 17:47:42 -04:00
def log_warning(self, obj, message):
"""
Log a warning.
"""
2020-07-06 01:58:28 -04:00
self._log(obj, message, level=LogLevelChoices.LOG_WARNING)
self._results[self.active_test]['warning'] += 1
2020-03-04 14:22:30 -05:00
self.logger.info(f"Warning | {obj}: {message}")
2017-09-19 17:47:42 -04:00
def log_failure(self, obj, message):
"""
Log a failure. Calling this method will automatically mark the report as failed.
"""
2020-07-06 01:58:28 -04:00
self._log(obj, message, level=LogLevelChoices.LOG_FAILURE)
2017-09-28 13:35:18 -04:00
self._results[self.active_test]['failure'] += 1
2020-03-04 14:22:30 -05:00
self.logger.info(f"Failure | {obj}: {message}")
2017-09-19 17:47:42 -04:00
self.failed = True
def run(self, job_result):
2017-09-19 17:47:42 -04:00
"""
Run the report and save its results. Each test method will be executed in order.
2017-09-19 17:47:42 -04:00
"""
2020-03-04 14:22:30 -05:00
self.logger.info(f"Running report")
job_result.status = JobResultStatusChoices.STATUS_RUNNING
job_result.save()
2020-03-04 14:22:30 -05:00
2017-09-19 17:47:42 -04:00
for method_name in self.test_methods:
self.active_test = method_name
test_method = getattr(self, method_name)
test_method()
2017-09-21 13:49:04 -04:00
2020-03-04 14:22:30 -05:00
if self.failed:
self.logger.warning("Report failed")
job_result.status = JobResultStatusChoices.STATUS_FAILED
2020-03-04 14:22:30 -05:00
else:
self.logger.info("Report completed successfully")
job_result.status = JobResultStatusChoices.STATUS_COMPLETED
job_result.data = self._results
job_result.completed = timezone.now()
job_result.save()
2020-03-04 14:22:30 -05:00
# Perform any post-run tasks
self.post_run()
def post_run(self):
"""
Extend this method to include any tasks which should execute after the report has been run.
"""
pass