From 336bfdcc2c0f55ceb06ed4b0ef9afd8bf6e6795e Mon Sep 17 00:00:00 2001 From: Seth Foster Date: Fri, 7 Jun 2024 12:16:22 -0400 Subject: [PATCH] make it work in autocommit mode Signed-off-by: Seth Foster --- awx/main/models/unified_jobs.py | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/awx/main/models/unified_jobs.py b/awx/main/models/unified_jobs.py index 06c2942b3aa3..39bc56f43bfb 100644 --- a/awx/main/models/unified_jobs.py +++ b/awx/main/models/unified_jobs.py @@ -17,7 +17,7 @@ # Django from django.conf import settings -from django.db import models, connection +from django.db import models, connection, transaction from django.core.exceptions import NON_FIELD_ERRORS from django.utils.translation import gettext_lazy as _ from django.utils.timezone import now @@ -269,13 +269,18 @@ def last_updated(self): def update_computed_fields(self): related_schedules = self.schedules.filter(enabled=True, next_run__isnull=False).order_by('-next_run') - # select for update will lock this row until the transaction is committed - # prevent race condition where new_next_schedule may be deleted during this transaction - new_next_schedule = related_schedules.select_for_update().first() + new_next_schedule = related_schedules.first() if new_next_schedule: if new_next_schedule.pk == self.next_schedule_id and new_next_schedule.next_run == self.next_job_run: return # no-op, common for infrequent schedules - self.next_schedule = new_next_schedule + + # If in a transaction, use select_for_update to lock the next schedule row, which + # prevents a race condition if new_next_schedule is deleted elsewhere during this transaction + if transaction.get_autocommit(): + self.next_schedule = related_schedules.first() + else: + self.next_schedule = related_schedules.select_for_update().first() + self.next_job_run = new_next_schedule.next_run self.save(update_fields=['next_schedule', 'next_job_run'])