From 8c06db5e91c7e0a0e9b0a239a4ca125312079a79 Mon Sep 17 00:00:00 2001 From: Ramgopal Nagaboina Date: Wed, 2 Sep 2026 19:22:38 -0400 Subject: [PATCH 1/5] framework: do not double-execute an async job after returning its queue item In executeQueueItem, when persisting the executing MS id fails (the DB-deadlock case the catch block exists for), the queue item is returned to the queue so it can be retried. Execution then fell through to scheduleExecution(job), so the job was dispatched now AND re-dequeued and dispatched again by the heartbeat, running the same job (VM start/deploy, volume create, snapshot, etc.) twice concurrently and defeating the sync queue's serialization. Return after returning the item. --- .../jobs/impl/AsyncJobManagerImpl.java | 5 +- ...yncJobManagerImplExecuteQueueItemTest.java | 70 +++++++++++++++++++ 2 files changed, 73 insertions(+), 2 deletions(-) create mode 100644 framework/jobs/src/test/java/org/apache/cloudstack/framework/jobs/impl/AsyncJobManagerImplExecuteQueueItemTest.java diff --git a/framework/jobs/src/main/java/org/apache/cloudstack/framework/jobs/impl/AsyncJobManagerImpl.java b/framework/jobs/src/main/java/org/apache/cloudstack/framework/jobs/impl/AsyncJobManagerImpl.java index b9c9b22d9eaa..11d9ca5fa3c5 100644 --- a/framework/jobs/src/main/java/org/apache/cloudstack/framework/jobs/impl/AsyncJobManagerImpl.java +++ b/framework/jobs/src/main/java/org/apache/cloudstack/framework/jobs/impl/AsyncJobManagerImpl.java @@ -523,7 +523,7 @@ public String obfuscatePassword(String result, boolean hidePassword) { return StringUtils.obfuscatePasswordInJsonLikeString(result); } - private void scheduleExecution(final AsyncJobVO job) { + protected void scheduleExecution(final AsyncJobVO job) { scheduleExecution(job, false); } @@ -701,7 +701,7 @@ private int getAndResetPendingSignals(AsyncJob job) { return signals; } - private void executeQueueItem(SyncQueueItemVO item, boolean fromPreviousSession) { + protected void executeQueueItem(SyncQueueItemVO item, boolean fromPreviousSession) { AsyncJobVO job = _jobDao.findById(item.getContentId()); if (job != null) { if (logger.isDebugEnabled()) { @@ -726,6 +726,7 @@ private void executeQueueItem(SyncQueueItemVO item, boolean fromPreviousSession) } catch (Throwable thr) { logger.error("Unexpected exception while returning job-" + item.getContentId() + " to queue", thr); } + return; } try { diff --git a/framework/jobs/src/test/java/org/apache/cloudstack/framework/jobs/impl/AsyncJobManagerImplExecuteQueueItemTest.java b/framework/jobs/src/test/java/org/apache/cloudstack/framework/jobs/impl/AsyncJobManagerImplExecuteQueueItemTest.java new file mode 100644 index 000000000000..a197d7b4f0a7 --- /dev/null +++ b/framework/jobs/src/test/java/org/apache/cloudstack/framework/jobs/impl/AsyncJobManagerImplExecuteQueueItemTest.java @@ -0,0 +1,70 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.framework.jobs.impl; + +import org.apache.cloudstack.framework.jobs.dao.AsyncJobDao; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; + +import com.cloud.utils.exception.CloudRuntimeException; + +@RunWith(MockitoJUnitRunner.Silent.class) +public class AsyncJobManagerImplExecuteQueueItemTest { + + @Mock + AsyncJobDao _jobDao; + @Mock + SyncQueueManager _queueMgr; + + @Spy + @InjectMocks + AsyncJobManagerImpl asyncJobManager = new AsyncJobManagerImpl(); + + @Test + public void executeQueueItemDoesNotScheduleWhenTheJobUpdateFailsAndItemIsReturned() { + long contentId = 10L; + long itemId = 20L; + long jobId = 1L; + + SyncQueueItemVO item = Mockito.mock(SyncQueueItemVO.class); + Mockito.when(item.getContentId()).thenReturn(contentId); + Mockito.when(item.getId()).thenReturn(itemId); + + AsyncJobVO job = Mockito.mock(AsyncJobVO.class); + Mockito.when(job.getId()).thenReturn(jobId); + Mockito.when(_jobDao.findById(contentId)).thenReturn(job); + + // Simulate the DB deadlock the catch block was written to survive. + Mockito.doThrow(new CloudRuntimeException("simulated DB deadlock")) + .when(_jobDao).update(Mockito.anyLong(), Mockito.any(AsyncJobVO.class)); + + // Stub the executor path so we can assert whether it is reached (and avoid the real submit). + Mockito.doNothing().when(asyncJobManager).scheduleExecution(Mockito.any(AsyncJobVO.class)); + + asyncJobManager.executeQueueItem(item, false); + + // The queue item was returned for a later retry; the job must NOT also be scheduled now, or it + // would run twice (once here and once when the heartbeat re-dequeues the returned item). + Mockito.verify(_queueMgr).returnItem(itemId); + Mockito.verify(asyncJobManager, Mockito.never()).scheduleExecution(Mockito.any(AsyncJobVO.class)); + } +} From bc3cde8356d8aa3e58a6aab2a5692100abb0f3bf Mon Sep 17 00:00:00 2001 From: Ramgopal Nagaboina Date: Sat, 5 Sep 2026 14:44:55 -0400 Subject: [PATCH 2/5] framework: simplify executeQueueItem exception handling Flatten executeQueueItem with an early return for the missing-job case and extract the duplicated return-item-to-queue and clear-executing-msid bookkeeping into helpers, removing the nested try blocks. No behavior change. --- .../jobs/impl/AsyncJobManagerImpl.java | 87 +++++++++---------- 1 file changed, 43 insertions(+), 44 deletions(-) diff --git a/framework/jobs/src/main/java/org/apache/cloudstack/framework/jobs/impl/AsyncJobManagerImpl.java b/framework/jobs/src/main/java/org/apache/cloudstack/framework/jobs/impl/AsyncJobManagerImpl.java index 11d9ca5fa3c5..8c3d965f9766 100644 --- a/framework/jobs/src/main/java/org/apache/cloudstack/framework/jobs/impl/AsyncJobManagerImpl.java +++ b/framework/jobs/src/main/java/org/apache/cloudstack/framework/jobs/impl/AsyncJobManagerImpl.java @@ -703,57 +703,56 @@ private int getAndResetPendingSignals(AsyncJob job) { protected void executeQueueItem(SyncQueueItemVO item, boolean fromPreviousSession) { AsyncJobVO job = _jobDao.findById(item.getContentId()); - if (job != null) { + if (job == null) { if (logger.isDebugEnabled()) { - logger.debug("Schedule queued job-" + job.getId()); - } - - job.setSyncSource(item); - - // - // TODO: a temporary solution to work-around DB deadlock situation - // - // to live with DB deadlocks, we will give a chance for job to be rescheduled - // in case of exceptions (most-likely DB deadlock exceptions) - try { - job.setExecutingMsid(getMsid()); - _jobDao.update(job.getId(), job); - } catch (Exception e) { - logger.warn("Unexpected exception while dispatching job-" + item.getContentId(), e); - - try { - _queueMgr.returnItem(item.getId()); - } catch (Throwable thr) { - logger.error("Unexpected exception while returning job-" + item.getContentId() + " to queue", thr); - } - return; + logger.debug("Unable to find related job for queue item: " + item.toString()); } + _queueMgr.purgeItem(item.getId()); + return; + } - try { - scheduleExecution(job); - } catch (RejectedExecutionException e) { - logger.warn("Execution for job-" + job.getId() + " is rejected, return it to the queue for next turn"); + if (logger.isDebugEnabled()) { + logger.debug("Schedule queued job-" + job.getId()); + } + job.setSyncSource(item); - try { - _queueMgr.returnItem(item.getId()); - } catch (Exception e2) { - logger.error("Unexpected exception while returning job-" + item.getContentId() + " to queue", e2); - } + // + // TODO: a temporary solution to work-around DB deadlock situation + // + // to live with DB deadlocks, we will give a chance for job to be rescheduled + // in case of exceptions (most-likely DB deadlock exceptions) + try { + job.setExecutingMsid(getMsid()); + _jobDao.update(job.getId(), job); + } catch (Exception e) { + logger.warn("Unexpected exception while dispatching job-" + item.getContentId(), e); + returnItemToQueue(item); + return; + } - try { - job.setExecutingMsid(null); - _jobDao.update(job.getId(), job); - } catch (Exception e3) { - logger.warn("Unexpected exception while update job-" + item.getContentId() + " msid for bookkeeping"); - } - } + try { + scheduleExecution(job); + } catch (RejectedExecutionException e) { + logger.warn("Execution for job-" + job.getId() + " is rejected, return it to the queue for next turn"); + returnItemToQueue(item); + clearExecutingMsid(job, item); + } + } - } else { - if (logger.isDebugEnabled()) { - logger.debug("Unable to find related job for queue item: " + item.toString()); - } + private void returnItemToQueue(SyncQueueItemVO item) { + try { + _queueMgr.returnItem(item.getId()); + } catch (Throwable thr) { + logger.error("Unexpected exception while returning job-" + item.getContentId() + " to queue", thr); + } + } - _queueMgr.purgeItem(item.getId()); + private void clearExecutingMsid(AsyncJobVO job, SyncQueueItemVO item) { + try { + job.setExecutingMsid(null); + _jobDao.update(job.getId(), job); + } catch (Exception e) { + logger.warn("Unexpected exception while update job-" + item.getContentId() + " msid for bookkeeping"); } } From 095d9b3ebe4e12633fd28cdb79be1da9d71c9574 Mon Sep 17 00:00:00 2001 From: Ramgopal Nagaboina Date: Thu, 10 Sep 2026 16:02:22 -0400 Subject: [PATCH 3/5] framework: move the executeQueueItem deadlock TODO into its javadoc Explain why a failed executing-msid update returns the item to the queue and what the proper fix would be, as asked in review. --- .../framework/jobs/impl/AsyncJobManagerImpl.java | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/framework/jobs/src/main/java/org/apache/cloudstack/framework/jobs/impl/AsyncJobManagerImpl.java b/framework/jobs/src/main/java/org/apache/cloudstack/framework/jobs/impl/AsyncJobManagerImpl.java index 8c3d965f9766..1502df1b7262 100644 --- a/framework/jobs/src/main/java/org/apache/cloudstack/framework/jobs/impl/AsyncJobManagerImpl.java +++ b/framework/jobs/src/main/java/org/apache/cloudstack/framework/jobs/impl/AsyncJobManagerImpl.java @@ -701,6 +701,15 @@ private int getAndResetPendingSignals(AsyncJob job) { return signals; } + /** + * Dispatches the job behind a sync queue item. + *

+ * TODO: stamping the executing management server id on the job can hit a DB deadlock. As a + * temporary workaround, a failed update returns the item to the sync queue so the job is retried + * on a later turn instead of failing. The proper fix is to remove the deadlock at its source, in + * the locking and transaction around the sync_queue and async_job updates on dispatch, after + * which this retry is no longer needed. + */ protected void executeQueueItem(SyncQueueItemVO item, boolean fromPreviousSession) { AsyncJobVO job = _jobDao.findById(item.getContentId()); if (job == null) { @@ -716,11 +725,6 @@ protected void executeQueueItem(SyncQueueItemVO item, boolean fromPreviousSessio } job.setSyncSource(item); - // - // TODO: a temporary solution to work-around DB deadlock situation - // - // to live with DB deadlocks, we will give a chance for job to be rescheduled - // in case of exceptions (most-likely DB deadlock exceptions) try { job.setExecutingMsid(getMsid()); _jobDao.update(job.getId(), job); From fd11c319e0763c3582a09c6901678166ed38bfbd Mon Sep 17 00:00:00 2001 From: rootnomad Date: Tue, 20 Oct 2026 09:53:56 -0400 Subject: [PATCH 4/5] framework: clear the executing msid before returning a rejected job to the queue When scheduleExecution rejects the job, executeQueueItem returned the sync queue item and then cleared the job's executing management-server id. Another management server could dequeue the returned item and stamp its own msid in that window, and the clearing update (a full-row update of the job VO) would then wipe it. Clear the msid while we still hold the item, then return it. --- .../jobs/impl/AsyncJobManagerImpl.java | 2 +- ...yncJobManagerImplExecuteQueueItemTest.java | 31 +++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/framework/jobs/src/main/java/org/apache/cloudstack/framework/jobs/impl/AsyncJobManagerImpl.java b/framework/jobs/src/main/java/org/apache/cloudstack/framework/jobs/impl/AsyncJobManagerImpl.java index 1502df1b7262..9086bbd52241 100644 --- a/framework/jobs/src/main/java/org/apache/cloudstack/framework/jobs/impl/AsyncJobManagerImpl.java +++ b/framework/jobs/src/main/java/org/apache/cloudstack/framework/jobs/impl/AsyncJobManagerImpl.java @@ -738,8 +738,8 @@ protected void executeQueueItem(SyncQueueItemVO item, boolean fromPreviousSessio scheduleExecution(job); } catch (RejectedExecutionException e) { logger.warn("Execution for job-" + job.getId() + " is rejected, return it to the queue for next turn"); - returnItemToQueue(item); clearExecutingMsid(job, item); + returnItemToQueue(item); } } diff --git a/framework/jobs/src/test/java/org/apache/cloudstack/framework/jobs/impl/AsyncJobManagerImplExecuteQueueItemTest.java b/framework/jobs/src/test/java/org/apache/cloudstack/framework/jobs/impl/AsyncJobManagerImplExecuteQueueItemTest.java index a197d7b4f0a7..ca5fae19c887 100644 --- a/framework/jobs/src/test/java/org/apache/cloudstack/framework/jobs/impl/AsyncJobManagerImplExecuteQueueItemTest.java +++ b/framework/jobs/src/test/java/org/apache/cloudstack/framework/jobs/impl/AsyncJobManagerImplExecuteQueueItemTest.java @@ -16,9 +16,12 @@ // under the License. package org.apache.cloudstack.framework.jobs.impl; +import java.util.concurrent.RejectedExecutionException; + import org.apache.cloudstack.framework.jobs.dao.AsyncJobDao; import org.junit.Test; import org.junit.runner.RunWith; +import org.mockito.InOrder; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; @@ -67,4 +70,32 @@ public void executeQueueItemDoesNotScheduleWhenTheJobUpdateFailsAndItemIsReturne Mockito.verify(_queueMgr).returnItem(itemId); Mockito.verify(asyncJobManager, Mockito.never()).scheduleExecution(Mockito.any(AsyncJobVO.class)); } + + @Test + public void executeQueueItemClearsExecutingMsidBeforeReturningItemOnRejectedExecution() { + long contentId = 10L; + long itemId = 20L; + long jobId = 1L; + + SyncQueueItemVO item = Mockito.mock(SyncQueueItemVO.class); + Mockito.when(item.getContentId()).thenReturn(contentId); + Mockito.when(item.getId()).thenReturn(itemId); + + AsyncJobVO job = Mockito.mock(AsyncJobVO.class); + Mockito.when(job.getId()).thenReturn(jobId); + Mockito.when(_jobDao.findById(contentId)).thenReturn(job); + + // Dispatch stamps the executing msid successfully, then the executor rejects the job. + Mockito.doThrow(new RejectedExecutionException("pool full")) + .when(asyncJobManager).scheduleExecution(Mockito.any(AsyncJobVO.class)); + + asyncJobManager.executeQueueItem(item, false); + + // The executing msid must be cleared while we still hold the item, before it goes back on the + // queue. Otherwise another management server could dequeue the item and stamp its own msid in + // the gap, and the clearing update would wipe it. + InOrder inOrder = Mockito.inOrder(job, _queueMgr); + inOrder.verify(job).setExecutingMsid(null); + inOrder.verify(_queueMgr).returnItem(itemId); + } } From b38a0c7e87d385759e96354a0ecbb56850160372 Mon Sep 17 00:00:00 2001 From: rootnomad Date: Tue, 20 Oct 2026 10:26:51 -0400 Subject: [PATCH 5/5] framework: still run a rejected-dispatch job when the requeue also fails The double-execution fix returned right after returnItem(), but if returnItem itself failed the job was neither requeued nor run and sat until the JobCancelThreshold cleanup. The original code fell through and still ran it once. Return only when the item was put back on the queue successfully, and fall through to schedule it otherwise, so the double-execution stays fixed without stranding the job. --- .../jobs/impl/AsyncJobManagerImpl.java | 10 +++++-- ...yncJobManagerImplExecuteQueueItemTest.java | 28 +++++++++++++++++++ 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/framework/jobs/src/main/java/org/apache/cloudstack/framework/jobs/impl/AsyncJobManagerImpl.java b/framework/jobs/src/main/java/org/apache/cloudstack/framework/jobs/impl/AsyncJobManagerImpl.java index 9086bbd52241..05cb80fcd354 100644 --- a/framework/jobs/src/main/java/org/apache/cloudstack/framework/jobs/impl/AsyncJobManagerImpl.java +++ b/framework/jobs/src/main/java/org/apache/cloudstack/framework/jobs/impl/AsyncJobManagerImpl.java @@ -730,8 +730,10 @@ protected void executeQueueItem(SyncQueueItemVO item, boolean fromPreviousSessio _jobDao.update(job.getId(), job); } catch (Exception e) { logger.warn("Unexpected exception while dispatching job-" + item.getContentId(), e); - returnItemToQueue(item); - return; + if (returnItemToQueue(item)) { + return; + } + // requeue failed: fall through so the job still runs once rather than being stranded until cleanup } try { @@ -743,11 +745,13 @@ protected void executeQueueItem(SyncQueueItemVO item, boolean fromPreviousSessio } } - private void returnItemToQueue(SyncQueueItemVO item) { + private boolean returnItemToQueue(SyncQueueItemVO item) { try { _queueMgr.returnItem(item.getId()); + return true; } catch (Throwable thr) { logger.error("Unexpected exception while returning job-" + item.getContentId() + " to queue", thr); + return false; } } diff --git a/framework/jobs/src/test/java/org/apache/cloudstack/framework/jobs/impl/AsyncJobManagerImplExecuteQueueItemTest.java b/framework/jobs/src/test/java/org/apache/cloudstack/framework/jobs/impl/AsyncJobManagerImplExecuteQueueItemTest.java index ca5fae19c887..b2452a1d46b2 100644 --- a/framework/jobs/src/test/java/org/apache/cloudstack/framework/jobs/impl/AsyncJobManagerImplExecuteQueueItemTest.java +++ b/framework/jobs/src/test/java/org/apache/cloudstack/framework/jobs/impl/AsyncJobManagerImplExecuteQueueItemTest.java @@ -98,4 +98,32 @@ public void executeQueueItemClearsExecutingMsidBeforeReturningItemOnRejectedExec inOrder.verify(job).setExecutingMsid(null); inOrder.verify(_queueMgr).returnItem(itemId); } + + @Test + public void executeQueueItemStillSchedulesWhenRequeueAlsoFailsSoJobIsNotStranded() { + long contentId = 10L; + long itemId = 20L; + long jobId = 1L; + + SyncQueueItemVO item = Mockito.mock(SyncQueueItemVO.class); + Mockito.when(item.getContentId()).thenReturn(contentId); + Mockito.when(item.getId()).thenReturn(itemId); + + AsyncJobVO job = Mockito.mock(AsyncJobVO.class); + Mockito.when(job.getId()).thenReturn(jobId); + Mockito.when(_jobDao.findById(contentId)).thenReturn(job); + + // Stamping the executing msid fails (the DB deadlock path), and returning the item also fails. + Mockito.doThrow(new CloudRuntimeException("simulated DB deadlock")) + .when(_jobDao).update(Mockito.anyLong(), Mockito.any(AsyncJobVO.class)); + Mockito.doThrow(new CloudRuntimeException("queue unavailable")) + .when(_queueMgr).returnItem(Mockito.anyLong()); + Mockito.doNothing().when(asyncJobManager).scheduleExecution(Mockito.any(AsyncJobVO.class)); + + asyncJobManager.executeQueueItem(item, false); + + // The requeue failed, so the job must still be scheduled once instead of sitting until cleanup. + Mockito.verify(_queueMgr).returnItem(itemId); + Mockito.verify(asyncJobManager).scheduleExecution(job); + } }