de.codecentric.boot.admin.server.domain.events.InstanceEvent Java Examples

The following examples show how to use de.codecentric.boot.admin.server.domain.events.InstanceEvent. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MailNotifier.java    From spring-boot-admin with Apache License 2.0 6 votes vote down vote up
@Override
protected Mono<Void> doNotify(InstanceEvent event, Instance instance) {
	return Mono.fromRunnable(() -> {
		Context ctx = new Context();
		ctx.setVariables(additionalProperties);
		ctx.setVariable("baseUrl", this.baseUrl);
		ctx.setVariable("event", event);
		ctx.setVariable("instance", instance);
		ctx.setVariable("lastStatus", getLastStatus(event.getInstance()));

		try {
			MimeMessage mimeMessage = mailSender.createMimeMessage();
			MimeMessageHelper message = new MimeMessageHelper(mimeMessage, StandardCharsets.UTF_8.name());
			message.setText(getBody(ctx).replaceAll("\\s+\\n", "\n"), true);
			message.setSubject(getSubject(ctx));
			message.setTo(this.to);
			message.setCc(this.cc);
			message.setFrom(this.from);
			mailSender.send(mimeMessage);
		}
		catch (MessagingException ex) {
			throw new RuntimeException("Error sending mail notification", ex);
		}
	});
}
 
Example #2
Source File: RemindingNotifierTest.java    From spring-boot-admin with Apache License 2.0 6 votes vote down vote up
@Test
public void should_resubscribe_after_error() {
	TestPublisher<InstanceEvent> eventPublisher = TestPublisher.create();

	Flux<InstanceEvent> emittedNotifications = Flux.create((emitter) -> {
		Notifier notifier = (event) -> {
			emitter.next(event);
			if (event.equals(errorTriggeringEvent)) {
				return Mono.error(new IllegalArgumentException("TEST-ERROR"));
			}
			return Mono.empty();
		};

		RemindingNotifier reminder = new RemindingNotifier(notifier, this.repository);
		eventPublisher.flux().flatMap(reminder::notify).subscribe();
		reminder.setCheckReminderInverval(Duration.ofMillis(10));
		reminder.setReminderPeriod(Duration.ofMillis(10));
		reminder.start();
	});

	StepVerifier.create(emittedNotifications).expectSubscription().then(() -> eventPublisher.next(appDown))
			.expectNext(appDown, appDown).then(() -> eventPublisher.next(errorTriggeringEvent))
			.thenConsumeWhile((e) -> !e.equals(errorTriggeringEvent))
			.expectNext(errorTriggeringEvent, appDown, appDown).thenCancel().verify();
}
 
Example #3
Source File: FilteringNotifierTest.java    From spring-boot-admin with Apache License 2.0 6 votes vote down vote up
@Test
public void test_filter() {
	TestNotifier delegate = new TestNotifier();
	FilteringNotifier notifier = new FilteringNotifier(delegate, repository);

	AbstractNotificationFilter trueFilter = new AbstractNotificationFilter() {
		@Override
		public boolean filter(InstanceEvent event, Instance instance) {
			return true;
		}
	};
	notifier.addFilter(trueFilter);

	StepVerifier.create(notifier.notify(event)).verifyComplete();

	assertThat(delegate.getEvents()).doesNotContain(event);

	notifier.removeFilter(trueFilter.getId());
	StepVerifier.create(notifier.notify(event)).verifyComplete();

	assertThat(delegate.getEvents()).contains(event);
}
 
Example #4
Source File: AbstractEventStoreTest.java    From spring-boot-admin with Apache License 2.0 6 votes vote down vote up
@Test
public void should_store_events() {
	InstanceEventStore store = createStore(100);
	StepVerifier.create(store.findAll()).verifyComplete();

	Instant now = Instant.now();
	InstanceEvent event1 = new InstanceRegisteredEvent(id, 0L, now, registration);
	InstanceEvent eventOther = new InstanceRegisteredEvent(InstanceId.of("other"), 0L, now.plusMillis(10),
			registration);
	InstanceEvent event2 = new InstanceDeregisteredEvent(id, 1L, now.plusMillis(20));

	StepVerifier.create(store).expectSubscription()
			.then(() -> StepVerifier.create(store.append(singletonList(event1))).verifyComplete())
			.expectNext(event1)
			.then(() -> StepVerifier.create(store.append(singletonList(eventOther))).verifyComplete())
			.expectNext(eventOther)
			.then(() -> StepVerifier.create(store.append(singletonList(event2))).verifyComplete())
			.expectNext(event2).thenCancel().verify();

	StepVerifier.create(store.find(id)).expectNext(event1, event2).verifyComplete();
	StepVerifier.create(store.find(InstanceId.of("-"))).verifyComplete();
	StepVerifier.create(store.findAll()).expectNext(event1, eventOther, event2).verifyComplete();
}
 
Example #5
Source File: SlackNotifier.java    From Moss with Apache License 2.0 6 votes vote down vote up
protected Object createMessage(InstanceEvent event, Instance instance) {
    Map<String, Object> messageJson = new HashMap<>();
    messageJson.put("username", username);
    if (icon != null) {
        messageJson.put("icon_emoji", ":" + icon + ":");
    }
    if (channel != null) {
        messageJson.put("channel", channel);
    }

    Map<String, Object> attachments = new HashMap<>();
    attachments.put("text", getText(event, instance));
    attachments.put("color", getColor(event));
    attachments.put("mrkdwn_in", Collections.singletonList("text"));
    messageJson.put("attachments", Collections.singletonList(attachments));

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    return new HttpEntity<>(messageJson, headers);
}
 
Example #6
Source File: HazelcastNotificationTrigger.java    From spring-boot-admin with Apache License 2.0 6 votes vote down vote up
@Override
protected Mono<Void> sendNotifications(InstanceEvent event) {
	while (true) {
		Long lastSentEvent = this.sentNotifications.getOrDefault(event.getInstance(), -1L);
		if (lastSentEvent >= event.getVersion()) {
			log.debug("Notifications already sent. Not triggering notifiers for {}", event);
			return Mono.empty();
		}

		if (lastSentEvent < 0) {
			if (this.sentNotifications.putIfAbsent(event.getInstance(), event.getVersion()) == null) {
				log.debug("Triggering notifiers for {}", event);
				return super.sendNotifications(event);
			}
		}
		else {
			if (this.sentNotifications.replace(event.getInstance(), lastSentEvent, event.getVersion())) {
				log.debug("Triggering notifiers for {}", event);
				return super.sendNotifications(event);
			}
		}
	}
}
 
Example #7
Source File: RemindingNotifierTest.java    From Moss with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<Void> notify(InstanceEvent event) {
    if (event.getInstance().getValue().equals("ERROR")) {
        throw new IllegalArgumentException("TEST-ERROR");
    }
    this.publish(Collections.singletonList(event));
    return Mono.empty();
}
 
Example #8
Source File: MailNotifierTest.java    From spring-boot-admin with Apache License 2.0 5 votes vote down vote up
@Test
public void should_not_propagate_error() {
	Notifier notifier = new AbstractStatusChangeNotifier(repository) {
		@Override
		protected Mono<Void> doNotify(InstanceEvent event, Instance application) {
			return Mono.error(new IllegalStateException("test"));
		}
	};
	StepVerifier
			.create(notifier.notify(
					new InstanceStatusChangedEvent(instance.getId(), instance.getVersion(), StatusInfo.ofUp())))
			.verifyComplete();
}
 
Example #9
Source File: MailNotifier.java    From Moss with Apache License 2.0 5 votes vote down vote up
@Override
protected Mono<Void> doNotify(InstanceEvent event, Instance instance) {
    return Mono.fromRunnable(() -> {
        Context ctx = new Context();
        ctx.setVariables(additionalProperties);
        ctx.setVariable("baseUrl", this.baseUrl);
        ctx.setVariable("event", event);
        ctx.setVariable("instance", instance);
        ctx.setVariable("lastStatus", getLastStatus(event.getInstance()));

        try {
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage, StandardCharsets.UTF_8.name());
            message.setText(getBody(ctx).replaceAll("\\s+\\n", "\n"), true);
            message.setSubject(getSubject(ctx));
            message.setTo(this.to);
            message.setCc(this.cc);
            message.setFrom(this.from);
            mailSender.send(mimeMessage);
        } catch (MessagingException ex) {
            throw new RuntimeException("Error sending mail notification", ex);
        }
    });
}
 
Example #10
Source File: AbstractEventStoreTest.java    From spring-boot-admin with Apache License 2.0 5 votes vote down vote up
@Test
public void should_shorten_log_on_exceeded_capacity() {
	InstanceEventStore store = createStore(2);

	InstanceEvent event1 = new InstanceRegisteredEvent(id, 0L, registration);
	InstanceEvent event2 = new InstanceStatusChangedEvent(id, 1L, StatusInfo.ofDown());
	InstanceEvent event3 = new InstanceStatusChangedEvent(id, 2L, StatusInfo.ofUp());

	StepVerifier.create(store.append(asList(event1, event2, event3))).verifyComplete();

	StepVerifier.create(store.findAll()).expectNext(event1, event3).verifyComplete();
}
 
Example #11
Source File: PagerdutyNotifier.java    From Moss with Apache License 2.0 5 votes vote down vote up
@Nullable
protected String getDescription(InstanceEvent event, Instance instance) {
    Map<String, Object> root = new HashMap<>();
    root.put("event", event);
    root.put("instance", instance);
    root.put("lastStatus", getLastStatus(event.getInstance()));
    StandardEvaluationContext context = new StandardEvaluationContext(root);
    context.addPropertyAccessor(new MapAccessor());

    return description.getValue(context, String.class);
}
 
Example #12
Source File: SlackNotifier.java    From spring-boot-admin with Apache License 2.0 5 votes vote down vote up
protected String getColor(InstanceEvent event) {
	if (event instanceof InstanceStatusChangedEvent) {
		return StatusInfo.STATUS_UP.equals(((InstanceStatusChangedEvent) event).getStatusInfo().getStatus())
				? "good" : "danger";
	}
	else {
		return "#439FE0";
	}
}
 
Example #13
Source File: HipchatNotifier.java    From Moss with Apache License 2.0 5 votes vote down vote up
@Override
protected Mono<Void> doNotify(InstanceEvent event, Instance instance) {
    return Mono.fromRunnable(() -> restTemplate.postForEntity(buildUrl(),
        createHipChatNotification(event, instance),
        Void.class
    ));
}
 
Example #14
Source File: HipchatNotifier.java    From Moss with Apache License 2.0 5 votes vote down vote up
protected HttpEntity<Map<String, Object>> createHipChatNotification(InstanceEvent event, Instance instance) {
    Map<String, Object> body = new HashMap<>();
    body.put("color", getColor(event));
    body.put("message", getMessage(event, instance));
    body.put("notify", getNotify());
    body.put("message_format", "html");

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    return new HttpEntity<>(body, headers);
}
 
Example #15
Source File: PagerdutyNotifier.java    From spring-boot-admin with Apache License 2.0 5 votes vote down vote up
@Nullable
protected String getDescription(InstanceEvent event, Instance instance) {
	Map<String, Object> root = new HashMap<>();
	root.put("event", event);
	root.put("instance", instance);
	root.put("lastStatus", getLastStatus(event.getInstance()));
	StandardEvaluationContext context = new StandardEvaluationContext(root);
	context.addPropertyAccessor(new MapAccessor());

	return description.getValue(context, String.class);
}
 
Example #16
Source File: LetsChatNotifier.java    From spring-boot-admin with Apache License 2.0 5 votes vote down vote up
@Override
protected Mono<Void> doNotify(InstanceEvent event, Instance instance) {
	HttpHeaders headers = new HttpHeaders();
	headers.setContentType(MediaType.APPLICATION_JSON);
	// Let's Chat requiers the token as basic username, the password can be an
	// arbitrary string.
	String auth = Base64Utils
			.encodeToString(String.format("%s:%s", token, username).getBytes(StandardCharsets.UTF_8));
	headers.add(HttpHeaders.AUTHORIZATION, String.format("Basic %s", auth));
	return Mono.fromRunnable(() -> restTemplate.exchange(createUrl(), HttpMethod.POST,
			new HttpEntity<>(createMessage(event, instance), headers), Void.class));
}
 
Example #17
Source File: AbstractEventNotifier.java    From spring-boot-admin with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<Void> notify(InstanceEvent event) {
	if (!enabled) {
		return Mono.empty();
	}

	return repository.find(event.getInstance()).filter((instance) -> shouldNotify(event, instance))
			.flatMap((instance) -> doNotify(event, instance))
			.doOnError((ex) -> getLogger().error("Couldn't notify for event {} ", event, ex)).then();
}
 
Example #18
Source File: AbstractEventStoreTest.java    From Moss with Apache License 2.0 5 votes vote down vote up
@Test
public void should_shorten_log_on_exceeded_capacity() {
    InstanceEventStore store = createStore(2);

    InstanceEvent event1 = new InstanceRegisteredEvent(id, 0L, registration);
    InstanceEvent event2 = new InstanceStatusChangedEvent(id, 1L, StatusInfo.ofDown());
    InstanceEvent event3 = new InstanceStatusChangedEvent(id, 2L, StatusInfo.ofUp());

    StepVerifier.create(store.append(asList(event1, event2, event3))).verifyComplete();

    StepVerifier.create(store.findAll()).expectNext(event1, event3).verifyComplete();
}
 
Example #19
Source File: DiscordNotifier.java    From spring-boot-admin with Apache License 2.0 5 votes vote down vote up
@Nullable
protected String createContent(InstanceEvent event, Instance instance) {
	Map<String, Object> root = new HashMap<>();
	root.put("event", event);
	root.put("instance", instance);
	root.put("lastStatus", getLastStatus(event.getInstance()));
	StandardEvaluationContext context = new StandardEvaluationContext(root);
	context.addPropertyAccessor(new MapAccessor());
	return message.getValue(context, String.class);
}
 
Example #20
Source File: FilteringNotifier.java    From spring-boot-admin with Apache License 2.0 5 votes vote down vote up
private boolean filter(InstanceEvent event, Instance instance) {
	cleanUp();
	for (Entry<String, NotificationFilter> entry : getNotificationFilters().entrySet()) {
		if (entry.getValue().filter(event, instance)) {
			LOGGER.debug("The event '{}' was suppressed by filter '{}'", event, entry);
			return true;
		}
	}
	return false;
}
 
Example #21
Source File: AbstractStatusChangeNotifier.java    From Moss with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean shouldNotify(InstanceEvent event, Instance instance) {
    if (event instanceof InstanceStatusChangedEvent) {
        InstanceStatusChangedEvent statusChange = (InstanceStatusChangedEvent) event;
        String from = getLastStatus(event.getInstance());
        String to = statusChange.getStatusInfo().getStatus();
        return Arrays.binarySearch(ignoreChanges, from + ":" + to) < 0 &&
               Arrays.binarySearch(ignoreChanges, "*:" + to) < 0 &&
               Arrays.binarySearch(ignoreChanges, from + ":*") < 0;
    }
    return false;
}
 
Example #22
Source File: InstanceEventMixinTest.java    From spring-boot-admin with Apache License 2.0 5 votes vote down vote up
@Test
public void verifyDeserializeOfInstanceRegistrationUpdatedEvent()
		throws JSONException, JsonProcessingException {
	String json = new JSONObject().put("instance", "test123").put("timestamp", 1587751031.000000000)
			.put("type", "REGISTRATION_UPDATED")
			.put("registration",
					new JSONObject().put("name", "test").put("healthUrl", "http://localhost:9080/heath"))
			.toString();

	InstanceEvent event = objectMapper.readValue(json, InstanceEvent.class);
	assertThat(event).isInstanceOf(InstanceRegistrationUpdatedEvent.class);
}
 
Example #23
Source File: MailNotifierTest.java    From Moss with Apache License 2.0 5 votes vote down vote up
@Test
public void should_not_propagate_error() {
    Notifier notifier = new AbstractStatusChangeNotifier(repository) {
        @Override
        protected Mono<Void> doNotify(InstanceEvent event, Instance application) {
            return Mono.error(new IllegalStateException("test"));
        }
    };
    StepVerifier.create(
        notifier.notify(new InstanceStatusChangedEvent(instance.getId(), instance.getVersion(), StatusInfo.ofUp())))
                .verifyComplete();
}
 
Example #24
Source File: RemindingNotifier.java    From Moss with Apache License 2.0 5 votes vote down vote up
protected boolean shouldStartReminder(InstanceEvent event) {
    if (event instanceof InstanceStatusChangedEvent) {
        return Arrays.binarySearch(reminderStatuses,
                ((InstanceStatusChangedEvent) event).getStatusInfo().getStatus()
        ) >= 0;
    }
    return false;
}
 
Example #25
Source File: RemindingNotifier.java    From Moss with Apache License 2.0 5 votes vote down vote up
protected boolean shouldEndReminder(InstanceEvent event) {
    if (event instanceof InstanceDeregisteredEvent) {
        return true;
    }
    if (event instanceof InstanceStatusChangedEvent) {
        return Arrays.binarySearch(reminderStatuses,
                ((InstanceStatusChangedEvent) event).getStatusInfo().getStatus()
        ) < 0;
    }
    return false;
}
 
Example #26
Source File: LoggingNotifier.java    From spring-boot-admin with Apache License 2.0 5 votes vote down vote up
@Override
protected Mono<Void> doNotify(InstanceEvent event, Instance instance) {
	return Mono.fromRunnable(() -> {
		if (event instanceof InstanceStatusChangedEvent) {
			LOGGER.info("Instance {} ({}) is {}", instance.getRegistration().getName(), event.getInstance(),
					((InstanceStatusChangedEvent) event).getStatusInfo().getStatus());
		}
		else {
			LOGGER.info("Instance {} ({}) {}", instance.getRegistration().getName(), event.getInstance(),
					event.getType());
		}
	});
}
 
Example #27
Source File: AbstractEventNotifier.java    From Moss with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<Void> notify(InstanceEvent event) {
    if (!enabled) {
        return Mono.empty();
    }

    return repository.find(event.getInstance())
                     .filter(instance -> shouldNotify(event, instance))
                     .flatMap(instance -> doNotify(event, instance))
                     .doOnError(ex -> getLogger().error("Couldn't notify for event {} ", event, ex))
                     .then();
}
 
Example #28
Source File: AbstractEventHandlerTest.java    From spring-boot-admin with Apache License 2.0 5 votes vote down vote up
@Test
public void should_resubscribe_after_error() {
	TestPublisher<InstanceEvent> testPublisher = TestPublisher.create();

	TestEventHandler eventHandler = new TestEventHandler(testPublisher.flux());
	eventHandler.start();

	StepVerifier.create(eventHandler.getFlux()).expectSubscription()
			.then(() -> testPublisher.next(firstEvent, errorEvent, secondEvent)).expectNext(firstEvent, secondEvent)
			.thenCancel().verify(Duration.ofSeconds(1));

}
 
Example #29
Source File: SlackNotifier.java    From spring-boot-admin with Apache License 2.0 5 votes vote down vote up
@Override
protected Mono<Void> doNotify(InstanceEvent event, Instance instance) {
	if (webhookUrl == null) {
		return Mono.error(new IllegalStateException("'webhookUrl' must not be null."));
	}
	return Mono
			.fromRunnable(() -> restTemplate.postForEntity(webhookUrl, createMessage(event, instance), Void.class));
}
 
Example #30
Source File: AdminServerAutoConfiguration.java    From spring-boot-admin with Apache License 2.0 5 votes vote down vote up
@Bean(initMethod = "start", destroyMethod = "stop")
@ConditionalOnMissingBean
public StatusUpdateTrigger statusUpdateTrigger(StatusUpdater statusUpdater, Publisher<InstanceEvent> events) {
	StatusUpdateTrigger trigger = new StatusUpdateTrigger(statusUpdater, events);
	trigger.setInterval(this.adminServerProperties.getMonitor().getStatusInterval());
	trigger.setLifetime(this.adminServerProperties.getMonitor().getStatusLifetime());
	return trigger;
}