io.grpc.ConnectivityState Java Examples

The following examples show how to use io.grpc.ConnectivityState. 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: GracefulSwitchLoadBalancer.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Override
public void handleNameResolutionError(final Status error) {
  class ErrorPicker extends SubchannelPicker {
    @Override
    public PickResult pickSubchannel(PickSubchannelArgs args) {
      return PickResult.withError(error);
    }

    @Override
    public String toString() {
      return MoreObjects.toStringHelper(ErrorPicker.class).add("error", error).toString();
    }
  }

  helper.updateBalancingState(
      ConnectivityState.TRANSIENT_FAILURE,
      new ErrorPicker());
}
 
Example #2
Source File: PickFirstLoadBalancerTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void nameResolutionSuccessAfterError() throws Exception {
  InOrder inOrder = inOrder(mockHelper);

  loadBalancer.handleNameResolutionError(Status.NOT_FOUND.withDescription("nameResolutionError"));
  inOrder.verify(mockHelper)
      .updateBalancingState(any(ConnectivityState.class), any(SubchannelPicker.class));
  verify(mockSubchannel, never()).requestConnection();

  loadBalancer.handleResolvedAddressGroups(servers, affinity);
  inOrder.verify(mockHelper).createSubchannel(eq(servers), eq(Attributes.EMPTY));
  inOrder.verify(mockHelper).updateBalancingState(eq(CONNECTING), pickerCaptor.capture());
  verify(mockSubchannel).requestConnection();

  assertEquals(mockSubchannel, pickerCaptor.getValue().pickSubchannel(mockArgs)
      .getSubchannel());

  assertEquals(pickerCaptor.getValue().pickSubchannel(mockArgs),
      pickerCaptor.getValue().pickSubchannel(mockArgs));

  verifyNoMoreInteractions(mockHelper);
}
 
Example #3
Source File: GrpcClientHealthAutoConfiguration.java    From grpc-spring-boot-starter with MIT License 6 votes vote down vote up
/**
 * Creates a HealthIndicator based on the channels' {@link ConnectivityState}s from the underlying
 * {@link GrpcChannelFactory}.
 *
 * @param factory The factory to derive the connectivity states from.
 * @return A health indicator bean, that uses the following assumption
 *         <code>DOWN == states.contains(TRANSIENT_FAILURE)</code>.
 */
@Bean
@Lazy
public HealthIndicator grpcChannelHealthIndicator(final GrpcChannelFactory factory) {
    return () -> {
        final ImmutableMap<String, ConnectivityState> states = ImmutableMap.copyOf(factory.getConnectivityState());
        final Health.Builder health;
        if (states.containsValue(ConnectivityState.TRANSIENT_FAILURE)) {
            health = Health.down();
        } else {
            health = Health.up();
        }
        return health.withDetails(states)
                .build();
    };
}
 
Example #4
Source File: GrpcRouteRoundRobinLbFactory.java    From saluki with Apache License 2.0 6 votes vote down vote up
private ConnectivityState getAggregatedState() {
  Set<ConnectivityState> states = EnumSet.noneOf(ConnectivityState.class);
  for (Subchannel subchannel : getSubchannels()) {
    states.add(getSubchannelStateInfoRef(subchannel).get().getState());
  }
  if (states.contains(READY)) {
    return READY;
  }
  if (states.contains(CONNECTING)) {
    return CONNECTING;
  }
  if (states.contains(IDLE)) {
    return CONNECTING;
  }
  return TRANSIENT_FAILURE;
}
 
Example #5
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 #6
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 #7
Source File: AbstractGrpcClient.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isServerReachable() {
    final ConnectivityState state = channel.getState(false);
    switch (state) {
        case READY:
        case IDLE:
            return true;
        case CONNECTING:
        case TRANSIENT_FAILURE:
        case SHUTDOWN:
            return false;
        default:
            log.error("Unrecognized channel connectivity state {}", state);
            return false;
    }
}
 
Example #8
Source File: PickFirstLoadBalancerTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void pickAfterResolvedAndUnchanged() throws Exception {
  loadBalancer.handleResolvedAddressGroups(servers, affinity);
  verify(mockSubchannel).requestConnection();
  loadBalancer.handleResolvedAddressGroups(servers, affinity);
  verifyNoMoreInteractions(mockSubchannel);

  verify(mockHelper).createSubchannel(anyListOf(EquivalentAddressGroup.class),
      any(Attributes.class));
  verify(mockHelper)
      .updateBalancingState(isA(ConnectivityState.class), isA(SubchannelPicker.class));
  // Updating the subchannel addresses is unnecessary, but doesn't hurt anything
  verify(mockHelper).updateSubchannelAddresses(
      eq(mockSubchannel), anyListOf(EquivalentAddressGroup.class));

  verifyNoMoreInteractions(mockHelper);
}
 
Example #9
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 #10
Source File: ConnectivityStateManager.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
/**
 * Connectivity state is changed to the specified value. Will trigger some notifications that have
 * been registered earlier by {@link ManagedChannel#notifyWhenStateChanged}.
 */
void gotoState(@Nonnull ConnectivityState newState) {
  checkNotNull(newState, "newState");
  if (state != newState && state != ConnectivityState.SHUTDOWN) {
    state = newState;
    if (listeners.isEmpty()) {
      return;
    }
    // Swap out callback list before calling them, because a callback may register new callbacks,
    // if run in direct executor, can cause ConcurrentModificationException.
    ArrayList<Listener> savedListeners = listeners;
    listeners = new ArrayList<>();
    for (Listener listener : savedListeners) {
      listener.runInExecutor();
    }
  }
}
 
Example #11
Source File: ManagedChannelImpl.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Override
public void updateBalancingState(
    final ConnectivityState newState, final SubchannelPicker newPicker) {
  checkNotNull(newState, "newState");
  checkNotNull(newPicker, "newPicker");
  logWarningIfNotInSyncContext("updateBalancingState()");
  final class UpdateBalancingState implements Runnable {
    @Override
    public void run() {
      if (LbHelperImpl.this != lbHelper) {
        return;
      }
      updateSubchannelPicker(newPicker);
      // It's not appropriate to report SHUTDOWN state from lb.
      // Ignore the case of newState == SHUTDOWN for now.
      if (newState != SHUTDOWN) {
        channelLogger.log(
            ChannelLogLevel.INFO, "Entering {0} state with picker: {1}", newState, newPicker);
        channelStateManager.gotoState(newState);
      }
    }
  }

  syncContext.execute(new UpdateBalancingState());
}
 
Example #12
Source File: ManagedChannelImpl.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Override
public void updateBalancingState(
    final ConnectivityState newState, final SubchannelPicker newPicker) {
  checkNotNull(newState, "newState");
  checkNotNull(newPicker, "newPicker");
  final class UpdateBalancingState implements Runnable {
    @Override
    public void run() {
      if (LbHelperImpl.this != lbHelper) {
        return;
      }
      updateSubchannelPicker(newPicker);
      // It's not appropriate to report SHUTDOWN state from lb.
      // Ignore the case of newState == SHUTDOWN for now.
      if (newState != SHUTDOWN) {
        channelLogger.log(ChannelLogLevel.INFO, "Entering {0} state", newState);
        channelStateManager.gotoState(newState);
      }
    }
  }

  syncContext.execute(new UpdateBalancingState());
}
 
Example #13
Source File: LbPolicyConfigurationTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void subchannelStateChange_updateChildPolicyWrapper() {
  ChildPolicyWrapper childPolicyWrapper = factory.createOrGet("foo.google.com");
  ChildPolicyReportingHelper childPolicyReportingHelper = childPolicyWrapper.getHelper();
  FakeSubchannel fakeSubchannel = new FakeSubchannel();
  when(helper.createSubchannel(any(CreateSubchannelArgs.class))).thenReturn(fakeSubchannel);
  Subchannel subchannel =
      childPolicyReportingHelper
          .createSubchannel(
              CreateSubchannelArgs.newBuilder()
                  .setAddresses(new EquivalentAddressGroup(mock(SocketAddress.class)))
                  .build());
  subchannel.start(new SubchannelStateListener() {
    @Override
    public void onSubchannelState(ConnectivityStateInfo newState) {
      // no-op
    }
  });

  fakeSubchannel.updateState(ConnectivityStateInfo.forNonError(ConnectivityState.CONNECTING));

  assertThat(childPolicyWrapper.getConnectivityStateInfo())
      .isEqualTo(ConnectivityStateInfo.forNonError(ConnectivityState.CONNECTING));
}
 
Example #14
Source File: RlsLoadBalancer.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Override
public void handleNameResolutionError(final Status error) {
  class ErrorPicker extends SubchannelPicker {
    @Override
    public PickResult pickSubchannel(PickSubchannelArgs args) {
      return PickResult.withError(error);
    }

    @Override
    public String toString() {
      return MoreObjects.toStringHelper(this)
          .add("error", error)
          .toString();
    }
  }

  if (routeLookupClient != null) {
    routeLookupClient.close();
    routeLookupClient = null;
    lbPolicyConfiguration = null;
  }
  helper.updateBalancingState(ConnectivityState.TRANSIENT_FAILURE, new ErrorPicker());
}
 
Example #15
Source File: GrpcClient.java    From sofa-jraft with Apache License 2.0 6 votes vote down vote up
private Channel getChannel(final Endpoint endpoint) {
    return this.managedChannelPool.computeIfAbsent(endpoint, ep -> {
        final ManagedChannel ch = ManagedChannelBuilder.forAddress(ep.getIp(), ep.getPort()) //
            .usePlaintext() //
            .directExecutor() //
            .build();
        // channel connection event
        ch.notifyWhenStateChanged(ConnectivityState.READY, () -> {
            final ReplicatorGroup rpGroup = replicatorGroup;
            if (rpGroup != null) {
                Utils.runInThread(() -> {
                    final PeerId peer = new PeerId();
                    if (peer.parse(ep.toString())) {
                        LOG.info("Peer {} is connected.", peer);
                        rpGroup.checkReplicator(peer, true);
                    } else {
                        LOG.error("Fail to parse peer: {}.", ep);
                    }
                });
            }
        });

        return ch;
    });
}
 
Example #16
Source File: WeightedTargetLoadBalancer.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Nullable
private static ConnectivityState aggregateState(
    @Nullable ConnectivityState overallState, ConnectivityState childState) {
  if (overallState == null) {
    return childState;
  }
  if (overallState == READY || childState == READY) {
    return READY;
  }
  if (overallState == CONNECTING || childState == CONNECTING) {
    return CONNECTING;
  }
  if (overallState == IDLE || childState == IDLE) {
    return IDLE;
  }
  return overallState;
}
 
Example #17
Source File: LbPolicyConfigurationTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void updateBalancingState_triggersListener() {
  ChildPolicyWrapper childPolicyWrapper = factory.createOrGet("foo.google.com");
  ChildPolicyReportingHelper childPolicyReportingHelper = childPolicyWrapper.getHelper();
  SubchannelPicker childPicker = mock(SubchannelPicker.class);

  childPolicyReportingHelper.updateBalancingState(ConnectivityState.READY, childPicker);

  verify(childLbStatusListener).onStatusChanged(ConnectivityState.READY);
  assertThat(childPolicyWrapper.getPicker()).isEqualTo(childPicker);
  // picker governs childPickers will be reported to parent LB
  verify(helper).updateBalancingState(ConnectivityState.READY, picker);
}
 
Example #18
Source File: XdsRoutingLoadBalancer.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Override
public void updateBalancingState(ConnectivityState newState, SubchannelPicker newPicker) {
  if (deactivated) {
    return;
  }
  currentState = newState;
  currentPicker = newPicker;
  updateOverallBalancingState();
}
 
Example #19
Source File: ManagedChannelImplTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void channelTracing_oobChannelStateChangeEvent() throws Exception {
  channelBuilder.maxTraceEvents(10);
  createChannel();
  OobChannel oobChannel = (OobChannel) helper.createOobChannel(addressGroup, "authority");
  timer.forwardNanos(1234);
  oobChannel.handleSubchannelStateChange(
      ConnectivityStateInfo.forNonError(ConnectivityState.CONNECTING));
  assertThat(getStats(oobChannel).channelTrace.events).contains(new ChannelTrace.Event.Builder()
      .setDescription("Entering CONNECTING state")
      .setSeverity(ChannelTrace.Event.Severity.CT_INFO)
      .setTimestampNanos(timer.getTicker().read())
      .build());
}
 
Example #20
Source File: ServiceConfigErrorHandlingTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Override
public void handleNameResolutionError(final Status error) {
  helper.updateBalancingState(ConnectivityState.TRANSIENT_FAILURE,
      new SubchannelPicker() {
        @Override
        public PickResult pickSubchannel(PickSubchannelArgs args) {
          return PickResult.withError(error);
        }
      });
}
 
Example #21
Source File: LrsLoadBalancer.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Override
public void handleNameResolutionError(Status error) {
  if (switchingLoadBalancer != null) {
    switchingLoadBalancer.handleNameResolutionError(error);
  } else {
    helper.updateBalancingState(ConnectivityState.TRANSIENT_FAILURE, new ErrorPicker(error));
  }
}
 
Example #22
Source File: WeightedTargetLoadBalancer.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
private void updateOverallBalancingState() {
  List<WeightedChildPicker> childPickers = new ArrayList<>();

  ConnectivityState overallState = null;
  for (String name : targets.keySet()) {
    ChildHelper childHelper = childHelpers.get(name);
    ConnectivityState childState = childHelper.currentState;
    overallState = aggregateState(overallState, childState);
    if (READY == childState) {
      int weight = targets.get(name).weight;
      childPickers.add(new WeightedChildPicker(weight, childHelper.currentPicker));
    }
  }

  SubchannelPicker picker;
  if (childPickers.isEmpty()) {
    if (overallState == TRANSIENT_FAILURE) {
      picker = new ErrorPicker(Status.UNAVAILABLE); // TODO: more details in status
    } else {
      picker = XdsSubchannelPickers.BUFFER_PICKER;
    }
  } else {
    picker = new WeightedRandomPicker(childPickers);
  }

  if (overallState != null) {
    helper.updateBalancingState(overallState, picker);
  }
}
 
Example #23
Source File: MilvusGrpcClient.java    From milvus-sdk-java with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isConnected() {
  if (channel == null) {
    return false;
  }
  ConnectivityState connectivityState = channel.getState(false);
  return connectivityState == ConnectivityState.READY;
}
 
Example #24
Source File: AbstractChannelFactory.java    From grpc-spring-boot-starter with MIT License 5 votes vote down vote up
/**
 * Watch the given channel for connectivity changes.
 *
 * @param name The name of the channel in the state overview.
 * @param channel The channel to watch the state of.
 */
protected void watchConnectivityState(final String name, final ManagedChannel channel) {
    final ConnectivityState state = channel.getState(false);
    this.channelStates.put(name, state);
    if (state != ConnectivityState.SHUTDOWN) {
        channel.notifyWhenStateChanged(state, () -> watchConnectivityState(name, channel));
    }
}
 
Example #25
Source File: InProcessOrAlternativeChannelFactory.java    From grpc-spring-boot-starter with MIT License 5 votes vote down vote up
@Override
public Map<String, ConnectivityState> getConnectivityState() {
    return ImmutableMap.<String, ConnectivityState>builder()
            .putAll(inProcessChannelFactory.getConnectivityState())
            .putAll(alternativeChannelFactory.getConnectivityState())
            .build();
}
 
Example #26
Source File: PriorityLoadBalancer.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Override
public void updateBalancingState(ConnectivityState newState, SubchannelPicker newPicker) {
  connectivityState = newState;
  picker = newPicker;
  if (deletionTimer != null && deletionTimer.isPending()) {
    return;
  }
  if (failOverTimer.isPending()) {
    if (newState.equals(READY) || newState.equals(TRANSIENT_FAILURE)) {
      failOverTimer.cancel();
    }
  }
  tryNextPriority(true);
}
 
Example #27
Source File: SubchannelStateManagerImplTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void getState_known() {
  subchannelStateManager.updateState("known", ConnectivityState.TRANSIENT_FAILURE);

  assertThat(subchannelStateManager.getState("known"))
      .isEqualTo(ConnectivityState.TRANSIENT_FAILURE);
}
 
Example #28
Source File: GrpclbState.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
/**
 * Make and use a picker out of the current lists and the states of subchannels if they have
 * changed since the last picker created.
 */
private void maybeUpdatePicker() {
  List<RoundRobinEntry> pickList = new ArrayList<>(backendList.size());
  Status error = null;
  boolean hasIdle = false;
  for (BackendEntry entry : backendList) {
    Subchannel subchannel = entry.result.getSubchannel();
    Attributes attrs = subchannel.getAttributes();
    ConnectivityStateInfo stateInfo = attrs.get(STATE_INFO).get();
    if (stateInfo.getState() == READY) {
      pickList.add(entry);
    } else if (stateInfo.getState() == TRANSIENT_FAILURE) {
      error = stateInfo.getStatus();
    } else if (stateInfo.getState() == IDLE) {
      hasIdle = true;
    }
  }
  ConnectivityState state;
  if (pickList.isEmpty()) {
    if (error != null && !hasIdle) {
      pickList.add(new ErrorEntry(error));
      state = TRANSIENT_FAILURE;
    } else {
      pickList.add(BUFFER_ENTRY);
      state = CONNECTING;
    }
  } else {
    state = READY;
  }
  maybeUpdatePicker(state, new RoundRobinPicker(dropList, pickList));
}
 
Example #29
Source File: MilvusGrpcClient.java    From milvus-sdk-java with Apache License 2.0 5 votes vote down vote up
private boolean channelIsReadyOrIdle() {
  if (channel == null) {
    return false;
  }
  ConnectivityState connectivityState = channel.getState(false);
  return connectivityState == ConnectivityState.READY
      || connectivityState
          == ConnectivityState.IDLE; // Since a new RPC would take the channel out of idle mode
}
 
Example #30
Source File: LrsLoadBalancerTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
private static void deliverSubchannelState(
    final NoopSubchannel subchannel, ConnectivityState state) {
  SubchannelPicker picker = new SubchannelPicker() {
    @Override
    public PickResult pickSubchannel(PickSubchannelArgs args) {
      return PickResult.withSubchannel(subchannel);
    }
  };
  subchannel.helper.updateBalancingState(state, picker);
}