Search in sources :

Example 1 with EventBusException

use of com.cloud.framework.events.EventBusException in project cosmic by MissionCriticalCloud.

the class RabbitMQEventBus method unsubscribe.

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

Example 2 with EventBusException

use of com.cloud.framework.events.EventBusException in project cosmic by MissionCriticalCloud.

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(final EventTopic topic, final 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
    final UUID queueId = UUID.randomUUID();
    final String queueName = queueId.toString();
    try {
        final 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
        final Connection connection = getConnection();
        final 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(final String queueName, final Envelope envelope, final AMQP.BasicProperties properties, final byte[] body) throws IOException {
                RabbitMQEventBus.this.handleDelivery(queueName, envelope, body);
            }
        });
        // update the channel details for the subscription
        final Ternary<String, Channel, EventSubscriber> queueDetails = s_subscribers.get(queueName);
        queueDetails.second(channel);
        s_subscribers.put(queueName, queueDetails);
    } catch (final AlreadyClosedException | ConnectException | NoSuchAlgorithmException | KeyManagementException | TimeoutException e) {
        s_logger.warn("Connection to AMQP service is lost. Subscription:" + queueName + " will be active after reconnection", e);
    } catch (final IOException e) {
        throw new EventBusException("Failed to subscribe to event due to " + e.getMessage(), e);
    }
    return queueId;
}
Also used : EventSubscriber(com.cloud.framework.events.EventSubscriber) DefaultConsumer(com.rabbitmq.client.DefaultConsumer) Channel(com.rabbitmq.client.Channel) Connection(com.rabbitmq.client.Connection) IOException(java.io.IOException) AlreadyClosedException(com.rabbitmq.client.AlreadyClosedException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Envelope(com.rabbitmq.client.Envelope) KeyManagementException(java.security.KeyManagementException) AMQP(com.rabbitmq.client.AMQP) EventBusException(com.cloud.framework.events.EventBusException) UUID(java.util.UUID) ConnectException(java.net.ConnectException) TimeoutException(java.util.concurrent.TimeoutException)

Example 3 with EventBusException

use of com.cloud.framework.events.EventBusException in project cosmic by MissionCriticalCloud.

the class ApiServer method handleAsyncJobPublishEvent.

@MessageHandler(topic = AsyncJob.Topics.JOB_EVENT_PUBLISH)
private void handleAsyncJobPublishEvent(final String subject, final String senderAddress, final Object args) {
    assert (args != null);
    final Pair<AsyncJob, String> eventInfo = (Pair<AsyncJob, String>) args;
    final AsyncJob job = eventInfo.first();
    final String jobEvent = eventInfo.second();
    if (s_logger.isTraceEnabled()) {
        s_logger.trace("Handle asyjob publish event " + jobEvent);
    }
    final EventBus eventBus;
    try {
        eventBus = ComponentContext.getComponent(EventBus.class);
    } catch (final NoSuchBeanDefinitionException nbe) {
        // no provider is configured to provide events bus, so just return
        return;
    }
    if (!job.getDispatcher().equalsIgnoreCase("ApiAsyncJobDispatcher")) {
        return;
    }
    final User userJobOwner = _accountMgr.getUserIncludingRemoved(job.getUserId());
    final Account jobOwner = _accountMgr.getAccount(userJobOwner.getAccountId());
    // Get the event type from the cmdInfo json string
    final String info = job.getCmdInfo();
    String cmdEventType = "unknown";
    if (info != null) {
        final Type type = new TypeToken<Map<String, String>>() {
        }.getType();
        final Map<String, String> cmdInfo = ApiGsonHelper.getBuilder().create().fromJson(info, type);
        final String eventTypeObj = cmdInfo.get("cmdEventType");
        if (eventTypeObj != null) {
            cmdEventType = eventTypeObj;
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("Retrieved cmdEventType from job info: " + cmdEventType);
            }
        } else {
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("Unable to locate cmdEventType marker in job info. publish as unknown event");
            }
        }
    }
    // For some reason, the instanceType / instanceId are not abstract, which means we may get null values.
    final String instanceType = job.getInstanceType() != null ? job.getInstanceType() : "unknown";
    final String instanceUuid = job.getInstanceId() != null ? ApiDBUtils.findJobInstanceUuid(job) : "";
    final Event event = new Event("management-server", EventCategory.ASYNC_JOB_CHANGE_EVENT.getName(), jobEvent, instanceType, instanceUuid);
    final Map<String, String> eventDescription = new HashMap<>();
    eventDescription.put("command", job.getCmd());
    eventDescription.put("user", userJobOwner.getUuid());
    eventDescription.put("account", jobOwner.getUuid());
    eventDescription.put("processStatus", "" + job.getProcessStatus());
    eventDescription.put("resultCode", "" + job.getResultCode());
    eventDescription.put("instanceUuid", instanceUuid);
    eventDescription.put("instanceType", instanceType);
    eventDescription.put("commandEventType", cmdEventType);
    eventDescription.put("jobId", job.getUuid());
    eventDescription.put("jobResult", job.getResult());
    eventDescription.put("cmdInfo", job.getCmdInfo());
    eventDescription.put("status", "" + job.getStatus());
    // If the event.accountinfo boolean value is set, get the human readable value for the username / domainname
    final Map<String, String> configs = _configDao.getConfiguration("management-server", new HashMap<String, String>());
    if (Boolean.valueOf(configs.get("event.accountinfo"))) {
        final DomainVO domain = _domainDao.findById(jobOwner.getDomainId());
        eventDescription.put("username", userJobOwner.getUsername());
        eventDescription.put("accountname", jobOwner.getAccountName());
        eventDescription.put("domainname", domain.getName());
    }
    event.setDescription(eventDescription);
    try {
        eventBus.publish(event);
    } catch (final EventBusException evx) {
        final String errMsg = "Failed to publish async job event on the the event bus.";
        s_logger.warn(errMsg, evx);
    }
}
Also used : UserAccount(com.cloud.user.UserAccount) Account(com.cloud.user.Account) User(com.cloud.user.User) HashMap(java.util.HashMap) EventBus(com.cloud.framework.events.EventBus) AsyncJob(com.cloud.framework.jobs.AsyncJob) DomainVO(com.cloud.domain.DomainVO) Type(java.lang.reflect.Type) Event(com.cloud.framework.events.Event) EventBusException(com.cloud.framework.events.EventBusException) NoSuchBeanDefinitionException(org.springframework.beans.factory.NoSuchBeanDefinitionException) Map(java.util.Map) HashMap(java.util.HashMap) Pair(com.cloud.utils.Pair) NameValuePair(org.apache.http.NameValuePair) MessageHandler(com.cloud.framework.messagebus.MessageHandler)

Example 4 with EventBusException

use of com.cloud.framework.events.EventBusException in project cosmic by MissionCriticalCloud.

the class VolumeStateListener method pubishOnEventBus.

private void pubishOnEventBus(final String event, final String status, final Volume vo, final State oldState, final State newState) {
    final String configKey = Config.PublishResourceStateEvent.key();
    final String value = _configDao.getValue(configKey);
    final boolean configValue = Boolean.parseBoolean(value);
    if (!configValue) {
        return;
    }
    try {
        s_eventBus = ComponentContext.getComponent(EventBus.class);
    } catch (final NoSuchBeanDefinitionException nbe) {
        // no provider is configured to provide events bus, so just return
        return;
    }
    final String resourceName = getEntityFromClassName(Volume.class.getName());
    final com.cloud.framework.events.Event eventMsg = new com.cloud.framework.events.Event(ManagementService.Name, EventCategory.RESOURCE_STATE_CHANGE_EVENT.getName(), event, resourceName, vo.getUuid());
    final Map<String, String> eventDescription = new HashMap<>();
    eventDescription.put("resource", resourceName);
    eventDescription.put("id", vo.getUuid());
    eventDescription.put("old-state", oldState.name());
    eventDescription.put("new-state", newState.name());
    final String eventDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z").format(new Date());
    eventDescription.put("eventDateTime", eventDate);
    eventMsg.setDescription(eventDescription);
    try {
        s_eventBus.publish(eventMsg);
    } catch (final EventBusException e) {
        s_logger.warn("Failed to state change event on the the event bus.");
    }
}
Also used : HashMap(java.util.HashMap) EventBus(com.cloud.framework.events.EventBus) Date(java.util.Date) Volume(com.cloud.storage.Volume) Event(com.cloud.storage.Volume.Event) EventBusException(com.cloud.framework.events.EventBusException) NoSuchBeanDefinitionException(org.springframework.beans.factory.NoSuchBeanDefinitionException) SimpleDateFormat(java.text.SimpleDateFormat)

Example 5 with EventBusException

use of com.cloud.framework.events.EventBusException in project cosmic by MissionCriticalCloud.

the class UserVmStateListener method pubishOnEventBus.

private void pubishOnEventBus(final String event, final String status, final VirtualMachine vo, final VirtualMachine.State oldState, final VirtualMachine.State newState) {
    final String configKey = Config.PublishResourceStateEvent.key();
    final String value = _configDao.getValue(configKey);
    final boolean configValue = Boolean.parseBoolean(value);
    if (!configValue) {
        return;
    }
    try {
        s_eventBus = ComponentContext.getComponent(EventBus.class);
    } catch (final NoSuchBeanDefinitionException nbe) {
        // no provider is configured to provide events bus, so just return
        return;
    }
    final String resourceName = getEntityFromClassName(VirtualMachine.class.getName());
    final com.cloud.framework.events.Event eventMsg = new com.cloud.framework.events.Event(ManagementService.Name, EventCategory.RESOURCE_STATE_CHANGE_EVENT.getName(), event, resourceName, vo.getUuid());
    final Map<String, String> eventDescription = new HashMap<>();
    eventDescription.put("resource", resourceName);
    eventDescription.put("id", vo.getUuid());
    eventDescription.put("old-state", oldState.name());
    eventDescription.put("new-state", newState.name());
    eventDescription.put("status", status);
    final String eventDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z").format(new Date());
    eventDescription.put("eventDateTime", eventDate);
    eventMsg.setDescription(eventDescription);
    try {
        s_eventBus.publish(eventMsg);
    } catch (final EventBusException e) {
        s_logger.warn("Failed to publish state change event on the the event bus.");
    }
}
Also used : HashMap(java.util.HashMap) EventBus(com.cloud.framework.events.EventBus) Date(java.util.Date) Event(com.cloud.vm.VirtualMachine.Event) EventBusException(com.cloud.framework.events.EventBusException) NoSuchBeanDefinitionException(org.springframework.beans.factory.NoSuchBeanDefinitionException) SimpleDateFormat(java.text.SimpleDateFormat)

Aggregations

EventBusException (com.cloud.framework.events.EventBusException)9 EventBus (com.cloud.framework.events.EventBus)6 HashMap (java.util.HashMap)6 NoSuchBeanDefinitionException (org.springframework.beans.factory.NoSuchBeanDefinitionException)6 SimpleDateFormat (java.text.SimpleDateFormat)5 Date (java.util.Date)5 Channel (com.rabbitmq.client.Channel)3 IOException (java.io.IOException)3 Event (com.cloud.framework.events.Event)2 EventSubscriber (com.cloud.framework.events.EventSubscriber)2 Account (com.cloud.user.Account)2 User (com.cloud.user.User)2 AlreadyClosedException (com.rabbitmq.client.AlreadyClosedException)2 Connection (com.rabbitmq.client.Connection)2 ConnectException (java.net.ConnectException)2 KeyManagementException (java.security.KeyManagementException)2 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)2 TimeoutException (java.util.concurrent.TimeoutException)2 CallContext (com.cloud.context.CallContext)1 HostPodVO (com.cloud.dc.HostPodVO)1