io.grpc.LoadBalancer.Helper Java Examples

The following examples show how to use io.grpc.LoadBalancer.Helper. 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: ManagedChannelImplTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void nameResolverReturnsEmptySubLists_becomeErrorByDefault() throws Exception {
  String errorDescription = "NameResolver returned no usable address";

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

  // LoadBalancer received the error
  verify(mockLoadBalancerProvider).newLoadBalancer(any(Helper.class));
  verify(mockLoadBalancer).handleNameResolutionError(statusCaptor.capture());
  Status status = statusCaptor.getValue();
  assertSame(Status.Code.UNAVAILABLE, status.getCode());
  assertThat(status.getDescription()).startsWith(errorDescription);

  // A resolution retry has been scheduled
  assertEquals(1, timer.numPendingTasks(NAME_RESOLVER_REFRESH_TASK_FILTER));
}
 
Example #2
Source File: LocalityStoreTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
  doReturn(mock(ChannelLogger.class)).when(helper).getChannelLogger();
  doReturn(syncContext).when(helper).getSynchronizationContext();
  doReturn(fakeClock.getScheduledExecutorService()).when(helper).getScheduledExecutorService();
  when(orcaOobUtil.newOrcaReportingHelperWrapper(any(Helper.class),
      any(OrcaOobReportListener.class)))
      .thenAnswer(new Answer<OrcaReportingHelperWrapper>() {
        @Override
        public OrcaReportingHelperWrapper answer(InvocationOnMock invocation) {
          Helper h = invocation.getArgument(0);
          FakeOrcaReportingHelperWrapper res =
              new FakeOrcaReportingHelperWrapper(h);
          childHelperWrappers.put(h.getAuthority(), res);
          return res;
        }
      });
  lbRegistry.register(lbProvider);
  localityStore =
      new LocalityStoreImpl(logId, helper, lbRegistry, random, loadStatsStore,
          orcaPerRequestUtil, orcaOobUtil);
}
 
Example #3
Source File: GrpclbLoadBalancerFactoryTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
@Test
public void getInstance() {
  Helper helper = mock(Helper.class);
  when(helper.getSynchronizationContext()).thenReturn(syncContext);
  when(helper.getScheduledExecutorService()).thenReturn(clock.getScheduledExecutorService());
  when(helper.getAuthority()).thenReturn("fakeauthority");
  when(helper.getChannelLogger()).thenReturn(mock(ChannelLogger.class));

  assertThat(GrpclbLoadBalancerFactory.getInstance().newLoadBalancer(helper))
      .isInstanceOf(io.grpc.grpclb.GrpclbLoadBalancer.class);

  verify(helper).getSynchronizationContext();
  verify(helper).getScheduledExecutorService();
  verify(helper).getAuthority();
  verify(helper).getChannelLogger();
  verifyNoMoreInteractions(helper);
}
 
Example #4
Source File: OrcaOobUtilTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
private Subchannel createSubchannel(final Helper helper, final int index,
    final Attributes attrs) {
  final AtomicReference<Subchannel> newSubchannel = new AtomicReference<>();
  syncContext.execute(
      new Runnable() {
        @Override
        public void run() {
          Subchannel s =
              helper.createSubchannel(
                  CreateSubchannelArgs.newBuilder()
                      .setAddresses(eagLists[index])
                      .setAttributes(attrs)
                      .build());
          s.start(mockStateListeners[index]);
          newSubchannel.set(s);
        }
      });
  return newSubchannel.get();
}
 
Example #5
Source File: ManagedChannelImplTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void getState_withRequestConnect() {
  channelBuilder.nameResolverFactory(
      new FakeNameResolverFactory.Builder(expectedUri).setResolvedAtStart(false).build());
  requestConnection = false;
  createChannel();

  assertEquals(IDLE, channel.getState(false));
  verify(mockLoadBalancerProvider, never()).newLoadBalancer(any(Helper.class));

  // call getState() with requestConnection = true
  assertEquals(IDLE, channel.getState(true));
  ArgumentCaptor<Helper> helperCaptor = ArgumentCaptor.forClass(null);
  verify(mockLoadBalancerProvider).newLoadBalancer(helperCaptor.capture());
  helper = helperCaptor.getValue();

  updateBalancingStateSafely(helper, CONNECTING, mockPicker);
  assertEquals(CONNECTING, channel.getState(false));
  assertEquals(CONNECTING, channel.getState(true));
  verify(mockLoadBalancerProvider).newLoadBalancer(any(Helper.class));
}
 
Example #6
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 #7
Source File: ManagedChannelImplTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void getState_withRequestConnect() {
  channelBuilder.nameResolverFactory(
      new FakeNameResolverFactory.Builder(expectedUri).setResolvedAtStart(false).build());
  requestConnection = false;
  createChannel();

  assertEquals(IDLE, channel.getState(false));
  verify(mockLoadBalancerFactory, never()).newLoadBalancer(any(Helper.class));

  // call getState() with requestConnection = true
  assertEquals(IDLE, channel.getState(true));
  ArgumentCaptor<Helper> helperCaptor = ArgumentCaptor.forClass(null);
  verify(mockLoadBalancerFactory).newLoadBalancer(helperCaptor.capture());
  helper = helperCaptor.getValue();

  helper.updateBalancingState(CONNECTING, mockPicker);
  assertEquals(CONNECTING, channel.getState(false));
  assertEquals(CONNECTING, channel.getState(true));
  verifyNoMoreInteractions(mockLoadBalancerFactory);
}
 
Example #8
Source File: ManagedChannelImplTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void idleTimeoutAndReconnect() {
  long idleTimeoutMillis = 2000L;
  channelBuilder.idleTimeout(idleTimeoutMillis, TimeUnit.MILLISECONDS);
  createChannel();

  timer.forwardNanos(TimeUnit.MILLISECONDS.toNanos(idleTimeoutMillis));
  assertEquals(IDLE, channel.getState(true /* request connection */));

  ArgumentCaptor<Helper> helperCaptor = ArgumentCaptor.forClass(Helper.class);
  // Two times of requesting connection will create loadBalancer twice.
  verify(mockLoadBalancerFactory, times(2)).newLoadBalancer(helperCaptor.capture());
  Helper helper2 = helperCaptor.getValue();

  // Updating on the old helper (whose balancer has been shutdown) does not change the channel
  // state.
  helper.updateBalancingState(CONNECTING, mockPicker);
  assertEquals(IDLE, channel.getState(false));

  helper2.updateBalancingState(CONNECTING, mockPicker);
  assertEquals(CONNECTING, channel.getState(false));
}
 
Example #9
Source File: ManagedChannelImplTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
private static Subchannel createSubchannelSafely(
    final Helper helper, final EquivalentAddressGroup addressGroup, final Attributes attrs,
    final SubchannelStateListener stateListener) {
  final AtomicReference<Subchannel> resultCapture = new AtomicReference<>();
  helper.getSynchronizationContext().execute(
      new Runnable() {
        @Override
        public void run() {
          Subchannel s = helper.createSubchannel(CreateSubchannelArgs.newBuilder()
              .setAddresses(addressGroup)
              .setAttributes(attrs)
              .build());
          s.start(stateListener);
          resultCapture.set(s);
        }
      });
  return resultCapture.get();
}
 
Example #10
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 #11
Source File: ManagedChannelImplIdlenessTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void updateSubchannelAddresses_newAddressConnects() {
  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();
  Subchannel subchannel = createSubchannelSafely(helper, servers.get(0), Attributes.EMPTY);

  subchannel.requestConnection();
  MockClientTransportInfo t0 = newTransports.poll();
  t0.listener.transportReady();

  helper.updateSubchannelAddresses(subchannel, servers.get(1));

  subchannel.requestConnection();
  MockClientTransportInfo t1 = newTransports.poll();
  t1.listener.transportReady();
}
 
Example #12
Source File: ManagedChannelImplIdlenessTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void updateSubchannelAddresses_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();
  Subchannel subchannel = createSubchannelSafely(helper, servers.get(0), Attributes.EMPTY);

  subchannel.requestConnection();
  MockClientTransportInfo t0 = newTransports.poll();
  t0.listener.transportReady();

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

  subchannel.requestConnection();
  assertNull(newTransports.poll());
}
 
Example #13
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 #14
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 #15
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 #16
Source File: LocalityStore.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
ChildHelper() {
  final ClientLoadCounter counter = loadStatsStore.getLocalityCounter(locality);
  Helper delegate = new ForwardingLoadBalancerHelper() {
    @Override
    protected Helper delegate() {
      return helper;
    }

    @Override
    public void updateBalancingState(
        ConnectivityState newState, SubchannelPicker newPicker) {
      logger.log(
          XdsLogLevel.INFO,
          "Update load balancing state for locality {0} to {1}", locality, newState);
      currentChildState = newState;
      currentChildPicker =
          new LoadRecordingSubchannelPicker(
              counter,
              new MetricsObservingSubchannelPicker(new MetricsRecordingListener(counter),
                  newPicker, orcaPerRequestUtil));

      priorityManager.updatePriorityState(priorityManager.getPriority(locality));
    }

    @Override
    public String getAuthority() {
      //FIXME: This should be a new proposed field of Locality, locality_name
      return locality.getSubZone();
    }
  };

  orcaReportingHelperWrapper =
      orcaOobUtil.newOrcaReportingHelperWrapper(
          delegate, new MetricsRecordingListener(counter));
  if (metricsReportIntervalNano > 0) {
    updateMetricsReportInterval(metricsReportIntervalNano);
  }
}
 
Example #17
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 #18
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 #19
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 #20
Source File: ManagedChannelImplIdlenessTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
private static void updateBalancingStateSafely(
    final Helper helper, final ConnectivityState state, final SubchannelPicker picker) {
  helper.getSynchronizationContext().execute(
      new Runnable() {
        @Override
        public void run() {
          helper.updateBalancingState(state, picker);
        }
      });
}
 
Example #21
Source File: ManagedChannelImplTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
private static void updateBalancingStateSafely(
    final Helper helper, final ConnectivityState state, final SubchannelPicker picker) {
  helper.getSynchronizationContext().execute(
      new Runnable() {
        @Override
        public void run() {
          helper.updateBalancingState(state, picker);
        }
      });
}
 
Example #22
Source File: GrpclbState.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
GrpclbState(
    GrpclbConfig config,
    Helper helper,
    SubchannelPool subchannelPool,
    TimeProvider time,
    Stopwatch stopwatch,
    BackoffPolicy.Provider backoffPolicyProvider) {
  this.config = checkNotNull(config, "config");
  this.helper = checkNotNull(helper, "helper");
  this.syncContext = checkNotNull(helper.getSynchronizationContext(), "syncContext");
  if (config.getMode() == Mode.ROUND_ROBIN) {
    this.subchannelPool = checkNotNull(subchannelPool, "subchannelPool");
    subchannelPool.registerListener(
        new PooledSubchannelStateListener() {
          @Override
          public void onSubchannelState(
              Subchannel subchannel, ConnectivityStateInfo newState) {
            handleSubchannelState(subchannel, newState);
          }
        });
  } else {
    this.subchannelPool = null;
  }
  this.time = checkNotNull(time, "time provider");
  this.stopwatch = checkNotNull(stopwatch, "stopwatch");
  this.timerService = checkNotNull(helper.getScheduledExecutorService(), "timerService");
  this.backoffPolicyProvider = checkNotNull(backoffPolicyProvider, "backoffPolicyProvider");
  if (config.getServiceName() != null) {
    this.serviceName = config.getServiceName();
  } else {
    this.serviceName = checkNotNull(helper.getAuthority(), "helper returns null authority");
  }
  this.logger = checkNotNull(helper.getChannelLogger(), "logger");
}
 
Example #23
Source File: ManagedChannelImplTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
private static void updateAddressesSafely(
    Helper helper, final Subchannel subchannel, final List<EquivalentAddressGroup> addrs) {
  helper.getSynchronizationContext().execute(
      new Runnable() {
        @Override
        public void run() {
          subchannel.updateAddresses(addrs);
        }
      });
}
 
Example #24
Source File: RoundRobinLoadBalancerFactoryTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
@Test
public void getInstance() {
  Helper helper = mock(Helper.class);
  assertThat(
      RoundRobinLoadBalancerFactory.getInstance().newLoadBalancer(helper).getClass().getName())
      .isEqualTo("io.grpc.util.RoundRobinLoadBalancer");
  verifyZeroInteractions(helper);
}
 
Example #25
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));
}
 
Example #26
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 #27
Source File: PriorityLoadBalancerTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Override
public LoadBalancer newLoadBalancer(Helper helper) {
  fooHelpers.add(helper);
  LoadBalancer childBalancer = mock(LoadBalancer.class);
  fooBalancers.add(childBalancer);
  return childBalancer;
}
 
Example #28
Source File: GrpclbState.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
GrpclbState(
    Helper helper,
    SubchannelPool subchannelPool,
    TimeProvider time,
    BackoffPolicy.Provider backoffPolicyProvider) {
  this.helper = checkNotNull(helper, "helper");
  this.syncContext = checkNotNull(helper.getSynchronizationContext(), "syncContext");
  this.subchannelPool = checkNotNull(subchannelPool, "subchannelPool");
  this.time = checkNotNull(time, "time provider");
  this.timerService = checkNotNull(helper.getScheduledExecutorService(), "timerService");
  this.backoffPolicyProvider = checkNotNull(backoffPolicyProvider, "backoffPolicyProvider");
  this.serviceName = checkNotNull(helper.getAuthority(), "helper returns null authority");
  this.logger = checkNotNull(helper.getChannelLogger(), "logger");
}
 
Example #29
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 #30
Source File: ManagedChannelImplTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void channelsAndSubchannels_instrumented_state() throws Exception {
  createChannel();

  ArgumentCaptor<Helper> helperCaptor = ArgumentCaptor.forClass(null);
  verify(mockLoadBalancerProvider).newLoadBalancer(helperCaptor.capture());
  helper = helperCaptor.getValue();

  assertEquals(IDLE, getStats(channel).state);
  updateBalancingStateSafely(helper, CONNECTING, mockPicker);
  assertEquals(CONNECTING, getStats(channel).state);

  AbstractSubchannel subchannel =
      (AbstractSubchannel) createSubchannelSafely(
          helper, addressGroup, Attributes.EMPTY, subchannelStateListener);

  assertEquals(IDLE, getStats(subchannel).state);
  requestConnectionSafely(helper, subchannel);
  assertEquals(CONNECTING, getStats(subchannel).state);

  MockClientTransportInfo transportInfo = transports.poll();

  assertEquals(CONNECTING, getStats(subchannel).state);
  transportInfo.listener.transportReady();
  assertEquals(READY, getStats(subchannel).state);

  assertEquals(CONNECTING, getStats(channel).state);
  updateBalancingStateSafely(helper, READY, mockPicker);
  assertEquals(READY, getStats(channel).state);

  channel.shutdownNow();
  assertEquals(SHUTDOWN, getStats(channel).state);
  assertEquals(SHUTDOWN, getStats(subchannel).state);
}