de.codecentric.boot.admin.server.domain.entities.Instance Java Examples
The following examples show how to use
de.codecentric.boot.admin.server.domain.entities.Instance.
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: InstanceRegistryTest.java From Moss with Apache License 2.0 | 6 votes |
@Test public void refresh() { // Given instance is already reegistered and has status and info. StatusInfo status = StatusInfo.ofUp(); Info info = Info.from(singletonMap("foo", "bar")); Registration registration = Registration.create("abc", "http://localhost:8080/health").build(); InstanceId id = idGenerator.generateId(registration); Instance app = Instance.create(id).register(registration).withStatusInfo(status).withInfo(info); StepVerifier.create(repository.save(app)).expectNextCount(1).verifyComplete(); // When instance registers second time InstanceId refreshId = registry.register(Registration.create("abc", "http://localhost:8080/health").build()) .block(); assertThat(refreshId).isEqualTo(id); StepVerifier.create(registry.getInstance(id)).assertNext(registered -> { // Then info and status are retained assertThat(registered.getInfo()).isEqualTo(info); assertThat(registered.getStatusInfo()).isEqualTo(status); }).verifyComplete(); }
Example #2
Source File: ChainingStrategy.java From Moss with Apache License 2.0 | 6 votes |
@Override public Mono<Endpoints> detectEndpoints(Instance instance) { Mono<Endpoints> result = Mono.empty(); for (EndpointDetectionStrategy delegate : delegates) { result = result.switchIfEmpty(delegate.detectEndpoints(instance)); } return result.switchIfEmpty(Mono.just(Endpoints.empty())); }
Example #3
Source File: ProbeEndpointsStrategyTest.java From Moss with Apache License 2.0 | 6 votes |
@Test public void should_return_empty() { //given Instance instance = Instance.create(InstanceId.of("id")) .register(Registration.create("test", wireMock.url("/mgmt/health")) .managementUrl(wireMock.url("/mgmt")) .build()); wireMock.stubFor(options(urlEqualTo("/mgmt/stats")).willReturn(aResponse().withStatus(HttpStatus.NOT_FOUND_404))); ProbeEndpointsStrategy strategy = new ProbeEndpointsStrategy(instanceWebClient, new String[]{"metrics:stats"}); //when StepVerifier.create(strategy.detectEndpoints(instance)) //then .verifyComplete(); }
Example #4
Source File: QueryIndexEndpointStrategyTest.java From Moss with Apache License 2.0 | 6 votes |
@Test public void should_return_empty_on_wrong_content_type() { //given Instance instance = Instance.create(InstanceId.of("id")) .register(Registration.create("test", wireMock.url("/mgmt/health")) .managementUrl(wireMock.url("/mgmt")) .build()); String body = "HELLOW WORLD"; wireMock.stubFor(get("/mgmt").willReturn(ok(body).withHeader("Content-Type", MediaType.TEXT_PLAIN_VALUE) .withHeader("Content-Length", Integer.toString(body.length()) ))); QueryIndexEndpointStrategy strategy = new QueryIndexEndpointStrategy(instanceWebClient); //when StepVerifier.create(strategy.detectEndpoints(instance)) //then .verifyComplete(); }
Example #5
Source File: FilteringNotifierTest.java From spring-boot-admin with Apache License 2.0 | 6 votes |
@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 #6
Source File: QueryIndexEndpointStrategyTest.java From Moss with Apache License 2.0 | 6 votes |
@Test public void should_return_endpoints() { //given Instance instance = Instance.create(InstanceId.of("id")) .register(Registration.create("test", wireMock.url("/mgmt/health")) .managementUrl(wireMock.url("/mgmt")) .build()); String body = "{\"_links\":{\"metrics-requiredMetricName\":{\"templated\":true,\"href\":\"\\/mgmt\\/metrics\\/{requiredMetricName}\"},\"self\":{\"templated\":false,\"href\":\"\\/mgmt\"},\"metrics\":{\"templated\":false,\"href\":\"\\/mgmt\\/stats\"},\"info\":{\"templated\":false,\"href\":\"\\/mgmt\\/info\"}}}"; wireMock.stubFor(get("/mgmt").willReturn(ok(body).withHeader("Content-Type", ActuatorMediaType.V2_JSON) .withHeader("Content-Length", Integer.toString(body.length()) ))); QueryIndexEndpointStrategy strategy = new QueryIndexEndpointStrategy(instanceWebClient); //when StepVerifier.create(strategy.detectEndpoints(instance)) //then .expectNext(Endpoints.single("metrics", "/mgmt/stats").withEndpoint("info", "/mgmt/info"))// .verifyComplete(); }
Example #7
Source File: DiscordNotifier.java From Moss with Apache License 2.0 | 6 votes |
protected Object createDiscordNotification(InstanceEvent event, Instance instance) { Map<String, Object> body = new HashMap<>(); body.put("content", createContent(event, instance)); body.put("tts", tts); if (avatarUrl != null) { body.put("avatar_url", avatarUrl); } if (username != null) { body.put("username", username); } HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.add(HttpHeaders.USER_AGENT, "RestTemplate"); return new HttpEntity<>(body, headers); }
Example #8
Source File: InfoUpdaterTest.java From spring-boot-admin with Apache License 2.0 | 6 votes |
@Test public void should_clear_info_on_http_error() { // given Instance instance = Instance.create(InstanceId.of("onl")) .register(Registration.create("foo", this.wireMock.url("/health")).build()) .withEndpoints(Endpoints.single("info", this.wireMock.url("/info"))).withStatusInfo(StatusInfo.ofUp()) .withInfo(Info.from(singletonMap("foo", "bar"))); StepVerifier.create(this.repository.save(instance)).expectNextCount(1).verifyComplete(); this.wireMock.stubFor(get("/info").willReturn(serverError())); // when StepVerifier.create(this.eventStore).expectSubscription() .then(() -> StepVerifier.create(this.updater.updateInfo(instance.getId())).verifyComplete()) // then .assertNext((event) -> assertThat(event).isInstanceOf(InstanceInfoChangedEvent.class)).thenCancel() .verify(); StepVerifier.create(this.repository.find(instance.getId())) .assertNext((app) -> assertThat(app.getInfo()).isEqualTo(Info.empty())).verifyComplete(); }
Example #9
Source File: InfoUpdaterTest.java From spring-boot-admin with Apache License 2.0 | 6 votes |
@Test public void should_retry() { // given Registration registration = Registration.create("foo", this.wireMock.url("/health")).build(); Instance instance = Instance.create(InstanceId.of("onl")).register(registration) .withEndpoints(Endpoints.single("info", this.wireMock.url("/info"))).withStatusInfo(StatusInfo.ofUp()); StepVerifier.create(this.repository.save(instance)).expectNextCount(1).verifyComplete(); this.wireMock.stubFor(get("/info").inScenario("retry").whenScenarioStateIs(STARTED) .willReturn(aResponse().withFixedDelay(5000)).willSetStateTo("recovered")); String body = "{ \"foo\": \"bar\" }"; this.wireMock.stubFor(get("/info").inScenario("retry").whenScenarioStateIs("recovered") .willReturn(okJson(body).withHeader("Content-Length", Integer.toString(body.length())))); // when StepVerifier.create(this.eventStore).expectSubscription() .then(() -> StepVerifier.create(this.updater.updateInfo(instance.getId())).verifyComplete()) // then .assertNext((event) -> assertThat(event).isInstanceOf(InstanceInfoChangedEvent.class)).thenCancel() .verify(); StepVerifier.create(this.repository.find(instance.getId())) .assertNext((app) -> assertThat(app.getInfo()).isEqualTo(Info.from(singletonMap("foo", "bar")))) .verifyComplete(); }
Example #10
Source File: MailNotifier.java From spring-boot-admin with Apache License 2.0 | 6 votes |
@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 #11
Source File: MicrosoftTeamsNotifier.java From Moss with Apache License 2.0 | 6 votes |
protected Message createMessage(Instance instance, String registeredTitle, String activitySubtitle) { List<Fact> facts = new ArrayList<>(); facts.add(new Fact(STATUS_KEY, instance.getStatusInfo().getStatus())); facts.add(new Fact(SERVICE_URL_KEY, instance.getRegistration().getServiceUrl())); facts.add(new Fact(HEALTH_URL_KEY, instance.getRegistration().getHealthUrl())); facts.add(new Fact(MANAGEMENT_URL_KEY, instance.getRegistration().getManagementUrl())); facts.add(new Fact(SOURCE_KEY, instance.getRegistration().getSource())); Section section = Section.builder() .activityTitle(instance.getRegistration().getName()) .activitySubtitle(activitySubtitle) .facts(facts) .build(); return Message.builder() .title(registeredTitle) .summary(messageSummary) .themeColor(themeColor) .sections(singletonList(section)) .build(); }
Example #12
Source File: ProbeEndpointsStrategyTest.java From spring-boot-admin with Apache License 2.0 | 6 votes |
@Test public void should_retry() { // given Instance instance = Instance.create(InstanceId.of("id")).register(Registration .create("test", this.wireMock.url("/mgmt/health")).managementUrl(this.wireMock.url("/mgmt")).build()); this.wireMock.stubFor(options(urlEqualTo("/mgmt/metrics")).inScenario("retry").whenScenarioStateIs(STARTED) .willReturn(aResponse().withFixedDelay(5000)).willSetStateTo("recovered")); this.wireMock.stubFor(options(urlEqualTo("/mgmt/metrics")).inScenario("retry").whenScenarioStateIs("recovered") .willReturn(ok())); this.wireMock.stubFor(options(urlEqualTo("/mgmt/stats")).willReturn(ok())); this.wireMock.stubFor(options(urlEqualTo("/mgmt/info")).willReturn(ok())); this.wireMock.stubFor(options(urlEqualTo("/mgmt/non-exist")).willReturn(notFound())); ProbeEndpointsStrategy strategy = new ProbeEndpointsStrategy(this.instanceWebClient, new String[] { "metrics:stats", "metrics", "info", "non-exist" }); // when StepVerifier.create(strategy.detectEndpoints(instance)) // then .expectNext(Endpoints.single("metrics", this.wireMock.url("/mgmt/stats")).withEndpoint("info", this.wireMock.url("/mgmt/info")))// .verifyComplete(); }
Example #13
Source File: StatusUpdaterTest.java From Moss with Apache License 2.0 | 6 votes |
@Before public void setup() { eventStore = new InMemoryEventStore(); repository = new EventsourcingInstanceRepository(eventStore); instance = Instance.create(InstanceId.of("id")) .register(Registration.create("foo", wireMock.url("/health")).build()); StepVerifier.create(repository.save(instance)).expectNextCount(1).verifyComplete(); updater = new StatusUpdater(repository, InstanceWebClient.builder() .connectTimeout(Duration.ofSeconds(2)) .readTimeout(Duration.ofSeconds(2)) .retries(singletonMap(Endpoint.HEALTH, 1)) .build() ); }
Example #14
Source File: QueryIndexEndpointStrategyTest.java From spring-boot-admin with Apache License 2.0 | 6 votes |
@Test public void should_return_empty_on_wrong_content_type() { // given Instance instance = Instance.create(InstanceId.of("id")).register(Registration .create("test", this.wireMock.url("/mgmt/health")).managementUrl(this.wireMock.url("/mgmt")).build()); String body = "HELLOW WORLD"; this.wireMock.stubFor(get("/mgmt").willReturn(ok(body).withHeader("Content-Type", MediaType.TEXT_PLAIN_VALUE))); QueryIndexEndpointStrategy strategy = new QueryIndexEndpointStrategy(this.instanceWebClient); // when StepVerifier.create(strategy.detectEndpoints(instance)) // then .verifyComplete(); }
Example #15
Source File: QueryIndexEndpointStrategyTest.java From spring-boot-admin with Apache License 2.0 | 6 votes |
@Test public void should_return_endpoints_with_aligned_scheme() { // given Instance instance = Instance.create(InstanceId.of("id")).register(Registration .create("test", this.wireMock.url("/mgmt/health")).managementUrl(this.wireMock.url("/mgmt")).build()); String host = "http://localhost:" + this.wireMock.httpsPort(); String body = "{\"_links\":{\"metrics-requiredMetricName\":{\"templated\":true,\"href\":\"" + host + "/mgmt/metrics/{requiredMetricName}\"},\"self\":{\"templated\":false,\"href\":\"" + host + "/mgmt\"},\"metrics\":{\"templated\":false,\"href\":\"" + host + "/mgmt/stats\"},\"info\":{\"templated\":false,\"href\":\"" + host + "/mgmt/info\"}}}"; this.wireMock.stubFor(get("/mgmt").willReturn(ok(body).withHeader("Content-Type", ActuatorMediaType.V2_JSON))); QueryIndexEndpointStrategy strategy = new QueryIndexEndpointStrategy(this.instanceWebClient); // when String secureHost = "https://localhost:" + this.wireMock.httpsPort(); StepVerifier.create(strategy.detectEndpoints(instance)) // then .expectNext(Endpoints.single("metrics", secureHost + "/mgmt/stats").withEndpoint("info", secureHost + "/mgmt/info"))// .verifyComplete(); }
Example #16
Source File: QueryIndexEndpointStrategy.java From spring-boot-admin with Apache License 2.0 | 6 votes |
protected Function<ClientResponse, Mono<Endpoints>> convert(Instance instance, String managementUrl) { return (response) -> { if (!response.statusCode().is2xxSuccessful()) { log.debug("Querying actuator-index for instance {} on '{}' failed with status {}.", instance.getId(), managementUrl, response.rawStatusCode()); return response.releaseBody().then(Mono.empty()); } if (!response.headers().contentType().map(actuatorMediaType::isCompatibleWith).orElse(false)) { log.debug("Querying actuator-index for instance {} on '{}' failed with incompatible Content-Type '{}'.", instance.getId(), managementUrl, response.headers().contentType().map(Objects::toString).orElse("(missing)")); return response.releaseBody().then(Mono.empty()); } log.debug("Querying actuator-index for instance {} on '{}' successful.", instance.getId(), managementUrl); return response.bodyToMono(Response.class).flatMap(this::convertResponse) .map(this.alignWithManagementUrl(instance.getId(), managementUrl)); }; }
Example #17
Source File: InstanceDiscoveryListener.java From Moss with Apache License 2.0 | 5 votes |
protected Mono<Void> removeStaleInstances(Set<InstanceId> registeredInstanceIds) { return repository.findAll() .filter(Instance::isRegistered) .filter(instance -> SOURCE.equals(instance.getRegistration().getSource())) .map(Instance::getId) .filter(id -> !registeredInstanceIds.contains(id)) .doOnNext(id -> log.info("Instance ({}) missing in DiscoveryClient services ", id)) .flatMap(registry::deregister) .then(); }
Example #18
Source File: BasicAuthHttpHeaderProvider.java From spring-boot-admin with Apache License 2.0 | 5 votes |
@Override public HttpHeaders getHeaders(Instance instance) { String username = getMetadataValue(instance, USERNAME_KEYS); String password = getMetadataValue(instance, PASSWORD_KEYS); HttpHeaders headers = new HttpHeaders(); if (StringUtils.hasText(username) && StringUtils.hasText(password)) { headers.set(HttpHeaders.AUTHORIZATION, encode(username, password)); } return headers; }
Example #19
Source File: CloudFoundryHttpHeaderProviderTest.java From spring-boot-admin with Apache License 2.0 | 5 votes |
@Test public void test_cloud_foundry_header() { Registration registration = Registration.create("foo", "http://health") .metadata("applicationId", "549e64cf-a478-423d-9d6d-02d803a028a8").metadata("instanceId", "0").build(); Instance instance = Instance.create(InstanceId.of("id")).register(registration); assertThat(headersProvider.getHeaders(instance).get("X-CF-APP-INSTANCE")) .containsOnly("549e64cf-a478-423d-9d6d-02d803a028a8:0"); }
Example #20
Source File: InstanceWebClientTest.java From Moss with Apache License 2.0 | 5 votes |
@Test public void should_error_on_unknown_endpoint() { Instance instance = Instance.create(InstanceId.of("id")) .register(Registration.create("test", wireMock.url("/status")).build()); Mono<ClientResponse> exchange = instanceWebClient.instance(instance).get().uri("unknown").exchange(); StepVerifier.create(exchange) .verifyErrorSatisfies(ex -> assertThat(ex).isInstanceOf(ResolveEndpointException.class) .hasMessageContaining("Endpoint 'unknown' not found")); }
Example #21
Source File: DiscordNotifier.java From spring-boot-admin with Apache License 2.0 | 5 votes |
@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, createDiscordNotification(event, instance), Void.class)); }
Example #22
Source File: MailNotifierTest.java From spring-boot-admin with Apache License 2.0 | 5 votes |
@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 #23
Source File: ProbeEndpointsStrategy.java From spring-boot-admin with Apache License 2.0 | 5 votes |
@Override public Mono<Endpoints> detectEndpoints(Instance instance) { if (instance.getRegistration().getManagementUrl() == null) { log.debug("Endpoint probe for instance {} omitted. No management-url registered.", instance.getId()); return Mono.empty(); } return Flux.fromIterable(this.endpoints).flatMap((endpoint) -> detectEndpoint(instance, endpoint)).collectList() .flatMap(this::convert); }
Example #24
Source File: HipchatNotifier.java From spring-boot-admin with Apache License 2.0 | 5 votes |
@Nullable protected String getMessage(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 #25
Source File: HipchatNotifier.java From Moss with Apache License 2.0 | 5 votes |
@Override protected Mono<Void> doNotify(InstanceEvent event, Instance instance) { return Mono.fromRunnable(() -> restTemplate.postForEntity(buildUrl(), createHipChatNotification(event, instance), Void.class )); }
Example #26
Source File: BasicAuthHttpHeaderProviderTest.java From Moss with Apache License 2.0 | 5 votes |
@Test public void test_auth_header() { Registration registration = Registration.create("foo", "http://health") .metadata("user.name", "test") .metadata("user.password", "drowssap") .build(); Instance instance = Instance.create(InstanceId.of("id")).register(registration); assertThat(headersProvider.getHeaders(instance).get(HttpHeaders.AUTHORIZATION)).containsOnly( "Basic dGVzdDpkcm93c3NhcA=="); }
Example #27
Source File: QueryIndexEndpointStrategyTest.java From spring-boot-admin with Apache License 2.0 | 5 votes |
@Test public void should_return_empty_on_not_found() { // given Instance instance = Instance.create(InstanceId.of("id")).register(Registration .create("test", this.wireMock.url("/mgmt/health")).managementUrl(this.wireMock.url("/mgmt")).build()); this.wireMock.stubFor(get("/mgmt").willReturn(notFound())); QueryIndexEndpointStrategy strategy = new QueryIndexEndpointStrategy(this.instanceWebClient); // when StepVerifier.create(strategy.detectEndpoints(instance)) // then .verifyComplete(); }
Example #28
Source File: PagerdutyNotifier.java From Moss with Apache License 2.0 | 5 votes |
protected Map<String, Object> createPagerdutyEvent(InstanceEvent event, Instance instance) { Map<String, Object> result = new HashMap<>(); result.put("service_key", serviceKey); result.put("incident_key", instance.getRegistration().getName() + "/" + event.getInstance()); result.put("description", getDescription(event, instance)); Map<String, Object> details = getDetails(event); result.put("details", details); if (event instanceof InstanceStatusChangedEvent) { if ("UP".equals(((InstanceStatusChangedEvent) event).getStatusInfo().getStatus())) { result.put("event_type", "resolve"); } else { result.put("event_type", "trigger"); if (client != null) { result.put("client", client); } if (clientUrl != null) { result.put("client_url", clientUrl); } Map<String, Object> context = new HashMap<>(); context.put("type", "link"); context.put("href", instance.getRegistration().getHealthUrl()); context.put("text", "Application health-endpoint"); result.put("contexts", singletonList(context)); } } return result; }
Example #29
Source File: LoggingNotifier.java From Moss with Apache License 2.0 | 5 votes |
@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 #30
Source File: MailNotifier.java From Moss with Apache License 2.0 | 5 votes |
@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); } }); }