io.grpc.LoadBalancer.PickResult Java Examples

The following examples show how to use io.grpc.LoadBalancer.PickResult. 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: LrsLoadBalancerTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void subchannelPickerInterceptedWithLoadRecording() {
  List<EquivalentAddressGroup> backendAddrs = createResolvedBackendAddresses(2);
  deliverResolvedAddresses(backendAddrs, "round_robin");
  FakeLoadBalancer childBalancer = (FakeLoadBalancer) childBalancers.poll();
  NoopSubchannel subchannel = childBalancer.subchannels.values().iterator().next();
  deliverSubchannelState(subchannel, ConnectivityState.READY);
  assertThat(loadRecorder.recording).isTrue();
  ArgumentCaptor<SubchannelPicker> pickerCaptor = ArgumentCaptor.forClass(null);
  verify(helper).updateBalancingState(eq(ConnectivityState.READY), pickerCaptor.capture());
  SubchannelPicker picker = pickerCaptor.getValue();
  assertThat(picker).isInstanceOf(LoadRecordingSubchannelPicker.class);
  PickResult result = picker.pickSubchannel(mock(PickSubchannelArgs.class));
  ClientStreamTracer.Factory tracerFactory = result.getStreamTracerFactory();
  assertThat(((LoadRecordingStreamTracerFactory) tracerFactory).getCounter())
      .isSameInstanceAs(counter);
  loadBalancer.shutdown();
  assertThat(childBalancer.shutdown).isTrue();
  assertThat(loadRecorder.recording).isFalse();
}
 
Example #2
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 #3
Source File: DelayedClientTransportTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void reprocess_NoPendingStream() {
  SubchannelPicker picker = mock(SubchannelPicker.class);
  AbstractSubchannel subchannel = mock(AbstractSubchannel.class);
  when(subchannel.obtainActiveTransport()).thenReturn(mockRealTransport);
  when(picker.pickSubchannel(any(PickSubchannelArgs.class))).thenReturn(
      PickResult.withSubchannel(subchannel));
  when(mockRealTransport.newStream(any(MethodDescriptor.class), any(Metadata.class),
          any(CallOptions.class))).thenReturn(mockRealStream);
  delayedTransport.reprocess(picker);
  verifyNoMoreInteractions(picker);
  verifyNoMoreInteractions(transportListener);

  // Though picker was not originally used, it will be saved and serve future streams.
  ClientStream stream = delayedTransport.newStream(method, headers, CallOptions.DEFAULT);
  verify(picker).pickSubchannel(new PickSubchannelArgsImpl(method, headers, CallOptions.DEFAULT));
  verify(subchannel).obtainActiveTransport();
  assertSame(mockRealStream, stream);
}
 
Example #4
Source File: GrpclbLoadBalancerTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void roundRobinPickerWithIdleEntry_andDrop() {
  GrpclbClientLoadRecorder loadRecorder =
      new GrpclbClientLoadRecorder(fakeClock.getTimeProvider());
  // 1 out of 2 requests are to be dropped
  DropEntry d = new DropEntry(loadRecorder, "LBTOKEN0003");
  List<DropEntry> dropList = Arrays.asList(null, d);

  Subchannel subchannel = mock(Subchannel.class);
  IdleSubchannelEntry entry = new IdleSubchannelEntry(subchannel, syncContext);

  RoundRobinPicker picker = new RoundRobinPicker(dropList, Collections.singletonList(entry));
  PickSubchannelArgs args = mock(PickSubchannelArgs.class);

  verify(subchannel, never()).requestConnection();
  assertThat(picker.pickSubchannel(args)).isSameInstanceAs(PickResult.withNoResult());
  verify(subchannel).requestConnection();

  assertThat(picker.pickSubchannel(args)).isSameInstanceAs(DROP_PICK_RESULT);

  verify(subchannel).requestConnection();
  assertThat(picker.pickSubchannel(args)).isSameInstanceAs(PickResult.withNoResult());
  // Only the first pick triggers requestConnection()
  verify(subchannel).requestConnection();
}
 
Example #5
Source File: RoundRobinLoadBalancerTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void nameResolutionErrorWithActiveChannels() throws Exception {
  final Subchannel readySubchannel = subchannels.values().iterator().next();
  loadBalancer.handleResolvedAddressGroups(servers, affinity);
  loadBalancer.handleSubchannelState(readySubchannel, ConnectivityStateInfo.forNonError(READY));
  loadBalancer.handleNameResolutionError(Status.NOT_FOUND.withDescription("nameResolutionError"));

  verify(mockHelper, times(3)).createSubchannel(any(List.class), any(Attributes.class));
  verify(mockHelper, times(3))
      .updateBalancingState(stateCaptor.capture(), pickerCaptor.capture());

  Iterator<ConnectivityState> stateIterator = stateCaptor.getAllValues().iterator();
  assertEquals(CONNECTING, stateIterator.next());
  assertEquals(READY, stateIterator.next());
  assertEquals(TRANSIENT_FAILURE, stateIterator.next());

  LoadBalancer.PickResult pickResult = pickerCaptor.getValue().pickSubchannel(mockArgs);
  assertEquals(readySubchannel, pickResult.getSubchannel());
  assertEquals(Status.OK.getCode(), pickResult.getStatus().getCode());

  LoadBalancer.PickResult pickResult2 = pickerCaptor.getValue().pickSubchannel(mockArgs);
  assertEquals(readySubchannel, pickResult2.getSubchannel());
  verifyNoMoreInteractions(mockHelper);
}
 
Example #6
Source File: GrpclbLoadBalancerTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void roundRobinPickerWithIdleEntry_noDrop() {
  Subchannel subchannel = mock(Subchannel.class);
  IdleSubchannelEntry entry = new IdleSubchannelEntry(subchannel, syncContext);

  RoundRobinPicker picker =
      new RoundRobinPicker(Collections.<DropEntry>emptyList(), Collections.singletonList(entry));
  PickSubchannelArgs args = mock(PickSubchannelArgs.class);

  verify(subchannel, never()).requestConnection();
  assertThat(picker.pickSubchannel(args)).isSameInstanceAs(PickResult.withNoResult());
  verify(subchannel).requestConnection();
  assertThat(picker.pickSubchannel(args)).isSameInstanceAs(PickResult.withNoResult());
  // Only the first pick triggers requestConnection()
  verify(subchannel).requestConnection();
}
 
Example #7
Source File: ManagedChannelImpl.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
void panic(final Throwable t) {
  if (panicMode) {
    // Preserve the first panic information
    return;
  }
  panicMode = true;
  cancelIdleTimer(/* permanent= */ true);
  shutdownNameResolverAndLoadBalancer(false);
  final class PanicSubchannelPicker extends SubchannelPicker {
    private final PickResult panicPickResult =
        PickResult.withDrop(
            Status.INTERNAL.withDescription("Panic! This is a bug!").withCause(t));

    @Override
    public PickResult pickSubchannel(PickSubchannelArgs args) {
      return panicPickResult;
    }
  }

  updateSubchannelPicker(new PanicSubchannelPicker());
  channelLogger.log(ChannelLogLevel.ERROR, "PANIC! Entering TRANSIENT_FAILURE");
  channelStateManager.gotoState(TRANSIENT_FAILURE);
}
 
Example #8
Source File: DelayedClientTransportTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void reprocess_NoPendingStream() {
  SubchannelPicker picker = mock(SubchannelPicker.class);
  AbstractSubchannel subchannel = mock(AbstractSubchannel.class);
  when(subchannel.getInternalSubchannel()).thenReturn(mockInternalSubchannel);
  when(picker.pickSubchannel(any(PickSubchannelArgs.class))).thenReturn(
      PickResult.withSubchannel(subchannel));
  when(mockRealTransport.newStream(any(MethodDescriptor.class), any(Metadata.class),
          any(CallOptions.class))).thenReturn(mockRealStream);
  delayedTransport.reprocess(picker);
  verifyNoMoreInteractions(picker);
  verifyNoMoreInteractions(transportListener);

  // Though picker was not originally used, it will be saved and serve future streams.
  ClientStream stream = delayedTransport.newStream(method, headers, CallOptions.DEFAULT);
  verify(picker).pickSubchannel(new PickSubchannelArgsImpl(method, headers, CallOptions.DEFAULT));
  verify(mockInternalSubchannel).obtainActiveTransport();
  assertSame(mockRealStream, stream);
}
 
Example #9
Source File: DelayedClientTransportTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void newStream_racesWithReprocessIdleMode() throws Exception {
  SubchannelPicker picker = new SubchannelPicker() {
    @Override public PickResult pickSubchannel(PickSubchannelArgs args) {
      // Assume entering idle mode raced with the pick
      delayedTransport.reprocess(null);
      // Act like IDLE LB
      return PickResult.withNoResult();
    }
  };

  // Because there is no pending stream yet, it will do nothing but save the picker.
  delayedTransport.reprocess(picker);

  ClientStream stream = delayedTransport.newStream(method, headers, callOptions);
  stream.start(streamListener);
  assertTrue(delayedTransport.hasPendingStreams());
  verify(transportListener).transportInUse(true);
}
 
Example #10
Source File: RoundRobinLoadBalancerTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void nameResolutionErrorWithActiveChannels() throws Exception {
  final Subchannel readySubchannel = subchannels.values().iterator().next();
  loadBalancer.handleResolvedAddresses(
      ResolvedAddresses.newBuilder().setAddresses(servers).setAttributes(affinity).build());
  deliverSubchannelState(readySubchannel, ConnectivityStateInfo.forNonError(READY));
  loadBalancer.handleNameResolutionError(Status.NOT_FOUND.withDescription("nameResolutionError"));

  verify(mockHelper, times(3)).createSubchannel(any(CreateSubchannelArgs.class));
  verify(mockHelper, times(3))
      .updateBalancingState(stateCaptor.capture(), pickerCaptor.capture());

  Iterator<ConnectivityState> stateIterator = stateCaptor.getAllValues().iterator();
  assertEquals(CONNECTING, stateIterator.next());
  assertEquals(READY, stateIterator.next());
  assertEquals(TRANSIENT_FAILURE, stateIterator.next());

  LoadBalancer.PickResult pickResult = pickerCaptor.getValue().pickSubchannel(mockArgs);
  assertEquals(readySubchannel, pickResult.getSubchannel());
  assertEquals(Status.OK.getCode(), pickResult.getStatus().getCode());

  LoadBalancer.PickResult pickResult2 = pickerCaptor.getValue().pickSubchannel(mockArgs);
  assertEquals(readySubchannel, pickResult2.getSubchannel());
  verifyNoMoreInteractions(mockHelper);
}
 
Example #11
Source File: OobChannel.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
void handleSubchannelStateChange(final ConnectivityStateInfo newState) {
  channelTracer.reportEvent(
      new ChannelTrace.Event.Builder()
          .setDescription("Entering " + newState.getState() + " state")
          .setSeverity(ChannelTrace.Event.Severity.CT_INFO)
          .setTimestampNanos(timeProvider.currentTimeNanos())
          .build());
  switch (newState.getState()) {
    case READY:
    case IDLE:
      delayedTransport.reprocess(subchannelPicker);
      break;
    case TRANSIENT_FAILURE:
      delayedTransport.reprocess(new SubchannelPicker() {
          final PickResult errorResult = PickResult.withError(newState.getStatus());

          @Override
          public PickResult pickSubchannel(PickSubchannelArgs args) {
            return errorResult;
          }
        });
      break;
    default:
      // Do nothing
  }
}
 
Example #12
Source File: GrpclbState.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
/**
 * For PICK_FIRST: creates a BackendEntry that includes all addresses.
 */
BackendEntry(Subchannel subchannel, TokenAttachingTracerFactory tracerFactory) {
  this.subchannel = checkNotNull(subchannel, "subchannel");
  this.result =
      PickResult.withSubchannel(subchannel, checkNotNull(tracerFactory, "tracerFactory"));
  this.token = null;
}
 
Example #13
Source File: LoadBalancerTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Test
public void pickResult_withSubchannelAndTracer() {
  PickResult result = PickResult.withSubchannel(subchannel, tracerFactory);
  assertThat(result.getSubchannel()).isSameAs(subchannel);
  assertThat(result.getStatus()).isSameAs(Status.OK);
  assertThat(result.getStreamTracerFactory()).isSameAs(tracerFactory);
  assertThat(result.isDrop()).isFalse();
}
 
Example #14
Source File: ManagedChannelImplTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void pickerReturnsStreamTracer_delayed() {
  ClientStream mockStream = mock(ClientStream.class);
  ClientStreamTracer.Factory factory1 = mock(ClientStreamTracer.Factory.class);
  ClientStreamTracer.Factory factory2 = mock(ClientStreamTracer.Factory.class);
  createChannel();

  CallOptions callOptions = CallOptions.DEFAULT.withStreamTracerFactory(factory1);
  ClientCall<String, Integer> call = channel.newCall(method, callOptions);
  call.start(mockCallListener, new Metadata());

  Subchannel subchannel =
      createSubchannelSafely(helper, addressGroup, Attributes.EMPTY, subchannelStateListener);
  requestConnectionSafely(helper, subchannel);
  MockClientTransportInfo transportInfo = transports.poll();
  transportInfo.listener.transportReady();
  ClientTransport mockTransport = transportInfo.transport;
  when(mockTransport.newStream(
          any(MethodDescriptor.class), any(Metadata.class), any(CallOptions.class)))
      .thenReturn(mockStream);
  when(mockPicker.pickSubchannel(any(PickSubchannelArgs.class))).thenReturn(
      PickResult.withSubchannel(subchannel, factory2));

  updateBalancingStateSafely(helper, READY, mockPicker);
  assertEquals(1, executor.runDueTasks());

  verify(mockPicker).pickSubchannel(any(PickSubchannelArgs.class));
  verify(mockTransport).newStream(same(method), any(Metadata.class), callOptionsCaptor.capture());
  assertEquals(
      Arrays.asList(factory1, factory2),
      callOptionsCaptor.getValue().getStreamTracerFactories());
  // The factories are safely not stubbed because we do not expect any usage of them.
  verifyZeroInteractions(factory1);
  verifyZeroInteractions(factory2);
}
 
Example #15
Source File: GrpclbState.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
/**
 * For ROUND_ROBIN: creates a BackendEntry whose usage will be reported to load recorder.
 */
BackendEntry(Subchannel subchannel, GrpclbClientLoadRecorder loadRecorder, String token) {
  this.subchannel = checkNotNull(subchannel, "subchannel");
  this.result =
      PickResult.withSubchannel(subchannel, checkNotNull(loadRecorder, "loadRecorder"));
  this.token = checkNotNull(token, "token");
}
 
Example #16
Source File: DelayedClientTransportTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Before public void setUp() {
  when(mockPicker.pickSubchannel(any(PickSubchannelArgs.class)))
      .thenReturn(PickResult.withSubchannel(mockSubchannel));
  when(mockSubchannel.getInternalSubchannel()).thenReturn(mockInternalSubchannel);
  when(mockInternalSubchannel.obtainActiveTransport()).thenReturn(mockRealTransport);
  when(mockRealTransport.newStream(same(method), same(headers), same(callOptions)))
      .thenReturn(mockRealStream);
  when(mockRealTransport2.newStream(same(method2), same(headers2), same(callOptions2)))
      .thenReturn(mockRealStream2);
  delayedTransport.start(transportListener);
}
 
Example #17
Source File: GrpclbState.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Override
public PickResult picked(Metadata headers) {
  if (connectionRequested.compareAndSet(false, true)) {
    syncContext.execute(new Runnable() {
        @Override
        public void run() {
          subchannel.requestConnection();
        }
      });
  }
  return PickResult.withNoResult();
}
 
Example #18
Source File: LoadBalancerTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Test
public void pickResult_withDrop() {
  PickResult result = PickResult.withDrop(status);
  assertThat(result.getSubchannel()).isNull();
  assertThat(result.getStatus()).isSameAs(status);
  assertThat(result.getStreamTracerFactory()).isNull();
  assertThat(result.isDrop()).isTrue();
}
 
Example #19
Source File: LoadBalancerTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Test
public void pickResult_withNoResult() {
  PickResult result = PickResult.withNoResult();
  assertThat(result.getSubchannel()).isNull();
  assertThat(result.getStatus()).isSameAs(Status.OK);
  assertThat(result.getStreamTracerFactory()).isNull();
  assertThat(result.isDrop()).isFalse();
}
 
Example #20
Source File: GrpcUtilTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void getTransportFromPickResult_dropPickResult_waitForReady() {
  Status status = Status.UNAVAILABLE;
  PickResult pickResult = PickResult.withDrop(status);
  ClientTransport transport = GrpcUtil.getTransportFromPickResult(pickResult, true);

  assertNotNull(transport);

  ClientStream stream = transport
      .newStream(TestMethodDescriptors.voidMethod(), new Metadata(), CallOptions.DEFAULT);
  ClientStreamListener listener = mock(ClientStreamListener.class);
  stream.start(listener);

  verify(listener).closed(eq(status), eq(RpcProgress.DROPPED), any(Metadata.class));
}
 
Example #21
Source File: LoadBalancerTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Test
public void pickResult_withError() {
  PickResult result = PickResult.withError(status);
  assertThat(result.getSubchannel()).isNull();
  assertThat(result.getStatus()).isSameAs(status);
  assertThat(result.getStreamTracerFactory()).isNull();
  assertThat(result.isDrop()).isFalse();
}
 
Example #22
Source File: GrpclbState.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Override
public PickResult picked(Metadata headers) {
  headers.discardAll(GrpclbConstants.TOKEN_METADATA_KEY);
  if (token != null) {
    headers.put(GrpclbConstants.TOKEN_METADATA_KEY, token);
  }
  return result;
}
 
Example #23
Source File: GrpcRoutePicker.java    From saluki with Apache License 2.0 5 votes vote down vote up
@Override
public PickResult pickSubchannel(PickSubchannelArgs args) {
  Map<String, Object> affinity =
      args.getCallOptions().getOption(GrpcCallOptions.CALLOPTIONS_CUSTOME_KEY);
  GrpcURL refUrl = (GrpcURL) affinity.get(GrpcCallOptions.GRPC_REF_URL);
  if (size > 0) {
    Subchannel subchannel = nextSubchannel(refUrl);
    affinity.put(GrpcCallOptions.GRPC_NAMERESOVER_ATTRIBUTES, nameResovleCache);
    return PickResult.withSubchannel(subchannel);
  }
  if (status != null) {
    return PickResult.withError(status);
  }
  return PickResult.withNoResult();
}
 
Example #24
Source File: GrpclbState.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Override
public PickResult pickSubchannel(PickSubchannelArgs args) {
  synchronized (pickList) {
    // Two-level round-robin.
    // First round-robin on dropList. If a drop entry is selected, request will be dropped.  If
    // a non-drop entry is selected, then round-robin on pickList.  This makes sure requests are
    // dropped at the same proportion as the drop entries appear on the round-robin list from
    // the balancer, while only backends from pickList are selected for the non-drop cases.
    if (!dropList.isEmpty()) {
      DropEntry drop = dropList.get(dropIndex);
      dropIndex++;
      if (dropIndex == dropList.size()) {
        dropIndex = 0;
      }
      if (drop != null) {
        return drop.picked();
      }
    }

    RoundRobinEntry pick = pickList.get(pickIndex);
    pickIndex++;
    if (pickIndex == pickList.size()) {
      pickIndex = 0;
    }
    return pick.picked(args.getHeaders());
  }
}
 
Example #25
Source File: DelayedClientTransportTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Before public void setUp() {
  MockitoAnnotations.initMocks(this);
  when(mockPicker.pickSubchannel(any(PickSubchannelArgs.class)))
      .thenReturn(PickResult.withSubchannel(mockSubchannel));
  when(mockSubchannel.obtainActiveTransport()).thenReturn(mockRealTransport);
  when(mockRealTransport.newStream(same(method), same(headers), same(callOptions)))
      .thenReturn(mockRealStream);
  when(mockRealTransport2.newStream(same(method2), same(headers2), same(callOptions2)))
      .thenReturn(mockRealStream2);
  delayedTransport.start(transportListener);
}
 
Example #26
Source File: GrpcUtilTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Test
public void getTransportFromPickResult_dropPickResult_failFast() {
  Status status = Status.UNAVAILABLE;
  PickResult pickResult = PickResult.withDrop(status);
  ClientTransport transport = GrpcUtil.getTransportFromPickResult(pickResult, false);

  assertNotNull(transport);

  ClientStream stream = transport
      .newStream(TestMethodDescriptors.voidMethod(), new Metadata(), CallOptions.DEFAULT);
  ClientStreamListener listener = mock(ClientStreamListener.class);
  stream.start(listener);

  verify(listener).closed(eq(status), eq(RpcProgress.DROPPED), any(Metadata.class));
}
 
Example #27
Source File: ManagedChannelImplTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
private void subtestFailRpcFromBalancer(boolean waitForReady, boolean drop, boolean shouldFail) {
  createChannel();

  // This call will be buffered by the channel, thus involve delayed transport
  CallOptions callOptions = CallOptions.DEFAULT;
  if (waitForReady) {
    callOptions = callOptions.withWaitForReady();
  } else {
    callOptions = callOptions.withoutWaitForReady();
  }
  ClientCall<String, Integer> call1 = channel.newCall(method, callOptions);
  call1.start(mockCallListener, new Metadata());

  SubchannelPicker picker = mock(SubchannelPicker.class);
  Status status = Status.UNAVAILABLE.withDescription("for test");

  when(picker.pickSubchannel(any(PickSubchannelArgs.class)))
      .thenReturn(drop ? PickResult.withDrop(status) : PickResult.withError(status));
  updateBalancingStateSafely(helper, READY, picker);

  executor.runDueTasks();
  if (shouldFail) {
    verify(mockCallListener).onClose(same(status), any(Metadata.class));
  } else {
    verifyZeroInteractions(mockCallListener);
  }

  // This call doesn't involve delayed transport
  ClientCall<String, Integer> call2 = channel.newCall(method, callOptions);
  call2.start(mockCallListener2, new Metadata());

  executor.runDueTasks();
  if (shouldFail) {
    verify(mockCallListener2).onClose(same(status), any(Metadata.class));
  } else {
    verifyZeroInteractions(mockCallListener2);
  }
}
 
Example #28
Source File: GrpcUtilTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Test
public void getTransportFromPickResult_errorPickResult_waitForReady() {
  Status status = Status.UNAVAILABLE;
  PickResult pickResult = PickResult.withError(status);
  ClientTransport transport = GrpcUtil.getTransportFromPickResult(pickResult, true);

  assertNull(transport);
}
 
Example #29
Source File: PickFirstLoadBalancerTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void nameResolutionErrorWithStateChanges() throws Exception {
  InOrder inOrder = inOrder(mockHelper);
  loadBalancer.handleResolvedAddresses(
      ResolvedAddresses.newBuilder().setAddresses(servers).setAttributes(affinity).build());
  inOrder.verify(mockHelper).createSubchannel(createArgsCaptor.capture());
  verify(mockSubchannel).start(stateListenerCaptor.capture());
  CreateSubchannelArgs args = createArgsCaptor.getValue();
  assertThat(args.getAddresses()).isEqualTo(servers);

  inOrder.verify(mockHelper).updateBalancingState(eq(CONNECTING), any(SubchannelPicker.class));

  SubchannelStateListener stateListener = stateListenerCaptor.getValue();

  stateListener.onSubchannelState(ConnectivityStateInfo.forTransientFailure(Status.UNAVAILABLE));
  inOrder.verify(mockHelper).updateBalancingState(
      eq(TRANSIENT_FAILURE), any(SubchannelPicker.class));

  Status error = Status.NOT_FOUND.withDescription("nameResolutionError");
  loadBalancer.handleNameResolutionError(error);
  inOrder.verify(mockHelper).updateBalancingState(eq(TRANSIENT_FAILURE), pickerCaptor.capture());

  PickResult pickResult = pickerCaptor.getValue().pickSubchannel(mockArgs);
  assertEquals(null, pickResult.getSubchannel());
  assertEquals(error, pickResult.getStatus());

  Status error2 = Status.NOT_FOUND.withDescription("nameResolutionError2");
  loadBalancer.handleNameResolutionError(error2);
  inOrder.verify(mockHelper).updateBalancingState(eq(TRANSIENT_FAILURE), pickerCaptor.capture());

  pickResult = pickerCaptor.getValue().pickSubchannel(mockArgs);
  assertEquals(null, pickResult.getSubchannel());
  assertEquals(error2, pickResult.getStatus());

  verifyNoMoreInteractions(mockHelper);
}
 
Example #30
Source File: PickFirstLoadBalancerTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Test
public void nameResolutionError() throws Exception {
  Status error = Status.NOT_FOUND.withDescription("nameResolutionError");
  loadBalancer.handleNameResolutionError(error);
  verify(mockHelper).updateBalancingState(eq(TRANSIENT_FAILURE), pickerCaptor.capture());
  PickResult pickResult = pickerCaptor.getValue().pickSubchannel(mockArgs);
  assertEquals(null, pickResult.getSubchannel());
  assertEquals(error, pickResult.getStatus());
  verify(mockSubchannel, never()).requestConnection();
  verifyNoMoreInteractions(mockHelper);
}