com.netflix.niws.loadbalancer.DiscoveryEnabledServer Java Examples

The following examples show how to use com.netflix.niws.loadbalancer.DiscoveryEnabledServer. 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: SingleMetadataMatcher.java    From spring-cloud-ribbon-extensions with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected boolean doApply(DiscoveryEnabledServer server) {
    String expected = current().get(metadataKey);
    Map<String, String> metadata = server.getInstanceInfo().getMetadata();
    String actual = metadata.get(metadataKey);
    boolean accept = (expected == null && actual == null) || (expected != null && expected.equals(actual));
    log.trace("Expected {}=[{}] vs {}:{}{} => {}",
            metadataKey,
            expected,
            server.getHostPort(),
            server.getMetaInfo().getAppName(),
            metadata,
            accept);
    return accept;
}
 
Example #2
Source File: DynamicMetadataMatcher.java    From spring-cloud-ribbon-extensions with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected boolean doApply(DiscoveryEnabledServer server) {
    String metadataKey = current().get(dynamicEntryKey);
    Map<String, String> metadata = server.getInstanceInfo().getMetadata();
    if (metadataKey != null) {
        String expected = current().get(metadataKey);
        String actual = metadata.get(metadataKey);
        boolean accept = (expected == null && actual == null) || (expected != null && expected.equals(actual));
        log.trace("Expected [{}={}] vs {}:{}{} => {}",
                metadataKey,
                expected,
                server.getHostPort(),
                server.getMetaInfo().getAppName(),
                metadata,
                accept);
        return accept;
    } else {
        log.trace("[{}] not defined! : {}{} => %b",
                dynamicEntryKey,
                server.getHostPort(),
                metadata,
                matchIfMissing);
        return matchIfMissing;
    }
}
 
Example #3
Source File: EurekaServerListProcessor.java    From spring-cloud-gray with Apache License 2.0 6 votes vote down vote up
protected List<Server> getUnUpServerList(String serviceId, List<InstanceStatus> instanceStatuses) {

        Application application = eurekaClient.getApplication(serviceId);
        if (Objects.isNull(application)) {
            return null;
        }
        return application.getInstancesAsIsFromEureka().stream()
                .filter(instanceInfo -> instanceStatuses.contains(EurekaInstatnceTransformer.toGrayInstanceStatus(instanceInfo.getStatus())))
                .map(instanceInfo -> {
                    DiscoveryEnabledServer server = new DiscoveryEnabledServer(instanceInfo, false);
                    String zone = server.getInstanceInfo().getMetadata().get("zone");
                    if (StringUtils.isNotEmpty(zone)) {
                        server.setZone(zone);
                    }
                    return server;
                })
                .collect(Collectors.toList());
    }
 
Example #4
Source File: ApimlLoadBalancer.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * This method stores the instance info of chosen instance in the RequestContext for later usage, for
 * example by authentication logic
 */
@Override
public Server chooseServer(Object key) {
    Server server = super.chooseServer(key);

    if (server == null) {
        return null;
    }

    if (server instanceof DiscoveryEnabledServer) {
        RequestContextUtils.setInstanceInfo(((DiscoveryEnabledServer) server).getInstanceInfo());
        RequestContextUtils.addDebugInfo("Load Balancer chooses: " + ((DiscoveryEnabledServer) server).getInstanceInfo());
    } else {
        throw new IllegalStateException("Unexpected error, please contact Broadcom support");
    }

    return server;
}
 
Example #5
Source File: ApimlLoadBalancerStub.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * This method stores the instance info of chosen instance in the RequestContext for later usage, for
 * example by authentication logic.
 */
@Override
public Server chooseServer(Object key) {
    Server server = new DiscoveryEnabledServer(applicationRegistry.getInstanceInfo(), true);
    server.setAlive(true);
    server.setReadyToServe(true);

    if (server instanceof DiscoveryEnabledServer) {
        RequestContextUtils.setInstanceInfo(((DiscoveryEnabledServer) server).getInstanceInfo());
        RequestContextUtils.addDebugInfo("Load Balancer chooses: " + ((DiscoveryEnabledServer) server).getInstanceInfo());
    } else {
        throw new IllegalStateException("Unexpected error, please contact Broadcom support");
    }

    return server;
}
 
Example #6
Source File: EurekaDynamicServerListLoadBalancerTest.java    From ribbon with Apache License 2.0 5 votes vote down vote up
@Test
public void testLoadBalancerHappyCase() throws Exception {
    Assert.assertNotEquals("the two test server list counts should be different",
            secondServerListSize, initialServerListSize);

    DynamicServerListLoadBalancer<DiscoveryEnabledServer> lb = null;
    try {
        Capture<EurekaEventListener> eventListenerCapture = new Capture<EurekaEventListener>();
        eurekaClientMock.registerEventListener(EasyMock.capture(eventListenerCapture));

        PowerMock.replay(DiscoveryClient.class);
        PowerMock.replay(eurekaClientMock);

        // actual testing
        // initial creation and loading of the first serverlist
        lb = new DynamicServerListLoadBalancer<DiscoveryEnabledServer>(
                config,
                new AvailabilityFilteringRule(),
                new DummyPing(),
                new DiscoveryEnabledNIWSServerList(vipAddress, eurekaClientProvider),
                new ZoneAffinityServerListFilter<DiscoveryEnabledServer>(),
                new EurekaNotificationServerListUpdater(eurekaClientProvider)
        );

        Assert.assertEquals(initialServerListSize, lb.getServerCount(false));

        // trigger an eureka CacheRefreshEvent
        eventListenerCapture.getValue().onEvent(new CacheRefreshedEvent());

        Assert.assertTrue(verifyFinalServerListCount(secondServerListSize, lb));

    } finally {
        if (lb != null) {
            lb.shutdown();

            PowerMock.verify(eurekaClientMock);
            PowerMock.verify(DiscoveryClient.class);
        }
    }
}
 
Example #7
Source File: AbstractSupportTest.java    From spring-cloud-ribbon-extensions with Apache License 2.0 5 votes vote down vote up
public DiscoveryEnabledServer createServer(String zone) {
    DiscoveryEnabledServer server = new DiscoveryEnabledServer(InstanceInfo.Builder.newBuilder()
            .setAppName(TestApplicationResource.SERVICE_ID)
            .setHostName("127.0.0.1")
            .setMetadata(new HashMap<>())
            .build(), false);
    server.setZone(zone);
    server.setAlive(true);
    server.setReadyToServe(true);
    return server;
}
 
Example #8
Source File: NoCanaryFilterMetaPredicate.java    From onetwo with Apache License 2.0 5 votes vote down vote up
@Override
public boolean apply(PredicateKey input) {
	if(!DiscoveryEnabledServer.class.isInstance(input.getServer())){
		return false;
	}
	DiscoveryEnabledServer server = (DiscoveryEnabledServer) input.getServer();
	Map<String, String> metaData = server.getInstanceInfo().getMetadata();
	return matchMetaData(metaData);
}
 
Example #9
Source File: CanaryFilterMetaPredicate.java    From onetwo with Apache License 2.0 5 votes vote down vote up
@Override
public boolean apply(PredicateKey input) {
	if(!DiscoveryEnabledServer.class.isInstance(input.getServer())){
		return false;
	}
	DiscoveryEnabledServer server = (DiscoveryEnabledServer) input.getServer();
	Map<String, String> metaData = server.getInstanceInfo().getMetadata();
	return matchMetaData(metaData);
}
 
Example #10
Source File: DiscoveryEnabledPredicate.java    From ribbon-discovery-filter-spring-cloud-starter with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public boolean apply(@Nullable PredicateKey input) {
    return input != null
            && input.getServer() instanceof DiscoveryEnabledServer
            && apply((DiscoveryEnabledServer) input.getServer());
}
 
Example #11
Source File: MetadataAwarePredicate.java    From ribbon-discovery-filter-spring-cloud-starter with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected boolean apply(DiscoveryEnabledServer server) {

    final RibbonFilterContext context = RibbonFilterContextHolder.getCurrentContext();
    final Set<Map.Entry<String, String>> attributes = Collections.unmodifiableSet(context.getAttributes().entrySet());
    final Map<String, String> metadata = server.getInstanceInfo().getMetadata();
    return metadata.entrySet().containsAll(attributes);
}
 
Example #12
Source File: DiscoveryUtils.java    From ribbon-discovery-filter-spring-cloud-starter with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T extends Server> List<T> servers(InstanceInfo... instanceInfos) {
    final List<T> result = new ArrayList<>();
    for (InstanceInfo info : instanceInfos) {
        result.add((T) new DiscoveryEnabledServer(info, false));
    }
    return result;
}
 
Example #13
Source File: RibbonDiscoveryFilterTest.java    From ribbon-discovery-filter-spring-cloud-starter with Apache License 2.0 5 votes vote down vote up
@Bean
public ServerList<?> ribbonServerList() {
    Map<String, String> metadata = new HashMap<>();
    metadata.put("version", "1.0");
    metadata.put("variant", "A");
    InstanceInfo instanceInfo = InstanceInfo.Builder.newBuilder()
            .setAppName("local")
            .setHostName("localhost")
            .setPort(8761)
            .setMetadata(metadata)
            .build();
    return new StaticServerList<>(Arrays.asList(new DiscoveryEnabledServer(instanceInfo, false)));
}
 
Example #14
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 #15
Source File: BasicNettyOrigin.java    From zuul with Apache License 2.0 5 votes vote down vote up
@Override
public String getIpAddrFromServer(Server server) {
    if (server instanceof DiscoveryEnabledServer) {
        DiscoveryEnabledServer discoveryServer = (DiscoveryEnabledServer) server;
        if (discoveryServer.getInstanceInfo() != null) {
            String ip = discoveryServer.getInstanceInfo().getIPAddr();
            if (!Strings.isNullOrEmpty(ip)) {
                return ip;
            }
        }
    }
    return null;
}
 
Example #16
Source File: DefaultClientChannelManager.java    From zuul with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
static InstanceInfo deriveInstanceInfoInternal(Server chosenServer) {
    if (chosenServer instanceof DiscoveryEnabledServer) {
        DiscoveryEnabledServer discoveryServer = (DiscoveryEnabledServer) chosenServer;
        return discoveryServer.getInstanceInfo();
    } else {
        return new InstanceInfo(
                /* instanceId= */ chosenServer.getId(),
                /* appName= */ null,
                /* appGroupName= */ null,
                /* ipAddr= */ chosenServer.getHost(),
                /* sid= */ chosenServer.getId(),
                /* port= */ null,
                /* securePort= */ null,
                /* homePageUrl= */ null,
                /* statusPageUrl= */ null,
                /* healthCheckUrl= */ null,
                /* secureHealthCheckUrl= */ null,
                /* vipAddress= */ null,
                /* secureVipAddress= */ null,
                /* countryId= */ 0,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null);
    }
}
 
Example #17
Source File: DefaultClientChannelManager.java    From zuul with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
static SocketAddress pickAddressInternal(Server chosenServer, @Nullable String connPoolConfigOriginName) {
    String rawHost;
    int port;
    if (chosenServer instanceof DiscoveryEnabledServer) {
        DiscoveryEnabledServer discoveryServer = (DiscoveryEnabledServer) chosenServer;
        // Configuration for whether to use IP address or host has already been applied in the
        // DiscoveryEnabledServer constructor.
        rawHost = discoveryServer.getHost();
        port = discoveryServer.getPort();
    } else {
        // create mock instance info for non-discovery instances
        rawHost = chosenServer.getHost();
        port = chosenServer.getPort();
    }

    InetSocketAddress serverAddr;
    try {
        InetAddress ipAddr = InetAddresses.forString(rawHost);
        serverAddr = new InetSocketAddress(ipAddr, port);
    } catch (IllegalArgumentException e1) {
        LOG.warn("NettyClientConnectionFactory got an unresolved address, addr: {}", rawHost);
        Counter unresolvedDiscoveryHost = SpectatorUtils.newCounter(
                "unresolvedDiscoveryHost",
                connPoolConfigOriginName == null ? "unknownOrigin" : connPoolConfigOriginName);
        unresolvedDiscoveryHost.increment();
        try {
            serverAddr = new InetSocketAddress(rawHost, port);
        } catch (RuntimeException e2) {
            e1.addSuppressed(e2);
            throw e1;
        }
    }

    return serverAddr;
}
 
Example #18
Source File: DefaultClientChannelManagerTest.java    From zuul with Apache License 2.0 5 votes vote down vote up
@Test
public void deriveInstanceInfoInternal_discovery() {
    InstanceInfo instanceInfo = Builder.newBuilder().setAppName("app").build();
    Server s = new DiscoveryEnabledServer(instanceInfo, true);

    InstanceInfo actual = DefaultClientChannelManager.deriveInstanceInfoInternal(s);

    assertSame(instanceInfo, actual);
}
 
Example #19
Source File: DefaultClientChannelManagerTest.java    From zuul with Apache License 2.0 5 votes vote down vote up
@Test
public void pickAddressInternal_discovery() {
    InstanceInfo instanceInfo =
            Builder.newBuilder().setAppName("app").setHostName("192.168.0.1").setPort(443).build();
    Server s = new DiscoveryEnabledServer(instanceInfo, true);

    SocketAddress addr = DefaultClientChannelManager.pickAddressInternal(s, "originname");

    Truth.assertThat(addr).isInstanceOf(InetSocketAddress.class);
    InetSocketAddress socketAddress = (InetSocketAddress) addr;
    assertEquals(InetAddresses.forString("192.168.0.1"), socketAddress.getAddress());
    assertEquals(443, socketAddress.getPort());
}
 
Example #20
Source File: DefaultClientChannelManagerTest.java    From zuul with Apache License 2.0 5 votes vote down vote up
@Test
public void pickAddressInternal_discovery_unresolved() {
    InstanceInfo instanceInfo =
            Builder.newBuilder().setAppName("app").setHostName("localhost").setPort(443).build();
    Server s = new DiscoveryEnabledServer(instanceInfo, true);

    SocketAddress addr = DefaultClientChannelManager.pickAddressInternal(s, "originname");

    Truth.assertThat(addr).isInstanceOf(InetSocketAddress.class);
    InetSocketAddress socketAddress = (InetSocketAddress) addr;

    assertTrue(socketAddress.toString(), socketAddress.getAddress().isLoopbackAddress());
    assertEquals(443, socketAddress.getPort());
}
 
Example #21
Source File: SingleStaticMetadataMatcher.java    From spring-cloud-ribbon-extensions with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected boolean doApply(DiscoveryEnabledServer server) {
    Map<String, String> metadata = server.getInstanceInfo().getMetadata();
    String actual = metadata.get(entryKey);
    boolean accept = entryValue.equals(actual);
    log.trace("Expected [{}={}] vs {}:{}{} => {}",
            entryKey,
            entryValue,
            server.getHostPort(),
            server.getMetaInfo().getAppName(),
            metadata,
            accept);
    return accept;
}
 
Example #22
Source File: TestZoneAvoidanceRuleWrapper.java    From summerframework with Apache License 2.0 5 votes vote down vote up
private static DiscoveryEnabledServer createDiscoveryEnabledServer(double load) {

        Map<String, String> metadata = new HashMap<>();
        ServerLoadStatus serverLoad = new ServerLoadStatus();
        serverLoad.calculateSystemInfo();
        serverLoad.setSystemLoadAverage(load);
        serverLoad.setOsName(serverLoad.getOsName() + "-" + load);
        String serverLoadJson = JsonUtil.toJson(serverLoad);
        metadata.put(Constants.EUREKA_METADATA_SERVERLOAD, serverLoadJson);
        InstanceInfo instanceInfo1 = InstanceInfo.Builder.newBuilder().setHostName("host" + load)
            .setAppName("app" + load).setMetadata(metadata).build();
        DiscoveryEnabledServer server = new DiscoveryEnabledServer(instanceInfo1, false);
        return server;
    }
 
Example #23
Source File: MetadataCanaryRuleHandler.java    From pig with MIT License 5 votes vote down vote up
@Override
public AbstractServerPredicate getPredicate() {
    return new AbstractServerPredicate() {
        @Override
        public boolean apply(PredicateKey predicateKey) {
            String targetVersion = RibbonVersionHolder.getContext();
            RibbonVersionHolder.clearContext();
            if (StrUtil.isBlank(targetVersion)) {
                log.debug("客户端未配置目标版本直接路由");
                return true;
            }

            DiscoveryEnabledServer server = (DiscoveryEnabledServer) predicateKey.getServer();
            final Map<String, String> metadata = server.getInstanceInfo().getMetadata();
            if (StrUtil.isBlank(metadata.get(SecurityConstants.VERSION))) {
                log.debug("当前微服务{} 未配置版本直接路由");
                return true;
            }

            if (metadata.get(SecurityConstants.VERSION).equals(targetVersion)) {
                return true;
            } else {
                log.debug("当前微服务{} 版本为{},目标版本{} 匹配失败", server.getInstanceInfo().getAppName()
                        , metadata.get(SecurityConstants.VERSION), targetVersion);
                return false;
            }
        }
    };
}
 
Example #24
Source File: ApimlLoadBalancerTest.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@Test
void givenServerList_whenChooseServer_thenSetChosenInstanceInfoToRequestContext() {
    InstanceInfo info = InstanceInfo.Builder.newBuilder()
        .setAppName("appname")
        .setInstanceId("instance")
        .build();
    underTest.addServer(new DiscoveryEnabledServer(info, true));

    underTest.chooseServer("instance");

    RequestContext context = RequestContext.getCurrentContext();
    assertThat(context.get(ApimlLoadBalancer.LOADBALANCED_INSTANCE_INFO_KEY), is(info));
}
 
Example #25
Source File: StrictMetadataMatcher.java    From spring-cloud-ribbon-extensions with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected boolean doApply(DiscoveryEnabledServer server) {
    Set<Entry<String, String>> expected = current().entrySet();
    Map<String, String> actual = server.getInstanceInfo().getMetadata();
    boolean accept = actual.entrySet().containsAll(expected);
    log.trace("Expected {} vs {}:{}{} => {}",
            expected,
            server.getHostPort(),
            server.getMetaInfo().getAppName(),
            actual,
            accept);
    return accept;
}
 
Example #26
Source File: DiscoveryEnabledServerPredicate.java    From spring-cloud-ribbon-extensions with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
@SuppressFBWarnings("BC_UNCONFIRMED_CAST_OF_RETURN_VALUE")
protected boolean doApply(PredicateKey input) {
    return input.getServer() instanceof DiscoveryEnabledServer
            && doApply((DiscoveryEnabledServer) input.getServer());
}
 
Example #27
Source File: InstanceIdMatcher.java    From spring-cloud-ribbon-extensions with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected boolean doApply(DiscoveryEnabledServer server) {
    String actual = server.getInstanceInfo().getInstanceId();
    boolean accept = expectedInstanceId.equals(actual);
    log.trace("Expected [{}] vs {}:{}[{}] => {}",
            expectedInstanceId,
            server.getHostPort(),
            server.getMetaInfo().getAppName(),
            actual,
            accept);
    return accept;
}
 
Example #28
Source File: DiscoveryEnabledPredicateTest.java    From spring-cloud-ribbon-extensions with Apache License 2.0 4 votes vote down vote up
@Test
public void should_filter_non_discovery_server() throws Exception {
    when(predicate.doApply(any(DiscoveryEnabledServer.class))).thenReturn(true);
    assertThat(predicate.apply(new PredicateKey(server)), is(false));
}
 
Example #29
Source File: AbstractSupportTest.java    From spring-cloud-ribbon-extensions with Apache License 2.0 4 votes vote down vote up
public void reset(DiscoveryEnabledServer server) {
    server.setAlive(true);
    server.setReadyToServe(true);
    server.getInstanceInfo().getMetadata().clear();
}
 
Example #30
Source File: DiscoveryEnabledPredicateTest.java    From spring-cloud-ribbon-extensions with Apache License 2.0 4 votes vote down vote up
@Test
public void should_not_filter_when_discovery_server() throws Exception {
    when(predicate.doApply(any(DiscoveryEnabledServer.class))).thenReturn(true);
    assertThat(predicate.apply(new PredicateKey(discoveryEnabledServer)), is(true));
}