io.grpc.LoadBalancer Java Examples

The following examples show how to use io.grpc.LoadBalancer. 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: CachingRlsLbClient.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
private void startFallbackChildPolicy() {
  String defaultTarget = lbPolicyConfig.getRouteLookupConfig().getDefaultTarget();
  fallbackChildPolicyWrapper = refCountedChildPolicyWrapperFactory.createOrGet(defaultTarget);

  LoadBalancerProvider lbProvider =
      lbPolicyConfig.getLoadBalancingPolicy().getEffectiveLbProvider();
  final LoadBalancer lb =
      lbProvider.newLoadBalancer(fallbackChildPolicyWrapper.getHelper());
  final ConfigOrError lbConfig =
      lbProvider
          .parseLoadBalancingPolicyConfig(
              lbPolicyConfig
                  .getLoadBalancingPolicy()
                  .getEffectiveChildPolicy(defaultTarget));
  helper.getSynchronizationContext().execute(
      new Runnable() {
        @Override
        public void run() {
          lb.handleResolvedAddresses(
              childLbResolvedAddressFactory.create(lbConfig.getConfig()));
          lb.requestConnection();
        }
      });
}
 
Example #2
Source File: GracefulSwitchLoadBalancerTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void newPolicyNameTheSameAsCurrentPolicy_shouldShutdownPendingLb() {
  gracefulSwitchLb.switchTo(lbProviders.get(lbPolicies[0]));
  LoadBalancer lb0 = balancers.get(lbPolicies[0]);

  gracefulSwitchLb.switchTo(lbProviders.get(lbPolicies[0]));
  assertThat(balancers.get(lbPolicies[0])).isSameInstanceAs(lb0);

  Helper helper0 = helpers.get(lb0);
  SubchannelPicker picker = mock(SubchannelPicker.class);
  helper0.updateBalancingState(READY, picker);

  gracefulSwitchLb.switchTo(lbProviders.get(lbPolicies[1]));
  LoadBalancer lb1 = balancers.get(lbPolicies[1]);

  gracefulSwitchLb.switchTo(lbProviders.get(lbPolicies[0]));
  verify(lb1).shutdown();
  assertThat(balancers.get(lbPolicies[0])).isSameInstanceAs(lb0);

  verifyNoMoreInteractions(lb0, lb1);
}
 
Example #3
Source File: AutoConfiguredLoadBalancerFactoryTest.java    From grpc-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(){}));
  Helper helper = new TestHelper() {
    @Override
    public Subchannel createSubchannel(CreateSubchannelArgs args) {
      assertThat(args.getAddresses()).isEqualTo(servers);
      return new TestSubchannel(args);
    }
  };
  AutoConfiguredLoadBalancer lb = lbf.newLoadBalancer(helper);
  LoadBalancer oldDelegate = lb.getDelegate();

  Status handleResult = lb.tryHandleResolvedAddresses(
      ResolvedAddresses.newBuilder()
          .setAddresses(servers)
          .setAttributes(Attributes.EMPTY)
          .setLoadBalancingPolicyConfig(null)
          .build());

  assertThat(handleResult.getCode()).isEqualTo(Status.Code.OK);
  assertThat(lb.getDelegate()).isSameInstanceAs(oldDelegate);
}
 
Example #4
Source File: OrcaOobUtil.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
static OrcaReportingHelperWrapper newOrcaReportingHelperWrapper(
    LoadBalancer.Helper delegate,
    OrcaOobReportListener listener,
    BackoffPolicy.Provider backoffPolicyProvider,
    Supplier<Stopwatch> stopwatchSupplier) {
  final OrcaReportingHelper orcaHelper =
      new OrcaReportingHelper(delegate, listener, backoffPolicyProvider, stopwatchSupplier);

  return new OrcaReportingHelperWrapper() {
    @Override
    public void setReportingConfig(OrcaReportingConfig config) {
      orcaHelper.setReportingConfig(config);
    }

    @Override
    public Helper asHelper() {
      return orcaHelper;
    }
  };
}
 
Example #5
Source File: CdsLoadBalancer.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Override
public void handleResolvedAddresses(ResolvedAddresses resolvedAddresses) {
  logger.log(XdsLogLevel.DEBUG, "Received resolution result: {0}", resolvedAddresses);
  if (xdsClientPool == null) {
    xdsClientPool = resolvedAddresses.getAttributes().get(XdsAttributes.XDS_CLIENT_POOL);
    checkNotNull(xdsClientPool, "missing xDS client pool");
    xdsClient = xdsClientPool.getObject();
  }

  Object lbConfig = resolvedAddresses.getLoadBalancingPolicyConfig();
  checkNotNull(lbConfig, "missing CDS lb config");
  CdsConfig newCdsConfig = (CdsConfig) lbConfig;
  logger.log(
      XdsLogLevel.INFO,
      "Received CDS lb config: cluster={0}", newCdsConfig.name);

  // If cluster is changed, do a graceful switch.
  if (!newCdsConfig.name.equals(clusterName)) {
    LoadBalancer.Factory clusterBalancerFactory = new ClusterBalancerFactory(newCdsConfig.name);
    switchingLoadBalancer.switchTo(clusterBalancerFactory);
  }
  switchingLoadBalancer.handleResolvedAddresses(resolvedAddresses);
  clusterName = newCdsConfig.name;
}
 
Example #6
Source File: ForwardingLoadBalancerHelperTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void allMethodsForwarded() throws Exception {
  final SocketAddress mockAddr = mock(SocketAddress.class);
  ForwardingTestUtil.testMethodsForwarded(
      LoadBalancer.Helper.class,
      mockDelegate,
      new TestHelper(),
      Collections.<Method>emptyList(),
      new ForwardingTestUtil.ArgumentProvider() {
        @Override
        public Object get(Method method, int argPos, Class<?> clazz) {
          if (clazz.equals(EquivalentAddressGroup.class)) {
            return new EquivalentAddressGroup(Arrays.asList(mockAddr));
          } else if (clazz.equals(List.class)) {
            return Collections.<Object>emptyList();
          }
          return null;
        }
      });
}
 
Example #7
Source File: GracefulSwitchLoadBalancerTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void createSubchannelForwarded() {
  gracefulSwitchLb.switchTo(lbProviders.get(lbPolicies[0]));
  LoadBalancer lb0 = balancers.get(lbPolicies[0]);
  Helper helper0 = helpers.get(lb0);
  SubchannelPicker picker = mock(SubchannelPicker.class);
  helper0.updateBalancingState(READY, picker);

  CreateSubchannelArgs createSubchannelArgs = newFakeCreateSubchannelArgs();
  helper0.createSubchannel(createSubchannelArgs);
  verify(mockHelper).createSubchannel(createSubchannelArgs);

  gracefulSwitchLb.switchTo(lbProviders.get(lbPolicies[1]));
  LoadBalancer lb1 = balancers.get(lbPolicies[1]);
  Helper helper1 = helpers.get(lb1);
  createSubchannelArgs = newFakeCreateSubchannelArgs();
  helper1.createSubchannel(createSubchannelArgs);
  verify(mockHelper).createSubchannel(createSubchannelArgs);

  createSubchannelArgs = newFakeCreateSubchannelArgs();
  helper0.createSubchannel(createSubchannelArgs);
  verify(mockHelper).createSubchannel(createSubchannelArgs);

  verifyNoMoreInteractions(lb0, lb1);
}
 
Example #8
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 #9
Source File: GracefulSwitchLoadBalancerTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void newPolicyNameTheSameAsPendingPolicy_shouldHaveNoEffect() {
  gracefulSwitchLb.switchTo(lbProviders.get(lbPolicies[0]));
  LoadBalancer lb0 = balancers.get(lbPolicies[0]);
  Helper helper0 = helpers.get(lb0);
  SubchannelPicker picker = mock(SubchannelPicker.class);
  helper0.updateBalancingState(READY, picker);

  gracefulSwitchLb.switchTo(lbProviders.get(lbPolicies[1]));
  LoadBalancer lb1 = balancers.get(lbPolicies[1]);

  gracefulSwitchLb.switchTo(lbProviders.get(lbPolicies[1]));
  assertThat(balancers.get(lbPolicies[1])).isSameInstanceAs(lb1);

  verifyNoMoreInteractions(lb0, lb1);
}
 
Example #10
Source File: ForwardingLoadBalancerTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Test
public void allMethodsForwarded() throws Exception {
  ForwardingTestUtil.testMethodsForwarded(
      LoadBalancer.class,
      mockDelegate,
      new TestBalancer(),
      Collections.<Method>emptyList());
}
 
Example #11
Source File: OrcaOobUtil.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Override
public OrcaReportingHelperWrapper newOrcaReportingHelperWrapper(
    LoadBalancer.Helper delegate,
    OrcaOobReportListener listener) {
  return newOrcaReportingHelperWrapper(
      delegate,
      listener,
      new ExponentialBackoffPolicy.Provider(),
      GrpcUtil.STOPWATCH_SUPPLIER);
}
 
Example #12
Source File: GracefulSwitchLoadBalancerTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void requestConnectionForwardedToLatestPolicies() {
  gracefulSwitchLb.switchTo(lbProviders.get(lbPolicies[0]));
  LoadBalancer lb0 = balancers.get(lbPolicies[0]);
  Helper helper0 = helpers.get(lb0);
  SubchannelPicker picker = mock(SubchannelPicker.class);
  helper0.updateBalancingState(READY, picker);

  gracefulSwitchLb.requestConnection();
  verify(lb0).requestConnection();

  gracefulSwitchLb.switchTo(lbProviders.get(lbPolicies[1]));
  LoadBalancer lb1 = balancers.get(lbPolicies[1]);
  gracefulSwitchLb.requestConnection();
  verify(lb1).requestConnection();

  gracefulSwitchLb.switchTo(lbProviders.get(lbPolicies[2]));
  verify(lb1).shutdown();
  LoadBalancer lb2 = balancers.get(lbPolicies[2]);
  gracefulSwitchLb.requestConnection();
  verify(lb2).requestConnection();

  // lb2 reports READY
  helpers.get(lb2).updateBalancingState(READY, mock(SubchannelPicker.class));
  verify(lb0).shutdown();

  gracefulSwitchLb.requestConnection();
  verify(lb2, times(2)).requestConnection();

  gracefulSwitchLb.switchTo(lbProviders.get(lbPolicies[3]));
  LoadBalancer lb3 = balancers.get(lbPolicies[3]);
  gracefulSwitchLb.requestConnection();
  verify(lb3).requestConnection();

  verifyNoMoreInteractions(lb0, lb1, lb2, lb3);
}
 
Example #13
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 #14
Source File: AgentClientMock.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Override
public void requestConnection() {
    LoadBalancer.Subchannel subchannel = result.getSubchannel();
    if (subchannel != null) {
        subchannel.requestConnection();
    }
}
 
Example #15
Source File: GracefulSwitchLoadBalancerTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void switchWhileOldPolicyGoesFromReadyToNotReady() {
  gracefulSwitchLb.switchTo(lbProviders.get(lbPolicies[0]));
  LoadBalancer lb0 = balancers.get(lbPolicies[0]);
  Helper helper0 = helpers.get(lb0);
  SubchannelPicker picker = mock(SubchannelPicker.class);
  helper0.updateBalancingState(READY, picker);

  gracefulSwitchLb.switchTo(lbProviders.get(lbPolicies[1]));
  verify(lb0, never()).shutdown();

  LoadBalancer lb1 = balancers.get(lbPolicies[1]);
  Helper helper1 = helpers.get(lb1);
  SubchannelPicker picker1 = mock(SubchannelPicker.class);
  helper1.updateBalancingState(CONNECTING, picker1);
  verify(mockHelper, never()).updateBalancingState(CONNECTING, picker1);

  picker = mock(SubchannelPicker.class);
  helper0.updateBalancingState(CONNECTING, picker);
  verify(lb0).shutdown();
  verify(mockHelper, never()).updateBalancingState(CONNECTING, picker);
  verify(mockHelper).updateBalancingState(CONNECTING, picker1);

  picker1 = mock(SubchannelPicker.class);
  helper1.updateBalancingState(READY, picker1);
  verify(mockHelper).updateBalancingState(READY, picker1);

  verifyNoMoreInteractions(lb0, lb1);
}
 
Example #16
Source File: LrsLoadBalancer.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Override
public void handleResolvedAddresses(ResolvedAddresses resolvedAddresses) {
  LrsConfig config = (LrsConfig) resolvedAddresses.getLoadBalancingPolicyConfig();
  LoadStatsStore store =
      resolvedAddresses.getAttributes().get(XdsAttributes.ATTR_CLUSTER_SERVICE_LOAD_STATS_STORE);
  checkNotNull(config, "missing LRS lb config");
  checkNotNull(store, "missing cluster service stats object");
  checkAndSetUp(config, store);

  if (switchingLoadBalancer == null) {
    loadStatsStore.addLocality(config.locality);
    final ClientLoadCounter counter = loadStatsStore.getLocalityCounter(config.locality);
    LoadBalancer.Helper loadRecordingHelper = new ForwardingLoadBalancerHelper() {
      @Override
      protected Helper delegate() {
        return helper;
      }

      @Override
      public void updateBalancingState(ConnectivityState newState, SubchannelPicker newPicker) {
        SubchannelPicker loadRecordingPicker =
            new LoadRecordingSubchannelPicker(counter, newPicker);
        super.updateBalancingState(newState, loadRecordingPicker);
      }
    };
    switchingLoadBalancer = new GracefulSwitchLoadBalancer(loadRecordingHelper);
  }
  String updatedChildPolicyName = config.childPolicy.getProvider().getPolicyName();
  if (!Objects.equals(childPolicyName, updatedChildPolicyName)) {
    switchingLoadBalancer.switchTo(config.childPolicy.getProvider());
    childPolicyName = updatedChildPolicyName;
  }
  ResolvedAddresses downStreamResult =
      resolvedAddresses.toBuilder()
          .setLoadBalancingPolicyConfig(config.childPolicy.getConfig())
          .build();
  switchingLoadBalancer.handleResolvedAddresses(downStreamResult);
}
 
Example #17
Source File: ManagedChannelImplTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void healthCheckingConfigPropagated() throws Exception {
  LoadBalancerRegistry.getDefaultRegistry().register(mockLoadBalancerProvider);
  try {
    FakeNameResolverFactory nameResolverFactory =
        new FakeNameResolverFactory.Builder(expectedUri)
            .setServers(Collections.singletonList(new EquivalentAddressGroup(socketAddress)))
            .build();
    channelBuilder.nameResolverFactory(nameResolverFactory);

    Map<String, Object> rawServiceConfig =
        parseConfig("{\"healthCheckConfig\": {\"serviceName\": \"service1\"}}");
    ManagedChannelServiceConfig managedChannelServiceConfig =
        createManagedChannelServiceConfig(rawServiceConfig, null);
    nameResolverFactory.nextConfigOrError.set(
        ConfigOrError.fromConfig(managedChannelServiceConfig));

    createChannel();

    ArgumentCaptor<ResolvedAddresses> resultCaptor =
        ArgumentCaptor.forClass(ResolvedAddresses.class);
    verify(mockLoadBalancer).handleResolvedAddresses(resultCaptor.capture());
    assertThat(resultCaptor.getValue().getAttributes()
        .get(LoadBalancer.ATTR_HEALTH_CHECKING_CONFIG))
        .containsExactly("serviceName", "service1");
  } finally {
    LoadBalancerRegistry.getDefaultRegistry().deregister(mockLoadBalancerProvider);
  }
}
 
Example #18
Source File: GracefulSwitchLoadBalancerTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void shutdownTriggeredWhenSwitchAndForwardedWhenSwitchLbShutdown() {
  gracefulSwitchLb.switchTo(lbProviders.get(lbPolicies[0]));
  LoadBalancer lb0 = balancers.get(lbPolicies[0]);
  Helper helper0 = helpers.get(lb0);
  SubchannelPicker picker = mock(SubchannelPicker.class);
  helper0.updateBalancingState(READY, picker);

  gracefulSwitchLb.switchTo(lbProviders.get(lbPolicies[1]));
  LoadBalancer lb1 = balancers.get(lbPolicies[1]);
  verify(lb1, never()).shutdown();

  gracefulSwitchLb.switchTo(lbProviders.get(lbPolicies[2]));
  verify(lb1).shutdown();
  LoadBalancer lb2 = balancers.get(lbPolicies[2]);
  verify(lb0, never()).shutdown();
  helpers.get(lb2).updateBalancingState(READY, mock(SubchannelPicker.class));
  verify(lb0).shutdown();

  gracefulSwitchLb.switchTo(lbProviders.get(lbPolicies[3]));
  LoadBalancer lb3 = balancers.get(lbPolicies[3]);
  verify(lb2, never()).shutdown();
  verify(lb3, never()).shutdown();

  gracefulSwitchLb.shutdown();
  verify(lb2).shutdown();
  verify(lb3).shutdown();

  verifyNoMoreInteractions(lb0, lb1, lb2, lb3);
}
 
Example #19
Source File: GracefulSwitchLoadBalancerTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void switchWhileOldPolicyIsNotReady() {
  gracefulSwitchLb.switchTo(lbProviders.get(lbPolicies[0]));
  LoadBalancer lb0 = balancers.get(lbPolicies[0]);
  Helper helper0 = helpers.get(lb0);
  SubchannelPicker picker = mock(SubchannelPicker.class);
  helper0.updateBalancingState(READY, picker);
  picker = mock(SubchannelPicker.class);
  helper0.updateBalancingState(CONNECTING, picker);

  verify(lb0, never()).shutdown();
  gracefulSwitchLb.switchTo(lbProviders.get(lbPolicies[1]));
  verify(lb0).shutdown();
  LoadBalancer lb1 = balancers.get(lbPolicies[1]);

  Helper helper1 = helpers.get(lb1);
  picker = mock(SubchannelPicker.class);
  helper1.updateBalancingState(CONNECTING, picker);
  verify(mockHelper).updateBalancingState(CONNECTING, picker);

  verify(lb1, never()).shutdown();
  gracefulSwitchLb.switchTo(lbProviders.get(lbPolicies[2]));
  verify(lb1).shutdown();
  LoadBalancer lb2 = balancers.get(lbPolicies[2]);

  verifyNoMoreInteractions(lb0, lb1, lb2);
}
 
Example #20
Source File: ManagedChannelImpl.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Deprecated
@Override
public void updateSubchannelAddresses(
    LoadBalancer.Subchannel subchannel, List<EquivalentAddressGroup> addrs) {
  checkArgument(subchannel instanceof SubchannelImpl,
      "subchannel must have been returned from createSubchannel");
  logWarningIfNotInSyncContext("updateSubchannelAddresses()");
  ((InternalSubchannel) subchannel.getInternalSubchannel()).updateAddresses(addrs);
}
 
Example #21
Source File: HealthCheckingLoadBalancerFactoryTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void util_newHealthCheckingLoadBalancer() {
  Factory hcFactory =
      new Factory() {
        @Override
        public LoadBalancer newLoadBalancer(Helper helper) {
          return HealthCheckingLoadBalancerUtil.newHealthCheckingLoadBalancer(
              origLbFactory, helper);
        }
      };

  // hcLb and wrappedHelper are already set in setUp().  For this special test case, we
  // clear wrappedHelper so that we can create hcLb again with the util.
  wrappedHelper = null;
  hcLb = hcFactory.newLoadBalancer(origHelper);

  // Verify that HC works
  Attributes resolutionAttrs = attrsWithHealthCheckService("BarService");
  ResolvedAddresses result = ResolvedAddresses.newBuilder()
      .setAddresses(resolvedAddressList)
      .setAttributes(resolutionAttrs)
      .build();
  hcLbEventDelivery.handleResolvedAddresses(result);
  verify(origLb).handleResolvedAddresses(result);
  createSubchannel(0, Attributes.EMPTY);
  assertThat(healthImpls[0].calls).isEmpty();
  deliverSubchannelState(0, ConnectivityStateInfo.forNonError(READY));
  assertThat(healthImpls[0].calls).hasSize(1);
}
 
Example #22
Source File: OrcaOobUtil.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
OrcaReportingHelper(
    LoadBalancer.Helper delegate,
    OrcaOobReportListener listener,
    BackoffPolicy.Provider backoffPolicyProvider,
    Supplier<Stopwatch> stopwatchSupplier) {
  this.delegate = checkNotNull(delegate, "delegate");
  this.listener = checkNotNull(listener, "listener");
  this.backoffPolicyProvider = checkNotNull(backoffPolicyProvider, "backoffPolicyProvider");
  this.stopwatchSupplier = checkNotNull(stopwatchSupplier, "stopwatchSupplier");
  syncContext = checkNotNull(delegate.getSynchronizationContext(), "syncContext");
}
 
Example #23
Source File: WeightedTargetLoadBalancer.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Override
public void handleNameResolutionError(Status error) {
  logger.log(XdsLogLevel.WARNING, "Received name resolution error: {0}", error);
  if (childBalancers.isEmpty()) {
    helper.updateBalancingState(TRANSIENT_FAILURE, new ErrorPicker(error));
  }
  for (LoadBalancer childBalancer : childBalancers.values()) {
    childBalancer.handleNameResolutionError(error);
  }
}
 
Example #24
Source File: WeightedTargetLoadBalancerTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Override
public LoadBalancer newLoadBalancer(Helper helper) {
  childHelpers.add(helper);
  LoadBalancer childBalancer = mock(LoadBalancer.class);
  childBalancers.add(childBalancer);
  fooLbCreated++;
  return childBalancer;
}
 
Example #25
Source File: WeightedTargetLoadBalancerTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Override
public LoadBalancer newLoadBalancer(Helper helper) {
  childHelpers.add(helper);
  LoadBalancer childBalancer = mock(LoadBalancer.class);
  childBalancers.add(childBalancer);
  barLbCreated++;
  return childBalancer;
}
 
Example #26
Source File: WeightedTargetLoadBalancerTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@After
public void tearDown() {
  weightedTargetLb.shutdown();
  for (LoadBalancer childBalancer : childBalancers) {
    verify(childBalancer).shutdown();
  }
}
 
Example #27
Source File: WeightedTargetLoadBalancerTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void handleNameResolutionError() {
  ArgumentCaptor<SubchannelPicker> pickerCaptor = ArgumentCaptor.forClass(null);
  ArgumentCaptor<Status> statusCaptor = ArgumentCaptor.forClass(null);

  // Error before any child balancer created.
  weightedTargetLb.handleNameResolutionError(Status.DATA_LOSS);

  verify(helper).updateBalancingState(eq(TRANSIENT_FAILURE), pickerCaptor.capture());
  PickResult pickResult = pickerCaptor.getValue().pickSubchannel(mock(PickSubchannelArgs.class));
  assertThat(pickResult.getStatus().getCode()).isEqualTo(Status.Code.DATA_LOSS);

  // Child configs updated.
  Map<String, WeightedPolicySelection> targets = ImmutableMap.of(
      // {foo, 10, config0}
      "target0", weightedLbConfig0,
      // {bar, 20, config1}
      "target1", weightedLbConfig1,
      // {bar, 30, config2}
      "target2", weightedLbConfig2,
      // {foo, 40, config3}
      "target3", weightedLbConfig3);
  weightedTargetLb.handleResolvedAddresses(
      ResolvedAddresses.newBuilder()
          .setAddresses(ImmutableList.<EquivalentAddressGroup>of())
          .setLoadBalancingPolicyConfig(new WeightedTargetConfig(targets))
          .build());

  // Error after child balancers created.
  weightedTargetLb.handleNameResolutionError(Status.ABORTED);

  for (LoadBalancer childBalancer : childBalancers) {
    verify(childBalancer).handleNameResolutionError(statusCaptor.capture());
    assertThat(statusCaptor.getValue().getCode()).isEqualTo(Status.Code.ABORTED);
  }
}
 
Example #28
Source File: LocalityStoreTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Override
public LoadBalancer newLoadBalancer(Helper helper) {
  LoadBalancer fakeLb = mock(LoadBalancer.class);
  loadBalancers.put(helper.getAuthority(), fakeLb);
  childHelpers.put(helper.getAuthority(), helper);
  return fakeLb;
}
 
Example #29
Source File: CachingRlsLbClient.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
private void createChildLbPolicy() {
  ChildLoadBalancingPolicy childPolicy = lbPolicyConfig.getLoadBalancingPolicy();
  LoadBalancerProvider lbProvider = childPolicy.getEffectiveLbProvider();
  ConfigOrError lbConfig =
      lbProvider
          .parseLoadBalancingPolicyConfig(
              childPolicy.getEffectiveChildPolicy(childPolicyWrapper.getTarget()));

  LoadBalancer lb = lbProvider.newLoadBalancer(childPolicyWrapper.getHelper());
  lb.handleResolvedAddresses(childLbResolvedAddressFactory.create(lbConfig.getConfig()));
  lb.requestConnection();
}
 
Example #30
Source File: ManagedChannelImplTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void nameResolverReturnsEmptySubLists_optionallyAllowed() throws Exception {
  when(mockLoadBalancer.canHandleEmptyAddressListFromNameResolution()).thenReturn(true);

  // Pass a FakeNameResolverFactory with an empty list and LB config
  FakeNameResolverFactory nameResolverFactory =
      new FakeNameResolverFactory.Builder(expectedUri).build();
  String rawLbConfig = "{ \"setting1\": \"high\" }";
  Map<String, Object> rawServiceConfig =
      parseConfig("{\"loadBalancingConfig\": [ {\"mock_lb\": " + rawLbConfig + " } ] }");
  ManagedChannelServiceConfig parsedServiceConfig =
      createManagedChannelServiceConfig(
          rawServiceConfig,
          new PolicySelection(
              mockLoadBalancerProvider,
              parseConfig(rawLbConfig),
              new Object()));
  nameResolverFactory.nextConfigOrError.set(ConfigOrError.fromConfig(parsedServiceConfig));
  channelBuilder.nameResolverFactory(nameResolverFactory);
  createChannel();

  // LoadBalancer received the empty list and the LB config
  verify(mockLoadBalancerProvider).newLoadBalancer(any(Helper.class));
  ArgumentCaptor<ResolvedAddresses> resultCaptor =
      ArgumentCaptor.forClass(ResolvedAddresses.class);
  verify(mockLoadBalancer).handleResolvedAddresses(resultCaptor.capture());
  assertThat(resultCaptor.getValue().getAddresses()).isEmpty();
  Attributes actualAttrs = resultCaptor.getValue().getAttributes();
  Map<String, ?> lbConfig = actualAttrs.get(LoadBalancer.ATTR_LOAD_BALANCING_CONFIG);
  assertEquals(ImmutableMap.of("setting1", "high"), lbConfig);

  // A no resolution retry
  assertEquals(0, timer.numPendingTasks(NAME_RESOLVER_REFRESH_TASK_FILTER));
}