use of org.apache.cloudstack.framework.events.Event 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.");
}
}
use of org.apache.cloudstack.framework.events.Event in project cloudstack by apache.
the class InMemoryEventBusTest method testPublishEmpty.
@Test
public void testPublishEmpty() throws Exception {
EventSubscriber subscriber = mock(EventSubscriber.class);
Event event = mock(Event.class);
InMemoryEventBus bus = new InMemoryEventBus();
bus.publish(event);
verify(subscriber, times(0)).onEvent(event);
}
use of org.apache.cloudstack.framework.events.Event 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;
}
use of org.apache.cloudstack.framework.events.Event in project cloudstack by apache.
the class InMemoryEventBusTest method testPublish.
@Test
public void testPublish() throws Exception {
EventTopic topic = mock(EventTopic.class);
EventSubscriber subscriber = mock(EventSubscriber.class);
Event event = mock(Event.class);
InMemoryEventBus bus = new InMemoryEventBus();
UUID uuid = bus.subscribe(topic, subscriber);
assertNotNull(uuid);
String uuidStr = uuid.toString();
assertTrue(UuidUtils.validateUUID(uuidStr));
assertTrue(bus.totalSubscribers() == 1);
bus.publish(event);
verify(subscriber, times(1)).onEvent(event);
bus.unsubscribe(uuid, subscriber);
assertTrue(bus.totalSubscribers() == 0);
}
use of org.apache.cloudstack.framework.events.Event in project cloudstack by apache.
the class HypervisorTemplateAdapterTest method setupUsageUtils.
public UsageEventUtils setupUsageUtils() throws EventBusException {
Mockito.when(_configDao.getValue(eq("publish.usage.events"))).thenReturn("true");
Mockito.when(_usageEventDao.persist(Mockito.any(UsageEventVO.class))).then(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
UsageEventVO vo = (UsageEventVO) invocation.getArguments()[0];
usageEvents.add(vo);
return null;
}
});
Mockito.when(_usageEventDao.listAll()).thenReturn(usageEvents);
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
Event event = (Event) invocation.getArguments()[0];
events.add(event);
return null;
}
}).when(_bus).publish(any(Event.class));
PowerMockito.mockStatic(ComponentContext.class);
when(ComponentContext.getComponent(eq(EventBus.class))).thenReturn(_bus);
UsageEventUtils utils = new UsageEventUtils();
Map<String, String> usageUtilsFields = new HashMap<String, String>();
usageUtilsFields.put("usageEventDao", "_usageEventDao");
usageUtilsFields.put("accountDao", "_accountDao");
usageUtilsFields.put("dcDao", "_dcDao");
usageUtilsFields.put("configDao", "_configDao");
for (String fieldName : usageUtilsFields.keySet()) {
try {
Field f = UsageEventUtils.class.getDeclaredField(fieldName);
f.setAccessible(true);
//Remember the old fields for cleanup later (see cleanupUsageUtils)
Field staticField = UsageEventUtils.class.getDeclaredField("s_" + fieldName);
staticField.setAccessible(true);
oldFields.put(f.getName(), staticField.get(null));
f.set(utils, this.getClass().getDeclaredField(usageUtilsFields.get(fieldName)).get(this));
} catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e) {
e.printStackTrace();
}
}
try {
Method method = UsageEventUtils.class.getDeclaredMethod("init");
method.setAccessible(true);
method.invoke(utils);
} catch (SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException e) {
e.printStackTrace();
}
return utils;
}
Aggregations