Java Code Examples for com.netflix.discovery.shared.Application#getInstances()

The following examples show how to use com.netflix.discovery.shared.Application#getInstances() . 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: EurekaRegisterHandler.java    From TarsJava with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public List<EndpointF> query(String name) {
    name = normalObjName(name);
    if (name == null) {
        return null;
    }
    Application application = client.getApplication(name);
    List<EndpointF> results = new ArrayList<EndpointF>();
    if (application == null) {
        return results;
    }
    for (InstanceInfo instanceInfo : application.getInstances()) {
        if (instanceInfo.getStatus() != InstanceStatus.UP) {
            continue;
        }
        EndpointF endpoint = convert2Endpoint(instanceInfo);
        if (endpoint != null) {
            results.add(endpoint);
        }
    }
    return results;
}
 
Example 2
Source File: EurekaResource.java    From jhipster-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 3
Source File: InstanceRegistry.java    From didi-eureka-server with MIT License 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 4
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 5
Source File: EurekaResource.java    From jhipster-microservices-example 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 6
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 7
Source File: ModuleMetadataUpdateTask.java    From oneplatform with Apache License 2.0 6 votes vote down vote up
private Map<String, ModuleEntity> getActiveModulesFromEureka(){
  	
  	Map<String, ModuleEntity> result = new HashMap<>();
  	List<Application> applications = eurekaClient.getApplications().getRegisteredApplications();
  	if(applications == null)return result;
  	ModuleEntity module;
  	for (Application application : applications) {
  		String serviceId = application.getName().toLowerCase();
	module = result.get(serviceId);
  		if(module == null){
  			module = new ModuleEntity();
  			module.setServiceId(serviceId);
  			result.put(serviceId.toLowerCase(), module);
  		}
  		
  		for (InstanceInfo instanceInfo : application.getInstances()) {
  			module.getServiceInstances().add(new ServiceInstance(instanceInfo));
	}
  		
}
  	
  	return result;
  }
 
Example 8
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 9
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 10
Source File: DiscoveryService.java    From tx-lcn with Apache License 2.0 5 votes vote down vote up
public List<InstanceInfo> getConfigServiceInstances() {
    Application application = eurekaClient.getApplication(tmKey);
    if (application == null) {
        LOGGER.error("获取eureka服务失败!");
    }
    return application != null ? application.getInstances() : new ArrayList<>();
}
 
Example 11
Source File: DiscoveryService.java    From Raincat with GNU Lesser General Public License v3.0 5 votes vote down vote up
public List<InstanceInfo> getConfigServiceInstances() {
    Application application = eurekaClient.getApplication(Constant.APPLICATION_NAME);
    if (application == null) {
        LOGGER.error("获取eureka服务失败!");
    }
    return application != null ? application.getInstances() : new ArrayList<>();
}
 
Example 12
Source File: DiscoveryService.java    From mini-platform with MIT License 5 votes vote down vote up
public List<InstanceInfo> getAdminServiceInstances() {
    Application application = eurekaClient.getApplication(ServiceNameConsts.APOLLO_ADMINSERVICE);
    if (application == null) {
        Tracer.logEvent("Apollo.EurekaDiscovery.NotFound", ServiceNameConsts.APOLLO_ADMINSERVICE);
    }
    return application != null ? application.getInstances() : Collections.emptyList();
}
 
Example 13
Source File: DiscoveryService.java    From mini-platform with MIT License 5 votes vote down vote up
public List<InstanceInfo> getMetaServiceInstances() {
    Application application = eurekaClient.getApplication(ServiceNameConsts.APOLLO_METASERVICE);
    if (application == null) {
        Tracer.logEvent("Apollo.EurekaDiscovery.NotFound", ServiceNameConsts.APOLLO_METASERVICE);
    }
    return application != null ? application.getInstances() : Collections.emptyList();
}
 
Example 14
Source File: InstanceLookupExecutor.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
private InstanceInfo findEurekaInstance(String serviceId) {
    Application application = eurekaClient.getApplication(serviceId);
    if (application == null) {
        throw new InstanceNotFoundException("Service '" + serviceId + "' is not registered to Discovery Service");
    }

    List<InstanceInfo> appInstances = application.getInstances();
    if (appInstances.isEmpty()) {
        throw new InstanceNotFoundException("'" + serviceId + "' has no running instances registered to Discovery Service");
    }

    return appInstances.get(0);
}
 
Example 15
Source File: GatewayNotifier.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
private List<InstanceInfo> getGatewayInstances() {
    final PeerAwareInstanceRegistry registry = getRegistry();
    final Application application = registry.getApplication(GATEWAY_SERVICE_ID);
    if (application == null) {
        logger.log("org.zowe.apiml.discovery.errorNotifyingGateway");
        return Collections.emptyList();
    }
    return application.getInstances();
}
 
Example 16
Source File: AuthenticationService.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Method will invalidate jwtToken. It could be called from two reasons:
 * - on logout phase (distribute = true)
 * - from another gateway instance to notify about change (distribute = false)
 *
 * @param jwtToken   token to invalidated
 * @param distribute distribute invalidation to another instances?
 * @return state of invalidate (true - token was invalidated)
 */
@CacheEvict(value = CACHE_VALIDATION_JWT_TOKEN, key = "#jwtToken")
@Cacheable(value = CACHE_INVALIDATED_JWT_TOKENS, key = "#jwtToken", condition = "#jwtToken != null")
public Boolean invalidateJwtToken(String jwtToken, boolean distribute) {
    /*
     * until ehCache is not distributed, send to other instances invalidation request
     */
    if (distribute) {
        final Application application = discoveryClient.getApplication(CoreService.GATEWAY.getServiceId());
        // wrong state, gateway have to exists (at least this current instance), return false like unsuccessful
        if (application == null) return Boolean.FALSE;

        final String myInstanceId = discoveryClient.getApplicationInfoManager().getInfo().getInstanceId();
        for (final InstanceInfo instanceInfo : application.getInstances()) {
            if (StringUtils.equals(myInstanceId, instanceInfo.getInstanceId())) continue;

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

    // invalidate token in z/OSMF
    final QueryResponse queryResponse = parseJwtToken(jwtToken);
    switch (queryResponse.getSource()) {
        case ZOWE:
            final String ltpaToken = getLtpaToken(jwtToken);
            if (ltpaToken != null) zosmfService.invalidate(LTPA, ltpaToken);
            break;
        case ZOSMF:
            zosmfService.invalidate(JWT, jwtToken);
            break;
        default:
            throw new TokenNotValidException("Unknown token type.");
    }

    return Boolean.TRUE;
}
 
Example 17
Source File: RibbonZuulCommon.java    From s2g-zuul with MIT License 5 votes vote down vote up
protected RestClient getRestClient() throws ZuulException {
		Application application = DiscoveryManager.getInstance().getDiscoveryClient().getApplication(serviceName);
		if (application == null) {
			throw new ZuulException( "Service-NotFoud",HttpServletResponse.SC_NOT_FOUND, serviceName + "服务未找到");
		}
		
		List<DiscoveryEnabledServer> instances = Lists.newArrayList();
		for (InstanceInfo info : application.getInstances()) {
			if (info.getStatus() == InstanceStatus.UP) {
				instances.add(new DiscoveryEnabledServer(info, false, false));
			}
		}

		RestClient client = (RestClient) ClientFactory.getNamedClient(serviceName);
		ZoneAwareLoadBalancer loadbalancer = (ZoneAwareLoadBalancer) client.getLoadBalancer();
		
//		//loadbalancer.setServersList(instances);		
//		IRule rule = new RandomRule();
//		int ruleLoad = ZuulCommandHelper.getLoadBalanceRule(commandGroup, commandKey);
//		if (ruleLoad == 2) {
//			rule = new ClientConfigEnabledRoundRobinRule();
//		} else if (ruleLoad == 3) {
//			rule=new AvailabilityFilteringRule();
//		} else if (ruleLoad == 3) {
//			rule=new ZoneAvoidanceRule();
//		} else if (ruleLoad == 4) {
//			rule=new RetryRule();
//		} else if (ruleLoad == 5) {
//			rule=new RoundRobinRule();
//		}else if (ruleLoad == 6) {
//			rule=new ResponseTimeWeightedRule();
//		}else if (ruleLoad == 7) {
//			rule=new WeightedResponseTimeRule();
//		}
//		loadbalancer.setRule(rule);
//		client.setLoadBalancer(loadbalancer);
		return client;
	}
 
Example 18
Source File: DefaultServerStore.java    From qconfig with MIT License 5 votes vote down vote up
@Override
public List<QConfigServer> getAvailableServers() {
    DiscoveryClient client = DiscoveryManager.getInstance().getDiscoveryClient();
    Application application = client.getApplication("eureka");
    if (application == null) {
        logger.warn("eureka application is null");
        return emptyServers();
    }

    List<InstanceInfo> instances = application.getInstances();
    if (instances == null || instances.isEmpty()) {
        logger.warn("eureka instance is empty");
        return emptyServers();
    }

    List<QConfigServer> servers = Lists.newArrayListWithCapacity(instances.size());
    for (InstanceInfo instance : instances) {
        logger.debug("eureka qconfig server instance {}:{}", instance.getIPAddr(), instance.getPort());
        try {
            String ip = instance.getIPAddr();
            if ("127.0.0.1".equals(ip)) {
                logger.warn("illegal qconfig server ip 127.0.0.1");
                Monitor.serverLocalIpError.inc();
                continue;
            }
            servers.add(new QConfigServer(ip, instance.getPort(), getRoom(ip)));
        } catch (Exception e) {
            // get room info error
            continue;
        }
    }

    if (servers.isEmpty()) {
        logger.warn("no legal eureka servers");
        return emptyServers();
    }
    return servers;
}
 
Example 19
Source File: EurekaHostsSupplier.java    From Raigad with Apache License 2.0 4 votes vote down vote up
@Override
public Supplier<List<Host>> getSupplier(final String clusterName)
{
    return new Supplier<List<Host>>() {

        @Override
        public List<Host> get() {

            if (discoveryClient == null) {
                LOG.error("Discovery client cannot be null");
                throw new RuntimeException("EurekaHostsSupplier needs a non-null DiscoveryClient");
            }

            LOG.debug("Raigad fetching instance list for app: " + clusterName);

            Application app = discoveryClient.getApplication(clusterName.toUpperCase());
            List<Host> hosts = new ArrayList<Host>();

            if (app == null) {
                LOG.warn("Cluster '{}' not found in eureka", clusterName);
                return hosts;
            }

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

            if (ins == null || ins.isEmpty()) {
                LOG.warn("Cluster '{}' found in eureka but has no instances", clusterName);
                return hosts;
            }

            hosts = Lists.newArrayList(Collections2.transform(
                    Collections2.filter(ins, new Predicate<InstanceInfo>() {
                        @Override
                        public boolean apply(InstanceInfo input) {
                            return input.getStatus() == InstanceInfo.InstanceStatus.UP;
                        }
                    }), new Function<InstanceInfo, Host>() {
                        @Override
                        public Host apply(InstanceInfo info) {
                            String[] parts = StringUtils.split(
                                    StringUtils.split(info.getHostName(), ".")[0], '-');

                            Host host = new Host(info.getHostName(), info.getPort())
                                    .addAlternateIpAddress(
                                            StringUtils.join(new String[] { parts[1], parts[2], parts[3],
                                                    parts[4] }, "."))
                                    .addAlternateIpAddress(info.getIPAddr())
                                    .setId(info.getId());

                            try {
                                if (info.getDataCenterInfo() instanceof AmazonInfo) {
                                    AmazonInfo amazonInfo = (AmazonInfo)info.getDataCenterInfo();
                                    host.setRack(amazonInfo.get(MetaDataKey.availabilityZone));
                                }
                            }
                            catch (Throwable t) {
                                LOG.error("Error getting rack for host " + host.getName(), t);
                            }

                            return host;
                        }
                    }));

            LOG.debug("Raigad found hosts from eureka - num hosts: " + hosts.size());

            return hosts;
        }
    };
}
 
Example 20
Source File: DiscoveryServerList.java    From s2g-zuul with MIT License 4 votes vote down vote up
private List<DiscoveryEnabledServer> obtainServersViaDiscovery() {
	List<DiscoveryEnabledServer> serverList = new ArrayList<DiscoveryEnabledServer>();

	DiscoveryClient discoveryClient = DiscoveryManager.getInstance().getDiscoveryClient();
	if (discoveryClient == null) {
		return new ArrayList<DiscoveryEnabledServer>();
	}
	// if (vipAddresses != null) {
	// for (String vipAddress : vipAddresses.split(",")) {
	// // if targetRegion is null, it will be interpreted as the same
	// // region of client
	// List<InstanceInfo> listOfinstanceInfo =
	// discoveryClient.getInstancesByVipAddress(vipAddress, isSecure,
	// targetRegion);
	// for (InstanceInfo ii : listOfinstanceInfo) {
	// if (ii.getStatus().equals(InstanceStatus.UP)) {
	//
	// if (shouldUseOverridePort) {
	// if (logger.isDebugEnabled()) {
	// logger.debug("Overriding port on client name: " + clientName + " to "
	// + overridePort);
	// }
	//
	// // copy is necessary since the InstanceInfo builder
	// // just uses the original reference,
	// // and we don't want to corrupt the global eureka
	// // copy of the object which may be
	// // used by other clients in our system
	// InstanceInfo copy = new InstanceInfo(ii);
	//
	// if (isSecure) {
	// ii = new
	// InstanceInfo.Builder(copy).setSecurePort(overridePort).build();
	// } else {
	// ii = new InstanceInfo.Builder(copy).setPort(overridePort).build();
	// }
	// }
	//
	// DiscoveryEnabledServer des = new DiscoveryEnabledServer(ii, isSecure,
	// shouldUseIpAddr);
	// des.setZone(DiscoveryClient.getZone(ii));
	// serverList.add(des);
	// }
	// }
	// if (serverList.size() > 0 && prioritizeVipAddressBasedServers) {
	// break; // if the current vipAddress has servers, we dont use
	// // subsequent vipAddress based servers
	// }
	// }
	// }

	Application application = discoveryClient.getApplication(clientName);

	if (application == null) {
		logger.error(clientName + "服务未找到");
	} else {
		for (InstanceInfo ii : application.getInstances()) {
			if (ii.getStatus() == InstanceStatus.UP) {
				if (shouldUseOverridePort) {
					if (logger.isDebugEnabled()) {
						logger.debug("Overriding port on client name: " + clientName + " to " + overridePort);
					}

					// copy is necessary since the InstanceInfo builder
					// just uses the original reference,
					// and we don't want to corrupt the global eureka
					// copy of the object which may be
					// used by other clients in our system
					InstanceInfo copy = new InstanceInfo(ii);

					if (isSecure) {
						ii = new InstanceInfo.Builder(copy).setSecurePort(overridePort).build();
					} else {
						ii = new InstanceInfo.Builder(copy).setPort(overridePort).build();
					}
				}

				DiscoveryEnabledServer des = new DiscoveryEnabledServer(ii, isSecure, shouldUseIpAddr);
				des.setZone(DiscoveryClient.getZone(ii));
				serverList.add(des);
			}
		}
	}

	return serverList;
}