io.grpc.NameResolver Java Examples

The following examples show how to use io.grpc.NameResolver. 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: StaticNameResolverProvider.java    From grpc-spring-boot-starter with MIT License 6 votes vote down vote up
/**
 * Creates a new {@link NameResolver} for the given authority and attributes.
 *
 * @param targetAuthority The authority to connect to.
 * @param defaultPort The default port to use, if none is specified.
 * @return The newly created name resolver for the given target.
 */
private NameResolver of(final String targetAuthority, int defaultPort) {
    requireNonNull(targetAuthority, "targetAuthority");
    // Determine target ips
    final String[] hosts = PATTERN_COMMA.split(targetAuthority);
    final List<EquivalentAddressGroup> targets = new ArrayList<>(hosts.length);
    for (final String host : hosts) {
        final URI uri = URI.create("//" + host);
        int port = uri.getPort();
        if (port == -1) {
            port = defaultPort;
        }
        targets.add(new EquivalentAddressGroup(new InetSocketAddress(uri.getHost(), port)));
    }
    if (targets.isEmpty()) {
        throw new IllegalArgumentException("Must have at least one target, but was: " + targetAuthority);
    }
    return new StaticNameResolver(targetAuthority, targets);
}
 
Example #3
Source File: ManagedChannelImplGetNameResolverTest.java    From grpc-nebula-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, Attributes params) {
      return null;
    }

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

    @Override
    public void start(final Listener listener) {
      listener.onAddresses(
          Collections.singletonList(new EquivalentAddressGroup(address)),
          Attributes.EMPTY);
    }

    @Override
    public void shutdown() {}
  };
}
 
Example #5
Source File: StaticNameResolverProvider.java    From grpc-spring-boot-starter with MIT License 6 votes vote down vote up
/**
 * Creates a new {@link NameResolver} for the given authority and attributes.
 *
 * @param targetAuthority The authority to connect to.
 * @param defaultPort The default port to use, if none is specified.
 * @return The newly created name resolver for the given target.
 */
private NameResolver of(final String targetAuthority, int defaultPort) {
    requireNonNull(targetAuthority, "targetAuthority");
    // Determine target ips
    final String[] hosts = PATTERN_COMMA.split(targetAuthority);
    final List<EquivalentAddressGroup> targets = new ArrayList<>(hosts.length);
    for (final String host : hosts) {
        final URI uri = URI.create("//" + host);
        int port = uri.getPort();
        if (port == -1) {
            port = defaultPort;
        }
        targets.add(new EquivalentAddressGroup(new InetSocketAddress(uri.getHost(), port)));
    }
    if (targets.isEmpty()) {
        throw new IllegalArgumentException("Must have at least one target, but was: " + targetAuthority);
    }
    return new StaticNameResolver(targetAuthority, targets);
}
 
Example #6
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 #7
Source File: DnsNameResolverTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
private DnsNameResolver newResolver(
    String name,
    int port,
    ProxyDetector proxyDetector,
    Stopwatch stopwatch,
    boolean isAndroid) {
  DnsNameResolver dnsResolver = new DnsNameResolver(
      null,
      name,
      Attributes.newBuilder().set(NameResolver.Factory.PARAMS_DEFAULT_PORT, port).build(),
      fakeExecutorResource,
      proxyDetector,
      stopwatch,
      isAndroid);
  // By default, using the mocked ResourceResolver to avoid I/O
  dnsResolver.setResourceResolver(new JndiResourceResolver(recordFetcher));
  return dnsResolver;
}
 
Example #8
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 #9
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 #10
Source File: OverrideAuthorityNameResolverTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void forwardsNonOverridenCalls() {
  NameResolver.Factory wrappedFactory = mock(NameResolver.Factory.class);
  NameResolver mockResolver = mock(NameResolver.class);
  when(wrappedFactory.newNameResolver(any(URI.class), any(NameResolver.Args.class)))
      .thenReturn(mockResolver);
  NameResolver.Factory factory =
      new OverrideAuthorityNameResolverFactory(wrappedFactory, "override:5678");
  NameResolver overrideResolver =
      factory.newNameResolver(URI.create("dns:///localhost:443"), ARGS);
  assertNotNull(overrideResolver);
  NameResolver.Listener2 listener = mock(NameResolver.Listener2.class);

  overrideResolver.start(listener);
  verify(mockResolver).start(listener);

  overrideResolver.shutdown();
  verify(mockResolver).shutdown();

  overrideResolver.refresh();
  verify(mockResolver).refresh();
}
 
Example #11
Source File: ControllerResolverFactory.java    From pravega with Apache License 2.0 6 votes vote down vote up
@Nullable
@Override
public NameResolver newNameResolver(URI targetUri, Attributes params) {
    final String scheme = targetUri.getScheme();
    if (!SCHEME_DISCOVER.equals(scheme) && !SCHEME_DISCOVER_TLS.equals(scheme) &&
            !SCHEME_DIRECT.equals(scheme) && !SCHEME_DIRECT_SSL.equals(scheme) && !SCHEME_DIRECT_TLS.equals(scheme)) {
        return null;
    }

    final String authority = targetUri.getAuthority();
    final List<InetSocketAddress> addresses = Splitter.on(',').splitToList(authority).stream().map(host -> {
        final String[] strings = host.split(":");
        Preconditions.checkArgument(strings.length == 2, "URI should have both address and port");
        return InetSocketAddress.createUnresolved(strings[0], Integer.parseInt(strings[1]));
    }).collect(Collectors.toList());

    return new ControllerNameResolver(authority, addresses, SCHEME_DISCOVER.equals(scheme) || SCHEME_DISCOVER_TLS.equals(scheme), executor);
}
 
Example #12
Source File: KubernetesNameResolverProvider.java    From grpc-by-example-java with Apache License 2.0 6 votes vote down vote up
@Nullable
@Override
public NameResolver newNameResolver(URI targetUri, Attributes params) {
  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[] parts = targetPath.split("/");
    if (parts.length != 4) {
      throw new IllegalArgumentException("Must be formatted like kubernetes:///{namespace}/{service}/{port}");
    }

    try {
      int port = Integer.valueOf(parts[3]);
      return new KubernetesNameResolver(parts[1], parts[2], port, params, GrpcUtil.TIMER_SERVICE,
          GrpcUtil.SHARED_CHANNEL_EXECUTOR);
    } catch (NumberFormatException e) {
      throw new IllegalArgumentException("Unable to parse port number", e);
    }
  } else {
    return null;
  }
}
 
Example #13
Source File: SelfNameResolverFactory.java    From grpc-spring-boot-starter with MIT License 5 votes vote down vote up
@Override
public NameResolver newNameResolver(URI targetUri, Args args) {
    if (SELF_SCHEME.equals(targetUri.getScheme()) || targetUri.toString().equals(SELF_SCHEME)) {
        return new SelfNameResolver(this.properties, args);
    }
    return null;
}
 
Example #14
Source File: XdsExperimentalNameResolverProviderTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void validName_noAuthority() {
  NameResolver resolver =
      provider.newNameResolver(URI.create("xds-experimental:///foo.googleapis.com"), args);
  assertThat(resolver).isNotNull();
  assertThat(resolver.getServiceAuthority()).isEqualTo("foo.googleapis.com");
}
 
Example #15
Source File: FallbackResolverTest.java    From grpc-java-contrib with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void firstShouldFind() throws Exception {
    NameResolver fakeResolver = new FakeResolver();
    FakeResolverProvider canResolve = new FakeResolverProvider("aaa://", fakeResolver);
    FakeResolverProvider cannotResolve = new FakeResolverProvider("bbb://", null);

    NameResolver.Factory factory = FallbackResolver.startWith(canResolve).thenCheck(cannotResolve);

    assertEquals(fakeResolver, factory.newNameResolver(new URI("aaa://foo"), Attributes.EMPTY));
}
 
Example #16
Source File: ManagedChannelImplTest.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 (!expectedUris.contains(targetUri)) {
    return null;
  }
  assertEquals(DEFAULT_PORT, args.getDefaultPort());
  FakeNameResolverFactory.FakeNameResolver resolver =
      new FakeNameResolverFactory.FakeNameResolver(targetUri, error);
  resolvers.add(resolver);
  return resolver;
}
 
Example #17
Source File: GrpcNameResolverFactory.java    From micronaut-grpc with Apache License 2.0 5 votes vote down vote up
/**
 * A GRPC name resolver factory that integrates with Micronaut's discovery client.
 * @param discoveryClient The discovery client
 * @param serviceInstanceLists The service instance list
 * @return The name resolver
 */
@Singleton
@Requires(beans = DiscoveryClient.class)
@Requires(property = ENABLED, value = StringUtils.TRUE, defaultValue = StringUtils.FALSE)
protected NameResolver.Factory nameResolverFactory(
        DiscoveryClient discoveryClient,
        List<ServiceInstanceList> serviceInstanceLists) {
    return new GrpcNameResolverProvider(discoveryClient, serviceInstanceLists);
}
 
Example #18
Source File: GrpcClusterMembershipNameResolverFactory.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public NameResolver newNameResolver(URI targetUri, Attributes params) {
    Preconditions.checkState(!closed, "Name resolver already closed");

    return allocatedResolvers.computeIfAbsent(targetUri, uri -> {
        ClusterMemberResolver resolver = clusterMemberResolverProvider.apply(targetUri);
        return new Allocation(
                resolver,
                new GrpcClusterMembershipLeaderNameResolver(configuration, resolver, addressSelector)
        );
    }).getGrpcClusterMembershipLeaderNameResolver();
}
 
Example #19
Source File: DnsNameResolver.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
DnsNameResolver(@Nullable String nsAuthority, String name, Attributes params,
    Resource<Executor> executorResource, ProxyDetector proxyDetector,
    Stopwatch stopwatch, boolean isAndroid) {
  // TODO: if a DNS server is provided as nsAuthority, use it.
  // https://www.captechconsulting.com/blogs/accessing-the-dusty-corners-of-dns-with-java
  this.executorResource = executorResource;
  // Must prepend a "//" to the name when constructing a URI, otherwise it will be treated as an
  // opaque URI, thus the authority and host of the resulted URI would be null.
  URI nameUri = URI.create("//" + checkNotNull(name, "name"));
  Preconditions.checkArgument(nameUri.getHost() != null, "Invalid DNS name: %s", name);
  authority = Preconditions.checkNotNull(nameUri.getAuthority(),
      "nameUri (%s) doesn't have an authority", nameUri);
  host = nameUri.getHost();
  if (nameUri.getPort() == -1) {
    Integer defaultPort = params.get(NameResolver.Factory.PARAMS_DEFAULT_PORT);
    if (defaultPort != null) {
      port = defaultPort;
    } else {
      throw new IllegalArgumentException(
          "name '" + name + "' doesn't contain a port, and default port is not set in params");
    }
  } else {
    port = nameUri.getPort();
  }
  this.proxyDetector = proxyDetector;
  this.resolveRunnable = new Resolve(this, stopwatch, getNetworkAddressCacheTtlNanos(isAndroid));
}
 
Example #20
Source File: ClientCalls.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
/**
 * 获取Argument值
 *
 * @Author yuanzhonglin
 * @since 2019/4/8
 */
private static Object getArgument(NameResolver nameResolver) {
  String serviceName = null;
  if (nameResolver != null) {
    serviceName = nameResolver.getServiceName();
  }
  final Object argument = ConsistentHashArguments.getArgument(serviceName);
  if (argument != null) {
    ConsistentHashArguments.resetArgument(serviceName);
  }
  return argument;
}
 
Example #21
Source File: ClientCalls.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
/**
 * 重选服务器
 *
 * @Author yuanzhonglin
 * @since 2019/4/8
 */
private static void reelectServer(Channel channel, String fullMethod){
  NameResolver nameResolver = channel.getNameResolver();
  if (nameResolver instanceof ZookeeperNameResolver) {

    ZookeeperNameResolver zkResolver = (ZookeeperNameResolver) nameResolver;
    String method = GrpcUtils.getSimpleMethodName(fullMethod);
    if (LoadBalanceMode.connection.name().equals(
            LoadBalanceUtil.getLoadBalanceMode(nameResolver, method))) {

      zkResolver.resolveServerInfo(getArgument(nameResolver), method);
    }
  }
}
 
Example #22
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 #23
Source File: OverrideAuthorityNameResolverTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void overridesAuthority() {
  NameResolver nameResolverMock = mock(NameResolver.class);
  NameResolver.Factory wrappedFactory = mock(NameResolver.Factory.class);
  when(wrappedFactory.newNameResolver(any(URI.class), any(NameResolver.Args.class)))
      .thenReturn(nameResolverMock);
  String override = "override:5678";
  NameResolver.Factory factory =
      new OverrideAuthorityNameResolverFactory(wrappedFactory, override);
  NameResolver nameResolver = factory.newNameResolver(URI.create("dns:///localhost:443"), ARGS);
  assertNotNull(nameResolver);
  assertEquals(override, nameResolver.getServiceAuthority());
}
 
Example #24
Source File: StaticEtcdNameResolverFactory.java    From etcd-java with Apache License 2.0 5 votes vote down vote up
private SubResolver[] createSubResolvers(NameResolver.Args args) {
    int count = uris.length;
    SubResolver[] resolvers = new SubResolver[count];
    for (int i = 0; i < count; i++) {
        resolvers[i] = new SubResolver(uris[i], args);
    }
    return resolvers;
}
 
Example #25
Source File: AbstractManagedChannelImplBuilderTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Test
public void nameResolverFactory_null() {
  NameResolver.Factory defaultValue = builder.getNameResolverFactory();
  builder.nameResolverFactory(mock(NameResolver.Factory.class));
  assertEquals(builder, builder.nameResolverFactory(null));
  assertEquals(defaultValue, builder.getNameResolverFactory());
}
 
Example #26
Source File: AbstractManagedChannelImplBuilderTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("deprecation")
public void nameResolverFactory_normal() {
  NameResolver.Factory nameResolverFactory = mock(NameResolver.Factory.class);
  assertEquals(builder, builder.nameResolverFactory(nameResolverFactory));
  assertEquals(nameResolverFactory, builder.getNameResolverFactory());
}
 
Example #27
Source File: ForwardingNameResolverTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void allMethodsForwarded() throws Exception {
  ForwardingTestUtil.testMethodsForwarded(
      NameResolver.class,
      delegate,
      forwarder,
      Collections.<Method>emptyList());
}
 
Example #28
Source File: ManagedChannelImplGetNameResolverTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Override
public NameResolver newNameResolver(URI targetUri, Attributes params) {
  if (expectedScheme.equals(targetUri.getScheme())) {
    return new FakeNameResolver(targetUri);
  }
  return null;
}
 
Example #29
Source File: DnsNameResolverTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
private DnsNameResolver newResolver(
    String name,
    Stopwatch stopwatch,
    boolean isAndroid,
    NameResolver.Args args) {
  DnsNameResolver dnsResolver =
      new DnsNameResolver(
          null, name, args, fakeExecutorResource, stopwatch, isAndroid);
  // By default, using the mocked ResourceResolver to avoid I/O
  dnsResolver.setResourceResolver(new JndiResourceResolver(recordFetcher));
  return dnsResolver;
}
 
Example #30
Source File: OverrideAuthorityNameResolverTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Test
public void wontWrapNull() {
  NameResolver.Factory wrappedFactory = mock(NameResolver.Factory.class);
  when(wrappedFactory.newNameResolver(any(URI.class), any(Attributes.class))).thenReturn(null);
  NameResolver.Factory factory =
      new OverrideAuthorityNameResolverFactory(wrappedFactory, "override:5678");
  assertEquals(null,
      factory.newNameResolver(URI.create("dns:///localhost:443"), Attributes.EMPTY));
}