com.netflix.appinfo.InstanceInfo Java Examples

The following examples show how to use com.netflix.appinfo.InstanceInfo. 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: SubstituteSwaggerGenerator.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
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 #2
Source File: InstanceRegistryTest.java    From didi-eureka-server with 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 #3
Source File: EurekaConfigServerBootstrapConfigurationTests.java    From spring-cloud-netflix with Apache License 2.0 6 votes vote down vote up
@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 #4
Source File: InstanceRegistryTests.java    From spring-cloud-netflix with Apache License 2.0 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
	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 #5
Source File: MetadataDefaultsServiceTest.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
@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 #6
Source File: EurekaResource.java    From flair-registry with 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 #7
Source File: ServiceControllerTest.java    From eureka-consul-adapter with 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 #8
Source File: EurekaDynamicServerListLoadBalancerTest.java    From ribbon with Apache License 2.0 6 votes vote down vote up
@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 #9
Source File: ChassisEurekaRegistrationTest.java    From chassis with 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 #10
Source File: ExtEurekaController.java    From onetwo with 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 #11
Source File: ClientConnectionsShutdown.java    From zuul with 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 #12
Source File: AuthenticationService.java    From api-layer with 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 File: EurekaRegistration.java    From spring-cloud-netflix with 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 #14
Source File: InstanceRefreshService.java    From api-layer with 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 #15
Source File: InstanceRegistry.java    From spring-cloud-netflix with 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 #16
Source File: EurekaInstatnceTransformer.java    From spring-cloud-gray with Apache License 2.0 6 votes vote down vote up
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 #17
Source File: EurekaInstatnceTransformer.java    From spring-cloud-gray with Apache License 2.0 6 votes vote down vote up
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 #18
Source File: GatewayNotifierTest.java    From api-layer with 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 #19
Source File: ServiceDefinitionProcessorTest.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
@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 #20
Source File: ApimlInstanceRegistry.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void register(InstanceInfo info, int leaseDuration, boolean isReplication) {
    try {
        register3ArgsMethodHandle.invokeWithArguments(this, info, leaseDuration, isReplication);
        handleRegistrationMethod.invokeWithArguments(this, info, leaseDuration, isReplication);
    } catch (ClassCastException | WrongMethodTypeException e) {
        throw new IllegalArgumentException(EXCEPTION_MESSAGE, e);
    } catch (RuntimeException re) {
        throw re;
    } catch (Throwable t) {
        throw new IllegalArgumentException(EXCEPTION_MESSAGE, t);
    }
}
 
Example #21
Source File: EurekaReactiveDiscoveryClientTests.java    From spring-cloud-netflix with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnFluxOfServices() {
	Applications applications = new Applications();
	Application app = new Application("my-service");
	app.addInstance(new InstanceInfo("instance", "my-service", "", "127.0.0.1", "",
			null, null, "", "", "", "", "", "", 0, null, "", null, null, null, null,
			null, null, null, null, null, null));
	applications.addApplication(app);
	when(eurekaClient.getApplications()).thenReturn(applications);
	Flux<String> services = this.client.getServices();
	StepVerifier.create(services).expectNext("my-service").expectComplete().verify();
}
 
Example #22
Source File: RequestAttempt.java    From zuul with Apache License 2.0 5 votes vote down vote up
public RequestAttempt(int attemptNumber, InstanceInfo server, String targetVip, String chosenWarmupLB, int status, String error, String exceptionType,
                      int readTimeout, int connectTimeout, int maxRetries)
{
    if (attemptNumber < 1) {
        throw new IllegalArgumentException("Attempt number must be greater than 0! - " + attemptNumber);
    }
    this.attempt = attemptNumber;
    this.vip = targetVip;

    if (server != null) {
        this.app = server.getAppName().toLowerCase();
        this.asg = server.getASGName();
        this.instanceId = server.getInstanceId();
        this.host = server.getHostName();
        this.port = server.getPort();

        // If targetVip is null, then try to use the actual server's vip.
        if (targetVip == null) {
            this.vip = server.getVIPAddress();
        }

        if (server.getDataCenterInfo() instanceof AmazonInfo) {
            this.availabilityZone = ((AmazonInfo) server.getDataCenterInfo()).getMetadata().get("availability-zone");

            // HACK - get region by just removing the last char from zone.
            String az = getAvailabilityZone();
            if (az != null && az.length() > 0) {
                this.region = az.substring(0, az.length() - 1);
            }
        }
    }
    
    this.status = status;
    this.error = error;
    this.exceptionType = exceptionType;
    this.readTimeout = readTimeout;
    this.connectTimeout = connectTimeout;
    this.maxRetries = maxRetries;
}
 
Example #23
Source File: EurekaUtils.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Construct base URL for specific InstanceInfo
 * @param instanceInfo Instance of service, for which we want to get an URL
 * @return URL to the instance
 */
public static final String getUrl(InstanceInfo instanceInfo) {
    if (instanceInfo.getSecurePort() == 0) {
        return "http://" + instanceInfo.getHostName() + ":" + instanceInfo.getPort();
    } else {
        return "https://" + instanceInfo.getHostName() + ":" + instanceInfo.getSecurePort();
    }
}
 
Example #24
Source File: AuthenticationServiceTest.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void invalidateToken() {
    TokenAuthentication tokenAuthentication;

    String jwt1 = authService.createJwtToken("user1", "domain1", "ltpa1");
    assertFalse(authService.isInvalidated(jwt1));
    tokenAuthentication = authService.validateJwtToken(jwt1);
    assertTrue(tokenAuthentication.isAuthenticated());

    InstanceInfo myInstance = mock(InstanceInfo.class);
    when(myInstance.getInstanceId()).thenReturn("myInstance01");
    ApplicationInfoManager applicationInfoManager = mock(ApplicationInfoManager.class);
    when(applicationInfoManager.getInfo()).thenReturn(myInstance);
    when(discoveryClient.getApplicationInfoManager()).thenReturn(applicationInfoManager);
    when(restTemplate.exchange(eq(zosmfUrl + "/zosmf/services/authenticate"), eq(HttpMethod.DELETE), any(), eq(String.class)))
        .thenReturn(new ResponseEntity<>(HttpStatus.OK));

    Application application = mock(Application.class);
    List<InstanceInfo> instances = Arrays.asList(
        createInstanceInfo("instance02", "hostname1", 10000, 10433),
        createInstanceInfo("myInstance01", "localhost", 10000, 10433),
        createInstanceInfo("instance03", "hostname2", 10001, 0)
    );
    when(application.getInstances()).thenReturn(instances);
    when(discoveryClient.getApplication("gateway")).thenReturn(application);

    authService.invalidateJwtToken(jwt1, true);
    assertTrue(authService.isInvalidated(jwt1));
    tokenAuthentication = authService.validateJwtToken(jwt1);
    assertFalse(tokenAuthentication.isAuthenticated());
    verify(restTemplate, times(2)).delete(anyString(), (Object[]) any());
    verify(restTemplate).delete("https://hostname1:10433/gateway/auth/invalidate/{}", jwt1);
    verify(restTemplate).delete("http://hostname2:10001/gateway/auth/invalidate/{}", jwt1);
    verify(restTemplate, times(1))
        .exchange(eq(zosmfUrl + "/zosmf/services/authenticate"), eq(HttpMethod.DELETE), any(), eq(String.class));
}
 
Example #25
Source File: EurekaReactiveDiscoveryClientTests.java    From spring-cloud-netflix with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnFluxOfServiceInstances() {
	InstanceInfo instanceInfo = new InstanceInfo(new InstanceInfo("instance",
			"my-service", "", "127.0.0.1", "", null, null, "", "", "", "", "", "", 0,
			null, "", null, null, null, null, null, null, null, null, null, null));
	when(eurekaClient.getInstancesByVipAddress("my-service", false))
			.thenReturn(singletonList(instanceInfo));
	Flux<ServiceInstance> instances = this.client.getInstances("my-service");
	StepVerifier.create(instances).expectNextCount(1).expectComplete().verify();
}
 
Example #26
Source File: EurekaHostsSupplier.java    From dyno with Apache License 2.0 5 votes vote down vote up
private List<Host> getUpdateFromEureka() {
    if (discoveryClient == null) {
        Logger.error("Discovery client cannot be null");
        throw new RuntimeException("EurekaHostsSupplier needs a non-null DiscoveryClient");
    }
    Logger.info("Dyno fetching instance list for app: " + applicationName);
    Application app = discoveryClient.getApplication(applicationName);
    List<Host> hosts = new ArrayList<Host>();

    if (app == null) {
        return hosts;
    }

    List<InstanceInfo> ins = app.getInstances();

    if (ins == null || ins.isEmpty()) {
        return hosts;
    }

    hosts = Lists.newArrayList(Collections2.transform(ins, info -> {
        Host.Status status = info.getStatus() == InstanceStatus.UP ? Host.Status.Up : Host.Status.Down;

        String rack = null;
        try {
            if (info.getDataCenterInfo() instanceof AmazonInfo) {
                AmazonInfo amazonInfo = (AmazonInfo) info.getDataCenterInfo();
                rack = amazonInfo.get(MetaDataKey.availabilityZone);
            }
        } catch (Throwable t) {
            Logger.error("Error getting rack for host " + info.getHostName(), t);
        }
        if (rack == null) {
            Logger.error("Rack wasn't found for host:" + info.getHostName() + " there may be issues matching it up to the token map");
        }
        Host host = new HostBuilder().setHostname(info.getHostName()).setIpAddress(info.getIPAddr()).setRack(rack).setStatus(status).createHost();
        return host;
    }));
    Logger.info("Dyno found hosts from eureka - num hosts: " + hosts.size());
    return hosts;
}
 
Example #27
Source File: InstanceRegistry.java    From didi-eureka-server with MIT License 5 votes vote down vote up
private int resolveInstanceLeaseDuration(final InstanceInfo info) {
	int leaseDuration = Lease.DEFAULT_DURATION_IN_SECS;
	if (info.getLeaseInfo() != null && info.getLeaseInfo().getDurationInSecs() > 0) {
		leaseDuration = info.getLeaseInfo().getDurationInSecs();
	}
	return leaseDuration;
}
 
Example #28
Source File: ArmeriaEurekaClientTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
private static List<Endpoint> endpointsFromApplication(Application application, boolean secureVip) {
    final Builder<Endpoint> builder = ImmutableList.builder();
    for (InstanceInfo instance : application.getInstances()) {
        builder.add(endpoint(instance, secureVip));
    }
    return builder.build();
}
 
Example #29
Source File: ServiceAuthenticationDecorator.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * If a service requires authentication,
 *   verify that the specific instance was selected upfront
 *   decide whether it requires valid JWT token and if it does
 *     verify that the request contains valid one
 *
 * Prevent ribbon from retrying if Authentication Exception was thrown or if valid JWT token is required and wasn't
 * provided.
 *
 * @param request Current http request.
 */
public void process(HttpRequest request) {
    final RequestContext context = RequestContext.getCurrentContext();

    if (context.get(AUTHENTICATION_COMMAND_KEY) instanceof ServiceAuthenticationServiceImpl.UniversalAuthenticationCommand) {
        InstanceInfo info = RequestContextUtils.getInstanceInfo().orElseThrow(
            () -> new RequestContextNotPreparedException("InstanceInfo of loadbalanced instance is not present in RequestContext")
        );
        final Authentication authentication = serviceAuthenticationService.getAuthentication(info);
        AuthenticationCommand cmd;

        try {
            final String jwtToken = authenticationService.getJwtTokenFromRequest(context.getRequest()).orElse(null);

            cmd = serviceAuthenticationService.getAuthenticationCommand(authentication, jwtToken);

            if (cmd == null) {
                return;
            }

            if (cmd.isRequiredValidJwt()) {
                if (jwtToken == null || !authenticationService.validateJwtToken(jwtToken).isAuthenticated()) {
                    throw new RequestAbortException(new BadCredentialsException("JWT Token is not authenticated"));
                }
            }
        }
        catch (AuthenticationException ae) {
            throw new RequestAbortException(ae);
        }

        cmd.applyToRequest(request);
    }
}
 
Example #30
Source File: WeatherBackendAdapterImpl.java    From cxf-spring-cloud-netflix-docker with MIT License 5 votes vote down vote up
private void logCallerInfo() {
    InstanceInfo weatherbackendEurekaInfo = eurekaClient.getApplication("weatherbackend").getInstances().get(0);
    LOG.info(String.format("Calling weatherbackend with Feign: '%s', '%s', '%s', '%s'",
            weatherbackendEurekaInfo.getHostName(),
            weatherbackendEurekaInfo.getPort(),
            weatherbackendEurekaInfo.getStatus(),
            weatherbackendEurekaInfo.getHomePageUrl()));
}