From e55b4a40a684a7fe8a7560690d994661a8318ac0 Mon Sep 17 00:00:00 2001 From: durdin85 <6603216+durdin85@users.noreply.github.com> Date: Wed, 11 Nov 2026 11:00:32 +0000 Subject: [PATCH 1/6] rabbitmq event bus: buffer events while the broker is unreachable Events published while the AMQP connection is down were discarded. Keep them in a bounded in-memory FIFO buffer and send them in order once the connection is back. - events are buffered only after the broker was reachable once - buffer is capped (bufferSize, default 1000, oldest dropped first) and entries expire (bufferExpiry, default 300000 ms) - publish() no longer connects on the calling thread while the broker is down - ReconnectionTask runs for the lifetime of the bus, so connections closed by the bus itself are re-established as well This change, including the unit test, was generated with an AI assistant (Claude Code). Fixes: #14676 Co-Authored-By: Claude Fable 5.2 --- .../mom/rabbitmq/RabbitMQEventBus.java | 134 ++++++++++++-- .../mom/rabbitmq/RabbitMQEventBusTest.java | 167 ++++++++++++++++++ 2 files changed, 285 insertions(+), 16 deletions(-) create mode 100644 plugins/event-bus/rabbitmq/src/test/java/org/apache/cloudstack/mom/rabbitmq/RabbitMQEventBusTest.java diff --git a/plugins/event-bus/rabbitmq/src/main/java/org/apache/cloudstack/mom/rabbitmq/RabbitMQEventBus.java b/plugins/event-bus/rabbitmq/src/main/java/org/apache/cloudstack/mom/rabbitmq/RabbitMQEventBus.java index b98147b5f031..fd1a7e26fc91 100644 --- a/plugins/event-bus/rabbitmq/src/main/java/org/apache/cloudstack/mom/rabbitmq/RabbitMQEventBus.java +++ b/plugins/event-bus/rabbitmq/src/main/java/org/apache/cloudstack/mom/rabbitmq/RabbitMQEventBus.java @@ -23,6 +23,7 @@ import java.net.ConnectException; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; +import java.util.ArrayDeque; import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; @@ -85,11 +86,23 @@ public static void setUseSsl(String useSsl) { private static Integer retryInterval; + // max number of events kept in memory while the AMQP server is unreachable, 0 disables buffering + private static Integer bufferSize = 1000; + + // time in milliseconds after which a buffered event is dropped if it could not be sent + private static Integer bufferExpiry = 300000; + + // events (routing key, description, time of buffering) waiting to be sent, oldest first + private static final ArrayDeque> s_buffer = new ArrayDeque<>(); + + // events are buffered only after the AMQP server was reachable at least once + private static volatile boolean s_connectedOnce = false; + // hashmap to book keep the registered subscribers private static ConcurrentHashMap> s_subscribers; // connection to AMQP server, - private static Connection s_connection = null; + private static volatile Connection s_connection = null; // AMQP server should consider messages acknowledged once delivered if _autoAck is true private static boolean s_autoAck = true; @@ -177,6 +190,14 @@ public static void setRetryInterval(Integer retryInterval) { RabbitMQEventBus.retryInterval = retryInterval; } + public static void setBufferSize(Integer bufferSize) { + RabbitMQEventBus.bufferSize = bufferSize; + } + + public static void setBufferExpiry(Integer bufferExpiry) { + RabbitMQEventBus.bufferExpiry = bufferExpiry; + } + /** Call to subscribe to interested set of events * * @param topic defines category and type of the events being subscribed to @@ -273,20 +294,98 @@ public void publish(Event event) throws EventBusException { String routingKey = createRoutingKey(event); String eventDescription = event.getDescription(); + // keep the order: nothing is sent directly while older events are waiting or the connection is down + if (bufferEvent(routingKey, eventDescription, false)) { + return; + } + try { - Connection connection = getConnection(); - Channel channel = createChannel(connection); - createExchange(channel, amqpExchangeName); - publishEventToExchange(channel, amqpExchangeName, routingKey, eventDescription); - channel.close(); + sendEvent(getConnection(), routingKey, eventDescription); } catch (AlreadyClosedException e) { closeConnection(); + if (bufferEvent(routingKey, eventDescription, true)) { + return; + } throw new EventBusException("Failed to publish event to message broker as connection to AMQP broker in lost"); + } catch (IOException e) { + if (bufferEvent(routingKey, eventDescription, true)) { + return; + } + throw new EventBusException("Failed to publish event to message broker due to " + e.getMessage()); } catch (Exception e) { throw new EventBusException("Failed to publish event to message broker due to " + e.getMessage()); } } + private void sendEvent(Connection connection, String routingKey, String eventDescription) throws Exception { + Channel channel = createChannel(connection); + createExchange(channel, amqpExchangeName); + publishEventToExchange(channel, amqpExchangeName, routingKey, eventDescription); + channel.close(); + } + + /** adds the event to the buffer, dropping the oldest one if the buffer is full + * + * @param sendFailed false if the event was not tried yet and has to be buffered only to keep the order + * @return true if the event was buffered, false if the caller has to deal with it + */ + private boolean bufferEvent(String routingKey, String eventDescription, boolean sendFailed) { + if (!s_connectedOnce || bufferSize <= 0) { + return false; + } + synchronized (s_buffer) { + if (!sendFailed && s_buffer.isEmpty() && s_connection != null) { + return false; + } + if (s_buffer.size() >= bufferSize) { + logger.warn("Event buffer is full, dropping the oldest event " + s_buffer.poll().first()); + } + s_buffer.add(new Ternary<>(routingKey, eventDescription, System.currentTimeMillis())); + } + return true; + } + + // drops the expired events and, if connected, sends the buffered ones in the order they were added + private void flushBuffer() { + while (true) { + Ternary bufferedEvent; + synchronized (s_buffer) { + bufferedEvent = s_buffer.peek(); + } + if (bufferedEvent == null) { + return; + } + + boolean expired = System.currentTimeMillis() - bufferedEvent.third() > bufferExpiry; + Connection connection = s_connection; + if (!expired && connection == null) { + return; + } + + if (expired) { + logger.warn("Dropping expired event " + bufferedEvent.first() + " as it could not be sent to AMQP server in time"); + } else { + try { + sendEvent(connection, bufferedEvent.first(), bufferedEvent.second()); + } catch (AlreadyClosedException e) { + closeConnection(); + return; + } catch (IOException e) { + return; // retry with the next run + } catch (Exception e) { + logger.warn("Dropping buffered event " + bufferedEvent.first() + " due to " + e.getMessage()); + } + } + + // the event stays in the buffer while being sent, so that newer events queue up behind it + synchronized (s_buffer) { + if (s_buffer.peek() == bufferedEvent) { + s_buffer.poll(); + } + } + } + } + /** creates a routing key from the event details. * created routing key will be used while publishing the message to exchange on AMQP server */ @@ -392,6 +491,7 @@ private synchronized Connection createConnection() throws KeyManagementException connection.addShutdownListener(disconnectHandler); connection.addBlockedListener(blockedConnectionHandler); s_connection = connection; + s_connectedOnce = true; return s_connection; } @@ -508,6 +608,7 @@ public synchronized boolean stop() { } closeConnection(); + executorService.shutdownNow(); return true; } @@ -540,35 +641,36 @@ public void shutdownCompleted(ShutdownSignalException shutdownSignalException) { } abortConnection(); // disconnected to AMQP server, so abort the connection and channels + // the ReconnectionTask started with the event bus takes care of the re-connect logger.warn("Connection has been shutdown by AMQP server. Attempting to reconnect."); - - // initiate re-connect process - ReconnectionTask reconnect = new ReconnectionTask(); - executorService.submit(reconnect); } } } - // retry logic to connect back to AMQP server after loss of connection + // runs for the lifetime of the event bus: connects back to AMQP server after any loss of connection + // and sends the events buffered in the meantime private class ReconnectionTask extends ManagedContextRunnable { - boolean connected = false; Connection connection = null; @Override protected void runInContext() { - while (!connected) { + while (true) { try { Thread.sleep(retryInterval); } catch (InterruptedException ie) { - // ignore timer interrupts + return; // event bus is being stopped + } + + flushBuffer(); + if (s_connection != null) { + continue; } try { try { connection = createConnection(); - connected = true; } catch (IOException ie) { continue; // can't establish connection to AMQP server yet, so continue } @@ -620,8 +722,8 @@ public void handleDelivery(String queueName, Envelope envelope, AMQP.BasicProper } catch (Exception e) { logger.warn("Failed to recreate queues and binding for the subscribers due to " + e.getMessage()); } + flushBuffer(); } - return; } } } diff --git a/plugins/event-bus/rabbitmq/src/test/java/org/apache/cloudstack/mom/rabbitmq/RabbitMQEventBusTest.java b/plugins/event-bus/rabbitmq/src/test/java/org/apache/cloudstack/mom/rabbitmq/RabbitMQEventBusTest.java new file mode 100644 index 000000000000..281e461575d8 --- /dev/null +++ b/plugins/event-bus/rabbitmq/src/test/java/org/apache/cloudstack/mom/rabbitmq/RabbitMQEventBusTest.java @@ -0,0 +1,167 @@ +// 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.mom.rabbitmq; + +import java.io.IOException; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.ArrayDeque; + +import org.apache.cloudstack.framework.events.Event; +import org.apache.cloudstack.framework.events.EventBusException; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.ArgumentMatchers; +import org.mockito.InOrder; +import org.mockito.Mockito; + +import com.rabbitmq.client.Channel; +import com.rabbitmq.client.Connection; + +public class RabbitMQEventBusTest { + + private RabbitMQEventBus eventBus; + private Connection connection; + private Channel channel; + + @Before + public void setUp() throws Exception { + eventBus = new RabbitMQEventBus(); + RabbitMQEventBus.setExchange("cloudstack-events"); + RabbitMQEventBus.setBufferSize(1000); + RabbitMQEventBus.setBufferExpiry(300000); + + channel = Mockito.mock(Channel.class); + connection = Mockito.mock(Connection.class); + Mockito.when(connection.createChannel()).thenReturn(channel); + + ((ArrayDeque)getField("s_buffer").get(null)).clear(); + setConnection(null); + getField("s_connectedOnce").set(null, true); + } + + @After + public void tearDown() throws Exception { + setConnection(null); + getField("s_connectedOnce").set(null, false); + } + + private Field getField(String name) throws Exception { + Field field = RabbitMQEventBus.class.getDeclaredField(name); + field.setAccessible(true); + return field; + } + + private void setConnection(Connection connection) throws Exception { + getField("s_connection").set(null, connection); + } + + private void flushBuffer() throws Exception { + Method method = RabbitMQEventBus.class.getDeclaredMethod("flushBuffer"); + method.setAccessible(true); + method.invoke(eventBus); + } + + private Event event(String description) { + Event event = new Event("server", "ActionEvent", "VM.START", "VirtualMachine", "uuid"); + event.setDescription(description); + return event; + } + + private void verifyPublished(InOrder inOrder, String description) throws IOException { + inOrder.verify(channel).basicPublish(ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), ArgumentMatchers.any(), + ArgumentMatchers.eq(description.getBytes())); + } + + private void verifyPublishedCount(int count) throws IOException { + Mockito.verify(channel, Mockito.times(count)).basicPublish(ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), + ArgumentMatchers.any(), ArgumentMatchers.any(byte[].class)); + } + + @Test(expected = EventBusException.class) + public void publishFailsWhenBrokerWasNeverReachable() throws Exception { + getField("s_connectedOnce").set(null, false); + RabbitMQEventBus.setServer("localhost"); + RabbitMQEventBus.setPort(1); + RabbitMQEventBus.setUsername("guest"); + RabbitMQEventBus.setPassword("guest"); + + eventBus.publish(event("1")); + } + + @Test + public void eventsPublishedWhileDisconnectedAreSentInOrderAfterReconnect() throws Exception { + eventBus.publish(event("1")); + eventBus.publish(event("2")); + Mockito.verifyNoInteractions(channel); + + setConnection(connection); + eventBus.publish(event("3")); // must not overtake the buffered ones + Mockito.verifyNoInteractions(channel); + + flushBuffer(); + InOrder inOrder = Mockito.inOrder(channel); + verifyPublished(inOrder, "1"); + verifyPublished(inOrder, "2"); + verifyPublished(inOrder, "3"); + + eventBus.publish(event("4")); // buffer is empty again, sent directly + verifyPublished(inOrder, "4"); + verifyPublishedCount(4); + } + + @Test + public void eventIsBufferedWhenSendingFails() throws Exception { + setConnection(connection); + Mockito.doThrow(new IOException("broken pipe")).doNothing().when(channel) + .basicPublish(ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), ArgumentMatchers.any(), ArgumentMatchers.any(byte[].class)); + + eventBus.publish(event("1")); + verifyPublishedCount(1); + + flushBuffer(); + verifyPublishedCount(2); + } + + @Test + public void oldestEventIsDroppedWhenBufferIsFull() throws Exception { + RabbitMQEventBus.setBufferSize(2); + eventBus.publish(event("1")); + eventBus.publish(event("2")); + eventBus.publish(event("3")); + + setConnection(connection); + flushBuffer(); + InOrder inOrder = Mockito.inOrder(channel); + verifyPublished(inOrder, "2"); + verifyPublished(inOrder, "3"); + verifyPublishedCount(2); + } + + @Test + public void expiredEventsAreDropped() throws Exception { + RabbitMQEventBus.setBufferExpiry(-1); + eventBus.publish(event("1")); + + flushBuffer(); // expires also without a connection + setConnection(connection); + flushBuffer(); + Mockito.verifyNoInteractions(channel); + } +} From 32200761ac1c628c566a3b23f5a3d52faeb81397 Mon Sep 17 00:00:00 2001 From: durdin85 <6603216+durdin85@users.noreply.github.com> Date: Wed, 11 Nov 2026 11:26:53 +0000 Subject: [PATCH 2/6] rabbitmq event bus: harden the reconnect loop - keep the buffer flush inside the try block, so an unexpected exception cannot end the only reconnect thread - check for an existing connection and connect under the same lock as getConnection(), so a connection created by publish() is not replaced and leaked Generated with an AI assistant (Claude Code). Co-Authored-By: Claude Fable 5.2 --- .../mom/rabbitmq/RabbitMQEventBus.java | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/plugins/event-bus/rabbitmq/src/main/java/org/apache/cloudstack/mom/rabbitmq/RabbitMQEventBus.java b/plugins/event-bus/rabbitmq/src/main/java/org/apache/cloudstack/mom/rabbitmq/RabbitMQEventBus.java index fd1a7e26fc91..b468710e7aad 100644 --- a/plugins/event-bus/rabbitmq/src/main/java/org/apache/cloudstack/mom/rabbitmq/RabbitMQEventBus.java +++ b/plugins/event-bus/rabbitmq/src/main/java/org/apache/cloudstack/mom/rabbitmq/RabbitMQEventBus.java @@ -663,14 +663,16 @@ protected void runInContext() { return; // event bus is being stopped } - flushBuffer(); - if (s_connection != null) { - continue; - } - try { + flushBuffer(); try { - connection = createConnection(); + // check and connect under the same lock as getConnection(), so a connection is never replaced + synchronized (RabbitMQEventBus.this) { + if (s_connection != null) { + continue; + } + connection = createConnection(); + } } catch (IOException ie) { continue; // can't establish connection to AMQP server yet, so continue } @@ -719,10 +721,10 @@ public void handleDelivery(String queueName, Envelope envelope, AMQP.BasicProper subscriberDetails.second(channel); s_subscribers.put(subscriberId, subscriberDetails); } + flushBuffer(); } catch (Exception e) { logger.warn("Failed to recreate queues and binding for the subscribers due to " + e.getMessage()); } - flushBuffer(); } } } From 0b85b3ddc3d9f847f1c3a34af3ae9c497e24ba15 Mon Sep 17 00:00:00 2001 From: durdin85 <6603216+durdin85@users.noreply.github.com> Date: Wed, 11 Nov 2026 12:52:11 +0000 Subject: [PATCH 3/6] rabbitmq event bus: log when events are buffered and re-sent Generated with an AI assistant (Claude Code). Co-Authored-By: Claude Fable 5.2 --- .../mom/rabbitmq/RabbitMQEventBus.java | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/plugins/event-bus/rabbitmq/src/main/java/org/apache/cloudstack/mom/rabbitmq/RabbitMQEventBus.java b/plugins/event-bus/rabbitmq/src/main/java/org/apache/cloudstack/mom/rabbitmq/RabbitMQEventBus.java index b468710e7aad..d7742ee32266 100644 --- a/plugins/event-bus/rabbitmq/src/main/java/org/apache/cloudstack/mom/rabbitmq/RabbitMQEventBus.java +++ b/plugins/event-bus/rabbitmq/src/main/java/org/apache/cloudstack/mom/rabbitmq/RabbitMQEventBus.java @@ -337,6 +337,9 @@ private boolean bufferEvent(String routingKey, String eventDescription, boolean if (!sendFailed && s_buffer.isEmpty() && s_connection != null) { return false; } + if (s_buffer.isEmpty()) { + logger.warn("Unable to send events to AMQP server, buffering them until they can be sent"); + } if (s_buffer.size() >= bufferSize) { logger.warn("Event buffer is full, dropping the oldest event " + s_buffer.poll().first()); } @@ -347,19 +350,20 @@ private boolean bufferEvent(String routingKey, String eventDescription, boolean // drops the expired events and, if connected, sends the buffered ones in the order they were added private void flushBuffer() { + int sent = 0; while (true) { Ternary bufferedEvent; synchronized (s_buffer) { bufferedEvent = s_buffer.peek(); } if (bufferedEvent == null) { - return; + break; } boolean expired = System.currentTimeMillis() - bufferedEvent.third() > bufferExpiry; Connection connection = s_connection; if (!expired && connection == null) { - return; + break; } if (expired) { @@ -367,11 +371,12 @@ private void flushBuffer() { } else { try { sendEvent(connection, bufferedEvent.first(), bufferedEvent.second()); + sent++; } catch (AlreadyClosedException e) { closeConnection(); - return; + break; } catch (IOException e) { - return; // retry with the next run + break; // retry with the next run } catch (Exception e) { logger.warn("Dropping buffered event " + bufferedEvent.first() + " due to " + e.getMessage()); } @@ -384,6 +389,9 @@ private void flushBuffer() { } } } + if (sent > 0) { + logger.info("Sent " + sent + " buffered events to AMQP server"); + } } /** creates a routing key from the event details. From 864308225935e94bb41d943df68d8bd011d54186 Mon Sep 17 00:00:00 2001 From: durdin85 <6603216+durdin85@users.noreply.github.com> Date: Fri, 27 Nov 2026 09:49:42 +0000 Subject: [PATCH 4/6] rabbitmq event bus: address review comments - reconnect and flush from a ScheduledExecutorService instead of a while(true) loop; the task catches Throwable, as the executor silently stops running a task that ended with an exception - loop over the buffer with while ((bufferedEvent = peekBuffer()) != null) - re-register every subscriber whose channel is not open, also when publish() or subscribe() re-established the connection - replace the two duplicated anonymous consumers by SubscriberConsumer - drop the s_ prefix of the fields, fix Javadoc and typos - log when the background thread has reconnected - default retryInterval to 10 s when it is not positive, as scheduleWithFixedDelay rejects such a delay Generated with an AI assistant (Claude Code). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0148pno3o4K3zhvhP3AJaJg3 --- .../mom/rabbitmq/RabbitMQEventBus.java | 370 +++++++++--------- .../mom/rabbitmq/RabbitMQEventBusTest.java | 80 +++- 2 files changed, 268 insertions(+), 182 deletions(-) diff --git a/plugins/event-bus/rabbitmq/src/main/java/org/apache/cloudstack/mom/rabbitmq/RabbitMQEventBus.java b/plugins/event-bus/rabbitmq/src/main/java/org/apache/cloudstack/mom/rabbitmq/RabbitMQEventBus.java index d7742ee32266..5135ed756837 100644 --- a/plugins/event-bus/rabbitmq/src/main/java/org/apache/cloudstack/mom/rabbitmq/RabbitMQEventBus.java +++ b/plugins/event-bus/rabbitmq/src/main/java/org/apache/cloudstack/mom/rabbitmq/RabbitMQEventBus.java @@ -27,8 +27,9 @@ import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import javax.naming.ConfigurationException; @@ -87,27 +88,31 @@ public static void setUseSsl(String useSsl) { private static Integer retryInterval; // max number of events kept in memory while the AMQP server is unreachable, 0 disables buffering - private static Integer bufferSize = 1000; + private static Integer maxEventBufferSize = 1000; // time in milliseconds after which a buffered event is dropped if it could not be sent - private static Integer bufferExpiry = 300000; + private static Integer eventBufferExpiryTime = 300000; - // events (routing key, description, time of buffering) waiting to be sent, oldest first - private static final ArrayDeque> s_buffer = new ArrayDeque<>(); + /** + * events, stored as {routing key, description, time of buffering}, waiting to be sent, oldest first + */ + private static final ArrayDeque> eventBuffer = new ArrayDeque<>(); - // events are buffered only after the AMQP server was reachable at least once - private static volatile boolean s_connectedOnce = false; + /** + * indicates whether a connection has ever been made, as events are buffered only after the AMQP server was reachable at least once + */ + private static volatile boolean hasBeenConnectedOnce = false; // hashmap to book keep the registered subscribers - private static ConcurrentHashMap> s_subscribers; + private static ConcurrentHashMap> subscribers; // connection to AMQP server, - private static volatile Connection s_connection = null; + private static volatile Connection connection = null; // AMQP server should consider messages acknowledged once delivered if _autoAck is true - private static boolean s_autoAck = true; + private static boolean autoAck = true; - private ExecutorService executorService; + private ScheduledExecutorService executorService; private static DisconnectHandler disconnectHandler; private static BlockedConnectionHandler blockedConnectionHandler; @@ -141,7 +146,7 @@ public boolean configure(String name, Map params) throws Configu } } - if (retryInterval == null) { + if (retryInterval == null || retryInterval <= 0) { retryInterval = 10000;// default to 10s to try out reconnect } @@ -149,8 +154,8 @@ public boolean configure(String name, Map params) throws Configu throw new ConfigurationException("Invalid port number/retry interval"); } - s_subscribers = new ConcurrentHashMap>(); - executorService = Executors.newCachedThreadPool(); + subscribers = new ConcurrentHashMap>(); + executorService = Executors.newSingleThreadScheduledExecutor(); disconnectHandler = new DisconnectHandler(); blockedConnectionHandler = new BlockedConnectionHandler(); @@ -190,12 +195,18 @@ public static void setRetryInterval(Integer retryInterval) { RabbitMQEventBus.retryInterval = retryInterval; } + /** + * maximum size to which the event buffer may grow + */ public static void setBufferSize(Integer bufferSize) { - RabbitMQEventBus.bufferSize = bufferSize; + maxEventBufferSize = bufferSize; } + /** + * expiry time, in milliseconds, to set for events that cannot be sent + */ public static void setBufferExpiry(Integer bufferExpiry) { - RabbitMQEventBus.bufferExpiry = bufferExpiry; + eventBufferExpiryTime = bufferExpiry; } /** Call to subscribe to interested set of events @@ -222,44 +233,9 @@ public UUID subscribe(EventTopic topic, EventSubscriber subscriber) throws Event String bindingKey = createBindingKey(topic); // store the subscriber details before creating channel - s_subscribers.put(queueName, new Ternary(bindingKey, null, subscriber)); - - // create a channel dedicated for this subscription - Connection connection = getConnection(); - Channel channel = createChannel(connection); - - // create a queue and bind it to the exchange with binding key formed from event topic - createExchange(channel, amqpExchangeName); - channel.queueDeclare(queueName, false, false, false, null); - channel.queueBind(queueName, amqpExchangeName, bindingKey); - - // register a callback handler to receive the events that a subscriber subscribed to - channel.basicConsume(queueName, s_autoAck, queueName, new DefaultConsumer(channel) { - @Override - public void handleDelivery(String queueName, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { - Ternary queueDetails = s_subscribers.get(queueName); - if (queueDetails != null) { - EventSubscriber subscriber = queueDetails.third(); - String routingKey = envelope.getRoutingKey(); - String eventSource = getEventSourceFromRoutingKey(routingKey); - String eventCategory = getEventCategoryFromRoutingKey(routingKey); - String eventType = getEventTypeFromRoutingKey(routingKey); - String resourceType = getResourceTypeFromRoutingKey(routingKey); - String resourceUUID = getResourceUUIDFromRoutingKey(routingKey); - Event event = new Event(eventSource, eventCategory, eventType, resourceType, resourceUUID); - event.setDescription(new String(body)); - - // deliver the event to call back object provided by subscriber - subscriber.onEvent(event); - } - } - }); - - // update the channel details for the subscription - Ternary queueDetails = s_subscribers.get(queueName); - queueDetails.second(channel); - s_subscribers.put(queueName, queueDetails); + subscribers.put(queueName, new Ternary(bindingKey, null, subscriber)); + registerSubscriber(getConnection(), queueName); } catch (AlreadyClosedException closedException) { logger.warn("Connection to AMQP service is lost. Subscription:" + queueName + " will be active after reconnection", closedException); } catch (ConnectException connectException) { @@ -271,16 +247,55 @@ public void handleDelivery(String queueName, Envelope envelope, AMQP.BasicProper return queueId; } + /** + * creates a queue for the subscriber, binds it to the exchange and registers a consumer that delivers the events to the subscriber + */ + private void registerSubscriber(Connection connection, String queueName) throws Exception { + Ternary subscriberDetails = subscribers.get(queueName); + + // create a channel dedicated for this subscription + Channel channel = createChannel(connection); + + // create a queue and bind it to the exchange with binding key formed from event topic + createExchange(channel, amqpExchangeName); + channel.queueDeclare(queueName, false, false, false, null); + channel.queueBind(queueName, amqpExchangeName, subscriberDetails.first()); + + // register a callback handler to receive the events that a subscriber subscribed to + channel.basicConsume(queueName, autoAck, queueName, new SubscriberConsumer(channel)); + + // update the channel details for the subscription + subscriberDetails.second(channel); + subscribers.put(queueName, subscriberDetails); + } + + /** + * registers the subscribers that have no open channel, i.e. all of them after a loss of connection + */ + private void registerDisconnectedSubscribers(Connection connection) { + for (Map.Entry> entry : subscribers.entrySet()) { + Channel channel = entry.getValue().second(); + if (channel != null && channel.isOpen()) { + continue; + } + try { + registerSubscriber(connection, entry.getKey()); + } catch (Exception e) { + logger.warn("Failed to recreate queues and binding for the subscribers due to " + e.getMessage()); + } + } + } + @Override public void unsubscribe(UUID subscriberId, EventSubscriber subscriber) throws EventBusException { logger.debug("unsubscribing '{}'", subscriberId); try { String classname = subscriber.getClass().getName(); String queueName = UuidUtils.nameUUIDFromBytes(classname.getBytes()).toString(); - Ternary queueDetails = s_subscribers.get(queueName); + Ternary queueDetails = subscribers.get(queueName); Channel channel = queueDetails.second(); channel.basicCancel(queueName); - s_subscribers.remove(queueName, queueDetails); + subscribers.remove(queueName, queueDetails); } catch (Exception e) { throw new EventBusException("Failed to unsubscribe from event bus due to " + e.getMessage()); } @@ -330,39 +345,35 @@ private void sendEvent(Connection connection, String routingKey, String eventDes * @return true if the event was buffered, false if the caller has to deal with it */ private boolean bufferEvent(String routingKey, String eventDescription, boolean sendFailed) { - if (!s_connectedOnce || bufferSize <= 0) { + if (!hasBeenConnectedOnce || maxEventBufferSize <= 0) { return false; } - synchronized (s_buffer) { - if (!sendFailed && s_buffer.isEmpty() && s_connection != null) { + synchronized (eventBuffer) { + if (!sendFailed && eventBuffer.isEmpty() && connection != null) { return false; } - if (s_buffer.isEmpty()) { + if (eventBuffer.isEmpty()) { logger.warn("Unable to send events to AMQP server, buffering them until they can be sent"); } - if (s_buffer.size() >= bufferSize) { - logger.warn("Event buffer is full, dropping the oldest event " + s_buffer.poll().first()); + if (eventBuffer.size() >= maxEventBufferSize) { + logger.warn("Event buffer is full, dropping the oldest event " + eventBuffer.poll().first()); } - s_buffer.add(new Ternary<>(routingKey, eventDescription, System.currentTimeMillis())); + eventBuffer.add(new Ternary<>(routingKey, eventDescription, System.currentTimeMillis())); } return true; } - // drops the expired events and, if connected, sends the buffered ones in the order they were added + /** + * drops the expired events and, if connected, sends the buffered ones in the order they were added. + * Must only be called by the ReconnectionTask: with more than one thread events could be sent twice or out of order. + */ private void flushBuffer() { int sent = 0; - while (true) { - Ternary bufferedEvent; - synchronized (s_buffer) { - bufferedEvent = s_buffer.peek(); - } - if (bufferedEvent == null) { - break; - } - - boolean expired = System.currentTimeMillis() - bufferedEvent.third() > bufferExpiry; - Connection connection = s_connection; - if (!expired && connection == null) { + Ternary bufferedEvent; + while ((bufferedEvent = peekBuffer()) != null) { + boolean expired = System.currentTimeMillis() - bufferedEvent.third() > eventBufferExpiryTime; + Connection currentConnection = connection; + if (!expired && currentConnection == null) { break; } @@ -370,7 +381,7 @@ private void flushBuffer() { logger.warn("Dropping expired event " + bufferedEvent.first() + " as it could not be sent to AMQP server in time"); } else { try { - sendEvent(connection, bufferedEvent.first(), bufferedEvent.second()); + sendEvent(currentConnection, bufferedEvent.first(), bufferedEvent.second()); sent++; } catch (AlreadyClosedException e) { closeConnection(); @@ -383,17 +394,30 @@ private void flushBuffer() { } // the event stays in the buffer while being sent, so that newer events queue up behind it - synchronized (s_buffer) { - if (s_buffer.peek() == bufferedEvent) { - s_buffer.poll(); - } - } + removeFromBuffer(bufferedEvent); } if (sent > 0) { logger.info("Sent " + sent + " buffered events to AMQP server"); } } + private Ternary peekBuffer() { + synchronized (eventBuffer) { + return eventBuffer.peek(); + } + } + + /** + * removes the event if it is still the oldest one, it might have been dropped from a full buffer already + */ + private void removeFromBuffer(Ternary bufferedEvent) { + synchronized (eventBuffer) { + if (eventBuffer.peek() == bufferedEvent) { + eventBuffer.poll(); + } + } + } + /** creates a routing key from the event details. * created routing key will be used while publishing the message to exchange on AMQP server */ @@ -467,7 +491,7 @@ private String createBindingKey(EventTopic topic) { } private synchronized Connection getConnection() throws Exception { - if (s_connection == null) { + if (connection == null) { try { return createConnection(); } catch (KeyManagementException | NoSuchAlgorithmException | IOException | TimeoutException e) { @@ -475,8 +499,26 @@ private synchronized Connection getConnection() throws Exception { throw e; } } else { - return s_connection; + return connection; + } + } + + /** + * @return the current connection, a new one if there was none, or null if the AMQP server cannot be reached + */ + private synchronized Connection connectIfDisconnected() { + if (connection == null) { + try { + Connection newConnection = createConnection(); + logger.info("Connected to AMQP server [AMQP host:{}, port:{}]", amqpHost, port); + return newConnection; + } catch (IOException e) { + logger.trace("Unable to establish connection to AMQP server yet", e); + } catch (Exception e) { + logger.warn("Failed to reconnect to AMQP server due to " + e.getMessage()); + } } + return connection; } private synchronized Connection createConnection() throws KeyManagementException, NoSuchAlgorithmException, IOException, TimeoutException { @@ -495,35 +537,35 @@ private synchronized Connection createConnection() throws KeyManagementException if (useSsl != null && !useSsl.isEmpty() && useSsl.equalsIgnoreCase("true")) { factory.useSslProtocol(secureProtocol); } - Connection connection = factory.newConnection(); - connection.addShutdownListener(disconnectHandler); - connection.addBlockedListener(blockedConnectionHandler); - s_connection = connection; - s_connectedOnce = true; - return s_connection; + Connection newConnection = factory.newConnection(); + newConnection.addShutdownListener(disconnectHandler); + newConnection.addBlockedListener(blockedConnectionHandler); + connection = newConnection; + hasBeenConnectedOnce = true; + return connection; } private synchronized void closeConnection() { try { - if (s_connection != null) { - s_connection.close(); + if (connection != null) { + connection.close(); } } catch (Exception e) { logger.warn("Failed to close connection to AMQP server due to " + e.getMessage()); } - s_connection = null; + connection = null; } private synchronized void abortConnection() { - if (s_connection == null) + if (connection == null) return; try { - s_connection.abort(); + connection.abort(); } catch (Exception e) { logger.warn("Failed to abort connection due to " + e.getMessage()); } - s_connection = null; + connection = null; } private String replaceNullWithWildcard(String key) { @@ -594,16 +636,16 @@ public String getName() { @Override public boolean start() { - ReconnectionTask reconnect = new ReconnectionTask(); // initiate connection to AMQP server - executorService.submit(reconnect); + // initiate connection to AMQP server + executorService.scheduleWithFixedDelay(new ReconnectionTask(), retryInterval, retryInterval, TimeUnit.MILLISECONDS); return true; } @Override public synchronized boolean stop() { - if (s_connection != null && s_connection.isOpen()) { - for (String subscriberId : s_subscribers.keySet()) { - Ternary subscriberDetails = s_subscribers.get(subscriberId); + if (connection != null && connection.isOpen()) { + for (String subscriberId : subscribers.keySet()) { + Ternary subscriberDetails = subscribers.get(subscriberId); Channel channel = subscriberDetails.second(); String queueName = subscriberId; try { @@ -642,98 +684,72 @@ private class DisconnectHandler implements ShutdownListener { public void shutdownCompleted(ShutdownSignalException shutdownSignalException) { if (!shutdownSignalException.isInitiatedByApplication()) { - for (String subscriberId : s_subscribers.keySet()) { - Ternary subscriberDetails = s_subscribers.get(subscriberId); + for (String subscriberId : subscribers.keySet()) { + Ternary subscriberDetails = subscribers.get(subscriberId); subscriberDetails.second(null); - s_subscribers.put(subscriberId, subscriberDetails); + subscribers.put(subscriberId, subscriberDetails); } abortConnection(); // disconnected to AMQP server, so abort the connection and channels - // the ReconnectionTask started with the event bus takes care of the re-connect logger.warn("Connection has been shutdown by AMQP server. Attempting to reconnect."); } } } - // runs for the lifetime of the event bus: connects back to AMQP server after any loss of connection - // and sends the events buffered in the meantime - private class ReconnectionTask extends ManagedContextRunnable { + /** + * delivers the events received from AMQP server to the subscriber + */ + private class SubscriberConsumer extends DefaultConsumer { - Connection connection = null; + SubscriberConsumer(Channel channel) { + super(channel); + } @Override - protected void runInContext() { + public void handleDelivery(String queueName, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { + Ternary subscriberDetails = subscribers.get(queueName); // queue name == subscriber ID + if (subscriberDetails != null) { + EventSubscriber subscriber = subscriberDetails.third(); + String routingKey = envelope.getRoutingKey(); + String eventSource = getEventSourceFromRoutingKey(routingKey); + String eventCategory = getEventCategoryFromRoutingKey(routingKey); + String eventType = getEventTypeFromRoutingKey(routingKey); + String resourceType = getResourceTypeFromRoutingKey(routingKey); + String resourceUUID = getResourceUUIDFromRoutingKey(routingKey); + + // create event object from the message details obtained from AMQP server + Event event = new Event(eventSource, eventCategory, eventType, resourceType, resourceUUID); + event.setDescription(new String(body)); + + // deliver the event to call back object provided by subscriber + subscriber.onEvent(event); + } + } + } - while (true) { - try { - Thread.sleep(retryInterval); - } catch (InterruptedException ie) { - return; // event bus is being stopped - } + /** + * scheduled for the lifetime of the event bus: connects back to AMQP server after any loss of connection + * and sends the events buffered in the meantime + */ + private class ReconnectionTask extends ManagedContextRunnable { - try { - flushBuffer(); - try { - // check and connect under the same lock as getConnection(), so a connection is never replaced - synchronized (RabbitMQEventBus.this) { - if (s_connection != null) { - continue; - } - connection = createConnection(); - } - } catch (IOException ie) { - continue; // can't establish connection to AMQP server yet, so continue - } - - // prepare consumer on AMQP server for each of subscriber - for (String subscriberId : s_subscribers.keySet()) { - Ternary subscriberDetails = s_subscribers.get(subscriberId); - String bindingKey = subscriberDetails.first(); - EventSubscriber subscriber = subscriberDetails.third(); - - /** create a queue with subscriber ID as queue name and bind it to the exchange - * with binding key formed from event topic - */ - Channel channel = createChannel(connection); - createExchange(channel, amqpExchangeName); - channel.queueDeclare(subscriberId, false, false, false, null); - channel.queueBind(subscriberId, amqpExchangeName, bindingKey); - - // register a callback handler to receive the events that a subscriber subscribed to - channel.basicConsume(subscriberId, s_autoAck, subscriberId, new DefaultConsumer(channel) { - @Override - public void handleDelivery(String queueName, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { - - Ternary subscriberDetails = s_subscribers.get(queueName); // queue name == subscriber ID - - if (subscriberDetails != null) { - EventSubscriber subscriber = subscriberDetails.third(); - String routingKey = envelope.getRoutingKey(); - String eventSource = getEventSourceFromRoutingKey(routingKey); - String eventCategory = getEventCategoryFromRoutingKey(routingKey); - String eventType = getEventTypeFromRoutingKey(routingKey); - String resourceType = getResourceTypeFromRoutingKey(routingKey); - String resourceUUID = getResourceUUIDFromRoutingKey(routingKey); - - // create event object from the message details obtained from AMQP server - Event event = new Event(eventSource, eventCategory, eventType, resourceType, resourceUUID); - event.setDescription(new String(body)); - - // deliver the event to call back object provided by subscriber - subscriber.onEvent(event); - } - } - }); - - // update the channel details for the subscription - subscriberDetails.second(channel); - s_subscribers.put(subscriberId, subscriberDetails); - } - flushBuffer(); - } catch (Exception e) { - logger.warn("Failed to recreate queues and binding for the subscribers due to " + e.getMessage()); - } + @Override + public void run() { + try { + super.run(); + } catch (Throwable t) { + // the executor would never run the task again if it ended with an exception + logger.error("Failed to reconnect to AMQP server or to send buffered events", t); + } + } + + @Override + protected void runInContext() { + Connection currentConnection = connectIfDisconnected(); + if (currentConnection != null) { + registerDisconnectedSubscribers(currentConnection); } + flushBuffer(); } } } diff --git a/plugins/event-bus/rabbitmq/src/test/java/org/apache/cloudstack/mom/rabbitmq/RabbitMQEventBusTest.java b/plugins/event-bus/rabbitmq/src/test/java/org/apache/cloudstack/mom/rabbitmq/RabbitMQEventBusTest.java index 281e461575d8..98613e513fe6 100644 --- a/plugins/event-bus/rabbitmq/src/test/java/org/apache/cloudstack/mom/rabbitmq/RabbitMQEventBusTest.java +++ b/plugins/event-bus/rabbitmq/src/test/java/org/apache/cloudstack/mom/rabbitmq/RabbitMQEventBusTest.java @@ -18,19 +18,28 @@ package org.apache.cloudstack.mom.rabbitmq; import java.io.IOException; +import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayDeque; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; import org.apache.cloudstack.framework.events.Event; import org.apache.cloudstack.framework.events.EventBusException; +import org.apache.cloudstack.framework.events.EventSubscriber; +import org.apache.cloudstack.managed.context.ManagedContext; +import org.apache.cloudstack.managed.context.ManagedContextRunnable; import org.junit.After; +import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentMatchers; import org.mockito.InOrder; import org.mockito.Mockito; +import com.cloud.utils.Ternary; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; @@ -39,6 +48,7 @@ public class RabbitMQEventBusTest { private RabbitMQEventBus eventBus; private Connection connection; private Channel channel; + private ConcurrentHashMap> subscribers; @Before public void setUp() throws Exception { @@ -51,15 +61,17 @@ public void setUp() throws Exception { connection = Mockito.mock(Connection.class); Mockito.when(connection.createChannel()).thenReturn(channel); - ((ArrayDeque)getField("s_buffer").get(null)).clear(); + subscribers = new ConcurrentHashMap<>(); + getField("subscribers").set(null, subscribers); + ((ArrayDeque)getField("eventBuffer").get(null)).clear(); setConnection(null); - getField("s_connectedOnce").set(null, true); + getField("hasBeenConnectedOnce").set(null, true); } @After public void tearDown() throws Exception { setConnection(null); - getField("s_connectedOnce").set(null, false); + getField("hasBeenConnectedOnce").set(null, false); } private Field getField(String name) throws Exception { @@ -69,7 +81,7 @@ private Field getField(String name) throws Exception { } private void setConnection(Connection connection) throws Exception { - getField("s_connection").set(null, connection); + getField("connection").set(null, connection); } private void flushBuffer() throws Exception { @@ -78,6 +90,16 @@ private void flushBuffer() throws Exception { method.invoke(eventBus); } + private Runnable reconnectionTask() throws Exception { + Constructor constructor = Class.forName(RabbitMQEventBus.class.getName() + "$ReconnectionTask").getDeclaredConstructor(RabbitMQEventBus.class); + constructor.setAccessible(true); + return (Runnable)constructor.newInstance(eventBus); + } + + private void addSubscriber(String queueName, Channel subscriberChannel) { + subscribers.put(queueName, new Ternary<>("#", subscriberChannel, Mockito.mock(EventSubscriber.class))); + } + private Event event(String description) { Event event = new Event("server", "ActionEvent", "VM.START", "VirtualMachine", "uuid"); event.setDescription(description); @@ -96,7 +118,7 @@ private void verifyPublishedCount(int count) throws IOException { @Test(expected = EventBusException.class) public void publishFailsWhenBrokerWasNeverReachable() throws Exception { - getField("s_connectedOnce").set(null, false); + getField("hasBeenConnectedOnce").set(null, false); RabbitMQEventBus.setServer("localhost"); RabbitMQEventBus.setPort(1); RabbitMQEventBus.setUsername("guest"); @@ -164,4 +186,52 @@ public void expiredEventsAreDropped() throws Exception { flushBuffer(); Mockito.verifyNoInteractions(channel); } + + @Test + public void onlySubscribersWithoutOpenChannelAreRegistered() throws Exception { + Channel openChannel = Mockito.mock(Channel.class); + Mockito.when(openChannel.isOpen()).thenReturn(true); + addSubscriber("open", openChannel); + addSubscriber("closed", Mockito.mock(Channel.class)); + addSubscriber("none", null); + setConnection(connection); // e.g. connected by subscribe() and not by the task itself + + reconnectionTask().run(); + + Mockito.verify(channel).queueBind("closed", "cloudstack-events", "#"); + Mockito.verify(channel).queueBind("none", "cloudstack-events", "#"); + Mockito.verify(channel, Mockito.never()).queueBind(ArgumentMatchers.eq("open"), ArgumentMatchers.anyString(), ArgumentMatchers.anyString()); + Assert.assertSame(openChannel, subscribers.get("open").second()); + Assert.assertSame(channel, subscribers.get("none").second()); + } + + @Test + public void bufferedEventsAreSentEvenIfSubscriberCannotBeRegistered() throws Exception { + addSubscriber("failing", null); + Mockito.when(channel.queueBind(ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), ArgumentMatchers.anyString())) + .thenThrow(new IOException("bind failed")); + eventBus.publish(event("1")); + setConnection(connection); + + reconnectionTask().run(); + verifyPublishedCount(1); + } + + @Test + public void reconnectionTaskKeepsRunningAfterUnexpectedFailure() throws Exception { + ManagedContext context = Mockito.mock(ManagedContext.class); + Mockito.doThrow(new IllegalStateException("context failure")).when(context).runWithContext(ArgumentMatchers.any()); + ManagedContextRunnable.initializeGlobalContext(context); + ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); + getField("executorService").set(eventBus, executorService); + RabbitMQEventBus.setRetryInterval(10); + try { + eventBus.start(); + Mockito.verify(context, Mockito.timeout(5000).atLeast(3)).runWithContext(ArgumentMatchers.any()); + } finally { + eventBus.stop(); + ManagedContextRunnable.setManagedContext(false); + } + Assert.assertTrue(executorService.isShutdown()); + } } From 06a68f485367e36ddbb549cf74bbdd55faed2e16 Mon Sep 17 00:00:00 2001 From: durdin85 <6603216+durdin85@users.noreply.github.com> Date: Fri, 27 Nov 2026 13:43:18 +0000 Subject: [PATCH 5/6] rabbitmq event bus: notice dead connections sooner, never resend a published event - request a heartbeat timeout of 10 s (bean property heartbeat) instead of the client default of 60 s: a connection that silently stopped working is noticed only after about two heartbeat timeouts, and until then events are sent on the API thread and wait for replies - count an event as sent once basicPublish() has returned; a failure to close the channel afterwards is only logged, as the broker may have the event already and sending it again could duplicate it - log the causes of AMQP client exceptions instead of "null" - document the bean properties on their setters Tested on a 4.22.1.1 management server against RabbitMQ 4.4.0, with outages simulated by iptables (connection reset and dropped packets). Generated with an AI assistant (Claude Code). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0148pno3o4K3zhvhP3AJaJg3 --- .../mom/rabbitmq/RabbitMQEventBus.java | 67 +++++++++++++++++-- .../mom/rabbitmq/RabbitMQEventBusTest.java | 30 +++++++++ 2 files changed, 91 insertions(+), 6 deletions(-) diff --git a/plugins/event-bus/rabbitmq/src/main/java/org/apache/cloudstack/mom/rabbitmq/RabbitMQEventBus.java b/plugins/event-bus/rabbitmq/src/main/java/org/apache/cloudstack/mom/rabbitmq/RabbitMQEventBus.java index 5135ed756837..82552e390c69 100644 --- a/plugins/event-bus/rabbitmq/src/main/java/org/apache/cloudstack/mom/rabbitmq/RabbitMQEventBus.java +++ b/plugins/event-bus/rabbitmq/src/main/java/org/apache/cloudstack/mom/rabbitmq/RabbitMQEventBus.java @@ -93,6 +93,15 @@ public static void setUseSsl(String useSsl) { // time in milliseconds after which a buffered event is dropped if it could not be sent private static Integer eventBufferExpiryTime = 300000; + /** + * heartbeat timeout, in seconds, requested from the AMQP server, which may lower it; 0 takes the value of the server. + * The client notices a connection that silently stopped working (e.g. packets dropped by a firewall) only after about + * two heartbeat timeouts without any data from the server. Until then events are still sent on the calling thread and + * wait for replies that never come, so with the client default of 60 seconds API calls could hang for about 2 minutes. + * RabbitMQ recommends values between 5 and 20 seconds. + */ + private static Integer heartbeat = 10; + /** * events, stored as {routing key, description, time of buffering}, waiting to be sent, oldest first */ @@ -109,7 +118,7 @@ public static void setUseSsl(String useSsl) { // connection to AMQP server, private static volatile Connection connection = null; - // AMQP server should consider messages acknowledged once delivered if _autoAck is true + // AMQP server should consider messages acknowledged once delivered if autoAck is true private static boolean autoAck = true; private ScheduledExecutorService executorService; @@ -191,24 +200,42 @@ public static void setExchange(String exchange) { RabbitMQEventBus.amqpExchangeName = exchange; } + /** + * time, in milliseconds, between two runs of the ReconnectionTask, set by the bean property "retryInterval". + * Default 10000 (10 seconds), also used for values of 0 or less. Each run reconnects if needed, drops the expired + * events and sends the buffered ones. + */ public static void setRetryInterval(Integer retryInterval) { RabbitMQEventBus.retryInterval = retryInterval; } /** - * maximum size to which the event buffer may grow + * maximum size to which the event buffer may grow, set by the bean property "bufferSize". + * Default 1000; when the buffer is full, the oldest event is dropped. 0 disables buffering: events that cannot be + * sent are dropped and publish() connects on the calling thread, as before buffering was added. */ public static void setBufferSize(Integer bufferSize) { maxEventBufferSize = bufferSize; } /** - * expiry time, in milliseconds, to set for events that cannot be sent + * expiry time, in milliseconds, to set for events that cannot be sent, set by the bean property "bufferExpiry". + * Default 300000 (5 minutes). Expired events are dropped by the next run of the ReconnectionTask, also while the + * AMQP server is unreachable, so an event is kept for at most bufferExpiry plus retryInterval. */ public static void setBufferExpiry(Integer bufferExpiry) { eventBufferExpiryTime = bufferExpiry; } + /** + * heartbeat timeout, in seconds, to request from the AMQP server, set by the bean property "heartbeat". + * Default 10; 0 takes the value of the server. A lower value notices a connection that silently stopped working + * sooner, see the field heartbeat for the reasoning. + */ + public static void setHeartbeat(Integer heartbeat) { + RabbitMQEventBus.heartbeat = heartbeat; + } + /** Call to subscribe to interested set of events * * @param topic defines category and type of the events being subscribed to @@ -332,11 +359,22 @@ public void publish(Event event) throws EventBusException { } } + /** + * sends the event on a channel of its own. Once basicPublish() has returned, the event counts as sent even if closing the + * channel fails: publishing gets no reply, so the event may already have reached the AMQP server and sending it again could + * duplicate it. Losing it instead is the same as losing an event still in the TCP send buffer when the connection breaks. + * This also covers events the AMQP server refused, e.g. due to missing write permissions on the exchange: the refusal is + * reported only when the channel is closed, and sending such an event again would fail the same way. + */ private void sendEvent(Connection connection, String routingKey, String eventDescription) throws Exception { Channel channel = createChannel(connection); createExchange(channel, amqpExchangeName); publishEventToExchange(channel, amqpExchangeName, routingKey, eventDescription); - channel.close(); + try { + channel.close(); + } catch (Exception e) { + logger.warn("Failed to close the channel after publishing event " + routingKey + ", the event might not have been delivered: " + getErrorMessage(e)); + } } /** adds the event to the buffer, dropping the oldest one if the buffer is full @@ -527,6 +565,7 @@ private synchronized Connection createConnection() throws KeyManagementException factory.setPassword(password); factory.setHost(amqpHost); factory.setPort(port); + factory.setRequestedHeartbeat(heartbeat); if (virtualHost != null && !virtualHost.isEmpty()) { factory.setVirtualHost(virtualHost); @@ -580,11 +619,27 @@ private Channel createChannel(Connection connection) throws Exception { try { return connection.createChannel(); } catch (java.io.IOException exception) { - logger.warn("Failed to create a channel due to " + exception.getMessage()); + logger.warn("Failed to create a channel due to " + getErrorMessage(exception)); throw exception; } } + /** + * @return the messages of the exception and of its causes. The AMQP client reports a lost connection as an IOException + * without a message, wrapping a ShutdownSignalException ("connection error") that in turn wraps the actual reason, e.g. + * "Connection reset" or "Heartbeat missing", so logging only getMessage() showed "null". + */ + private static String getErrorMessage(Throwable exception) { + StringBuilder message = new StringBuilder(); + for (Throwable cause = exception; cause != null; cause = cause.getCause()) { + // skip messages already included, e.g. by exceptions created with the cause as their message + if (cause.getMessage() != null && message.indexOf(cause.getMessage()) < 0) { + message.append(message.length() > 0 ? ": " : "").append(cause.getMessage()); + } + } + return message.length() > 0 ? message.toString() : exception.toString(); + } + private void createExchange(Channel channel, String exchangeName) throws Exception { try { channel.exchangeDeclare(exchangeName, "topic", true); @@ -599,7 +654,7 @@ private void publishEventToExchange(Channel channel, String exchangeName, String byte[] messageBodyBytes = eventDescription.getBytes(); channel.basicPublish(exchangeName, routingKey, MessageProperties.PERSISTENT_TEXT_PLAIN, messageBodyBytes); } catch (Exception e) { - logger.error("Failed to publish event " + routingKey + " on exchange " + exchangeName + " of message broker due to " + e.getMessage()); + logger.error("Failed to publish event " + routingKey + " on exchange " + exchangeName + " of message broker due to " + getErrorMessage(e)); throw e; } } diff --git a/plugins/event-bus/rabbitmq/src/test/java/org/apache/cloudstack/mom/rabbitmq/RabbitMQEventBusTest.java b/plugins/event-bus/rabbitmq/src/test/java/org/apache/cloudstack/mom/rabbitmq/RabbitMQEventBusTest.java index 98613e513fe6..c9efab5ff004 100644 --- a/plugins/event-bus/rabbitmq/src/test/java/org/apache/cloudstack/mom/rabbitmq/RabbitMQEventBusTest.java +++ b/plugins/event-bus/rabbitmq/src/test/java/org/apache/cloudstack/mom/rabbitmq/RabbitMQEventBusTest.java @@ -21,6 +21,7 @@ import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; +import java.net.SocketException; import java.util.ArrayDeque; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executors; @@ -42,6 +43,7 @@ import com.cloud.utils.Ternary; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; +import com.rabbitmq.client.ShutdownSignalException; public class RabbitMQEventBusTest { @@ -161,6 +163,34 @@ public void eventIsBufferedWhenSendingFails() throws Exception { verifyPublishedCount(2); } + @Test + public void eventIsNotSentAgainWhenClosingTheChannelFails() throws Exception { + setConnection(connection); + Mockito.doThrow(new IOException()).doNothing().when(channel).close(); + + eventBus.publish(event("1")); + flushBuffer(); + Assert.assertTrue(((ArrayDeque)getField("eventBuffer").get(null)).isEmpty()); + verifyPublishedCount(1); + + eventBus.publish(event("2")); // nothing buffered, sent directly + verifyPublishedCount(2); + } + + @Test + public void errorMessageIncludesTheCauses() throws Exception { + Method method = RabbitMQEventBus.class.getDeclaredMethod("getErrorMessage", Throwable.class); + method.setAccessible(true); + ShutdownSignalException shutdown = new ShutdownSignalException(true, false, null, connection); + shutdown.initCause(new SocketException("Connection reset")); + IOException exception = new IOException(); + exception.initCause(shutdown); + + Assert.assertEquals("connection error: Connection reset", method.invoke(null, exception)); + Assert.assertEquals("java.net.SocketException: broken pipe", method.invoke(null, new IOException(new SocketException("broken pipe")))); + Assert.assertEquals("java.io.IOException", method.invoke(null, new IOException())); + } + @Test public void oldestEventIsDroppedWhenBufferIsFull() throws Exception { RabbitMQEventBus.setBufferSize(2); From 355fcfa61d57d9ee85d23266119046309750534e Mon Sep 17 00:00:00 2001 From: durdin85 <6603216+durdin85@users.noreply.github.com> Date: Fri, 4 Dec 2026 12:12:07 +0000 Subject: [PATCH 6/6] rabbitmq event bus: trim and clarify comments Comment changes only, as suggested in the review: drop comments that repeat the code, turn the buffer limit comments into Javadoc and reword the comment in flushBuffer() that read as contradicting the code below it. The compiled bytecode is unchanged. Generated with an AI assistant (Claude Code). Co-Authored-By: Claude Opus 5.5 --- .../mom/rabbitmq/RabbitMQEventBus.java | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/plugins/event-bus/rabbitmq/src/main/java/org/apache/cloudstack/mom/rabbitmq/RabbitMQEventBus.java b/plugins/event-bus/rabbitmq/src/main/java/org/apache/cloudstack/mom/rabbitmq/RabbitMQEventBus.java index 82552e390c69..e6797d4e6a4d 100644 --- a/plugins/event-bus/rabbitmq/src/main/java/org/apache/cloudstack/mom/rabbitmq/RabbitMQEventBus.java +++ b/plugins/event-bus/rabbitmq/src/main/java/org/apache/cloudstack/mom/rabbitmq/RabbitMQEventBus.java @@ -87,10 +87,14 @@ public static void setUseSsl(String useSsl) { private static Integer retryInterval; - // max number of events kept in memory while the AMQP server is unreachable, 0 disables buffering + /** + * max number of events kept in memory while the AMQP server is unreachable, 0 disables buffering + */ private static Integer maxEventBufferSize = 1000; - // time in milliseconds after which a buffered event is dropped if it could not be sent + /** + * time in milliseconds after which a buffered event is dropped if it could not be sent + */ private static Integer eventBufferExpiryTime = 300000; /** @@ -280,10 +284,8 @@ public UUID subscribe(EventTopic topic, EventSubscriber subscriber) throws Event private void registerSubscriber(Connection connection, String queueName) throws Exception { Ternary subscriberDetails = subscribers.get(queueName); - // create a channel dedicated for this subscription Channel channel = createChannel(connection); - // create a queue and bind it to the exchange with binding key formed from event topic createExchange(channel, amqpExchangeName); channel.queueDeclare(queueName, false, false, false, null); channel.queueBind(queueName, amqpExchangeName, subscriberDetails.first()); @@ -291,7 +293,6 @@ private void registerSubscriber(Connection connection, String queueName) throws // register a callback handler to receive the events that a subscriber subscribed to channel.basicConsume(queueName, autoAck, queueName, new SubscriberConsumer(channel)); - // update the channel details for the subscription subscriberDetails.second(channel); subscribers.put(queueName, subscriberDetails); } @@ -336,8 +337,8 @@ public void publish(Event event) throws EventBusException { String routingKey = createRoutingKey(event); String eventDescription = event.getDescription(); - // keep the order: nothing is sent directly while older events are waiting or the connection is down if (bufferEvent(routingKey, eventDescription, false)) { + // keep the order: nothing is sent directly while older events are waiting or the connection is down, so return if buffering succeeds. return; } @@ -431,7 +432,7 @@ private void flushBuffer() { } } - // the event stays in the buffer while being sent, so that newer events queue up behind it + // removed only now: while it was being sent, the event stayed in the buffer so that newer events queued up behind it removeFromBuffer(bufferedEvent); } if (sent > 0) { @@ -632,7 +633,6 @@ private Channel createChannel(Connection connection) throws Exception { private static String getErrorMessage(Throwable exception) { StringBuilder message = new StringBuilder(); for (Throwable cause = exception; cause != null; cause = cause.getCause()) { - // skip messages already included, e.g. by exceptions created with the cause as their message if (cause.getMessage() != null && message.indexOf(cause.getMessage()) < 0) { message.append(message.length() > 0 ? ": " : "").append(cause.getMessage()); } @@ -691,7 +691,6 @@ public String getName() { @Override public boolean start() { - // initiate connection to AMQP server executorService.scheduleWithFixedDelay(new ReconnectionTask(), retryInterval, retryInterval, TimeUnit.MILLISECONDS); return true; } @@ -772,11 +771,9 @@ public void handleDelivery(String queueName, Envelope envelope, AMQP.BasicProper String resourceType = getResourceTypeFromRoutingKey(routingKey); String resourceUUID = getResourceUUIDFromRoutingKey(routingKey); - // create event object from the message details obtained from AMQP server Event event = new Event(eventSource, eventCategory, eventType, resourceType, resourceUUID); event.setDescription(new String(body)); - // deliver the event to call back object provided by subscriber subscriber.onEvent(event); } }