io.grpc.EquivalentAddressGroup Java Examples

The following examples show how to use io.grpc.EquivalentAddressGroup. 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: MultipleAddressNameResolverFactory.java    From glowroot with Apache License 2.0 6 votes vote down vote up
@Override
public void onAddresses(List<EquivalentAddressGroup> servers, Attributes attributes) {
    synchronized (lock) {
        if (closed) {
            return;
        }
        this.servers.addAll(servers);
        if (this.attributes == null) {
            this.attributes = attributes;
        } else if (!attributes.equals(this.attributes)) {
            throw new IllegalStateException("New attributes \"" + attributes
                    + "\" are not the same as existing attributes: " + this.attributes);
        }
        if (++onAddressesCount == nameResolvers.size()) {
            Collections.shuffle(this.servers);
            listener.onAddresses(this.servers, attributes);
            close();
        }
    }
}
 
Example #2
Source File: CachedSubchannelPoolTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Before
@SuppressWarnings("unchecked")
public void setUp() {
  doAnswer(new Answer<Subchannel>() {
      @Override
      public Subchannel answer(InvocationOnMock invocation) throws Throwable {
        Subchannel subchannel = mock(Subchannel.class);
        List<EquivalentAddressGroup> eagList =
            (List<EquivalentAddressGroup>) invocation.getArguments()[0];
        Attributes attrs = (Attributes) invocation.getArguments()[1];
        when(subchannel.getAllAddresses()).thenReturn(eagList);
        when(subchannel.getAttributes()).thenReturn(attrs);
        mockSubchannels.add(subchannel);
        return subchannel;
      }
    }).when(helper).createSubchannel(any(List.class), any(Attributes.class));
  when(helper.getSynchronizationContext()).thenReturn(syncContext);
  when(helper.getScheduledExecutorService()).thenReturn(clock.getScheduledExecutorService());
  pool.init(helper);
}
 
Example #3
Source File: ManagedChannelImplIdlenessTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void updateOobChannelAddresses_existingAddressDoesNotConnect() {
  ClientCall<String, Integer> call = channel.newCall(method, CallOptions.DEFAULT);
  call.start(mockCallListener, new Metadata()); // Create LB
  ArgumentCaptor<Helper> helperCaptor = ArgumentCaptor.forClass(null);
  verify(mockLoadBalancerFactory).newLoadBalancer(helperCaptor.capture());
  Helper helper = helperCaptor.getValue();
  ManagedChannel oobChannel = helper.createOobChannel(servers.get(0), "localhost");

  oobChannel.newCall(method, CallOptions.DEFAULT).start(mockCallListener, new Metadata());
  MockClientTransportInfo t0 = newTransports.poll();
  t0.listener.transportReady();

  List<SocketAddress> changedList = new ArrayList<>(servers.get(0).getAddresses());
  changedList.add(new FakeSocketAddress("aDifferentServer"));
  helper.updateOobChannelAddresses(oobChannel, new EquivalentAddressGroup(changedList));

  oobChannel.newCall(method, CallOptions.DEFAULT).start(mockCallListener, new Metadata());
  assertNull(newTransports.poll());
}
 
Example #4
Source File: ManagedChannelImplTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void channelTracing_nameResolvedEvent() throws Exception {
  timer.forwardNanos(1234);
  channelBuilder.maxTraceEvents(10);
  FakeNameResolverFactory nameResolverFactory =
      new FakeNameResolverFactory.Builder(expectedUri)
          .setServers(Collections.singletonList(new EquivalentAddressGroup(socketAddress)))
          .build();
  channelBuilder.nameResolverFactory(nameResolverFactory);
  createChannel();
  assertThat(getStats(channel).channelTrace.events).contains(new ChannelTrace.Event.Builder()
      .setDescription("Address resolved: "
          + Collections.singletonList(new EquivalentAddressGroup(socketAddress)))
      .setSeverity(ChannelTrace.Event.Severity.CT_INFO)
      .setTimestampNanos(timer.getTicker().read())
      .build());
}
 
Example #5
Source File: GrpclbLoadBalancerTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void nameResolutionFailsThenRecover() {
  Status error = Status.NOT_FOUND.withDescription("www.google.com not found");
  deliverNameResolutionError(error);
  verify(helper).updateBalancingState(eq(TRANSIENT_FAILURE), pickerCaptor.capture());
  assertThat(logs).containsExactly(
      "DEBUG: Error: " + error,
      "INFO: TRANSIENT_FAILURE: picks="
          + "[Status{code=NOT_FOUND, description=www.google.com not found, cause=null}],"
          + " drops=[]")
      .inOrder();
  logs.clear();

  RoundRobinPicker picker = (RoundRobinPicker) pickerCaptor.getValue();
  assertThat(picker.dropList).isEmpty();
  assertThat(picker.pickList).containsExactly(new ErrorEntry(error));

  // Recover with a subsequent success
  List<EquivalentAddressGroup> grpclbBalancerList = createResolvedBalancerAddresses(1);
  EquivalentAddressGroup eag = grpclbBalancerList.get(0);

  deliverResolvedAddresses(Collections.<EquivalentAddressGroup>emptyList(), grpclbBalancerList);

  verify(helper).createOobChannel(eq(eag), eq(lbAuthority(0)));
  verify(mockLbService).balanceLoad(lbResponseObserverCaptor.capture());
}
 
Example #6
Source File: PickFirstLoadBalancerTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void pickAfterResolvedAndChanged() throws Exception {
  SocketAddress socketAddr = new FakeSocketAddress("newserver");
  List<EquivalentAddressGroup> newServers =
      Lists.newArrayList(new EquivalentAddressGroup(socketAddr));

  InOrder inOrder = inOrder(mockHelper);

  loadBalancer.handleResolvedAddressGroups(servers, affinity);
  inOrder.verify(mockHelper).createSubchannel(eq(servers), any(Attributes.class));
  inOrder.verify(mockHelper).updateBalancingState(eq(CONNECTING), pickerCaptor.capture());
  verify(mockSubchannel).requestConnection();
  assertEquals(mockSubchannel, pickerCaptor.getValue().pickSubchannel(mockArgs).getSubchannel());

  loadBalancer.handleResolvedAddressGroups(newServers, affinity);
  inOrder.verify(mockHelper).updateSubchannelAddresses(eq(mockSubchannel), eq(newServers));

  verifyNoMoreInteractions(mockSubchannel);
  verifyNoMoreInteractions(mockHelper);
}
 
Example #7
Source File: CdsLoadBalancerTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void clusterWatcher_resourceNotExist() {
  ResolvedAddresses resolvedAddresses = ResolvedAddresses.newBuilder()
      .setAddresses(ImmutableList.<EquivalentAddressGroup>of())
      .setAttributes(Attributes.newBuilder()
          .set(XdsAttributes.XDS_CLIENT_POOL, xdsClientPool)
          .build())
      .setLoadBalancingPolicyConfig(new CdsConfig("foo.googleapis.com"))
      .build();
  cdsLoadBalancer.handleResolvedAddresses(resolvedAddresses);

  ArgumentCaptor<ClusterWatcher> clusterWatcherCaptor = ArgumentCaptor.forClass(null);
  verify(xdsClient).watchClusterData(eq("foo.googleapis.com"), clusterWatcherCaptor.capture());

  ClusterWatcher clusterWatcher = clusterWatcherCaptor.getValue();
  ArgumentCaptor<SubchannelPicker> pickerCaptor = ArgumentCaptor.forClass(null);
  clusterWatcher.onResourceDoesNotExist("foo.googleapis.com");
  assertThat(edsLoadBalancers).isEmpty();
  verify(helper).updateBalancingState(eq(TRANSIENT_FAILURE), pickerCaptor.capture());
  PickResult result = pickerCaptor.getValue().pickSubchannel(mock(PickSubchannelArgs.class));
  assertThat(result.getStatus().getCode()).isEqualTo(Code.UNAVAILABLE);
  assertThat(result.getStatus().getDescription())
      .isEqualTo("Resource foo.googleapis.com is unavailable");
}
 
Example #8
Source File: GrpclbLoadBalancerTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
private void subtestShutdownWithoutSubchannel(GrpclbConfig grpclbConfig) {
  List<EquivalentAddressGroup> grpclbBalancerList = createResolvedBalancerAddresses(1);
  deliverResolvedAddresses(
      Collections.<EquivalentAddressGroup>emptyList(),
      grpclbBalancerList,
      grpclbConfig);
  verify(mockLbService).balanceLoad(lbResponseObserverCaptor.capture());
  assertEquals(1, lbRequestObservers.size());
  StreamObserver<LoadBalanceRequest> requestObserver = lbRequestObservers.poll();

  verify(requestObserver, never()).onCompleted();
  balancer.shutdown();
  ArgumentCaptor<Throwable> throwableCaptor = ArgumentCaptor.forClass(Throwable.class);
  verify(requestObserver).onError(throwableCaptor.capture());
  assertThat(Status.fromThrowable(throwableCaptor.getValue()).getCode())
      .isEqualTo(Code.CANCELLED);
}
 
Example #9
Source File: AutoConfiguredLoadBalancerFactoryTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void decideLoadBalancerProvider_serviceConfigFailsOnUnknown() {
  Map<String, Object> serviceConfig = new HashMap<String, Object>();
  serviceConfig.put("loadBalancingPolicy", "MAGIC_BALANCER");
  List<EquivalentAddressGroup> servers =
      Collections.singletonList(
          new EquivalentAddressGroup(
              new SocketAddress(){},
              Attributes.EMPTY));
  try {
    AutoConfiguredLoadBalancer.decideLoadBalancerProvider(servers, serviceConfig);
    fail();
  } catch (PolicyNotFoundException e) {
    assertThat(e.policy).isEqualTo("magic_balancer");
    assertThat(e.choiceReason).contains("service-config specifies load-balancing policy");
  }
}
 
Example #10
Source File: EdsLoadBalancerTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
private void deliverResolvedAddresses(
    @Nullable String edsServiceName,
    @Nullable String lrsServerName,
    PolicySelection endpointPickingPolicy) {
  EdsConfig config =
      new EdsConfig(CLUSTER_NAME, edsServiceName, lrsServerName, endpointPickingPolicy);
  ResolvedAddresses.Builder resolvedAddressBuilder = ResolvedAddresses.newBuilder()
      .setAddresses(ImmutableList.<EquivalentAddressGroup>of())
      .setLoadBalancingPolicyConfig(config);
  if (isFullFlow) {
    resolvedAddressBuilder.setAttributes(
        Attributes.newBuilder().set(XdsAttributes.XDS_CLIENT_POOL,
            xdsClientPoolFromResolveAddresses).build());
  }
  edsLb.handleResolvedAddresses(resolvedAddressBuilder.build());
}
 
Example #11
Source File: ServiceConfigErrorHandlingTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void emptyAddresses_validConfig_firstResolution_lbNeedsAddress() throws Exception {
  FakeNameResolverFactory nameResolverFactory =
      new FakeNameResolverFactory.Builder(expectedUri)
          .setServers(Collections.<EquivalentAddressGroup>emptyList())
          .build();
  channelBuilder.nameResolverFactory(nameResolverFactory);

  Map<String, Object> rawServiceConfig =
      parseJson("{\"loadBalancingConfig\": [{\"round_robin\": {}}]}");
  nameResolverFactory.nextRawServiceConfig.set(rawServiceConfig);

  createChannel();

  assertThat(channel.getState(true)).isEqualTo(ConnectivityState.TRANSIENT_FAILURE);
  assertWithMessage("Empty address should schedule NameResolver retry")
      .that(getNameResolverRefresh())
      .isNotNull();
}
 
Example #12
Source File: AutoConfiguredLoadBalancerFactoryTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void handleResolvedAddressGroups_keepOldBalancer() {
  final List<EquivalentAddressGroup> servers =
      Collections.singletonList(
          new EquivalentAddressGroup(new SocketAddress(){}, Attributes.EMPTY));
  Helper helper = new TestHelper() {
    @Override
    public Subchannel createSubchannel(List<EquivalentAddressGroup> addrs, Attributes attrs) {
      assertThat(addrs).isEqualTo(servers);
      return new TestSubchannel(addrs, attrs);
    }

    @Override
    public void updateBalancingState(ConnectivityState newState, SubchannelPicker newPicker) {
      // noop
    }
  };
  AutoConfiguredLoadBalancer lb =
      (AutoConfiguredLoadBalancer) lbf.newLoadBalancer(helper);
  LoadBalancer oldDelegate = lb.getDelegate();

  lb.handleResolvedAddressGroups(servers, Attributes.EMPTY);

  assertThat(lb.getDelegate()).isSameAs(oldDelegate);
}
 
Example #13
Source File: HealthCheckingLoadBalancerFactory.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Override
public Subchannel createSubchannel(List<EquivalentAddressGroup> addrs, Attributes attrs) {
  // HealthCheckState is not thread-safe, we are requiring the original LoadBalancer calls
  // createSubchannel() from the SynchronizationContext.
  syncContext.throwIfNotInThisSynchronizationContext();
  HealthCheckState hcState = new HealthCheckState(
      this, delegateBalancer, syncContext, delegate.getScheduledExecutorService());
  hcStates.add(hcState);
  Subchannel subchannel = super.createSubchannel(
      addrs, attrs.toBuilder().set(KEY_HEALTH_CHECK_STATE, hcState).build());
  hcState.init(subchannel);
  if (healthCheckedService != null) {
    hcState.setServiceName(healthCheckedService);
  }
  return subchannel;
}
 
Example #14
Source File: PickFirstLoadBalancer.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
/**
 * 删除客户端与离线服务端之间的无效subchannel
 *
 * @author sxp
 * @since 2019/12/02
 */
@Override
public void removeInvalidCacheSubchannels(Set<String> removeHostPorts) {
  if (removeHostPorts == null || removeHostPorts.isEmpty()) {
    return;
  }

  Subchannel theSubchannel;
  EquivalentAddressGroup server;

  for (String hostAndPort: removeHostPorts) {
    server = getAddressGroupByHostAndPort(hostAndPort);
    if (server == null) {
      continue;
    }
    theSubchannel = subchannels.remove(server);
    if (theSubchannel != null) {
      logger.info("关闭" + server + "subchannel");
      theSubchannel.shutdown();
    }
  }
}
 
Example #15
Source File: CdsLoadBalancer.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
private static List<EquivalentAddressGroup> addUpstreamTlsContext(
    List<EquivalentAddressGroup> addresses,
    UpstreamTlsContext upstreamTlsContext) {
  if (upstreamTlsContext == null || addresses == null) {
    return addresses;
  }
  ArrayList<EquivalentAddressGroup> copyList = new ArrayList<>(addresses.size());
  for (EquivalentAddressGroup eag : addresses) {
    EquivalentAddressGroup eagCopy =
        new EquivalentAddressGroup(eag.getAddresses(),
            eag.getAttributes()
            .toBuilder()
            .set(XdsAttributes.ATTR_UPSTREAM_TLS_CONTEXT, upstreamTlsContext)
            .build()
            );
    copyList.add(eagCopy);
  }
  return copyList;
}
 
Example #16
Source File: PickFirstLoadBalancerTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void pickAfterResolvedAndUnchanged() throws Exception {
  loadBalancer.handleResolvedAddresses(
      ResolvedAddresses.newBuilder().setAddresses(servers).setAttributes(affinity).build());
  verify(mockSubchannel).start(any(SubchannelStateListener.class));
  verify(mockSubchannel).requestConnection();
  loadBalancer.handleResolvedAddresses(
      ResolvedAddresses.newBuilder().setAddresses(servers).setAttributes(affinity).build());
  verify(mockSubchannel).updateAddresses(eq(servers));
  verifyNoMoreInteractions(mockSubchannel);

  verify(mockHelper).createSubchannel(createArgsCaptor.capture());
  assertThat(createArgsCaptor.getValue()).isNotNull();
  verify(mockHelper)
      .updateBalancingState(isA(ConnectivityState.class), isA(SubchannelPicker.class));
  // Updating the subchannel addresses is unnecessary, but doesn't hurt anything
  verify(mockSubchannel).updateAddresses(ArgumentMatchers.<EquivalentAddressGroup>anyList());

  verifyNoMoreInteractions(mockHelper);
}
 
Example #17
Source File: GrpclbLoadBalancerTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
private void deliverResolvedAddresses(
    final List<EquivalentAddressGroup> backendAddrs,
    List<EquivalentAddressGroup> balancerAddrs,
    final GrpclbConfig grpclbConfig) {
  final Attributes attrs =
      Attributes.newBuilder().set(GrpclbConstants.ATTR_LB_ADDRS, balancerAddrs).build();
  syncContext.execute(new Runnable() {
    @Override
    public void run() {
      balancer.handleResolvedAddresses(
          ResolvedAddresses.newBuilder()
              .setAddresses(backendAddrs)
              .setAttributes(attrs)
              .setLoadBalancingPolicyConfig(grpclbConfig)
              .build());
    }
  });
}
 
Example #18
Source File: GrpclbNameResolverTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void resolve_nullResourceResolver() throws Exception {
  InetAddress backendAddr = InetAddress.getByAddress(new byte[] {127, 0, 0, 0});
  AddressResolver mockAddressResolver = mock(AddressResolver.class);
  when(mockAddressResolver.resolveAddress(anyString()))
      .thenReturn(Collections.singletonList(backendAddr));
  ResourceResolver resourceResolver = null;

  resolver.setAddressResolver(mockAddressResolver);
  resolver.setResourceResolver(resourceResolver);

  resolver.start(mockListener);
  assertThat(fakeClock.runDueTasks()).isEqualTo(1);
  verify(mockListener).onResult(resultCaptor.capture());
  ResolutionResult result = resultCaptor.getValue();
  assertThat(result.getAddresses())
      .containsExactly(
          new EquivalentAddressGroup(new InetSocketAddress(backendAddr, DEFAULT_PORT)));
  assertThat(result.getAttributes()).isEqualTo(Attributes.EMPTY);
  assertThat(result.getServiceConfig()).isNull();
}
 
Example #19
Source File: AbstractManagedChannelImplBuilder.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Override
public NameResolver newNameResolver(URI notUsedUri, Attributes params) {
  return new NameResolver() {
    @Override
    public String getServiceAuthority() {
      return authority;
    }

    @Override
    public void start(final Listener listener) {
      listener.onAddresses(
          Collections.singletonList(new EquivalentAddressGroup(address)),
          Attributes.EMPTY);
    }

    @Override
    public void shutdown() {}
  };
}
 
Example #20
Source File: InternalSubchannel.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Override
public ListenableFuture<ChannelStats> getStats() {
  SettableFuture<ChannelStats> ret = SettableFuture.create();
  ChannelStats.Builder builder = new ChannelStats.Builder();

  List<EquivalentAddressGroup> addressGroupsSnapshot;
  List<InternalWithLogId> transportsSnapshot;
  synchronized (lock) {
    addressGroupsSnapshot = addressIndex.getGroups();
    transportsSnapshot = new ArrayList<InternalWithLogId>(transports);
  }

  builder.setTarget(addressGroupsSnapshot.toString()).setState(getState());
  builder.setSockets(transportsSnapshot);
  callsTracer.updateBuilder(builder);
  channelTracer.updateBuilder(builder);
  ret.set(builder.build());
  return ret;
}
 
Example #21
Source File: AddressFilterTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void filterAddresses() {
  Attributes.Key<String> key1 = Attributes.Key.create("key1");
  Attributes attributes1 = Attributes.newBuilder().set(key1, "value1").build();
  EquivalentAddressGroup eag0 = new EquivalentAddressGroup(new InetSocketAddress(8000));
  EquivalentAddressGroup eag1 =
      new EquivalentAddressGroup(new InetSocketAddress(8001), attributes1);
  EquivalentAddressGroup eag2 = new EquivalentAddressGroup(new InetSocketAddress(8002));
  EquivalentAddressGroup eag3 =
      new EquivalentAddressGroup(
          Arrays.<SocketAddress>asList(new InetSocketAddress(8003), new InetSocketAddress(8083)));
  eag0 = AddressFilter.setPathFilter(eag0, Arrays.asList("A", "C"));
  eag1 = AddressFilter.setPathFilter(eag1, Arrays.asList("A", "B"));
  eag2 = AddressFilter.setPathFilter(eag2, Arrays.asList("D", "C"));
  eag3 = AddressFilter.setPathFilter(eag3, Arrays.asList("A", "B"));

  List<EquivalentAddressGroup> addresses =
      AddressFilter.filter(Arrays.asList(eag0, eag1, eag2, eag3), "A");
  assertThat(addresses).hasSize(3);
  addresses = AddressFilter.filter(addresses, "B");
  assertThat(addresses).hasSize(2);
  EquivalentAddressGroup filteredAddress0 = addresses.get(0);
  EquivalentAddressGroup filteredAddress1 = addresses.get(1);
  assertThat(filteredAddress0.getAddresses()).containsExactlyElementsIn(eag1.getAddresses());
  assertThat(filteredAddress0.getAttributes().get(key1)).isEqualTo("value1");
  assertThat(filteredAddress1.getAddresses()).containsExactlyElementsIn(eag3.getAddresses());
}
 
Example #22
Source File: CdsLoadBalancerTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void clusterWatcher_resourceRemoved() {
  ResolvedAddresses resolvedAddresses = ResolvedAddresses.newBuilder()
      .setAddresses(ImmutableList.<EquivalentAddressGroup>of())
      .setAttributes(Attributes.newBuilder()
          .set(XdsAttributes.XDS_CLIENT_POOL, xdsClientPool)
          .build())
      .setLoadBalancingPolicyConfig(new CdsConfig("foo.googleapis.com"))
      .build();
  cdsLoadBalancer.handleResolvedAddresses(resolvedAddresses);

  ArgumentCaptor<ClusterWatcher> clusterWatcherCaptor = ArgumentCaptor.forClass(null);
  verify(xdsClient).watchClusterData(eq("foo.googleapis.com"), clusterWatcherCaptor.capture());

  ClusterWatcher clusterWatcher = clusterWatcherCaptor.getValue();
  ArgumentCaptor<SubchannelPicker> pickerCaptor = ArgumentCaptor.forClass(null);
  clusterWatcher.onClusterChanged(
      ClusterUpdate.newBuilder()
          .setClusterName("foo.googleapis.com")
          .setEdsServiceName("edsServiceFoo.googleapis.com")
          .setLbPolicy("round_robin")
          .build());
  assertThat(edsLoadBalancers).hasSize(1);
  assertThat(edsLbHelpers).hasSize(1);
  LoadBalancer edsLoadBalancer = edsLoadBalancers.poll();
  Helper edsHelper = edsLbHelpers.poll();
  SubchannelPicker subchannelPicker = mock(SubchannelPicker.class);
  edsHelper.updateBalancingState(READY, subchannelPicker);
  verify(helper).updateBalancingState(eq(READY), same(subchannelPicker));

  clusterWatcher.onResourceDoesNotExist("foo.googleapis.com");
  verify(edsLoadBalancer).shutdown();
  verify(helper).updateBalancingState(eq(TRANSIENT_FAILURE), pickerCaptor.capture());
  PickResult result = pickerCaptor.getValue().pickSubchannel(mock(PickSubchannelArgs.class));
  assertThat(result.getStatus().getCode()).isEqualTo(Code.UNAVAILABLE);
  assertThat(result.getStatus().getDescription())
      .isEqualTo("Resource foo.googleapis.com is unavailable");
}
 
Example #23
Source File: PickFirstLoadBalancer.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Override
public void handleSubchannelState(Subchannel subchannel, ConnectivityStateInfo stateInfo) {
  ConnectivityState currentState = stateInfo.getState();
  if (currentState == SHUTDOWN) {
    return;
  }

  EquivalentAddressGroup addressGroup = subchannel.getAddresses();
  Subchannel theSubchannel = subchannels.get(addressGroup);
  if (theSubchannel == null) {
    return;
  }

  if (theSubchannel != currentSubchannel) {
    return;
  }

  SubchannelPicker picker;
  switch (currentState) {
    case IDLE:
      picker = new RequestConnectionPicker(subchannel);
      break;
    case CONNECTING:
      // It's safe to use RequestConnectionPicker here, so when coming from IDLE we could leave
      // the current picker in-place. But ignoring the potential optimization is simpler.
      picker = new Picker(PickResult.withNoResult());
      break;
    case READY:
      picker = new Picker(PickResult.withSubchannel(subchannel));
      break;
    case TRANSIENT_FAILURE:
      picker = new Picker(PickResult.withError(stateInfo.getStatus()));
      break;
    default:
      throw new IllegalArgumentException("Unsupported state:" + currentState);
  }

  helper.updateBalancingState(currentState, picker);
}
 
Example #24
Source File: JndiResourceResolverTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Test
public void srvRecordLookup() throws Exception {
  AddressResolver addressResolver = mock(AddressResolver.class);
  when(addressResolver.resolveAddress("foo.example.com."))
      .thenReturn(Arrays.asList(InetAddress.getByName("127.1.2.3")));
  when(addressResolver.resolveAddress("bar.example.com."))
      .thenReturn(Arrays.asList(
          InetAddress.getByName("127.3.2.1"), InetAddress.getByName("::1")));
  when(addressResolver.resolveAddress("unknown.example.com."))
      .thenThrow(new UnknownHostException("unknown.example.com."));
  RecordFetcher recordFetcher = mock(RecordFetcher.class);
  when(recordFetcher.getAllRecords("SRV", "dns:///service.example.com"))
      .thenReturn(Arrays.asList(
          "0 0 314 foo.example.com.", "0 0 42 bar.example.com.", "0 0 1 unknown.example.com."));

  List<EquivalentAddressGroup> golden = Arrays.asList(
      new EquivalentAddressGroup(
          Arrays.<SocketAddress>asList(new InetSocketAddress("127.1.2.3", 314)),
          Attributes.newBuilder()
            .set(GrpcAttributes.ATTR_LB_ADDR_AUTHORITY, "foo.example.com")
            .build()),
      new EquivalentAddressGroup(
          Arrays.<SocketAddress>asList(
              new InetSocketAddress("127.3.2.1", 42),
              new InetSocketAddress("::1", 42)),
          Attributes.newBuilder()
            .set(GrpcAttributes.ATTR_LB_ADDR_AUTHORITY, "bar.example.com")
            .build()));
  JndiResourceResolver resolver = new JndiResourceResolver(recordFetcher);
  assertThat(resolver.resolveSrv(addressResolver, "service.example.com")).isEqualTo(golden);
}
 
Example #25
Source File: InternalSubchannel.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
public void increment() {
  EquivalentAddressGroup group = addressGroups.get(groupIndex);
  addressIndex++;
  if (addressIndex >= group.getAddresses().size()) {
    groupIndex++;
    addressIndex = 0;
  }
}
 
Example #26
Source File: PickFirstLoadBalancerTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
  for (int i = 0; i < 3; i++) {
    SocketAddress addr = new FakeSocketAddress("server" + i);
    servers.add(new EquivalentAddressGroup(addr));
    socketAddresses.add(addr);
  }

  when(mockSubchannel.getAllAddresses()).thenThrow(new UnsupportedOperationException());
  when(mockHelper.getSynchronizationContext()).thenReturn(syncContext);
  when(mockHelper.createSubchannel(any(CreateSubchannelArgs.class))).thenReturn(mockSubchannel);

  loadBalancer = new PickFirstLoadBalancer(mockHelper);
}
 
Example #27
Source File: GrpclbLoadBalancerTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void grpclbThenNameResolutionFails() {
  InOrder inOrder = inOrder(helper, subchannelPool);
  // Go to GRPCLB first
  List<EquivalentAddressGroup> grpclbBalancerList = createResolvedBalancerAddresses(1);
  deliverResolvedAddresses(Collections.<EquivalentAddressGroup>emptyList(), grpclbBalancerList);

  verify(helper).createOobChannel(eq(grpclbBalancerList.get(0)), eq(lbAuthority(0)));
  assertEquals(1, fakeOobChannels.size());
  ManagedChannel oobChannel = fakeOobChannels.poll();
  verify(mockLbService).balanceLoad(lbResponseObserverCaptor.capture());
  StreamObserver<LoadBalanceResponse> lbResponseObserver = lbResponseObserverCaptor.getValue();

  // Let name resolution fail before round-robin list is ready
  Status error = Status.NOT_FOUND.withDescription("www.google.com not found");
  deliverNameResolutionError(error);

  inOrder.verify(helper).updateBalancingState(eq(TRANSIENT_FAILURE), pickerCaptor.capture());
  RoundRobinPicker picker = (RoundRobinPicker) pickerCaptor.getValue();
  assertThat(picker.dropList).isEmpty();
  assertThat(picker.pickList).containsExactly(new ErrorEntry(error));
  assertFalse(oobChannel.isShutdown());

  // Simulate receiving LB response
  List<ServerEntry> backends = Arrays.asList(
      new ServerEntry("127.0.0.1", 2000, "TOKEN1"),
      new ServerEntry("127.0.0.1", 2010, "TOKEN2"));
  lbResponseObserver.onNext(buildInitialResponse());
  lbResponseObserver.onNext(buildLbResponse(backends));

  inOrder.verify(subchannelPool).takeOrCreateSubchannel(
      eq(new EquivalentAddressGroup(backends.get(0).addr, LB_BACKEND_ATTRS)),
      any(Attributes.class));
  inOrder.verify(subchannelPool).takeOrCreateSubchannel(
      eq(new EquivalentAddressGroup(backends.get(1).addr, LB_BACKEND_ATTRS)),
      any(Attributes.class));
}
 
Example #28
Source File: InternalSubchannelTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test public void index_updateGroups_resets() {
  SocketAddress addr1 = new FakeSocketAddress();
  SocketAddress addr2 = new FakeSocketAddress();
  SocketAddress addr3 = new FakeSocketAddress();
  Index index = new Index(Arrays.asList(
      new EquivalentAddressGroup(Arrays.asList(addr1)),
      new EquivalentAddressGroup(Arrays.asList(addr2, addr3))));
  index.increment();
  index.increment();
  // We want to make sure both groupIndex and addressIndex are reset
  index.updateGroups(Arrays.asList(
      new EquivalentAddressGroup(Arrays.asList(addr1)),
      new EquivalentAddressGroup(Arrays.asList(addr2, addr3))));
  assertThat(index.getCurrentAddress()).isSameInstanceAs(addr1);
}
 
Example #29
Source File: ManagedChannelImplTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void shutdownWithNoTransportsEverCreated() {
  channelBuilder.nameResolverFactory(
      new FakeNameResolverFactory.Builder(expectedUri)
          .setServers(Collections.singletonList(new EquivalentAddressGroup(socketAddress)))
          .build());
  createChannel();
  verify(executorPool).getObject();
  verify(executorPool, never()).returnObject(any());
  channel.shutdown();
  assertTrue(channel.isShutdown());
  assertTrue(channel.isTerminated());
  verify(executorPool).returnObject(executor.getScheduledExecutorService());
}
 
Example #30
Source File: GrpclbNameResolver.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Override
protected InternalResolutionResult doResolve(boolean forceTxt) {
  List<EquivalentAddressGroup> balancerAddrs = resolveBalancerAddresses();
  InternalResolutionResult result = super.doResolve(!balancerAddrs.isEmpty());
  if (!balancerAddrs.isEmpty()) {
    result.attributes =
        Attributes.newBuilder()
            .set(GrpclbConstants.ATTR_LB_ADDRS, balancerAddrs)
            .build();
  }
  return result;
}