Sfoglia il codice sorgente

Fixes #23844: Prevent recreation of jobs deleted while running (#23866)

Saving the outcome of a job whose record was deleted while it ran
inserted the record again. The terminal save and the rescheduling error
now only update an existing record, and a deleted job is skipped without
a notification. A failed background API request is saved on termination.
Martin Hauser 2 giorni fa
parent
commit
c0df170925

+ 3 - 2
netbox/core/models/jobs.py

@@ -254,7 +254,8 @@ class Job(models.Model):
     def terminate(self, status=JobStatusChoices.STATUS_COMPLETED, error=None, *, dispatch=True):
     def terminate(self, status=JobStatusChoices.STATUS_COMPLETED, error=None, *, dispatch=True):
         """
         """
         Mark the job as completed, optionally specifying a particular termination status. With dispatch=False, the
         Mark the job as completed, optionally specifying a particular termination status. With dispatch=False, the
-        owner's notification and job_end are left to a later _dispatch_termination() call.
+        owner's notification and job_end are left to a later _dispatch_termination() call. A deleted job raises
+        NotUpdated rather than being re-created.
         """
         """
         if status not in JobStatusChoices.TERMINAL_STATE_CHOICES:
         if status not in JobStatusChoices.TERMINAL_STATE_CHOICES:
             raise ValueError(
             raise ValueError(
@@ -270,7 +271,7 @@ class Job(models.Model):
         self.completed = timezone.now()
         self.completed = timezone.now()
         if self.started:
         if self.started:
             self.execution_time = self.completed - self.started
             self.execution_time = self.completed - self.started
-        self.save()
+        self.save(force_update=True)
 
 
         if dispatch:
         if dispatch:
             self._dispatch_termination()
             self._dispatch_termination()

+ 13 - 1
netbox/core/tests/test_models.py

@@ -9,7 +9,7 @@ from unittest.mock import MagicMock, patch
 from django.contrib.contenttypes.models import ContentType
 from django.contrib.contenttypes.models import ContentType
 from django.core.exceptions import ObjectDoesNotExist
 from django.core.exceptions import ObjectDoesNotExist
 from django.core.management import call_command
 from django.core.management import call_command
-from django.db import IntegrityError, connection
+from django.db import IntegrityError, connection, transaction
 from django.test import TestCase, override_settings, tag
 from django.test import TestCase, override_settings, tag
 from django.test.utils import CaptureQueriesContext
 from django.test.utils import CaptureQueriesContext
 from django.utils import timezone, translation
 from django.utils import timezone, translation
@@ -631,6 +631,18 @@ class JobTestCase(TestCase):
         self.assertEqual(notification.event_type, JOB_FAILED)
         self.assertEqual(notification.event_type, JOB_FAILED)
         mock_job_end.send.assert_called_once_with(job)
         mock_job_end.send.assert_called_once_with(job)
 
 
+    @patch('core.models.jobs.job_end')
+    def test_terminate_deleted_job(self, mock_job_end):
+        """A deleted Job is not re-created on termination."""
+        job = self._make_job(None, JobNotificationChoices.NOTIFICATION_NEVER)
+        Job.objects.filter(pk=job.pk).delete()
+
+        with self.assertRaises(Job.NotUpdated), transaction.atomic():
+            job.terminate()
+
+        self.assertFalse(Job.objects.filter(pk=job.pk).exists())
+        mock_job_end.send.assert_not_called()
+
     @patch('core.models.jobs.job_end')
     @patch('core.models.jobs.job_end')
     def test_execution_time_set_on_terminate(self, mock_job_end):
     def test_execution_time_set_on_terminate(self, mock_job_end):
         """
         """

+ 17 - 8
netbox/netbox/jobs.py

@@ -11,6 +11,7 @@ from pathlib import Path
 from django.contrib.auth import get_user_model
 from django.contrib.auth import get_user_model
 from django.core.exceptions import ImproperlyConfigured, PermissionDenied, ValidationError
 from django.core.exceptions import ImproperlyConfigured, PermissionDenied, ValidationError
 from django.core.handlers.wsgi import WSGIRequest
 from django.core.handlers.wsgi import WSGIRequest
+from django.db import router, transaction
 from django.db.models import ProtectedError, RestrictedError
 from django.db.models import ProtectedError, RestrictedError
 from django.http import Http404, QueryDict
 from django.http import Http404, QueryDict
 from django.utils import timezone
 from django.utils import timezone
@@ -169,8 +170,15 @@ class JobRunner(ABC):
                             cls._reschedule(job, **kwargs)
                             cls._reschedule(job, **kwargs)
                     finally:
                     finally:
                         if status is not None:
                         if status is not None:
-                            job.terminate(status=status, error=error, dispatch=False)
-                            terminated = True
+                            # Prevent recreation of a job deleted while running without aborting an outer transaction
+                            using = router.db_for_write(job.__class__, instance=job)
+                            try:
+                                with transaction.atomic(using=using):
+                                    job.terminate(status=status, error=error, dispatch=False)
+                            except Job.NotUpdated:
+                                logger.warning(f"Not saving job {job} (PK: {job.pk}): it was deleted while running")
+                            else:
+                                terminated = True
             finally:
             finally:
                 # Outside the schedule lock, so slow job_end receivers cannot delay enqueue_once() callers
                 # Outside the schedule lock, so slow job_end receivers cannot delay enqueue_once() callers
                 if terminated:
                 if terminated:
@@ -222,7 +230,13 @@ class JobRunner(ABC):
                 'levelname': 'ERROR',
                 'levelname': 'ERROR',
                 'msg': message,
                 'msg': message,
             }))
             }))
-            job.save()
+            # An interruption can skip termination, so save the error now without re-creating a deleted job
+            using = router.db_for_write(job.__class__, instance=job)
+            try:
+                with transaction.atomic(using=using):
+                    job.save(using=using, force_update=True)
+            except Job.NotUpdated:
+                pass
 
 
     @classmethod
     @classmethod
     def get_jobs(cls, instance=None):
     def get_jobs(cls, instance=None):
@@ -386,11 +400,9 @@ class AsyncAPIJob(JobRunner):
             user = User.objects.get(pk=user_pk)
             user = User.objects.get(pk=user_pk)
         except User.DoesNotExist:
         except User.DoesNotExist:
             self.job.error = "The requesting user no longer exists."
             self.job.error = "The requesting user no longer exists."
-            self.job.save()
             raise JobFailed()
             raise JobFailed()
         if not user.is_active:
         if not user.is_active:
             self.job.error = "The requesting user is no longer active."
             self.job.error = "The requesting user is no longer active."
-            self.job.save()
             raise JobFailed()
             raise JobFailed()
 
 
         django_request = self._build_request(request, payload, scheme)
         django_request = self._build_request(request, payload, scheme)
@@ -453,7 +465,4 @@ class AsyncAPIJob(JobRunner):
             # mark the job failed (JobRunner.handle reserves "errored" for unhandled crashes).
             # mark the job failed (JobRunner.handle reserves "errored" for unhandled crashes).
             detail = response.data.get('detail') if isinstance(response.data, dict) else None
             detail = response.data.get('detail') if isinstance(response.data, dict) else None
             self.job.error = str(detail) if detail else f"Request failed with status {response.status_code}."
             self.job.error = str(detail) if detail else f"Request failed with status {response.status_code}."
-            self.job.save()
             raise JobFailed()
             raise JobFailed()
-
-        # On success, job.data is persisted by JobRunner.handle() -> job.terminate().

+ 47 - 11
netbox/netbox/tests/test_api_background.py

@@ -13,12 +13,11 @@ from contextlib import contextmanager
 from unittest.mock import patch
 from unittest.mock import patch
 
 
 from django.contrib.contenttypes.models import ContentType
 from django.contrib.contenttypes.models import ContentType
-from django.test import RequestFactory
+from django.test import RequestFactory, tag
 from rest_framework import status
 from rest_framework import status
 from rest_framework.test import APIRequestFactory
 from rest_framework.test import APIRequestFactory
 
 
 from core.choices import JobStatusChoices
 from core.choices import JobStatusChoices
-from core.exceptions import JobFailed
 from core.models import Job, ObjectChange
 from core.models import Job, ObjectChange
 from dcim.api.views import RegionViewSet
 from dcim.api.views import RegionViewSet
 from dcim.models import DeviceType, Manufacturer, Region
 from dcim.models import DeviceType, Manufacturer, Region
@@ -420,20 +419,57 @@ class BackgroundBulkWriteTests(RQQueueTestMixin, APITestCase):
         request_copy = copy_safe_request(raw_request)
         request_copy = copy_safe_request(raw_request)
 
 
         job = Job.objects.create(name='Bulk update regions', user=self.user, job_id=uuid.uuid4())
         job = Job.objects.create(name='Bulk update regions', user=self.user, job_id=uuid.uuid4())
-        with self.assertRaises(JobFailed):
-            AsyncAPIJob(job).run(
+        AsyncAPIJob.handle(
+            job=job,
+            viewset_class='dcim.api.views.RegionViewSet',
+            action='bulk_update',
+            payload=[{'id': self.regions[0].pk, 'description': 'x'}],
+            user_pk=self.user.pk,
+            request=request_copy,
+            scheme='http',
+            action_kwargs={'partial': True},
+        )
+        job.refresh_from_db()
+        self.assertEqual(job.status, JobStatusChoices.STATUS_FAILED)
+        self.assertIn('active', job.error.lower())
+        self.regions[0].refresh_from_db()
+        self.assertNotEqual(self.regions[0].description, 'x')
+
+    @tag('regression')  # Ref: #23844
+    def test_rejected_request_does_not_recreate_deleted_job(self):
+        self.grant('add', 'view')
+
+        factory = RequestFactory()
+        raw_request = factory.post('/api/dcim/regions/', data=[], content_type='application/json')
+        raw_request.user = self.user
+        request_copy = copy_safe_request(raw_request)
+        job = Job.objects.create(name='Bulk create regions', user=self.user, job_id=uuid.uuid4())
+
+        # Simulate a concurrent deletion after the request is rejected
+        @contextmanager
+        def deleting_processor(request):
+            yield
+            Job.objects.get(pk=job.pk).delete()
+
+        with (
+            patch.dict(registry, {'request_processors': [deleting_processor]}),
+            patch.object(RegionViewSet, 'background_enabled', False),
+            patch.object(job, '_dispatch_termination') as dispatch,
+        ):
+            AsyncAPIJob.handle(
+                job=job,
                 viewset_class='dcim.api.views.RegionViewSet',
                 viewset_class='dcim.api.views.RegionViewSet',
-                action='bulk_update',
-                payload=[{'id': self.regions[0].pk, 'description': 'x'}],
+                action='bulk_create',
+                payload=[{'name': 'Region A', 'slug': 'region-a'}],
                 user_pk=self.user.pk,
                 user_pk=self.user.pk,
                 request=request_copy,
                 request=request_copy,
                 scheme='http',
                 scheme='http',
-                action_kwargs={'partial': True},
             )
             )
-        job.refresh_from_db()
-        self.assertIn('active', job.error.lower())
-        self.regions[0].refresh_from_db()
-        self.assertNotEqual(self.regions[0].description, 'x')
+
+        self.assertEqual(job.status, JobStatusChoices.STATUS_FAILED)
+        self.assertFalse(Job.objects.filter(pk=job.pk).exists())
+        self.assertFalse(Region.objects.filter(slug='region-a').exists())
+        dispatch.assert_not_called()
 
 
     # ------------------------------------------------------------------ host parsing
     # ------------------------------------------------------------------ host parsing
 
 

+ 96 - 0
netbox/netbox/tests/test_jobs.py

@@ -172,6 +172,28 @@ class JobRunnerTestCase(BaseJobRunnerTestCase):
         job_end.send.assert_not_called()
         job_end.send.assert_not_called()
         self.assertFalse(Job.objects.filter(pk=stale_job.pk).exists())
         self.assertFalse(Job.objects.filter(pk=stale_job.pk).exists())
 
 
+    @tag('regression')  # Ref: #23844
+    def test_handle_job_deleted_during_run(self):
+        """A Job deleted while running is not re-created and keeps its schedule."""
+        for interval in (None, 60):
+            with self.subTest(interval=interval):
+                job = Job.objects.create(name=f'Deleted job {interval}', job_id=uuid.uuid4(), interval=interval)
+
+                def delete_job():
+                    Job.objects.get(pk=job.pk).delete()
+
+                with (
+                    patch.object(TestJobRunner, 'run', side_effect=delete_job),
+                    patch.object(job, '_dispatch_termination') as dispatch,
+                    self.assertLogs('netbox.jobs', 'WARNING'),
+                ):
+                    TestJobRunner.handle(job)
+
+                self.assertFalse(Job.objects.filter(pk=job.pk).exists())
+                dispatch.assert_not_called()
+                successors = Job.objects.filter(name=job.name).values_list('status', 'interval')
+                self.assertEqual(list(successors), [(JobStatusChoices.STATUS_SCHEDULED, 60)] if interval else [])
+
     def test_handle_non_waiting_job(self):
     def test_handle_non_waiting_job(self):
         """A running or terminated Job neither runs nor reschedules and keeps its row."""
         """A running or terminated Job neither runs nor reschedules and keeps its row."""
         for status in (JobStatusChoices.STATUS_RUNNING, *JobStatusChoices.TERMINAL_STATE_CHOICES):
         for status in (JobStatusChoices.STATUS_RUNNING, *JobStatusChoices.TERMINAL_STATE_CHOICES):
@@ -331,6 +353,26 @@ class JobRunnerTestCase(BaseJobRunnerTestCase):
                 send_end.assert_called_once_with(job)
                 send_end.assert_called_once_with(job)
                 self.assertEqual(Notification.objects.filter(user=user, object_id=job.pk).count(), 1)
                 self.assertEqual(Notification.objects.filter(user=user, object_id=job.pk).count(), 1)
 
 
+    @tag('regression')  # Ref: #23844
+    def test_handle_deleted_job_with_invalid_reschedule(self):
+        """A reschedule rejected as invalid does not re-create a Job deleted while running."""
+        job = Job.objects.create(name=TestJobRunner.name, job_id=uuid.uuid4(), interval=60)
+
+        def delete_job():
+            Job.objects.get(pk=job.pk).delete()
+
+        with (
+            patch.object(TestJobRunner, 'run', side_effect=delete_job),
+            patch.object(TestJobRunner, 'enqueue', side_effect=ValidationError('Simulated validation error')),
+            patch.object(job, '_dispatch_termination') as dispatch,
+            disable_logging(),
+        ):
+            TestJobRunner.handle(job)
+
+        self.assertIn('Simulated validation error', job.log_entries[-1]['message'])
+        self.assertFalse(Job.objects.filter(pk=job.pk).exists())
+        dispatch.assert_not_called()
+
     def test_handle_terminates_job_when_reschedule_fails(self):
     def test_handle_terminates_job_when_reschedule_fails(self):
         """An unexpected reschedule failure still ends the job once, then propagates."""
         """An unexpected reschedule failure still ends the job once, then propagates."""
         user = User.objects.create_user(username='job-owner')
         user = User.objects.create_user(username='job-owner')
@@ -350,6 +392,25 @@ class JobRunnerTestCase(BaseJobRunnerTestCase):
         send_end.assert_called_once_with(job)
         send_end.assert_called_once_with(job)
         self.assertEqual(Notification.objects.filter(user=user, object_id=job.pk).count(), 1)
         self.assertEqual(Notification.objects.filter(user=user, object_id=job.pk).count(), 1)
 
 
+    def test_handle_deleted_job_with_reschedule_error(self):
+        """An unexpected reschedule failure still propagates for a Job deleted while running."""
+        job = Job.objects.create(name=TestJobRunner.name, job_id=uuid.uuid4(), interval=60)
+
+        def delete_job():
+            Job.objects.get(pk=job.pk).delete()
+
+        with (
+            patch.object(TestJobRunner, 'run', side_effect=delete_job),
+            patch.object(TestJobRunner, 'enqueue', side_effect=RuntimeError('Simulated queue error')),
+            patch.object(job, '_dispatch_termination') as dispatch,
+            disable_warnings('netbox.jobs'),
+            self.assertRaisesMessage(RuntimeError, 'Simulated queue error'),
+        ):
+            TestJobRunner.handle(job)
+
+        self.assertFalse(Job.objects.filter(pk=job.pk).exists())
+        dispatch.assert_not_called()
+
     def test_handle_terminates_job_once_when_end_receiver_fails(self):
     def test_handle_terminates_job_once_when_end_receiver_fails(self):
         """A failing job_end receiver after a successful run leaves the job completed and propagates."""
         """A failing job_end receiver after a successful run leaves the job completed and propagates."""
         user = User.objects.create_user(username='job-owner')
         user = User.objects.create_user(username='job-owner')
@@ -381,6 +442,23 @@ class JobRunnerTestCase(BaseJobRunnerTestCase):
         successor = TestJobRunner.get_jobs(instance).exclude(pk=job.pk).get()
         successor = TestJobRunner.get_jobs(instance).exclude(pk=job.pk).get()
         self.assertEqual((successor.status, successor.interval), (JobStatusChoices.STATUS_SCHEDULED, 60))
         self.assertEqual((successor.status, successor.interval), (JobStatusChoices.STATUS_SCHEDULED, 60))
 
 
+    def test_handle_keeps_reschedule_error_after_interrupt(self):
+        """An interrupted Job keeps the error of a rejected reschedule without recording an outcome."""
+        job = Job.objects.create(name=TestJobRunner.name, job_id=uuid.uuid4(), interval=60)
+
+        with (
+            patch.object(TestJobRunner, 'run', side_effect=SystemExit),
+            patch.object(TestJobRunner, 'enqueue', side_effect=ValidationError('Simulated validation error')),
+            disable_logging(),
+            self.assertRaises(SystemExit),
+        ):
+            TestJobRunner.handle(job)
+
+        job.refresh_from_db()
+        self.assertEqual(job.status, JobStatusChoices.STATUS_RUNNING)
+        self.assertIsNone(job.completed)
+        self.assertIn('Simulated validation error', job.log_entries[-1]['message'])
+
     def test_handle_terminal_save_error(self):
     def test_handle_terminal_save_error(self):
         """A failed terminal save propagates and sends no notification or job_end."""
         """A failed terminal save propagates and sends no notification or job_end."""
         user = User.objects.create_user(username='job-owner')
         user = User.objects.create_user(username='job-owner')
@@ -811,6 +889,24 @@ class SystemJobTestCase(BaseJobRunnerTestCase):
         waiting = TestSystemJobRunner.get_jobs().filter(status__in=JobStatusChoices.ENQUEUED_STATE_CHOICES)
         waiting = TestSystemJobRunner.get_jobs().filter(status__in=JobStatusChoices.ENQUEUED_STATE_CHOICES)
         self.assertEqual(list(waiting.values_list('status', 'interval')), [(JobStatusChoices.STATUS_SCHEDULED, 60)])
         self.assertEqual(list(waiting.values_list('status', 'interval')), [(JobStatusChoices.STATUS_SCHEDULED, 60)])
 
 
+    def test_handle_keeps_schedule_of_deleted_system_job(self):
+        """A system job deleted while running is not re-created and leaves one successor."""
+        job = TestSystemJobRunner.enqueue(interval=60)
+
+        def delete_job():
+            Job.objects.get(pk=job.pk).delete()
+
+        with (
+            patch.object(TestSystemJobRunner, 'run', side_effect=delete_job),
+            patch.object(job, '_dispatch_termination') as dispatch,
+            self.assertLogs('netbox.jobs', 'WARNING'),
+        ):
+            TestSystemJobRunner.handle(job)
+
+        dispatch.assert_not_called()
+        jobs = TestSystemJobRunner.get_jobs().values_list('status', 'interval')
+        self.assertEqual(list(jobs), [(JobStatusChoices.STATUS_SCHEDULED, 60)])
+
     def test_handle_sends_job_end_outside_schedule_lock(self):
     def test_handle_sends_job_end_outside_schedule_lock(self):
         """A system job is saved as ended under the schedule lock, then notifies and sends job_end outside it."""
         """A system job is saved as ended under the schedule lock, then notifies and sends job_end outside it."""
         user = User.objects.create_user(username='job-owner')
         user = User.objects.create_user(username='job-owner')

+ 11 - 10
netbox/users/tests/test_api.py

@@ -3,7 +3,7 @@ import uuid
 from django.test import RequestFactory, override_settings
 from django.test import RequestFactory, override_settings
 from django.urls import reverse
 from django.urls import reverse
 
 
-from core.exceptions import JobFailed
+from core.choices import JobStatusChoices
 from core.models import Job, ObjectType
 from core.models import Job, ObjectType
 from netbox.jobs import AsyncAPIJob
 from netbox.jobs import AsyncAPIJob
 from users.constants import TOKEN_DEFAULT_LENGTH
 from users.constants import TOKEN_DEFAULT_LENGTH
@@ -595,17 +595,18 @@ class TokenTestCase(
                 job = Job.objects.create(
                 job = Job.objects.create(
                     name='Bulk create tokens', user=self.user, job_id=uuid.uuid4()
                     name='Bulk create tokens', user=self.user, job_id=uuid.uuid4()
                 )
                 )
-                with self.assertRaises(JobFailed):
-                    AsyncAPIJob(job).run(
-                        viewset_class='users.api.views.TokenViewSet',
-                        action=action,
-                        payload=[{'user': user.pk}],
-                        user_pk=self.user.pk,
-                        request=request_copy,
-                        scheme='http',
-                    )
+                AsyncAPIJob.handle(
+                    job=job,
+                    viewset_class='users.api.views.TokenViewSet',
+                    action=action,
+                    payload=[{'user': user.pk}],
+                    user_pk=self.user.pk,
+                    request=request_copy,
+                    scheme='http',
+                )
 
 
                 job.refresh_from_db()
                 job.refresh_from_db()
+                self.assertEqual(job.status, JobStatusChoices.STATUS_FAILED)
                 self.assertEqual(job.data['status_code'], 400)
                 self.assertEqual(job.data['status_code'], 400)
                 self.assertEqual(
                 self.assertEqual(
                     job.error, 'Background processing is not supported for this endpoint.'
                     job.error, 'Background processing is not supported for this endpoint.'