Search in sources :

Example 1 with EventBusException

use of org.apache.cloudstack.framework.events.EventBusException in project cloudstack by apache.

the class UsageEventUtils method publishUsageEvent.

private static void publishUsageEvent(String usageEventType, Long accountId, Long zoneId, String resourceType, String resourceUUID) {
    String configKey = "publish.usage.events";
    String value = s_configDao.getValue(configKey);
    boolean configValue = Boolean.parseBoolean(value);
    if (!configValue)
        return;
    try {
        s_eventBus = ComponentContext.getComponent(EventBus.class);
    } catch (NoSuchBeanDefinitionException nbe) {
        // no provider is configured to provide events bus, so just return
        return;
    }
    Account account = s_accountDao.findById(accountId);
    DataCenterVO dc = s_dcDao.findById(zoneId);
    // if account has been deleted, this might be called during cleanup of resources and results in null pointer
    if (account == null)
        return;
    // if an invalid zone is passed in, create event without zone UUID
    String zoneUuid = null;
    if (dc != null)
        zoneUuid = dc.getUuid();
    Event event = new Event(Name, EventCategory.USAGE_EVENT.getName(), usageEventType, resourceType, resourceUUID);
    Map<String, String> eventDescription = new HashMap<String, String>();
    eventDescription.put("account", account.getUuid());
    eventDescription.put("zone", zoneUuid);
    eventDescription.put("event", usageEventType);
    eventDescription.put("resource", resourceType);
    eventDescription.put("id", resourceUUID);
    String eventDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z").format(new Date());
    eventDescription.put("eventDateTime", eventDate);
    event.setDescription(eventDescription);
    try {
        s_eventBus.publish(event);
    } catch (EventBusException e) {
        s_logger.warn("Failed to publish usage event on the the event bus.");
    }
}
Also used : DataCenterVO(com.cloud.dc.DataCenterVO) Account(com.cloud.user.Account) HashMap(java.util.HashMap) Event(org.apache.cloudstack.framework.events.Event) EventBusException(org.apache.cloudstack.framework.events.EventBusException) EventBus(org.apache.cloudstack.framework.events.EventBus) NoSuchBeanDefinitionException(org.springframework.beans.factory.NoSuchBeanDefinitionException) SimpleDateFormat(java.text.SimpleDateFormat) Date(java.util.Date)

Example 2 with EventBusException

use of org.apache.cloudstack.framework.events.EventBusException in project cloudstack by apache.

the class RabbitMQEventBus method subscribe.

/** Call to subscribe to interested set of events
     *
     * @param topic defines category and type of the events being subscribed to
     * @param subscriber subscriber that intends to receive event notification
     * @return UUID that represents the subscription with event bus
     * @throws EventBusException
     */
@Override
public UUID subscribe(EventTopic topic, EventSubscriber subscriber) throws EventBusException {
    if (subscriber == null || topic == null) {
        throw new EventBusException("Invalid EventSubscriber/EventTopic object passed.");
    }
    // create a UUID, that will be used for managing subscriptions and also used as queue name
    // for on the queue used for the subscriber on the AMQP broker
    UUID queueId = UUID.randomUUID();
    String queueName = queueId.toString();
    try {
        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<String, Channel, EventSubscriber> 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<String, Channel, EventSubscriber> queueDetails = s_subscribers.get(queueName);
        queueDetails.second(channel);
        s_subscribers.put(queueName, queueDetails);
    } catch (AlreadyClosedException closedException) {
        s_logger.warn("Connection to AMQP service is lost. Subscription:" + queueName + " will be active after reconnection");
    } catch (ConnectException connectException) {
        s_logger.warn("Connection to AMQP service is lost. Subscription:" + queueName + " will be active after reconnection");
    } catch (Exception e) {
        throw new EventBusException("Failed to subscribe to event due to " + e.getMessage());
    }
    return queueId;
}
Also used : EventSubscriber(org.apache.cloudstack.framework.events.EventSubscriber) DefaultConsumer(com.rabbitmq.client.DefaultConsumer) Ternary(com.cloud.utils.Ternary) Channel(com.rabbitmq.client.Channel) Connection(com.rabbitmq.client.Connection) IOException(java.io.IOException) AlreadyClosedException(com.rabbitmq.client.AlreadyClosedException) Envelope(com.rabbitmq.client.Envelope) ConfigurationException(javax.naming.ConfigurationException) ShutdownSignalException(com.rabbitmq.client.ShutdownSignalException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) ConnectException(java.net.ConnectException) EventBusException(org.apache.cloudstack.framework.events.EventBusException) IOException(java.io.IOException) AlreadyClosedException(com.rabbitmq.client.AlreadyClosedException) AMQP(com.rabbitmq.client.AMQP) Event(org.apache.cloudstack.framework.events.Event) EventBusException(org.apache.cloudstack.framework.events.EventBusException) UUID(java.util.UUID) ConnectException(java.net.ConnectException)

Example 3 with EventBusException

use of org.apache.cloudstack.framework.events.EventBusException in project cloudstack by apache.

the class InMemoryEventBus method subscribe.

@Override
public UUID subscribe(EventTopic topic, EventSubscriber subscriber) throws EventBusException {
    if (subscriber == null || topic == null) {
        throw new EventBusException("Invalid EventSubscriber/EventTopic object passed.");
    }
    UUID subscriberId = UUID.randomUUID();
    subscribers.put(subscriberId, new Pair<EventTopic, EventSubscriber>(topic, subscriber));
    return subscriberId;
}
Also used : EventSubscriber(org.apache.cloudstack.framework.events.EventSubscriber) EventTopic(org.apache.cloudstack.framework.events.EventTopic) EventBusException(org.apache.cloudstack.framework.events.EventBusException) UUID(java.util.UUID)

Example 4 with EventBusException

use of org.apache.cloudstack.framework.events.EventBusException in project cloudstack by apache.

the class RabbitMQEventBus method unsubscribe.

@Override
public void unsubscribe(UUID subscriberId, EventSubscriber subscriber) throws EventBusException {
    try {
        String classname = subscriber.getClass().getName();
        String queueName = UUID.nameUUIDFromBytes(classname.getBytes()).toString();
        Ternary<String, Channel, EventSubscriber> queueDetails = s_subscribers.get(queueName);
        Channel channel = queueDetails.second();
        channel.basicCancel(queueName);
        s_subscribers.remove(queueName, queueDetails);
    } catch (Exception e) {
        throw new EventBusException("Failed to unsubscribe from event bus due to " + e.getMessage());
    }
}
Also used : EventSubscriber(org.apache.cloudstack.framework.events.EventSubscriber) Channel(com.rabbitmq.client.Channel) EventBusException(org.apache.cloudstack.framework.events.EventBusException) ConfigurationException(javax.naming.ConfigurationException) ShutdownSignalException(com.rabbitmq.client.ShutdownSignalException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) ConnectException(java.net.ConnectException) EventBusException(org.apache.cloudstack.framework.events.EventBusException) IOException(java.io.IOException) AlreadyClosedException(com.rabbitmq.client.AlreadyClosedException)

Example 5 with EventBusException

use of org.apache.cloudstack.framework.events.EventBusException in project cloudstack by apache.

the class ActionEventUtils method publishOnEventBus.

private static void publishOnEventBus(long userId, long accountId, String eventCategory, String eventType, Event.State state, String description) {
    String configKey = Config.PublishActionEvent.key();
    String value = s_configDao.getValue(configKey);
    boolean configValue = Boolean.parseBoolean(value);
    if (!configValue)
        return;
    try {
        s_eventBus = ComponentContext.getComponent(EventBus.class);
    } catch (NoSuchBeanDefinitionException nbe) {
        // no provider is configured to provide events bus, so just return
        return;
    }
    // get the entity details for which ActionEvent is generated
    String entityType = null;
    String entityUuid = null;
    CallContext context = CallContext.current();
    //Get entity Class(Example - VirtualMachine.class) from the event Type eg. - VM.CREATE
    Class<?> entityClass = EventTypes.getEntityClassForEvent(eventType);
    if (entityClass != null) {
        //Get uuid from id
        Object param = context.getContextParameter(entityClass);
        if (param != null) {
            try {
                entityUuid = getEntityUuid(entityClass, param);
                entityType = entityClass.getName();
            } catch (Exception e) {
                s_logger.debug("Caught exception while finding entityUUID, moving on");
            }
        }
    }
    org.apache.cloudstack.framework.events.Event event = new org.apache.cloudstack.framework.events.Event(ManagementService.Name, eventCategory, eventType, EventTypes.getEntityForEvent(eventType), entityUuid);
    Map<String, String> eventDescription = new HashMap<String, String>();
    Project project = s_projectDao.findByProjectAccountId(accountId);
    Account account = s_accountDao.findById(accountId);
    User user = s_userDao.findById(userId);
    // if account has been deleted, this might be called during cleanup of resources and results in null pointer
    if (account == null)
        return;
    if (user == null)
        return;
    if (project != null)
        eventDescription.put("project", project.getUuid());
    eventDescription.put("user", user.getUuid());
    eventDescription.put("account", account.getUuid());
    eventDescription.put("event", eventType);
    eventDescription.put("status", state.toString());
    eventDescription.put("entity", entityType);
    eventDescription.put("entityuuid", entityUuid);
    //Put all the first class entities that are touched during the action. For now atleast put in the vmid.
    populateFirstClassEntities(eventDescription);
    eventDescription.put("description", description);
    String eventDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z").format(new Date());
    eventDescription.put("eventDateTime", eventDate);
    event.setDescription(eventDescription);
    try {
        s_eventBus.publish(event);
    } catch (EventBusException e) {
        s_logger.warn("Failed to publish action event on the the event bus.");
    }
}
Also used : Account(com.cloud.user.Account) User(com.cloud.user.User) HashMap(java.util.HashMap) EventBus(org.apache.cloudstack.framework.events.EventBus) CallContext(org.apache.cloudstack.context.CallContext) EventBusException(org.apache.cloudstack.framework.events.EventBusException) NoSuchBeanDefinitionException(org.springframework.beans.factory.NoSuchBeanDefinitionException) Date(java.util.Date) Project(com.cloud.projects.Project) EventBusException(org.apache.cloudstack.framework.events.EventBusException) NoSuchBeanDefinitionException(org.springframework.beans.factory.NoSuchBeanDefinitionException) SimpleDateFormat(java.text.SimpleDateFormat)

Aggregations

EventBusException (org.apache.cloudstack.framework.events.EventBusException)11 HashMap (java.util.HashMap)7 EventBus (org.apache.cloudstack.framework.events.EventBus)7 NoSuchBeanDefinitionException (org.springframework.beans.factory.NoSuchBeanDefinitionException)7 SimpleDateFormat (java.text.SimpleDateFormat)6 Date (java.util.Date)6 Account (com.cloud.user.Account)3 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)3 AlreadyClosedException (com.rabbitmq.client.AlreadyClosedException)3 Channel (com.rabbitmq.client.Channel)3 ShutdownSignalException (com.rabbitmq.client.ShutdownSignalException)3 IOException (java.io.IOException)3 ConnectException (java.net.ConnectException)3 ConfigurationException (javax.naming.ConfigurationException)3 EventSubscriber (org.apache.cloudstack.framework.events.EventSubscriber)3 DataCenterVO (com.cloud.dc.DataCenterVO)2 User (com.cloud.user.User)2 Connection (com.rabbitmq.client.Connection)2 UUID (java.util.UUID)2 Event (org.apache.cloudstack.framework.events.Event)2