Search in sources :

Example 91 with EquivalentAddressGroup

use of io.grpc.EquivalentAddressGroup in project grpc-java by grpc.

the class InternalSubchannelTest method eagAuthorityOverride_propagatesToTransport.

@Test
public void eagAuthorityOverride_propagatesToTransport() {
    SocketAddress addr = new SocketAddress() {
    };
    String overriddenAuthority = "authority-override";
    Attributes attr = Attributes.newBuilder().set(EquivalentAddressGroup.ATTR_AUTHORITY_OVERRIDE, overriddenAuthority).build();
    createInternalSubchannel(new EquivalentAddressGroup(Arrays.asList(addr), attr));
    // First attempt
    assertNull(internalSubchannel.obtainActiveTransport());
    assertEquals(CONNECTING, internalSubchannel.getState());
    verify(mockTransportFactory).newClientTransport(eq(addr), eq(createClientTransportOptions().setAuthority(overriddenAuthority).setEagAttributes(attr)), isA(TransportLogger.class));
}
Also used : TransportLogger(io.grpc.internal.InternalSubchannel.TransportLogger) EquivalentAddressGroup(io.grpc.EquivalentAddressGroup) Attributes(io.grpc.Attributes) SocketAddress(java.net.SocketAddress) Test(org.junit.Test)

Example 92 with EquivalentAddressGroup

use of io.grpc.EquivalentAddressGroup in project grpc-java by grpc.

the class InternalSubchannelTest method index_seekTo.

@Test
public void index_seekTo() {
    SocketAddress addr1 = new FakeSocketAddress();
    SocketAddress addr2 = new FakeSocketAddress();
    SocketAddress addr3 = new FakeSocketAddress();
    Index index = new Index(Arrays.asList(new EquivalentAddressGroup(Arrays.asList(addr1, addr2)), new EquivalentAddressGroup(Arrays.asList(addr3))));
    assertThat(index.seekTo(addr3)).isTrue();
    assertThat(index.getCurrentAddress()).isSameInstanceAs(addr3);
    assertThat(index.seekTo(addr1)).isTrue();
    assertThat(index.getCurrentAddress()).isSameInstanceAs(addr1);
    assertThat(index.seekTo(addr2)).isTrue();
    assertThat(index.getCurrentAddress()).isSameInstanceAs(addr2);
    index.seekTo(new FakeSocketAddress());
    // Failed seekTo doesn't change the index
    assertThat(index.getCurrentAddress()).isSameInstanceAs(addr2);
}
Also used : EquivalentAddressGroup(io.grpc.EquivalentAddressGroup) Index(io.grpc.internal.InternalSubchannel.Index) SocketAddress(java.net.SocketAddress) Test(org.junit.Test)

Example 93 with EquivalentAddressGroup

use of io.grpc.EquivalentAddressGroup in project grpc-java by grpc.

the class ChildLbResolvedAddressFactoryTest method create.

@Test
public void create() {
    List<EquivalentAddressGroup> addrs = new ArrayList<>();
    addrs.add(new EquivalentAddressGroup(mock(SocketAddress.class)));
    Attributes attr = Attributes.newBuilder().build();
    ChildLbResolvedAddressFactory factory = new ChildLbResolvedAddressFactory(addrs, attr);
    Object config1 = new Object();
    ResolvedAddresses resolvedAddress = factory.create(config1);
    assertThat(resolvedAddress.getAddresses()).isEqualTo(addrs);
    assertThat(resolvedAddress.getAttributes()).isEqualTo(attr);
    assertThat(resolvedAddress.getLoadBalancingPolicyConfig()).isEqualTo(config1);
    Object config2 = "different object";
    resolvedAddress = factory.create(config2);
    assertThat(resolvedAddress.getAddresses()).isEqualTo(addrs);
    assertThat(resolvedAddress.getAttributes()).isEqualTo(attr);
    assertThat(resolvedAddress.getLoadBalancingPolicyConfig()).isEqualTo(config2);
}
Also used : EquivalentAddressGroup(io.grpc.EquivalentAddressGroup) ArrayList(java.util.ArrayList) Attributes(io.grpc.Attributes) ResolvedAddresses(io.grpc.LoadBalancer.ResolvedAddresses) Test(org.junit.Test)

Example 94 with EquivalentAddressGroup

use of io.grpc.EquivalentAddressGroup in project grpc-java by grpc.

the class RingHashLoadBalancer method handleResolvedAddresses.

@Override
public void handleResolvedAddresses(ResolvedAddresses resolvedAddresses) {
    logger.log(XdsLogLevel.DEBUG, "Received resolution result: {0}", resolvedAddresses);
    List<EquivalentAddressGroup> addrList = resolvedAddresses.getAddresses();
    if (addrList.isEmpty()) {
        handleNameResolutionError(Status.UNAVAILABLE.withDescription("Ring hash lb error: EDS " + "resolution was successful, but returned server addresses are empty."));
        return;
    }
    Map<EquivalentAddressGroup, EquivalentAddressGroup> latestAddrs = stripAttrs(addrList);
    Set<EquivalentAddressGroup> removedAddrs = Sets.newHashSet(Sets.difference(subchannels.keySet(), latestAddrs.keySet()));
    RingHashConfig config = (RingHashConfig) resolvedAddresses.getLoadBalancingPolicyConfig();
    Map<EquivalentAddressGroup, Long> serverWeights = new HashMap<>();
    long totalWeight = 0L;
    for (EquivalentAddressGroup eag : addrList) {
        Long weight = eag.getAttributes().get(InternalXdsAttributes.ATTR_SERVER_WEIGHT);
        // each occurrence of the address will be counted a weight value of one.
        if (weight == null) {
            weight = 1L;
        }
        totalWeight += weight;
        EquivalentAddressGroup addrKey = stripAttrs(eag);
        if (serverWeights.containsKey(addrKey)) {
            serverWeights.put(addrKey, serverWeights.get(addrKey) + weight);
        } else {
            serverWeights.put(addrKey, weight);
        }
        Subchannel existingSubchannel = subchannels.get(addrKey);
        if (existingSubchannel != null) {
            existingSubchannel.updateAddresses(Collections.singletonList(eag));
            continue;
        }
        Attributes attr = Attributes.newBuilder().set(STATE_INFO, new Ref<>(ConnectivityStateInfo.forNonError(IDLE))).build();
        final Subchannel subchannel = helper.createSubchannel(CreateSubchannelArgs.newBuilder().setAddresses(eag).setAttributes(attr).build());
        subchannel.start(new SubchannelStateListener() {

            @Override
            public void onSubchannelState(ConnectivityStateInfo newState) {
                processSubchannelState(subchannel, newState);
            }
        });
        subchannels.put(addrKey, subchannel);
    }
    long minWeight = Collections.min(serverWeights.values());
    double normalizedMinWeight = (double) minWeight / totalWeight;
    // Scale up the number of hashes per host such that the least-weighted host gets a whole
    // number of hashes on the the ring. Other hosts might not end up with whole numbers, and
    // that's fine (the ring-building algorithm can handle this). This preserves the original
    // implementation's behavior: when weights aren't provided, all hosts should get an equal
    // number of hashes. In the case where this number exceeds the max_ring_size, it's scaled
    // back down to fit.
    double scale = Math.min(Math.ceil(normalizedMinWeight * config.minRingSize) / normalizedMinWeight, (double) config.maxRingSize);
    ring = buildRing(serverWeights, totalWeight, scale);
    // Shut down subchannels for delisted addresses.
    List<Subchannel> removedSubchannels = new ArrayList<>();
    for (EquivalentAddressGroup addr : removedAddrs) {
        removedSubchannels.add(subchannels.remove(addr));
    }
    // Update the picker before shutting down the subchannels, to reduce the chance of race
    // between picking a subchannel and shutting it down.
    updateBalancingState();
    for (Subchannel subchann : removedSubchannels) {
        shutdownSubchannel(subchann);
    }
}
Also used : HashMap(java.util.HashMap) Attributes(io.grpc.Attributes) ArrayList(java.util.ArrayList) ConnectivityStateInfo(io.grpc.ConnectivityStateInfo) EquivalentAddressGroup(io.grpc.EquivalentAddressGroup)

Example 95 with EquivalentAddressGroup

use of io.grpc.EquivalentAddressGroup in project jetcd by coreos.

the class EtcdClusterNameResolver method doResolve.

private void doResolve() {
    Listener savedListener;
    synchronized (lock) {
        if (shutdown) {
            return;
        }
        resolving = true;
        savedListener = listener;
    }
    try {
        if (authority == null) {
            throw new RuntimeException("Unable to resolve endpoint " + targetUri);
        }
        EtcdCluster cluster = EtcdClusterExtension.cluster(authority);
        if (cluster == null) {
            throw new RuntimeException("Unable to find cluster " + authority);
        }
        List<EquivalentAddressGroup> servers = cluster.containers().stream().map(container -> {
            return new EquivalentAddressGroup(container.getClientAddress(), Attributes.newBuilder().set(EquivalentAddressGroup.ATTR_AUTHORITY_OVERRIDE, container.node()).build());
        }).collect(Collectors.toList());
        savedListener.onAddresses(servers, Attributes.EMPTY);
    } catch (Exception e) {
        LOGGER.warn("Error wile getting list of servers", e);
        savedListener.onError(Status.NOT_FOUND);
    } finally {
        resolving = false;
    }
}
Also used : Logger(org.slf4j.Logger) Attributes(io.grpc.Attributes) Executor(java.util.concurrent.Executor) LoggerFactory(org.slf4j.LoggerFactory) Collectors(java.util.stream.Collectors) EquivalentAddressGroup(io.grpc.EquivalentAddressGroup) List(java.util.List) EtcdCluster(io.etcd.jetcd.launcher.EtcdCluster) GrpcUtil(io.grpc.internal.GrpcUtil) SharedResourceHolder(io.grpc.internal.SharedResourceHolder) Preconditions(com.google.common.base.Preconditions) URI(java.net.URI) NameResolver(io.grpc.NameResolver) Status(io.grpc.Status) EtcdCluster(io.etcd.jetcd.launcher.EtcdCluster) EquivalentAddressGroup(io.grpc.EquivalentAddressGroup)

Aggregations

EquivalentAddressGroup (io.grpc.EquivalentAddressGroup)173 Test (org.junit.Test)133 Subchannel (io.grpc.LoadBalancer.Subchannel)54 SocketAddress (java.net.SocketAddress)42 SubchannelPicker (io.grpc.LoadBalancer.SubchannelPicker)41 PickSubchannelArgs (io.grpc.LoadBalancer.PickSubchannelArgs)39 Status (io.grpc.Status)39 Attributes (io.grpc.Attributes)37 CreateSubchannelArgs (io.grpc.LoadBalancer.CreateSubchannelArgs)33 InOrder (org.mockito.InOrder)31 Helper (io.grpc.LoadBalancer.Helper)30 Metadata (io.grpc.Metadata)29 ArrayList (java.util.ArrayList)26 InetSocketAddress (java.net.InetSocketAddress)24 PickResult (io.grpc.LoadBalancer.PickResult)22 UnsupportedClientTransportFactoryBuilder (io.grpc.internal.ManagedChannelImplBuilder.UnsupportedClientTransportFactoryBuilder)20 PolicySelection (io.grpc.internal.ServiceConfigUtil.PolicySelection)20 InitialLoadBalanceResponse (io.grpc.lb.v1.InitialLoadBalanceResponse)19 LoadBalanceResponse (io.grpc.lb.v1.LoadBalanceResponse)19 ClientTransportFactoryBuilder (io.grpc.internal.ManagedChannelImplBuilder.ClientTransportFactoryBuilder)18