io.grpc.LoadBalancerRegistry Java Examples

The following examples show how to use io.grpc.LoadBalancerRegistry. 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: ServiceConfigErrorHandlingTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  when(mockLoadBalancer.canHandleEmptyAddressListFromNameResolution()).thenCallRealMethod();
  LoadBalancerRegistry.getDefaultRegistry().register(mockLoadBalancerProvider);
  expectedUri = new URI(TARGET);
  when(mockTransportFactory.getScheduledExecutorService())
      .thenReturn(timer.getScheduledExecutorService());
  when(executorPool.getObject()).thenReturn(executor.getScheduledExecutorService());

  channelBuilder =
      new ChannelBuilder()
          .nameResolverFactory(new FakeNameResolverFactory.Builder(expectedUri).build())
          .defaultLoadBalancingPolicy(MOCK_POLICY_NAME)
          .userAgent(USER_AGENT)
          .idleTimeout(
              AbstractManagedChannelImplBuilder.IDLE_MODE_MAX_TIMEOUT_DAYS, TimeUnit.DAYS)
          .offloadExecutor(blockingExecutor);
  channelBuilder.executorPool = executorPool;
  channelBuilder.binlog = null;
  channelBuilder.channelz = channelz;
}
 
Example #2
Source File: EdsLoadBalancer.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
EdsLoadBalancer(
    Helper helper,
    LoadBalancerRegistry lbRegistry,
    LocalityStoreFactory localityStoreFactory,
    Bootstrapper bootstrapper,
    XdsChannelFactory channelFactory) {
  this.helper = checkNotNull(helper, "helper");
  this.lbRegistry = checkNotNull(lbRegistry, "lbRegistry");
  this.localityStoreFactory = checkNotNull(localityStoreFactory, "localityStoreFactory");
  this.bootstrapper = checkNotNull(bootstrapper, "bootstrapper");
  this.channelFactory = checkNotNull(channelFactory, "channelFactory");
  this.switchingLoadBalancer = new GracefulSwitchLoadBalancer(helper);
  logId = InternalLogId.allocate("eds-lb", helper.getAuthority());
  logger = XdsLogger.withLogId(logId);
  logger.log(XdsLogLevel.INFO, "Created");
}
 
Example #3
Source File: LocalityStore.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
LocalityStoreImpl(
    InternalLogId logId,
    Helper helper,
    LoadBalancerRegistry lbRegistry,
    ThreadSafeRandom random,
    LoadStatsStore loadStatsStore,
    OrcaPerRequestUtil orcaPerRequestUtil,
    OrcaOobUtil orcaOobUtil) {
  this.helper = checkNotNull(helper, "helper");
  loadBalancerProvider = checkNotNull(
      lbRegistry.getProvider(ROUND_ROBIN),
      "Unable to find '%s' LoadBalancer", ROUND_ROBIN);
  this.random = checkNotNull(random, "random");
  this.loadStatsStore = checkNotNull(loadStatsStore, "loadStatsStore");
  this.orcaPerRequestUtil = checkNotNull(orcaPerRequestUtil, "orcaPerRequestUtil");
  this.orcaOobUtil = checkNotNull(orcaOobUtil, "orcaOobUtil");
  logger = XdsLogger.withLogId(checkNotNull(logId, "logId"));
}
 
Example #4
Source File: LbPolicyConfigurationTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void childLoadBalancingPolicy_noPolicyProvided() {
  LoadBalancerProvider mockProvider = mock(LoadBalancerProvider.class);
  when(mockProvider.getPolicyName()).thenReturn("rls");
  when(mockProvider.isAvailable()).thenReturn(true);

  LoadBalancerRegistry.getDefaultRegistry().register(mockProvider);
  try {
    ChildLoadBalancingPolicy.create(
        "targetFieldName",
        ImmutableList.<Map<String, ?>>of(
            ImmutableMap.<String, Object>of(
                "rls", ImmutableMap.of(), "rls2", ImmutableMap.of())));
    fail("parsing exception expected");
  } catch (InvalidChildPolicyConfigException e) {
    assertThat(e).hasMessageThat()
        .contains("childPolicy should have exactly one loadbalancing policy");
  } finally {
    LoadBalancerRegistry.getDefaultRegistry().deregister(mockProvider);
  }
}
 
Example #5
Source File: ManagedChannelImplTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  when(mockLoadBalancer.canHandleEmptyAddressListFromNameResolution()).thenCallRealMethod();
  LoadBalancerRegistry.getDefaultRegistry().register(mockLoadBalancerProvider);
  expectedUri = new URI(TARGET);
  transports = TestUtils.captureTransports(mockTransportFactory);
  when(mockTransportFactory.getScheduledExecutorService())
      .thenReturn(timer.getScheduledExecutorService());
  when(executorPool.getObject()).thenReturn(executor.getScheduledExecutorService());
  when(balancerRpcExecutorPool.getObject())
      .thenReturn(balancerRpcExecutor.getScheduledExecutorService());

  channelBuilder =
      new ChannelBuilder()
          .nameResolverFactory(new FakeNameResolverFactory.Builder(expectedUri).build())
          .defaultLoadBalancingPolicy(MOCK_POLICY_NAME)
          .userAgent(USER_AGENT)
          .idleTimeout(
              AbstractManagedChannelImplBuilder.IDLE_MODE_MAX_TIMEOUT_DAYS, TimeUnit.DAYS)
          .offloadExecutor(offloadExecutor);
  channelBuilder.executorPool = executorPool;
  channelBuilder.binlog = null;
  channelBuilder.channelz = channelz;
}
 
Example #6
Source File: ControllerResolverFactory.java    From pravega with Apache License 2.0 6 votes vote down vote up
/**
 * Creates the NameResolver instance.
 *
 * @param authority         The authority string used to create the URI.
 * @param bootstrapServers  The initial set of controller endpoints.
 * @param enableDiscovery   Whether to use the controller's discovery API.
 * @param executor          The executor to run resolve tasks on.
 */
ControllerNameResolver(final String authority, final List<InetSocketAddress> bootstrapServers,
                       final boolean enableDiscovery, ScheduledExecutorService executor) {
    this.authority = authority;
    this.bootstrapServers = ImmutableList.copyOf(bootstrapServers);
    this.enableDiscovery = enableDiscovery;
    if (this.enableDiscovery) {
        // We will use the direct scheme to send the discovery RPC request to the controller bootstrap servers.
        String connectString = "tcp://";
        final List<String> strings = this.bootstrapServers.stream()
                .map(server -> server.getHostString() + ":" + server.getPort())
                .collect(Collectors.toList());
        connectString = connectString + String.join(",", strings);

        this.client = ControllerServiceGrpc.newBlockingStub(ManagedChannelBuilder
                .forTarget(connectString)
                .nameResolverFactory(new ControllerResolverFactory(executor))
                .loadBalancerFactory(LoadBalancerRegistry.getDefaultRegistry().getProvider("round_robin"))
                .usePlaintext()
                .build());
    } else {
        this.client = null;
    }

    this.scheduledExecutor = executor;
}
 
Example #7
Source File: ManagedChannelImplTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void enableServiceConfigLookUp_resolverReturnsNoConfig_noDefaultConfig() {
  LoadBalancerRegistry.getDefaultRegistry().register(mockLoadBalancerProvider);
  try {
    FakeNameResolverFactory nameResolverFactory =
        new FakeNameResolverFactory.Builder(expectedUri)
            .setServers(ImmutableList.of(addressGroup)).build();
    channelBuilder.nameResolverFactory(nameResolverFactory);

    Map<String, Object> rawServiceConfig = Collections.emptyMap();
    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().getAddresses()).containsExactly(addressGroup);
    verify(mockLoadBalancer, never()).handleNameResolutionError(any(Status.class));
  } finally {
    LoadBalancerRegistry.getDefaultRegistry().deregister(mockLoadBalancerProvider);
  }
}
 
Example #8
Source File: ManagedChannelImplTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void enableServiceConfigLookUp_resolverReturnsNoConfig_withDefaultConfig()
    throws Exception {
  LoadBalancerRegistry.getDefaultRegistry().register(mockLoadBalancerProvider);
  try {
    FakeNameResolverFactory nameResolverFactory =
        new FakeNameResolverFactory.Builder(expectedUri)
            .setServers(ImmutableList.of(addressGroup)).build();
    channelBuilder.nameResolverFactory(nameResolverFactory);
    Map<String, Object> defaultServiceConfig =
        parseConfig("{\"methodConfig\":[{"
            + "\"name\":[{\"service\":\"SimpleService1\"}],"
            + "\"waitForReady\":true}]}");
    channelBuilder.defaultServiceConfig(defaultServiceConfig);

    nameResolverFactory.nextConfigOrError.set(null);

    createChannel();
    ArgumentCaptor<ResolvedAddresses> resultCaptor =
        ArgumentCaptor.forClass(ResolvedAddresses.class);
    verify(mockLoadBalancer).handleResolvedAddresses(resultCaptor.capture());
    assertThat(resultCaptor.getValue().getAddresses()).containsExactly(addressGroup);
    verify(mockLoadBalancer, never()).handleNameResolutionError(any(Status.class));
  } finally {
    LoadBalancerRegistry.getDefaultRegistry().deregister(mockLoadBalancerProvider);
  }
}
 
Example #9
Source File: ManagedChannelImplTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void enableServiceConfigLookUp_withDefaultConfig() throws Exception {
  LoadBalancerRegistry.getDefaultRegistry().register(mockLoadBalancerProvider);
  try {
    FakeNameResolverFactory nameResolverFactory =
        new FakeNameResolverFactory.Builder(expectedUri)
            .setServers(ImmutableList.of(addressGroup)).build();
    channelBuilder.nameResolverFactory(nameResolverFactory);
    Map<String, Object> defaultServiceConfig =
        parseConfig("{\"methodConfig\":[{"
            + "\"name\":[{\"service\":\"SimpleService1\"}],"
            + "\"waitForReady\":true}]}");
    channelBuilder.defaultServiceConfig(defaultServiceConfig);

    Map<String, Object> rawServiceConfig =
        parseConfig("{\"methodConfig\":[{"
            + "\"name\":[{\"service\":\"SimpleService2\"}],"
            + "\"waitForReady\":false}]}");
    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().getAddresses()).containsExactly(addressGroup);
    verify(mockLoadBalancer, never()).handleNameResolutionError(any(Status.class));
  } finally {
    LoadBalancerRegistry.getDefaultRegistry().deregister(mockLoadBalancerProvider);
  }
}
 
Example #10
Source File: ManagedChannelImplTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void disableServiceConfigLookUp_withDefaultConfig() throws Exception {
  LoadBalancerRegistry.getDefaultRegistry().register(mockLoadBalancerProvider);
  try {
    FakeNameResolverFactory nameResolverFactory =
        new FakeNameResolverFactory.Builder(expectedUri)
            .setServers(ImmutableList.of(addressGroup)).build();
    channelBuilder.nameResolverFactory(nameResolverFactory);
    channelBuilder.disableServiceConfigLookUp();
    Map<String, Object> defaultServiceConfig =
        parseConfig("{\"methodConfig\":[{"
            + "\"name\":[{\"service\":\"SimpleService1\"}],"
            + "\"waitForReady\":true}]}");
    channelBuilder.defaultServiceConfig(defaultServiceConfig);

    Map<String, Object> rawServiceConfig = new HashMap<>();
    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().getAddresses()).containsExactly(addressGroup);
    verify(mockLoadBalancer, never()).handleNameResolutionError(any(Status.class));
  } finally {
    LoadBalancerRegistry.getDefaultRegistry().deregister(mockLoadBalancerProvider);
  }
}
 
Example #11
Source File: ManagedChannelImplTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void disableServiceConfigLookUp_noDefaultConfig() throws Exception {
  LoadBalancerRegistry.getDefaultRegistry().register(mockLoadBalancerProvider);
  try {
    FakeNameResolverFactory nameResolverFactory =
        new FakeNameResolverFactory.Builder(expectedUri)
            .setServers(ImmutableList.of(addressGroup)).build();
    channelBuilder.nameResolverFactory(nameResolverFactory);
    channelBuilder.disableServiceConfigLookUp();

    Map<String, Object> rawServiceConfig =
        parseConfig("{\"methodConfig\":[{"
            + "\"name\":[{\"service\":\"SimpleService1\"}],"
            + "\"waitForReady\":true}]}");
    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().getAddresses()).containsExactly(addressGroup);
    verify(mockLoadBalancer, never()).handleNameResolutionError(any(Status.class));
  } finally {
    LoadBalancerRegistry.getDefaultRegistry().deregister(mockLoadBalancerProvider);
  }
}
 
Example #12
Source File: ServiceConfigUtil.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
/**
 * Parses and selects a load balancing policy from a non-empty list of raw configs. If selection
 * is successful, the returned ConfigOrError object will include a {@link
 * ServiceConfigUtil.PolicySelection} as its config value.
 */
public static ConfigOrError selectLbPolicyFromList(
    List<LbConfig> lbConfigs, LoadBalancerRegistry lbRegistry) {
  List<String> policiesTried = new ArrayList<>();
  for (LbConfig lbConfig : lbConfigs) {
    String policy = lbConfig.getPolicyName();
    LoadBalancerProvider provider = lbRegistry.getProvider(policy);
    if (provider == null) {
      policiesTried.add(policy);
    } else {
      if (!policiesTried.isEmpty()) {
        Logger.getLogger(ServiceConfigUtil.class.getName()).log(
            Level.FINEST,
            "{0} specified by Service Config are not available", policiesTried);
      }
      ConfigOrError parsedLbPolicyConfig =
          provider.parseLoadBalancingPolicyConfig(lbConfig.getRawConfigValue());
      if (parsedLbPolicyConfig.getError() != null) {
        return parsedLbPolicyConfig;
      }
      return ConfigOrError.fromConfig(new PolicySelection(
          provider, lbConfig.rawConfigValue, parsedLbPolicyConfig.getConfig()));
    }
  }
  return ConfigOrError.fromError(
      Status.UNKNOWN.withDescription(
          "None of " + policiesTried + " specified by Service Config are available."));
}
 
Example #13
Source File: HealthCheckingRoundRobinLoadBalancerProviderTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void registry() {
  LoadBalancerProvider hcRoundRobin =
      LoadBalancerRegistry.getDefaultRegistry().getProvider("round_robin");
  assertThat(hcRoundRobin).isInstanceOf(
      HealthCheckingRoundRobinLoadBalancerProvider.class);
}
 
Example #14
Source File: LbPolicyConfiguration.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
/** Creates ChildLoadBalancingPolicy. */
@SuppressWarnings("unchecked")
static ChildLoadBalancingPolicy create(
    String childPolicyConfigTargetFieldName, List<Map<String, ?>> childPolicies)
    throws InvalidChildPolicyConfigException {
  Map<String, Object> effectiveChildPolicy = null;
  LoadBalancerProvider effectiveLbProvider = null;
  List<String> policyTried = new ArrayList<>();

  LoadBalancerRegistry lbRegistry = LoadBalancerRegistry.getDefaultRegistry();
  for (Map<String, ?> childPolicy : childPolicies) {
    if (childPolicy.isEmpty()) {
      continue;
    }
    if (childPolicy.size() != 1) {
      throw
          new InvalidChildPolicyConfigException(
              "childPolicy should have exactly one loadbalancing policy");
    }
    String policyName = childPolicy.keySet().iterator().next();
    LoadBalancerProvider provider = lbRegistry.getProvider(policyName);
    if (provider != null) {
      effectiveLbProvider = provider;
      effectiveChildPolicy = Collections.unmodifiableMap(childPolicy);
      break;
    }
    policyTried.add(policyName);
  }
  if (effectiveChildPolicy == null) {
    throw
        new InvalidChildPolicyConfigException(
            String.format("no valid childPolicy found, policy tried: %s", policyTried));
  }
  return
      new ChildLoadBalancingPolicy(
          childPolicyConfigTargetFieldName,
          (Map<String, Object>) effectiveChildPolicy.values().iterator().next(),
          effectiveLbProvider);
}
 
Example #15
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 #16
Source File: CdsLoadBalancer.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
CdsLoadBalancer(Helper helper, LoadBalancerRegistry lbRegistry,
    TlsContextManager tlsContextManager) {
  checkNotNull(helper, "helper");
  this.lbRegistry = lbRegistry;
  this.switchingLoadBalancer = new GracefulSwitchLoadBalancer(helper);
  this.tlsContextManager = tlsContextManager;
  logger = XdsLogger.withLogId(InternalLogId.allocate("cds-lb", helper.getAuthority()));
  logger.log(XdsLogLevel.INFO, "Created");
}
 
Example #17
Source File: HealthCheckingRoundRobinLoadBalancerProviderTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Test
public void registry() {
  LoadBalancerProvider hcRoundRobin =
      LoadBalancerRegistry.getDefaultRegistry().getProvider("round_robin");
  assertThat(hcRoundRobin).isInstanceOf(
      HealthCheckingRoundRobinLoadBalancerProvider.class);
}
 
Example #18
Source File: LocalityStore.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
LocalityStoreImpl(
    InternalLogId logId,
    Helper helper,
    LoadBalancerRegistry lbRegistry,
    LoadStatsStore loadStatsStore) {
  this(
      logId,
      helper,
      lbRegistry,
      ThreadSafeRandom.ThreadSafeRandomImpl.instance,
      loadStatsStore,
      OrcaPerRequestUtil.getInstance(),
      OrcaOobUtil.getInstance());
}
 
Example #19
Source File: LocalityStore.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Override
LocalityStore newLocalityStore(
    InternalLogId logId,
    Helper helper,
    LoadBalancerRegistry lbRegistry,
    LoadStatsStore loadStatsStore) {
  return new LocalityStoreImpl(logId, helper, lbRegistry, loadStatsStore);
}
 
Example #20
Source File: XdsRoutingLoadBalancerProvider.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
private static PolicySelection parseAction(
    Map<String, ?> rawAction, LoadBalancerRegistry registry) {
  List<LbConfig> childConfigCandidates = ServiceConfigUtil.unwrapLoadBalancingConfigList(
      JsonUtil.getListOfObjects(rawAction, "childPolicy"));
  if (childConfigCandidates == null || childConfigCandidates.isEmpty()) {
    throw new RuntimeException("childPolicy not specified");
  }
  ConfigOrError selectedConfigOrError =
      ServiceConfigUtil.selectLbPolicyFromList(childConfigCandidates, registry);
  if (selectedConfigOrError.getError() != null) {
    throw selectedConfigOrError.getError().asRuntimeException();
  }
  return (PolicySelection) selectedConfigOrError.getConfig();
}
 
Example #21
Source File: ControllerImpl.java    From pravega with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new instance of the Controller client class.
 *
 * @param config        The configuration for this client implementation.
 * @param executor      The executor service to be used for handling retries.
 */
public ControllerImpl(final ControllerImplConfig config,
                      final ScheduledExecutorService executor) {
    this(NettyChannelBuilder.forTarget(config.getClientConfig().getControllerURI().toString())
                            .nameResolverFactory(new ControllerResolverFactory(executor))
                            .loadBalancerFactory(LoadBalancerRegistry.getDefaultRegistry().getProvider("round_robin"))
                            .keepAliveTime(DEFAULT_KEEPALIVE_TIME_MINUTES, TimeUnit.MINUTES),
            config, executor);
    log.info("Controller client connecting to server at {}", config.getClientConfig().getControllerURI().getAuthority());
}
 
Example #22
Source File: GrpcChannelControllerImpl.java    From onos with Apache License 2.0 5 votes vote down vote up
@Activate
public void activate() {
    componentConfigService.registerProperties(getClass());
    channels = new ConcurrentHashMap<>();
    interceptors = new ConcurrentHashMap<>();
    LoadBalancerRegistry.getDefaultRegistry()
            .register(PICK_FIRST_LOAD_BALANCER_PROVIDER);
    NameResolverRegistry.getDefaultRegistry()
            .register(DNS_NAME_RESOLVER_PROVIDER);
    log.info("Started");
}
 
Example #23
Source File: GrpcChannelControllerImpl.java    From onos with Apache License 2.0 5 votes vote down vote up
@Deactivate
public void deactivate() {
    LoadBalancerRegistry.getDefaultRegistry()
            .deregister(PICK_FIRST_LOAD_BALANCER_PROVIDER);
    NameResolverRegistry.getDefaultRegistry()
            .register(DNS_NAME_RESOLVER_PROVIDER);
    componentConfigService.unregisterProperties(getClass(), false);
    channels.values().forEach(ManagedChannel::shutdownNow);
    channels.clear();
    channels = null;
    interceptors.values().forEach(GrpcLoggingInterceptor::close);
    interceptors.clear();
    interceptors = null;
    log.info("Stopped");
}
 
Example #24
Source File: EdsLoadBalancer.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
EdsLoadBalancer(Helper helper) {
  this(
      helper,
      LoadBalancerRegistry.getDefaultRegistry(),
      LocalityStoreFactory.getInstance(),
      Bootstrapper.getInstance(),
      XdsChannelFactory.getInstance());
}
 
Example #25
Source File: EdsLoadBalancerProvider.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Override
public ConfigOrError parseLoadBalancingPolicyConfig(
    Map<String, ?> rawLoadBalancingPolicyConfig) {
  LoadBalancerRegistry registry = LoadBalancerRegistry.getDefaultRegistry();
  try {
    String cluster = JsonUtil.getString(rawLoadBalancingPolicyConfig, "cluster");
    if (cluster == null) {
      return ConfigOrError.fromError(Status.INTERNAL.withDescription("Cluster name required"));
    }
    String edsServiceName = JsonUtil.getString(rawLoadBalancingPolicyConfig, "edsServiceName");
    String lrsServerName =
        JsonUtil.getString(rawLoadBalancingPolicyConfig, "lrsLoadReportingServerName");

    // TODO(chengyuanzhang): figure out locality_picking_policy parsing and its default value.

    LbConfig roundRobinConfig = new LbConfig("round_robin", ImmutableMap.<String, Object>of());
    List<LbConfig> endpointPickingPolicy =
        ServiceConfigUtil
            .unwrapLoadBalancingConfigList(
                JsonUtil.getListOfObjects(
                    rawLoadBalancingPolicyConfig, "endpointPickingPolicy"));
    if (endpointPickingPolicy == null || endpointPickingPolicy.isEmpty()) {
      endpointPickingPolicy = Collections.singletonList(roundRobinConfig);
    }
    ConfigOrError endpointPickingConfigOrError =
        ServiceConfigUtil.selectLbPolicyFromList(endpointPickingPolicy, registry);
    if (endpointPickingConfigOrError.getError() != null) {
      return endpointPickingConfigOrError;
    }
    PolicySelection endpointPickingSelection =
        (PolicySelection) endpointPickingConfigOrError.getConfig();
    return ConfigOrError.fromConfig(
        new EdsConfig(cluster, edsServiceName, lrsServerName, endpointPickingSelection));
  } catch (RuntimeException e) {
    return ConfigOrError.fromError(
        Status.fromThrowable(e).withDescription(
            "Failed to parse EDS LB config: " + rawLoadBalancingPolicyConfig));
  }
}
 
Example #26
Source File: ManagedChannelImplTest.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
@After
public void cleanUp() {
  LoadBalancerRegistry.getDefaultRegistry().deregister(mockLoadBalancerProvider);
}
 
Example #27
Source File: ServiceConfigErrorHandlingTest.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
@After
public void cleanUp() {
  LoadBalancerRegistry.getDefaultRegistry().deregister(mockLoadBalancerProvider);
}
 
Example #28
Source File: GrpclbLoadBalancerFactory.java    From grpc-nebula-java with Apache License 2.0 4 votes vote down vote up
private GrpclbLoadBalancerFactory() {
  provider = checkNotNull(
      LoadBalancerRegistry.getDefaultRegistry().getProvider("grpclb"),
      "grpclb balancer not available");
}
 
Example #29
Source File: ManagedChannelImplIdlenessTest.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
@After
public void cleanUp() {
  LoadBalancerRegistry.getDefaultRegistry().deregister(mockLoadBalancerProvider);
}
 
Example #30
Source File: ManagedChannelImplIdlenessTest.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
@Before
@SuppressWarnings("deprecation") // For NameResolver.Listener
public void setUp() {
  LoadBalancerRegistry.getDefaultRegistry().register(mockLoadBalancerProvider);
  when(mockNameResolver.getServiceAuthority()).thenReturn(AUTHORITY);
  when(mockNameResolverFactory
      .newNameResolver(any(URI.class), any(NameResolver.Args.class)))
      .thenReturn(mockNameResolver);
  when(mockTransportFactory.getScheduledExecutorService())
      .thenReturn(timer.getScheduledExecutorService());

  class Builder extends AbstractManagedChannelImplBuilder<Builder> {
    Builder(String target) {
      super(target);
    }

    @Override protected ClientTransportFactory buildTransportFactory() {
      throw new UnsupportedOperationException();
    }

    @Override public Builder usePlaintext() {
      throw new UnsupportedOperationException();
    }
  }

  Builder builder = new Builder("fake://target")
      .nameResolverFactory(mockNameResolverFactory)
      .defaultLoadBalancingPolicy(MOCK_POLICY_NAME)
      .idleTimeout(IDLE_TIMEOUT_SECONDS, TimeUnit.SECONDS)
      .userAgent(USER_AGENT);
  builder.executorPool = executorPool;
  channel = new ManagedChannelImpl(
      builder, mockTransportFactory, new FakeBackoffPolicyProvider(),
      oobExecutorPool, timer.getStopwatchSupplier(),
      Collections.<ClientInterceptor>emptyList(),
      TimeProvider.SYSTEM_TIME_PROVIDER);
  newTransports = TestUtils.captureTransports(mockTransportFactory);

  for (int i = 0; i < 2; i++) {
    ArrayList<SocketAddress> addrs = Lists.newArrayList();
    for (int j = 0; j < 2; j++) {
      addrs.add(new FakeSocketAddress("servergroup" + i + "server" + j));
    }
    servers.add(new EquivalentAddressGroup(addrs));
  }
  verify(mockNameResolverFactory).newNameResolver(any(URI.class), any(NameResolver.Args.class));
  // Verify the initial idleness
  verify(mockLoadBalancerProvider, never()).newLoadBalancer(any(Helper.class));
  verify(mockTransportFactory, never()).newClientTransport(
      any(SocketAddress.class),
      any(ClientTransportFactory.ClientTransportOptions.class),
      any(ChannelLogger.class));
  verify(mockNameResolver, never()).start(any(NameResolver.Listener.class));
  verify(mockNameResolver, never()).start(any(NameResolver.Listener2.class));
}