Java Code Examples for com.netflix.appinfo.InstanceInfo

The following examples show how to use com.netflix.appinfo.InstanceInfo. These examples are extracted from open source projects. 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 Project: flair-registry   Source File: EurekaResource.java    License: Apache License 2.0 6 votes vote down vote up
private List<Map<String, Object>> getApplications() {
    List<Application> sortedApplications = getRegistry().getSortedApplications();
    ArrayList<Map<String, Object>> apps = new ArrayList<>();
    for (Application app : sortedApplications) {
        LinkedHashMap<String, Object> appData = new LinkedHashMap<>();
        apps.add(appData);
        appData.put("name", app.getName());
        List<Map<String, Object>> instances = new ArrayList<>();
        for (InstanceInfo info : app.getInstances()) {
            Map<String, Object> instance = new HashMap<>();
            instance.put("instanceId", info.getInstanceId());
            instance.put("homePageUrl", info.getHomePageUrl());
            instance.put("healthCheckUrl", info.getHealthCheckUrl());
            instance.put("statusPageUrl", info.getStatusPageUrl());
            instance.put("status", info.getStatus().name());
            instance.put("metadata", info.getMetadata());
            instances.add(instance);
        }
        appData.put("instances", instances);
    }
    return apps;
}
 
Example 2
@Test
public void testRegister() throws Exception {
	// creating instance info
	final LeaseInfo leaseInfo = getLeaseInfo();
	final InstanceInfo instanceInfo = getInstanceInfo(APP_NAME, HOST_NAME,
			INSTANCE_ID, PORT, leaseInfo);
	// calling tested method
	instanceRegistry.register(instanceInfo, false);
	// event of proper type is registered
	assertThat(this.testEvents.applicationEvents.size()).isEqualTo(1);
	assertThat(this.testEvents.applicationEvents
			.get(0) instanceof EurekaInstanceRegisteredEvent).isTrue();
	// event details are correct
	final EurekaInstanceRegisteredEvent registeredEvent = (EurekaInstanceRegisteredEvent) (this.testEvents.applicationEvents
			.get(0));
	assertThat(registeredEvent.getInstanceInfo()).isEqualTo(instanceInfo);
	assertThat(registeredEvent.getLeaseDuration())
			.isEqualTo(leaseInfo.getDurationInSecs());
	assertThat(registeredEvent.getSource()).isEqualTo(instanceRegistry);
	assertThat(registeredEvent.isReplication()).isFalse();
}
 
Example 3
@Before
public void setUp() {
    PowerMock.mockStatic(DiscoveryClient.class);

    EasyMock
            .expect(DiscoveryClient.getZone(EasyMock.isA(InstanceInfo.class)))
            .andReturn("zone")
            .anyTimes();

    eurekaClientMock = setUpEurekaClientMock(servers);
    eurekaClientProvider = new Provider<EurekaClient>() {
        @Override
        public EurekaClient get() {
            return eurekaClientMock;
        }
    };

    config = DefaultClientConfigImpl.getClientConfigWithDefaultValues();
    config.set(CommonClientConfigKey.DeploymentContextBasedVipAddresses, vipAddress);
    config.set(CommonClientConfigKey.ServerListUpdaterClassName, EurekaNotificationServerListUpdater.class.getName());
}
 
Example 4
Source Project: spring-cloud-netflix   Source File: EurekaRegistration.java    License: Apache License 2.0 6 votes vote down vote up
public EurekaRegistration build() {
	Assert.notNull(instanceConfig, "instanceConfig may not be null");

	if (this.applicationInfoManager == null) {
		InstanceInfo instanceInfo = new InstanceInfoFactory()
				.create(this.instanceConfig);
		this.applicationInfoManager = new ApplicationInfoManager(
				this.instanceConfig, instanceInfo);
	}
	if (this.eurekaClient == null) {
		Assert.notNull(this.clientConfig,
				"if eurekaClient is null, EurekaClientConfig may not be null");
		Assert.notNull(this.publisher,
				"if eurekaClient is null, ApplicationEventPublisher may not be null");

		this.eurekaClient = new CloudEurekaClient(this.applicationInfoManager,
				this.clientConfig, this.publisher);
	}
	return new EurekaRegistration(instanceConfig, eurekaClient,
			applicationInfoManager, healthCheckHandler);
}
 
Example 5
Source Project: api-layer   Source File: InstanceRefreshService.java    License: Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Compare cached instances against eureka delta to send back a change-list
 *
 * @param delta retrieved from Eureka
 * @return changed instances
 */
private Set<InstanceInfo> updateDelta(Applications delta) {
    int deltaCount = 0;
    Set<InstanceInfo> updatedInstances = new HashSet<>();
    for (Application app : delta.getRegisteredApplications()) {
        for (InstanceInfo instance : app.getInstances()) {
            ++deltaCount;
            if (InstanceInfo.ActionType.ADDED.equals(instance.getActionType())) {
                log.debug("Added instance {} to the list of changed instances ", instance.getId());
                updatedInstances.add(instance);
            } else if (InstanceInfo.ActionType.MODIFIED.equals(instance.getActionType())) {
                log.debug("Modified instance {} added to the list of changed instances ", instance.getId());
                updatedInstances.add(instance);
            } else if (InstanceInfo.ActionType.DELETED.equals(instance.getActionType())) {
                log.debug("Deleted instance {} added to the list of changed instances ", instance.getId());
                instance.setStatus(InstanceInfo.InstanceStatus.DOWN);
                updatedInstances.add(instance);
            }
        }
    }

    log.debug("The total number of changed instances fetched by the delta processor : {}", deltaCount);
    return updatedInstances;
}
 
Example 6
Source Project: spring-cloud-netflix   Source File: InstanceRegistry.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean renew(final String appName, final String serverId,
		boolean isReplication) {
	log("renew " + appName + " serverId " + serverId + ", isReplication {}"
			+ isReplication);
	List<Application> applications = getSortedApplications();
	for (Application input : applications) {
		if (input.getName().equals(appName)) {
			InstanceInfo instance = null;
			for (InstanceInfo info : input.getInstances()) {
				if (info.getId().equals(serverId)) {
					instance = info;
					break;
				}
			}
			publishEvent(new EurekaInstanceRenewedEvent(this, appName, serverId,
					instance, isReplication));
			break;
		}
	}
	return super.renew(appName, serverId, isReplication);
}
 
Example 7
Source Project: api-layer   Source File: GatewayNotifierTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testServiceUpdated() {
    verify(restTemplate, never()).delete(anyString());

    List<InstanceInfo> instances = Arrays.asList(
        createInstanceInfo("hostname1", 1000, 1433),
        createInstanceInfo("hostname2", 1000, 0)
    );

    Application application = mock(Application.class);
    when(application.getInstances()).thenReturn(instances);
    when(registry.getApplication("GATEWAY")).thenReturn(application);

    gatewayNotifierSync.serviceUpdated("testService", null);
    verify(restTemplate, times(1)).delete("https://hostname1:1433/gateway/cache/services/testService");
    verify(restTemplate, times(1)).delete("http://hostname2:1000/gateway/cache/services/testService");

    gatewayNotifierSync.serviceUpdated(null, null);
    verify(restTemplate, times(1)).delete("https://hostname1:1433/gateway/cache/services");
    verify(restTemplate, times(1)).delete("http://hostname2:1000/gateway/cache/services");

    verify(restTemplate, times(4)).delete(anyString());
}
 
Example 8
public String generateSubstituteSwaggerForService(InstanceInfo service,
                                                  ApiInfo api,
                                                  String gatewayScheme, String gatewayHost) {
    String title = service.getMetadata().get(SERVICE_TITLE);
    String description = service.getMetadata().get(SERVICE_DESCRIPTION);
    String basePath = (api.getGatewayUrl().startsWith("/") ? "" : "/") + api.getGatewayUrl()
        + (api.getGatewayUrl().endsWith("/") ? "" : "/") + service.getAppName().toLowerCase();

    Template t = ve.getTemplate("substitute_swagger.json");
    VelocityContext context = new VelocityContext();
    context.put("title", title);
    context.put("description", description);
    context.put("version", api.getVersion());
    context.put("scheme", gatewayScheme);
    context.put("host", gatewayHost);
    context.put("basePath", basePath);
    context.put("documentationUrl", api.getDocumentationUrl());

    StringWriter w = new StringWriter();
    t.merge(context, w);

    return w.toString();
}
 
Example 9
@Test
public void testProcessServicesDataWithAuthenticationMetadata() {
    String routedServiceYaml = "services:\n" +
        "    - serviceId: casamplerestapiservice\n" +
        "      instanceBaseUrls:\n" +
        "        - https://localhost:10019/casamplerestapiservice/\n" +
        "      authentication:\n" +
        "        scheme: httpBasicPassTicket\n" +
        "        applid: TSTAPPL\n";
    StaticRegistrationResult result = processServicesData(routedServiceYaml);
    assertEquals(new ArrayList<>(), result.getErrors());
    List<InstanceInfo> instances = result.getInstances();
    assertEquals(1, instances.size());
    assertEquals("httpBasicPassTicket", instances.get(0).getMetadata().get(AUTHENTICATION_SCHEME));
    assertEquals("TSTAPPL", instances.get(0).getMetadata().get(AUTHENTICATION_APPLID));
}
 
Example 10
public static InstanceStatus toGrayInstanceStatus(InstanceInfo.InstanceStatus status) {
    if (status == null) {
        return InstanceStatus.UNKNOWN;
    }
    switch (status) {
        case DOWN:
            return InstanceStatus.DOWN;
        case UP:
            return InstanceStatus.UP;
        case STARTING:
            return InstanceStatus.STARTING;
        case OUT_OF_SERVICE:
            return InstanceStatus.OUT_OF_SERVICE;
        default:
            return InstanceStatus.UNKNOWN;
    }
}
 
Example 11
public static InstanceInfo.InstanceStatus toEurekaInstanceStatus(InstanceStatus status) {
    switch (status) {
        case UP:
            return InstanceInfo.InstanceStatus.UP;
        case DOWN:
            return InstanceInfo.InstanceStatus.DOWN;
        case UNKNOWN:
            return InstanceInfo.InstanceStatus.UNKNOWN;
        case STARTING:
            return InstanceInfo.InstanceStatus.STARTING;
        case OUT_OF_SERVICE:
            return InstanceInfo.InstanceStatus.OUT_OF_SERVICE;
        default:
            log.error("不支持{}类型的实例状态", status);
            throw new UnsupportedOperationException("不支持的实例状态");

    }
}
 
Example 12
Source Project: api-layer   Source File: AuthenticationService.java    License: Eclipse Public License 2.0 6 votes vote down vote up
/**
 * This method get all invalidated JWT token in the cache and distributes them to instance of Gateway with name
 * in argument toInstanceId. If instance cannot be find it return false. A notification can throw an runtime
 * exception. In all other cases all invalidated token are distributed and method returns true.
 *
 * @param toInstanceId instanceId of Gateway where invalidated JWT token should be sent
 * @return true if all token were sent, otherwise false
 */
public boolean distributeInvalidate(String toInstanceId) {
    final Application application = discoveryClient.getApplication(CoreService.GATEWAY.getServiceId());
    if (application == null) return false;

    final InstanceInfo instanceInfo = application.getByInstanceId(toInstanceId);
    if (instanceInfo == null) return false;

    final String url = EurekaUtils.getUrl(instanceInfo) + AuthController.CONTROLLER_PATH + "/invalidate/{}";

    final Collection<String> invalidated = cacheUtils.getAllRecords(cacheManager, CACHE_INVALIDATED_JWT_TOKENS);
    for (final String invalidatedToken : invalidated) {
        restTemplate.delete(url, invalidatedToken);
    }

    return true;
}
 
Example 13
Source Project: zuul   Source File: ClientConnectionsShutdown.java    License: Apache License 2.0 6 votes vote down vote up
private void initDiscoveryListener()
{
    this.discoveryClient.registerEventListener(event -> {
        if (event instanceof StatusChangeEvent) {
            StatusChangeEvent sce = (StatusChangeEvent) event;

            LOG.info("Received " + sce.toString());

            if (sce.getPreviousStatus() == InstanceInfo.InstanceStatus.UP
                && (sce.getStatus() == InstanceInfo.InstanceStatus.OUT_OF_SERVICE || sce.getStatus() == InstanceInfo.InstanceStatus.DOWN))
            {
                // TODO - Also should stop accepting any new client connections now too?

                // Schedule to gracefully close all the client connections.
                if (ENABLED.get()) {
                    executor.schedule(() -> {
                        gracefullyShutdownClientChannels();
                    }, DELAY_AFTER_OUT_OF_SERVICE_MS.get(), TimeUnit.MILLISECONDS);
                }
            }
        }
    });
}
 
Example 14
Source Project: onetwo   Source File: ExtEurekaController.java    License: Apache License 2.0 6 votes vote down vote up
protected String refreshInstanceConfig(InstanceInfo inst) {
		InstanceInfoMeta meta = InstanceInfoMeta.newInstance(inst);
		String url = meta.getRefreshConfigUrl();

		String authHeaderName = meta.getAuthHeaderName(this.authHeaderName);
		
		String auth = RequestUtils.getCookieValue(request, authHeaderName);
		HttpHeaders headers = RestUtils.createHeader(MediaType.APPLICATION_JSON_UTF8);
		if (StringUtils.isNotBlank(auth)) {
//			headers.set("auth", auth);
			headers.set("Cookie", authHeaderName+"="+auth);
		}

		if (log.isInfoEnabled()) {
			log.info("refresh config post url: {}, auth: {}", url, auth);
		}
		
		HttpEntity<?> entity = new HttpEntity<>(null, headers);
		String result = this.restTemplate.postForEntity(url, entity, String.class).getBody();
		return result;
	}
 
Example 15
Source Project: chassis   Source File: ChassisEurekaRegistrationTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
 public void testServiceRegistration() throws InterruptedException {
 	// Registers "chasis-default-name" with a Eurkea server running on local host.
 	//   http://localhost:8184/v2/apps/chassis-default-name

 	// tell eureka the service is up which causes a registration
 	ApplicationInfoManager.getInstance().setInstanceStatus(InstanceInfo.InstanceStatus.UP);
 	
 	// get application registration from Eureka
 	DiscoveryClient client = DiscoveryManager.getInstance().getDiscoveryClient();
 	InstanceInfo instanceInfo = null;
 	for (int i = 0; (instanceInfo == null) && (i < 50); i++) {
 		Thread.sleep(5000);
 		try {
	instanceInfo =  client.getNextServerFromEureka("default-service", false);
} catch (RuntimeException e) {
	// eat not found runtime exception
}
 	}
 	Assert.assertNotNull(instanceInfo);
 	Assert.assertEquals(InstanceStatus.UP, instanceInfo.getStatus());
 	System.out.println("done");
 }
 
Example 16
Source Project: eureka-consul-adapter   Source File: ServiceControllerTest.java    License: MIT License 6 votes vote down vote up
@Test
public void service_sampleService_jsonObject_preferHostName() throws Exception {

    Applications applications = mock2Applications();
    Mockito.when(registry.getApplications()).thenReturn(applications);
    Application ms1 = applications.getRegisteredApplications().get(0);

    InstanceInfo instance1 = mock1Instance();
    ms1.addInstance(instance1);

    InstanceInfo instance2 = mock1Instance("2","1.2.3.5", "2.ms1.com", 81, true);
    ms1.addInstance(instance2);

    Mockito.when(registry.getApplication("ms1")).thenReturn(ms1);

    instanceInfoMapper.setPreferHostName(true);

    performAsync("/v1/catalog/service/ms1?wait=1ms")
            .andExpect(content().contentType("application/json;charset=UTF-8"))
            .andExpect(jsonPath("$[0].Address", Matchers.is("ms1.com")))
            .andExpect(jsonPath("$[0].ServiceAddress", Matchers.is("ms1.com")))

            .andExpect(jsonPath("$[1].Address", Matchers.is("2.ms1.com")))
            .andExpect(jsonPath("$[1].ServiceAddress", Matchers.is("2.ms1.com")));
}
 
Example 17
@Test
public void testUpdating() {
    serviceDefinitionProcessor.setLocation("api-defs");

    staticServicesRegistrationService.reloadServices();
    Map<String, InstanceInfo> map = staticServicesRegistrationService.getStaticInstances().stream()
        .collect(Collectors.toMap(InstanceInfo::getId, Function.identity()));

    assertEquals(
        "TSTAPPL4",
        map.get("STATIC-localhost:toAddAuth:10012").getMetadata().get(AUTHENTICATION_APPLID)
    );

    assertEquals(
        "TSTAPPL5",
        map.get("STATIC-localhost:toReplaceAuth:10012").getMetadata().get(AUTHENTICATION_APPLID)
    );

    assertEquals(
        "TSTAPPL3",
        map.get("STATIC-localhost:nowFixedAuth:10012").getMetadata().get(AUTHENTICATION_APPLID)
    );
}
 
Example 18
@SuppressWarnings("unchecked")
@Bean
public EurekaHttpClient mockEurekaHttpClient() {
	InstanceInfo instanceInfo = InstanceInfo.Builder.newBuilder()
			.setAppName("configserver").build();
	List<InstanceInfo> instanceInfos = Collections.singletonList(instanceInfo);

	Applications applications = mock(Applications.class);
	when(applications.getInstancesByVirtualHostName("configserver"))
			.thenReturn(instanceInfos);

	EurekaHttpResponse<Applications> response = mock(EurekaHttpResponse.class);
	when(response.getStatusCode()).thenReturn(200);
	when(response.getEntity()).thenReturn(applications);

	EurekaHttpClient client = mock(EurekaHttpClient.class);
	when(client.getApplications("us-east-1")).thenReturn(response);
	return client;
}
 
Example 19
Source Project: didi-eureka-server   Source File: InstanceRegistryTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testRegister() throws Exception {
	// creating instance info
	final LeaseInfo leaseInfo = getLeaseInfo();
	final InstanceInfo instanceInfo = getInstanceInfo(APP_NAME, HOST_NAME, INSTANCE_ID, PORT, leaseInfo);
	// calling tested method
	instanceRegistry.register(instanceInfo, false);
	// event of proper type is registered
	assertEquals(1, this.testEvents.applicationEvents.size());
	assertTrue(this.testEvents.applicationEvents.get(0) instanceof EurekaInstanceRegisteredEvent);
	// event details are correct
	final EurekaInstanceRegisteredEvent registeredEvent =
			(EurekaInstanceRegisteredEvent) (this.testEvents.applicationEvents.get(0));
	assertEquals(instanceInfo, registeredEvent.getInstanceInfo());
	assertEquals(leaseInfo.getDurationInSecs(), registeredEvent.getLeaseDuration());
	assertEquals(instanceRegistry, registeredEvent.getSource());
	assertFalse(registeredEvent.isReplication());
}
 
Example 20
public Optional<InstanceInfo> chooseNext() {
    long now = clock.wallTime();

    Map<String, EurekaInstance> eurekaInstances = eurekaInstancesRef.get();
    if (eurekaInstances.isEmpty()) {
        return Optional.empty();
    }

    return chooseNextHealthy(eurekaInstances, now);
}
 
Example 21
Source Project: Moss   Source File: EurekaServiceInstanceConverterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void convert_missing_mgmtpath() {
    InstanceInfo instanceInfo = mock(InstanceInfo.class);
    when(instanceInfo.getHealthCheckUrl()).thenReturn("http://localhost:80/mgmt/ping");
    EurekaServiceInstance service = mock(EurekaServiceInstance.class);
    when(service.getInstanceInfo()).thenReturn(instanceInfo);
    when(service.getUri()).thenReturn(URI.create("http://localhost:80"));
    when(service.getServiceId()).thenReturn("test");

    Registration registration = new EurekaServiceInstanceConverter().convert(service);

    assertThat(registration.getManagementUrl()).isEqualTo("http://localhost:80/actuator");
}
 
Example 22
Source Project: Moss   Source File: EurekaServiceInstanceConverterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void convert_secure_healthUrl() {
    InstanceInfo instanceInfo = mock(InstanceInfo.class);
    when(instanceInfo.getSecureHealthCheckUrl()).thenReturn("https://localhost:80/health");
    EurekaServiceInstance service = mock(EurekaServiceInstance.class);
    when(service.getInstanceInfo()).thenReturn(instanceInfo);
    when(service.getUri()).thenReturn(URI.create("http://localhost:80"));
    when(service.getServiceId()).thenReturn("test");

    Registration registration = new EurekaServiceInstanceConverter().convert(service);

    assertThat(registration.getHealthUrl()).isEqualTo("https://localhost:80/health");
}
 
Example 23
Source Project: didi-eureka-server   Source File: CloudJacksonJson.java    License: MIT License 5 votes vote down vote up
static InstanceInfo updateIfNeeded(final InstanceInfo info) {
	if (info.getInstanceId() == null && info.getMetadata() != null) {
		String instanceId = info.getMetadata().get("instanceId");
		if (StringUtils.hasText(instanceId)) {
			// backwards compatibility for Angel
			if (StringUtils.hasText(info.getHostName()) && !instanceId.startsWith(info.getHostName())) {
				instanceId = info.getHostName()+":"+instanceId;
			}
			return new InstanceInfo.Builder(info).setInstanceId(instanceId).build();
		}
	}
	return info;
}
 
Example 24
Source Project: api-layer   Source File: APIDocRetrievalService.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Get ApiDoc url
 *
 * @param apiInfo      the apiInfo of service instance
 * @param instanceInfo the information about service instance
 * @param routes       the routes of service instance
 * @return the url of apidoc
 */
private String getApiDocUrl(ApiInfo apiInfo, InstanceInfo instanceInfo, RoutedServices routes) {
    String apiDocUrl = null;
    if (apiInfo == null) {
        apiDocUrl = createApiDocUrlFromRouting(instanceInfo, routes);
    } else if (apiInfo.getSwaggerUrl() != null) {
        apiDocUrl = apiInfo.getSwaggerUrl();
    }

    return apiDocUrl;
}
 
Example 25
private EurekaHttpResponse<InstanceInfo> getInstanceInternal(String urlPath) {
	urlPath = serviceUrl + urlPath;

	ResponseEntity<InstanceInfo> response = restTemplate.exchange(urlPath,
			HttpMethod.GET, null, InstanceInfo.class);

	return anEurekaHttpResponse(response.getStatusCodeValue(),
			response.getStatusCodeValue() == HttpStatus.OK.value()
					&& response.hasBody() ? response.getBody() : null)
							.headers(headersOf(response)).build();
}
 
Example 26
Source Project: fw-spring-cloud   Source File: MyHealthCheckHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public InstanceInfo.InstanceStatus getStatus(InstanceInfo.InstanceStatus instanceStatus) {
    if(myHealthIndicator.health().getStatus().equals(Status.UP)){
        log.info("第三方服务可以正常访问");
        return InstanceInfo.InstanceStatus.UP;
    }else{
        log.info("第三方服务访问异常");
        return InstanceInfo.InstanceStatus.DOWN;
    }
}
 
Example 27
Source Project: api-layer   Source File: GatewayNotifierTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private InstanceInfo createInstanceInfo(String serviceId, String hostName, int port, int securePort) {
    InstanceInfo out = mock(InstanceInfo.class);
    when(out.getHostName()).thenReturn(hostName);
    when(out.getPort()).thenReturn(port);
    when(out.getSecurePort()).thenReturn(securePort);
    when(out.getInstanceId()).thenReturn(hostName + ":" + serviceId + ":" + (securePort == 0 ? port : securePort));
    return out;
}
 
Example 28
Source Project: riposte   Source File: EurekaVipAddressService.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @return A {@link CompletableFuture} that when it completes will call {@link
 * #getActiveInstanceInfosForVipAddress(String, Optional)} to determine the *next* active {@link InstanceInfo} that
 * should be called for the given VIP name, or an empty Optional if no active instances were found. If you pass in
 * an {@link Executor} for the {@code longRunningTaskExecutor} argument then it will be used to execute the future,
 * otherwise the default will be used (typically the Java common fork-join pool).
 */
public CompletableFuture<Optional<InstanceInfo>> getActiveInstanceInfoForVipAddress(
        String vipName, Optional<Executor> longRunningTaskExecutor
) {
    return longRunningTaskExecutor
            .map(executor -> CompletableFuture.supplyAsync(
                    () -> getActiveInstanceInfoForVipAddressBlocking(vipName), executor)
            )
            .orElse(
                    CompletableFuture.supplyAsync(() -> getActiveInstanceInfoForVipAddressBlocking(vipName))
            );
}
 
Example 29
private String takeStateReasonOf(Job<?> job, Task task) {
    List<InstanceInfo> instances = eurekaClient.getInstancesById(task.getId());

    if (CollectionsExt.isNullOrEmpty(instances)) {
        return JobFunctions.isDisabled(job) ? "not registered, and job disabled" : "not registered";
    }

    // If it is finished, ignore Eureka status
    if (task.getStatus().getState() == TaskState.Finished) {
        return "terminated";
    }

    return instances.get(0).getStatus().name();
}
 
Example 30
private void mockStatusInEureka(AgentInstance instance, InstanceStatus eurekaStatus) {
    InstanceInfo instanceInfo = InstanceInfo.Builder.newBuilder()
            .setInstanceId(instance.getId())
            .setAppName("testApp")
            .setStatus(eurekaStatus)
            .build();
    when(eurekaClient.getInstancesById(instance.getId())).thenReturn(singletonList(instanceInfo));

    monitor.onEvent(new CacheRefreshedEvent());
}