DaanHoogland commented on code in PR #14677:
URL: https://github.com/apache/cloudstack/pull/14677#discussion_r4754608191


##########
plugins/event-bus/rabbitmq/src/main/java/org/apache/cloudstack/mom/rabbitmq/RabbitMQEventBus.java:
##########
@@ -85,16 +87,41 @@ 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

Review Comment:
   ```suggestion
       /**
        * max number of events kept in memory while the AMQP server is 
unreachable, 0 disables buffering
        */
   ```



##########
plugins/event-bus/rabbitmq/src/main/java/org/apache/cloudstack/mom/rabbitmq/RabbitMQEventBus.java:
##########
@@ -85,16 +87,41 @@ 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 maxEventBufferSize = 1000;
+
+    // time in milliseconds after which a buffered event is dropped if it 
could not be sent

Review Comment:
   ```suggestion
       /**
        * time in milliseconds after which a buffered event is dropped if it 
could not be sent
        */
   ```



##########
plugins/event-bus/rabbitmq/src/main/java/org/apache/cloudstack/mom/rabbitmq/RabbitMQEventBus.java:
##########
@@ -250,16 +274,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<String, Channel, EventSubscriber> subscriberDetails = 
subscribers.get(queueName);
+
+        // create a channel dedicated for this subscription

Review Comment:
   ```suggestion
   ```



##########
plugins/event-bus/rabbitmq/src/main/java/org/apache/cloudstack/mom/rabbitmq/RabbitMQEventBus.java:
##########
@@ -250,16 +274,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<String, Channel, EventSubscriber> 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

Review Comment:
   ```suggestion
   ```



##########
plugins/event-bus/rabbitmq/src/main/java/org/apache/cloudstack/mom/rabbitmq/RabbitMQEventBus.java:
##########
@@ -250,16 +274,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<String, Channel, EventSubscriber> 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

Review Comment:
   ```suggestion
   ```



##########
plugins/event-bus/rabbitmq/src/main/java/org/apache/cloudstack/mom/rabbitmq/RabbitMQEventBus.java:
##########
@@ -273,20 +336,126 @@ 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());
         }
     }
 
+    /**
+     * 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);
+        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
+     *
+     * @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 (!hasBeenConnectedOnce || maxEventBufferSize <= 0) {
+            return false;
+        }
+        synchronized (eventBuffer) {
+            if (!sendFailed && eventBuffer.isEmpty() && connection != null) {
+                return false;
+            }
+            if (eventBuffer.isEmpty()) {
+                logger.warn("Unable to send events to AMQP server, buffering 
them until they can be sent");
+            }
+            if (eventBuffer.size() >= maxEventBufferSize) {
+                logger.warn("Event buffer is full, dropping the oldest event " 
+ eventBuffer.poll().first());
+            }
+            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.
+     * 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;
+        Ternary<String, String, Long> bufferedEvent;
+        while ((bufferedEvent = peekBuffer()) != null) {
+            boolean expired = System.currentTimeMillis() - 
bufferedEvent.third() > eventBufferExpiryTime;
+            Connection currentConnection = connection;
+            if (!expired && currentConnection == null) {
+                break;
+            }
+
+            if (expired) {
+                logger.warn("Dropping expired event " + bufferedEvent.first() 
+ " as it could not be sent to AMQP server in time");
+            } else {
+                try {
+                    sendEvent(currentConnection, bufferedEvent.first(), 
bufferedEvent.second());
+                    sent++;
+                } catch (AlreadyClosedException e) {
+                    closeConnection();
+                    break;
+                } catch (IOException e) {
+                    break; // 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

Review Comment:
   this one seems contradictory to the code below it. can you revise the 
comment?



##########
plugins/event-bus/rabbitmq/src/main/java/org/apache/cloudstack/mom/rabbitmq/RabbitMQEventBus.java:
##########
@@ -273,20 +336,126 @@ 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;
+        }

Review Comment:
   ```suggestion
           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;
           }
   ```



##########
plugins/event-bus/rabbitmq/src/main/java/org/apache/cloudstack/mom/rabbitmq/RabbitMQEventBus.java:
##########
@@ -430,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

Review Comment:
   ```suggestion
   ```



##########
plugins/event-bus/rabbitmq/src/main/java/org/apache/cloudstack/mom/rabbitmq/RabbitMQEventBus.java:
##########
@@ -533,95 +739,72 @@ private class DisconnectHandler implements 
ShutdownListener {
         public void shutdownCompleted(ShutdownSignalException 
shutdownSignalException) {
             if (!shutdownSignalException.isInitiatedByApplication()) {
 
-                for (String subscriberId : s_subscribers.keySet()) {
-                    Ternary<String, Channel, EventSubscriber> 
subscriberDetails = s_subscribers.get(subscriberId);
+                for (String subscriberId : subscribers.keySet()) {
+                    Ternary<String, Channel, EventSubscriber> 
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
                 logger.warn("Connection has been shutdown by AMQP server. 
Attempting to reconnect.");
+            }
+        }
+    }
+
+    /**
+     * delivers the events received from AMQP server to the subscriber
+     */
+    private class SubscriberConsumer extends DefaultConsumer {
 
-                // initiate re-connect process
-                ReconnectionTask reconnect = new ReconnectionTask();
-                executorService.submit(reconnect);
+        SubscriberConsumer(Channel channel) {
+            super(channel);
+        }
+
+        @Override
+        public void handleDelivery(String queueName, Envelope envelope, 
AMQP.BasicProperties properties, byte[] body) throws IOException {
+            Ternary<String, Channel, EventSubscriber> 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

Review Comment:
   ```suggestion
   ```



##########
plugins/event-bus/rabbitmq/src/main/java/org/apache/cloudstack/mom/rabbitmq/RabbitMQEventBus.java:
##########
@@ -486,16 +691,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

Review Comment:
   ```suggestion
   ```



##########
plugins/event-bus/rabbitmq/src/main/java/org/apache/cloudstack/mom/rabbitmq/RabbitMQEventBus.java:
##########
@@ -533,95 +739,72 @@ private class DisconnectHandler implements 
ShutdownListener {
         public void shutdownCompleted(ShutdownSignalException 
shutdownSignalException) {
             if (!shutdownSignalException.isInitiatedByApplication()) {
 
-                for (String subscriberId : s_subscribers.keySet()) {
-                    Ternary<String, Channel, EventSubscriber> 
subscriberDetails = s_subscribers.get(subscriberId);
+                for (String subscriberId : subscribers.keySet()) {
+                    Ternary<String, Channel, EventSubscriber> 
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
                 logger.warn("Connection has been shutdown by AMQP server. 
Attempting to reconnect.");
+            }
+        }
+    }
+
+    /**
+     * delivers the events received from AMQP server to the subscriber
+     */
+    private class SubscriberConsumer extends DefaultConsumer {
 
-                // initiate re-connect process
-                ReconnectionTask reconnect = new ReconnectionTask();
-                executorService.submit(reconnect);
+        SubscriberConsumer(Channel channel) {
+            super(channel);
+        }
+
+        @Override
+        public void handleDelivery(String queueName, Envelope envelope, 
AMQP.BasicProperties properties, byte[] body) throws IOException {
+            Ternary<String, Channel, EventSubscriber> 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

Review Comment:
   ```suggestion
   ```



##########
plugins/event-bus/rabbitmq/src/main/java/org/apache/cloudstack/mom/rabbitmq/RabbitMQEventBus.java:
##########
@@ -533,95 +739,72 @@ private class DisconnectHandler implements 
ShutdownListener {
         public void shutdownCompleted(ShutdownSignalException 
shutdownSignalException) {
             if (!shutdownSignalException.isInitiatedByApplication()) {
 
-                for (String subscriberId : s_subscribers.keySet()) {
-                    Ternary<String, Channel, EventSubscriber> 
subscriberDetails = s_subscribers.get(subscriberId);
+                for (String subscriberId : subscribers.keySet()) {
+                    Ternary<String, Channel, EventSubscriber> 
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
                 logger.warn("Connection has been shutdown by AMQP server. 
Attempting to reconnect.");
+            }
+        }
+    }
+
+    /**
+     * delivers the events received from AMQP server to the subscriber
+     */
+    private class SubscriberConsumer extends DefaultConsumer {
 
-                // initiate re-connect process
-                ReconnectionTask reconnect = new ReconnectionTask();
-                executorService.submit(reconnect);
+        SubscriberConsumer(Channel channel) {
+            super(channel);
+        }
+
+        @Override
+        public void handleDelivery(String queueName, Envelope envelope, 
AMQP.BasicProperties properties, byte[] body) throws IOException {
+            Ternary<String, Channel, EventSubscriber> 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);
             }
         }
     }
 
-    // retry logic to connect back to AMQP server after loss of connection
+    /**
+     * 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 {
 
-        boolean connected = false;
-        Connection connection = null;
+        @Override
+        public void run() {
+            try {
+                super.run();
+            } catch (Throwable t) {
+                // the executor would never run the task again if it ended 
with an exception

Review Comment:
   ```suggestion
   ```
   I agree but on the other hand `Throwable` is a very wide net. If you feel it 
is needed...



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to