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

Closes #12068: Establish a direct relationship from jobs to objects (#12075)

* Reference database object by GFK when running scripts & reports via UI

* Reference database object by GFK when running scripts & reports via API

* Remove old enqueue_job() method

* Enable filtering jobs by object

* Introduce ObjectJobsView

* Add tabbed views for report & script jobs

* Add object_id to JobSerializer

* Move generic relation to JobsMixin

* Clean up old naming
This commit is contained in:
Jeremy Stretch
2023-03-28 15:47:09 -04:00
committed by GitHub
parent 15590f1f48
commit d2a694a878
33 changed files with 583 additions and 353 deletions

View File

@ -5,7 +5,6 @@ import traceback
import uuid
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
@ -13,7 +12,7 @@ from core.choices import JobStatusChoices
from core.models import Job
from extras.api.serializers import ScriptOutputSerializer
from extras.context_managers import change_logging
from extras.scripts import get_script
from extras.scripts import get_module_and_script
from extras.signals import clear_webhooks
from utilities.exceptions import AbortTransaction
from utilities.utils import NetBoxFakeRequest
@ -49,8 +48,8 @@ class Command(BaseCommand):
except AbortTransaction:
script.log_info("Database changes have been reverted automatically.")
clear_webhooks.send(request)
job_result.data = ScriptOutputSerializer(script).data
job_result.terminate()
job.data = ScriptOutputSerializer(script).data
job.terminate()
except Exception as e:
stacktrace = traceback.format_exc()
script.log_failure(
@ -59,10 +58,10 @@ class Command(BaseCommand):
script.log_info("Database changes have been reverted due to error.")
logger.error(f"Exception raised during script execution: {e}")
clear_webhooks.send(request)
job_result.data = ScriptOutputSerializer(script).data
job_result.terminate(status=JobStatusChoices.STATUS_ERRORED)
job.data = ScriptOutputSerializer(script).data
job.terminate(status=JobStatusChoices.STATUS_ERRORED)
logger.info(f"Script completed in {job_result.duration}")
logger.info(f"Script completed in {job.duration}")
# Params
script = options['script']
@ -73,7 +72,8 @@ class Command(BaseCommand):
except TypeError:
data = {}
module, name = script.split('.', 1)
module_name, script_name = script.split('.', 1)
module, script = get_module_and_script(module_name, script_name)
# Take user from command line if provided and exists, other
if options['user']:
@ -90,7 +90,7 @@ class Command(BaseCommand):
stdouthandler.setLevel(logging.DEBUG)
stdouthandler.setFormatter(formatter)
logger = logging.getLogger(f"netbox.scripts.{module}.{name}")
logger = logging.getLogger(f"netbox.scripts.{script.full_name}")
logger.addHandler(stdouthandler)
try:
@ -105,17 +105,14 @@ class Command(BaseCommand):
except KeyError:
raise CommandError(f"Invalid log level: {loglevel}")
# Get the script
script = get_script(module, name)()
# Parse the parameters
# Initialize the script form
script = script()
form = script.as_form(data, None)
script_content_type = ContentType.objects.get(app_label='extras', model='script')
# Create the job result
job_result = Job.objects.create(
name=script.full_name,
obj_type=script_content_type,
# Create the job
job = Job.objects.create(
instance=module,
name=script.name,
user=User.objects.filter(is_superuser=True).order_by('pk')[0],
job_id=uuid.uuid4()
)
@ -127,12 +124,12 @@ class Command(BaseCommand):
'FILES': {},
'user': user,
'path': '',
'id': job_result.job_id
'id': job.job_id
})
if form.is_valid():
job_result.status = JobStatusChoices.STATUS_RUNNING
job_result.save()
job.status = JobStatusChoices.STATUS_RUNNING
job.save()
logger.info(f"Running script (commit={commit})")
script.request = request
@ -146,5 +143,5 @@ class Command(BaseCommand):
for field, errors in form.errors.get_json_data().items():
for error in errors:
logger.error(f'\t{field}: {error.get("message")}')
job_result.status = JobStatusChoices.STATUS_ERRORED
job_result.save()
job.status = JobStatusChoices.STATUS_ERRORED
job.save()