Java Code Examples for io.grpc.NameResolver#Args

The following examples show how to use io.grpc.NameResolver#Args . 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: GrpclbNameResolverTest.java    From grpc-java with Apache License 2.0 7 votes vote down vote up
@Before
public void setUp() {
  GrpclbNameResolver.setEnableTxt(true);
  NameResolver.Args args =
      NameResolver.Args.newBuilder()
          .setDefaultPort(DEFAULT_PORT)
          .setProxyDetector(GrpcUtil.NOOP_PROXY_DETECTOR)
          .setSynchronizationContext(syncContext)
          .setServiceConfigParser(serviceConfigParser)
          .setChannelLogger(mock(ChannelLogger.class))
          .build();
  resolver =
      new GrpclbNameResolver(
          null, NAME, args, fakeExecutorResource, fakeClock.getStopwatchSupplier().get(),
          /* isAndroid */false);
  hostName = resolver.getHost();
  assertThat(hostName).isEqualTo(NAME);
}
 
Example 2
Source File: DnsNameResolverTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
private DnsNameResolver newResolver(
    String name,
    final int defaultPort,
    final ProxyDetector proxyDetector,
    Stopwatch stopwatch,
    boolean isAndroid) {
  NameResolver.Args args =
      NameResolver.Args.newBuilder()
          .setDefaultPort(defaultPort)
          .setProxyDetector(proxyDetector)
          .setSynchronizationContext(syncContext)
          .setServiceConfigParser(mock(ServiceConfigParser.class))
          .setChannelLogger(mock(ChannelLogger.class))
          .build();
  return newResolver(name, stopwatch, isAndroid, args);
}
 
Example 3
Source File: DiscoveryClientResolverFactory.java    From grpc-spring-boot-starter with MIT License 6 votes vote down vote up
@Nullable
@Override
public NameResolver newNameResolver(final URI targetUri, final NameResolver.Args args) {
    if (DISCOVERY_SCHEME.equals(targetUri.getScheme())) {
        final String serviceName = targetUri.getPath();
        if (serviceName == null || serviceName.length() <= 1 || !serviceName.startsWith("/")) {
            throw new IllegalArgumentException("Incorrectly formatted target uri; "
                    + "expected: '" + DISCOVERY_SCHEME + ":[//]/<service-name>'; "
                    + "but was '" + targetUri.toString() + "'");
        }
        final AtomicReference<DiscoveryClientNameResolver> reference = new AtomicReference<>();
        final DiscoveryClientNameResolver discoveryClientNameResolver =
                new DiscoveryClientNameResolver(serviceName.substring(1), this.client, args,
                        GrpcUtil.SHARED_CHANNEL_EXECUTOR,
                        () -> this.discoveryClientNameResolvers.remove(reference.get()));
        reference.set(discoveryClientNameResolver);
        this.discoveryClientNameResolvers.add(discoveryClientNameResolver);
        return discoveryClientNameResolver;
    }
    return null;
}
 
Example 4
Source File: DiscoveryClientResolverFactory.java    From grpc-spring-boot-starter with MIT License 6 votes vote down vote up
@Nullable
@Override
public NameResolver newNameResolver(final URI targetUri, final NameResolver.Args args) {
    if (DISCOVERY_SCHEME.equals(targetUri.getScheme())) {
        final String serviceName = targetUri.getPath();
        if (serviceName == null || serviceName.length() <= 1 || !serviceName.startsWith("/")) {
            throw new IllegalArgumentException("Incorrectly formatted target uri; "
                    + "expected: '" + DISCOVERY_SCHEME + ":[//]/<service-name>'; "
                    + "but was '" + targetUri.toString() + "'");
        }
        final AtomicReference<DiscoveryClientNameResolver> reference = new AtomicReference<>();
        final DiscoveryClientNameResolver discoveryClientNameResolver =
                new DiscoveryClientNameResolver(serviceName.substring(1), this.client, args,
                        GrpcUtil.SHARED_CHANNEL_EXECUTOR,
                        () -> this.discoveryClientNameResolvers.remove(reference.get()));
        reference.set(discoveryClientNameResolver);
        this.discoveryClientNameResolvers.add(discoveryClientNameResolver);
        return discoveryClientNameResolver;
    }
    return null;
}
 
Example 5
Source File: ManagedChannelImplGetNameResolverTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void validTargetNoResovler() {
  Factory nameResolverFactory = new NameResolver.Factory() {
    @Override
    public NameResolver newNameResolver(URI targetUri, NameResolver.Args args) {
      return null;
    }

    @Override
    public String getDefaultScheme() {
      return "defaultscheme";
    }
  };
  try {
    ManagedChannelImpl.getNameResolver(
        "foo.googleapis.com:8080", nameResolverFactory, NAMERESOLVER_ARGS);
    fail("Should fail");
  } catch (IllegalArgumentException e) {
    // expected
  }
}
 
Example 6
Source File: AbstractManagedChannelImplBuilder.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Override
public NameResolver newNameResolver(URI notUsedUri, NameResolver.Args args) {
  return new NameResolver() {
    @Override
    public String getServiceAuthority() {
      return authority;
    }

    @Override
    public void start(Listener2 listener) {
      listener.onResult(
          ResolutionResult.newBuilder()
              .setAddresses(Collections.singletonList(new EquivalentAddressGroup(address)))
              .setAttributes(Attributes.EMPTY)
              .build());
    }

    @Override
    public void shutdown() {}
  };
}
 
Example 7
Source File: DnsNameResolverProvider.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Override
public DnsNameResolver newNameResolver(URI targetUri, NameResolver.Args args) {
  if (SCHEME.equals(targetUri.getScheme())) {
    String targetPath = Preconditions.checkNotNull(targetUri.getPath(), "targetPath");
    Preconditions.checkArgument(targetPath.startsWith("/"),
        "the path component (%s) of the target (%s) must start with '/'", targetPath, targetUri);
    String name = targetPath.substring(1);
    return new DnsNameResolver(
        targetUri.getAuthority(),
        name,
        args,
        GrpcUtil.SHARED_CHANNEL_EXECUTOR,
        Stopwatch.createUnstarted(),
        InternalServiceProviders.isAndroid(getClass().getClassLoader()));
  } else {
    return null;
  }
}
 
Example 8
Source File: OverrideAuthorityNameResolverFactory.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public NameResolver newNameResolver(URI targetUri, NameResolver.Args args) {
  final NameResolver resolver = delegate.newNameResolver(targetUri, args);
  // Do not wrap null values. We do not want to impede error signaling.
  if (resolver == null) {
    return null;
  }
  return new ForwardingNameResolver(resolver) {
    @Override
    public String getServiceAuthority() {
      return authorityOverride;
    }
  };
}
 
Example 9
Source File: DnsNameResolverTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testExecutor_custom() throws Exception {
  final List<InetAddress> answer = createAddressList(2);
  final AtomicInteger executions = new AtomicInteger();

  NameResolver.Args args =
      NameResolver.Args.newBuilder()
          .setDefaultPort(81)
          .setProxyDetector(GrpcUtil.NOOP_PROXY_DETECTOR)
          .setSynchronizationContext(syncContext)
          .setServiceConfigParser(mock(ServiceConfigParser.class))
          .setChannelLogger(mock(ChannelLogger.class))
          .setOffloadExecutor(
              new Executor() {
                @Override
                public void execute(Runnable command) {
                  executions.incrementAndGet();
                  command.run();
                }
              })
          .build();

  DnsNameResolver resolver =
      newResolver("foo.googleapis.com", Stopwatch.createUnstarted(), false, args);
  AddressResolver mockResolver = mock(AddressResolver.class);
  when(mockResolver.resolveAddress(anyString())).thenReturn(answer);
  resolver.setAddressResolver(mockResolver);

  resolver.start(mockListener);
  assertEquals(0, fakeExecutor.runDueTasks());
  verify(mockListener).onResult(resultCaptor.capture());
  assertAnswerMatches(answer, 81, resultCaptor.getValue());
  assertEquals(0, fakeClock.numPendingTasks());

  resolver.shutdown();

  assertThat(fakeExecutorResource.createCount.get()).isEqualTo(0);
  assertThat(executions.get()).isEqualTo(1);
}
 
Example 10
Source File: ManagedChannelImplGetNameResolverTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Override
public NameResolver newNameResolver(URI targetUri, NameResolver.Args args) {
  if (expectedScheme.equals(targetUri.getScheme())) {
    return new FakeNameResolver(targetUri);
  }
  return null;
}
 
Example 11
Source File: ManagedChannelImplTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void lbHelper_getNameResolverArgs() {
  createChannel();

  NameResolver.Args args = helper.getNameResolverArgs();
  assertThat(args.getDefaultPort()).isEqualTo(DEFAULT_PORT);
  assertThat(args.getProxyDetector()).isSameInstanceAs(GrpcUtil.DEFAULT_PROXY_DETECTOR);
  assertThat(args.getSynchronizationContext())
      .isSameInstanceAs(helper.getSynchronizationContext());
  assertThat(args.getServiceConfigParser()).isNotNull();
}
 
Example 12
Source File: XdsSdsClientServerTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Override
public NameResolver newNameResolver(final URI targetUri, NameResolver.Args args) {
  if (!expectedUri.equals(targetUri)) {
    return null;
  }
  FakeNameResolver resolver = new FakeNameResolver();
  resolvers.add(resolver);
  return resolver;
}
 
Example 13
Source File: SmartNameResolverFactory.java    From jetcd with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public NameResolver newNameResolver(URI targetUri, NameResolver.Args args) {
    if ("etcd".equals(targetUri.getScheme())) {
        return new SmartNameResolver(this.authority, this.uris, this.loader);
    } else {
        return null;
    }
}
 
Example 14
Source File: StaticNameResolverProvider.java    From grpc-spring-boot-starter with MIT License 5 votes vote down vote up
@Nullable
@Override
public NameResolver newNameResolver(final URI targetUri, final NameResolver.Args args) {
    if (STATIC_SCHEME.equals(targetUri.getScheme())) {
        return of(targetUri.getAuthority(), args.getDefaultPort());
    }
    return null;
}
 
Example 15
Source File: StaticNameResolverProvider.java    From grpc-spring-boot-starter with MIT License 5 votes vote down vote up
@Nullable
@Override
public NameResolver newNameResolver(final URI targetUri, final NameResolver.Args args) {
    if (STATIC_SCHEME.equals(targetUri.getScheme())) {
        return of(targetUri.getAuthority(), args.getDefaultPort());
    }
    return null;
}
 
Example 16
Source File: ServiceConfigErrorHandlingTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Override
public NameResolver newNameResolver(final URI targetUri, NameResolver.Args args) {
  if (!expectedUri.equals(targetUri)) {
    return null;
  }
  assertEquals(DEFAULT_PORT, args.getDefaultPort());
  FakeNameResolver resolver = new FakeNameResolver(args.getServiceConfigParser());
  resolvers.add(resolver);
  return resolver;
}
 
Example 17
Source File: ManagedChannelImpl.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
@Override
public NameResolver.Args getNameResolverArgs() {
  return nameResolverArgs;
}
 
Example 18
Source File: StaticEtcdNameResolverFactory.java    From etcd-java with Apache License 2.0 4 votes vote down vote up
public SubResolver(URI uri, NameResolver.Args args) {
    this.resolver = DNS_PROVIDER.newNameResolver(uri, args);
}
 
Example 19
Source File: ForwardingLoadBalancerHelper.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
@Override
public NameResolver.Args getNameResolverArgs() {
  return delegate().getNameResolverArgs();
}
 
Example 20
Source File: DnsNameResolverTest.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
@Test
public void resolve_presentResourceResolver() throws Exception {
  DnsNameResolver.enableTxt = true;
  InetAddress backendAddr = InetAddresses.fromInteger(0x7f000001);
  AddressResolver mockAddressResolver = mock(AddressResolver.class);
  when(mockAddressResolver.resolveAddress(anyString()))
      .thenReturn(Collections.singletonList(backendAddr));
  ResourceResolver mockResourceResolver = mock(ResourceResolver.class);
  when(mockResourceResolver.resolveTxt(anyString()))
      .thenReturn(
          Collections.singletonList(
              "grpc_config=[{\"clientLanguage\": [\"java\"], \"serviceConfig\": {}}]"));
  ServiceConfigParser serviceConfigParser = new ServiceConfigParser() {
    @Override
    public ConfigOrError parseServiceConfig(Map<String, ?> rawServiceConfig) {
      return ConfigOrError.fromConfig(rawServiceConfig);
    }
  };
  NameResolver.Args args =
      NameResolver.Args.newBuilder()
          .setDefaultPort(DEFAULT_PORT)
          .setProxyDetector(GrpcUtil.NOOP_PROXY_DETECTOR)
          .setSynchronizationContext(syncContext)
          .setServiceConfigParser(serviceConfigParser)
          .build();

  String name = "foo.googleapis.com";
  DnsNameResolver resolver = newResolver(name, Stopwatch.createUnstarted(), false, args);
  resolver.setAddressResolver(mockAddressResolver);
  resolver.setResourceResolver(mockResourceResolver);

  resolver.start(mockListener);
  assertEquals(1, fakeExecutor.runDueTasks());
  verify(mockListener).onResult(resultCaptor.capture());
  ResolutionResult result = resultCaptor.getValue();
  InetSocketAddress resolvedBackendAddr =
      (InetSocketAddress) Iterables.getOnlyElement(
          Iterables.getOnlyElement(result.getAddresses()).getAddresses());
  assertThat(resolvedBackendAddr.getAddress()).isEqualTo(backendAddr);
  assertThat(result.getServiceConfig().getConfig()).isNotNull();
  verify(mockAddressResolver).resolveAddress(name);
  verify(mockResourceResolver).resolveTxt("_grpc_config." + name);
}