Java Code Examples for io.grpc.netty.GrpcSslContexts#forClient()

The following examples show how to use io.grpc.netty.GrpcSslContexts#forClient() . 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: HelloWorldClientTls.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
private static SslContext buildSslContext(String trustCertCollectionFilePath,
                                          String clientCertChainFilePath,
                                          String clientPrivateKeyFilePath) throws SSLException {
    SslContextBuilder builder = GrpcSslContexts.forClient();
    if (trustCertCollectionFilePath != null) {
        builder.trustManager(new File(trustCertCollectionFilePath));
    }
    if (clientCertChainFilePath != null && clientPrivateKeyFilePath != null) {
        builder.keyManager(new File(clientCertChainFilePath), new File(clientPrivateKeyFilePath));
    }
    return builder.build();
}
 
Example 2
Source File: LoadBalancedClusterMessageSender.java    From txle with Apache License 2.0 6 votes vote down vote up
private static SslContext buildSslContext(AlphaClusterConfig clusterConfig) throws SSLException {
  SslContextBuilder builder = GrpcSslContexts.forClient();
  // openssl must be used because some older JDk does not support cipher suites required by http2,
  // and the performance of JDK ssl is pretty low compared to openssl.
  builder.sslProvider(SslProvider.OPENSSL);

  Properties prop = new Properties();
  try {
    prop.load(LoadBalancedClusterMessageSender.class.getClassLoader().getResourceAsStream("ssl.properties"));
  } catch (IOException e) {
    throw new IllegalArgumentException("Unable to read ssl.properties.", e);
  }

  builder.protocols(prop.getProperty("protocols").split(","));
  builder.ciphers(Arrays.asList(prop.getProperty("ciphers").split(",")));
  builder.trustManager(new File(clusterConfig.getCertChain()));

  if (clusterConfig.isEnableMutualAuth()) {
    builder.keyManager(new File(clusterConfig.getCert()), new File(clusterConfig.getKey()));
  }

  return builder.build();
}
 
Example 3
Source File: RemoteSignatureSource.java    From compass with GNU Affero General Public License v3.0 5 votes vote down vote up
private static SslContext buildSslContext(
    String trustCertCollectionFilePath,
    String clientCertChainFilePath,
    String clientPrivateKeyFilePath) throws SSLException {
  SslContextBuilder builder = GrpcSslContexts.forClient();
  if (trustCertCollectionFilePath != null) {
    builder.trustManager(new File(trustCertCollectionFilePath));
  }
  if (clientCertChainFilePath != null && !clientCertChainFilePath.isEmpty()
      && clientPrivateKeyFilePath != null && !clientPrivateKeyFilePath.isEmpty()) {
    builder.keyManager(new File(clientCertChainFilePath), new File(clientPrivateKeyFilePath));
  }
  return builder.build();
}
 
Example 4
Source File: HelloWorldTlsServiceTest.java    From quarkus-quickstarts with Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void init() throws SSLException {
    SslContextBuilder builder = GrpcSslContexts.forClient();
    builder.trustManager(new File("src/main/resources/tls/ca.pem"));
    SslContext context = builder.build();

    channel = NettyChannelBuilder.forAddress("localhost", 9000)
            .sslContext(context)
            .build();
}
 
Example 5
Source File: HelloWorldMutualTlsServiceTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void init() throws SSLException {
    SslContextBuilder builder = GrpcSslContexts.forClient();
    builder.trustManager(new File("src/main/resources/tls/ca.pem"));
    builder.keyManager(new File("src/main/resources/tls/client.pem"),
            new File("src/main/resources/tls/client.key"));
    SslContext context = builder.build();

    channel = NettyChannelBuilder.forAddress("localhost", 9000)
            .sslContext(context)
            .build();
}
 
Example 6
Source File: HelloWorldTlsServiceTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void init() throws SSLException {
    SslContextBuilder builder = GrpcSslContexts.forClient();
    builder.trustManager(new File("src/main/resources/tls/ca.pem"));
    SslContext context = builder.build();

    channel = NettyChannelBuilder.forAddress("localhost", 9000)
            .sslContext(context)
            .build();
}
 
Example 7
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 channelBuilder The channel builder to connect to the service instance.
 * @param config         The configuration for this client implementation.
 * @param executor       The executor service to be used internally.
 */
@VisibleForTesting
public ControllerImpl(ManagedChannelBuilder<?> channelBuilder, final ControllerImplConfig config,
                      final ScheduledExecutorService executor) {
    Preconditions.checkNotNull(channelBuilder, "channelBuilder");
    this.executor = executor;
    this.retryConfig = createRetryConfig(config);

    if (config.getClientConfig().isEnableTlsToController()) {
        log.debug("Setting up a SSL/TLS channel builder");
        SslContextBuilder sslContextBuilder;
        String trustStore = config.getClientConfig().getTrustStore();
        sslContextBuilder = GrpcSslContexts.forClient();
        if (!Strings.isNullOrEmpty(trustStore)) {
            sslContextBuilder = sslContextBuilder.trustManager(new File(trustStore));
        }
        try {
            channelBuilder = ((NettyChannelBuilder) channelBuilder).sslContext(sslContextBuilder.build())
                                                                   .negotiationType(NegotiationType.TLS);
        } catch (SSLException e) {
            throw new CompletionException(e);
        }
    } else {
        log.debug("Using a plaintext channel builder");
        channelBuilder = ((NettyChannelBuilder) channelBuilder).negotiationType(NegotiationType.PLAINTEXT);
    }

    // Trace channel.
    channelBuilder = channelBuilder.intercept(RPCTracingHelpers.getClientInterceptor());

    // Create Async RPC client.
    this.channel = channelBuilder.build();
    this.client = getClientWithCredentials(config);
    this.timeoutMillis = config.getTimeoutMillis();
}
 
Example 8
Source File: TLSChannelBuilder.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@Override
public NettyChannelBuilder build(
    NettyChannelBuilder managedChannelBuilder) throws AgentPackageNotFoundException, SSLException {
    File caFile = new File(AgentPackagePath.getPath(), CA_FILE_NAME);
    if (caFile.exists() && caFile.isFile()) {
        SslContextBuilder builder = GrpcSslContexts.forClient();
        builder.trustManager(caFile);
        managedChannelBuilder = managedChannelBuilder.negotiationType(NegotiationType.TLS)
                                                     .sslContext(builder.build());
    }
    return managedChannelBuilder;
}
 
Example 9
Source File: HelloWorldClientTls.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
private static SslContext buildSslContext(String trustCertCollectionFilePath,
                                          String clientCertChainFilePath,
                                          String clientPrivateKeyFilePath) throws SSLException {
    SslContextBuilder builder = GrpcSslContexts.forClient();
    if (trustCertCollectionFilePath != null) {
        builder.trustManager(new File(trustCertCollectionFilePath));
    }
    if (clientCertChainFilePath != null && clientPrivateKeyFilePath != null) {
        builder.keyManager(new File(clientCertChainFilePath), new File(clientPrivateKeyFilePath));
    }
    return builder.build();
}
 
Example 10
Source File: EtcdClient.java    From etcd-java with Apache License 2.0 4 votes vote down vote up
private SslContextBuilder sslBuilder() {
    return sslContextBuilder != null ? sslContextBuilder
            : (sslContextBuilder = GrpcSslContexts.forClient());
}
 
Example 11
Source File: Channels.java    From quarkus with Apache License 2.0 4 votes vote down vote up
public static Channel createChannel(String name) throws SSLException {
    InstanceHandle<GrpcClientConfigProvider> instance = Arc.container().instance(GrpcClientConfigProvider.class);

    if (!instance.isAvailable()) {
        throw new IllegalStateException("Unable to find the GrpcClientConfigProvider");
    }

    GrpcClientConfiguration config = instance.get().getConfiguration(name);
    String host = config.host;
    int port = config.port;
    boolean plainText = !config.ssl.trustStore.isPresent();
    Optional<Boolean> usePlainText = config.plainText;
    if (usePlainText.isPresent()) {
        plainText = usePlainText.get();
    }

    SslContext context = null;
    if (!plainText) {
        Path trustStorePath = config.ssl.trustStore.orElse(null);
        Path certificatePath = config.ssl.certificate.orElse(null);
        Path keyPath = config.ssl.key.orElse(null);
        SslContextBuilder sslContextBuilder = GrpcSslContexts.forClient();
        if (trustStorePath != null) {
            sslContextBuilder.trustManager(trustStorePath.toFile());
        }

        if (certificatePath != null && keyPath != null) {
            sslContextBuilder.keyManager(certificatePath.toFile(), keyPath.toFile());
        }

        context = sslContextBuilder.build();
    }

    NettyChannelBuilder builder = NettyChannelBuilder.forAddress(host, port)
            .flowControlWindow(config.flowControlWindow.orElse(DEFAULT_FLOW_CONTROL_WINDOW))
            .keepAliveWithoutCalls(config.keepAliveWithoutCalls)
            .maxHedgedAttempts(config.maxHedgedAttempts)
            .maxRetryAttempts(config.maxRetryAttempts)
            .maxInboundMetadataSize(config.maxInboundMessageSize.orElse(DEFAULT_MAX_HEADER_LIST_SIZE))
            .maxInboundMetadataSize(config.maxInboundMessageSize.orElse(DEFAULT_MAX_MESSAGE_SIZE))
            .negotiationType(NegotiationType.valueOf(config.negotiationType.toUpperCase()));

    if (config.retry) {
        builder.enableRetry();
    } else {
        builder.disableRetry();
    }

    if (config.maxTraceEvents.isPresent()) {
        builder.maxTraceEvents(config.maxTraceEvents.getAsInt());
    }
    Optional<String> userAgent = config.userAgent;
    if (userAgent.isPresent()) {
        builder.userAgent(userAgent.get());
    }
    if (config.retryBufferSize.isPresent()) {
        builder.retryBufferSize(config.retryBufferSize.getAsLong());
    }
    if (config.perRpcBufferLimit.isPresent()) {
        builder.perRpcBufferLimit(config.perRpcBufferLimit.getAsLong());
    }
    Optional<String> overrideAuthority = config.overrideAuthority;
    if (overrideAuthority.isPresent()) {
        builder.overrideAuthority(overrideAuthority.get());
    }
    Optional<Duration> keepAliveTime = config.keepAliveTime;
    if (keepAliveTime.isPresent()) {
        builder.keepAliveTime(keepAliveTime.get().toMillis(), TimeUnit.MILLISECONDS);
    }
    Optional<Duration> keepAliveTimeout = config.keepAliveTimeout;
    if (keepAliveTimeout.isPresent()) {
        builder.keepAliveTimeout(keepAliveTimeout.get().toMillis(), TimeUnit.MILLISECONDS);
    }
    Optional<Duration> idleTimeout = config.idleTimeout;
    if (idleTimeout.isPresent()) {
        builder.keepAliveTimeout(idleTimeout.get().toMillis(), TimeUnit.MILLISECONDS);
    }

    if (plainText) {
        builder.usePlaintext();
    }
    if (context != null) {
        builder.sslContext(context);
    }

    // Client-side interceptors
    Instance<ClientInterceptor> interceptors = Arc.container().beanManager().createInstance()
            .select(ClientInterceptor.class);
    for (ClientInterceptor clientInterceptor : getSortedInterceptors(interceptors)) {
        builder.intercept(clientInterceptor);
    }

    return builder.build();
}
 
Example 12
Source File: CentralConnection.java    From glowroot with Apache License 2.0 4 votes vote down vote up
CentralConnection(String collectorAddress, @Nullable String collectorAuthority,
        List<File> confDirs, AtomicBoolean inConnectionFailure) throws SSLException {
    ParsedCollectorAddress parsedCollectorAddress = parseCollectorAddress(collectorAddress);
    eventLoopGroup = EventLoopGroups.create("Glowroot-GRPC-Worker-ELG");
    channelExecutor =
            Executors.newSingleThreadExecutor(ThreadFactories.create("Glowroot-GRPC-Executor"));
    NettyChannelBuilder builder;
    if (parsedCollectorAddress.targets().size() == 1) {
        CollectorTarget target = parsedCollectorAddress.targets().get(0);
        builder = NettyChannelBuilder.forAddress(target.host(), target.port());
        if (collectorAuthority != null) {
            builder.overrideAuthority(collectorAuthority);
        }
    } else {
        // this connection mechanism may be deprecated in the future in favor resolving a single
        // address to multiple collectors via DNS (above)
        String authority;
        if (collectorAuthority != null) {
            authority = collectorAuthority;
        } else if (!parsedCollectorAddress.https()) {
            authority = "dummy-service-authority";
        } else {
            throw new IllegalStateException("collector.authority is required when connecting"
                    + " over HTTPS to a comma-separated list of glowroot central collectors");
        }
        builder = NettyChannelBuilder.forTarget("dummy-target")
                .nameResolverFactory(new MultipleAddressNameResolverFactory(
                        parsedCollectorAddress.targets(), authority));
    }
    // single address may resolve to multiple collectors above via DNS, so need to specify round
    // robin here even if only single address (first part of conditional above)
    builder.loadBalancerFactory(RoundRobinLoadBalancerFactory.getInstance())
            .eventLoopGroup(eventLoopGroup)
            .executor(channelExecutor)
            // aggressive keep alive, shouldn't even be used since gauge data is sent every
            // 5 seconds and keep alive will only kick in after 10 seconds of not hearing back
            // from the server
            .keepAliveTime(10, SECONDS);
    if (parsedCollectorAddress.https()) {
        SslContextBuilder sslContext = GrpcSslContexts.forClient();
        File trustCertCollectionFile = getTrustCertCollectionFile(confDirs);
        if (trustCertCollectionFile != null) {
            sslContext.trustManager(trustCertCollectionFile);
        }
        channel = builder.sslContext(sslContext.build())
                .negotiationType(NegotiationType.TLS)
                .build();
    } else {
        channel = builder.negotiationType(NegotiationType.PLAINTEXT)
                .build();
    }
    retryExecutor = Executors.newSingleThreadScheduledExecutor(
            ThreadFactories.create("Glowroot-Collector-Retry"));
    this.inConnectionFailure = inConnectionFailure;
    this.collectorAddress = collectorAddress;
}
 
Example 13
Source File: InvokeGRPC.java    From nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Whenever this processor is triggered, we need to construct a client in order to communicate
 * with the configured gRPC service.
 *
 * @param context the processor context
 */
@OnScheduled
public void initializeClient(final ProcessContext context) throws Exception {

    channelReference.set(null);
    blockingStubReference.set(null);
    final ComponentLog logger = getLogger();

    final String host = context.getProperty(PROP_SERVICE_HOST).getValue();
    final int port = context.getProperty(PROP_SERVICE_PORT).asInteger();
    final Integer maxMessageSize = context.getProperty(PROP_MAX_MESSAGE_SIZE).asDataSize(DataUnit.B).intValue();
    String userAgent = USER_AGENT_PREFIX;
    try {
        userAgent += "_" + InetAddress.getLocalHost().getHostName();
    } catch (final UnknownHostException e) {
        logger.warn("Unable to determine local hostname. Defaulting gRPC user agent to {}.", new Object[]{USER_AGENT_PREFIX}, e);
    }

    final NettyChannelBuilder nettyChannelBuilder = NettyChannelBuilder.forAddress(host, port)
            // supports both gzip and plaintext, but will compress by default.
            .compressorRegistry(CompressorRegistry.getDefaultInstance())
            .decompressorRegistry(DecompressorRegistry.getDefaultInstance())
            .maxInboundMessageSize(maxMessageSize)
            .userAgent(userAgent);

    // configure whether or not we're using secure comms
    final boolean useSecure = context.getProperty(PROP_USE_SECURE).asBoolean();
    final SSLContextService sslContextService = context.getProperty(PROP_SSL_CONTEXT_SERVICE).asControllerService(SSLContextService.class);
    final SSLContext sslContext = sslContextService == null ? null : sslContextService.createSSLContext(SslContextFactory.ClientAuth.NONE);

    if (useSecure && sslContext != null) {
        SslContextBuilder sslContextBuilder = GrpcSslContexts.forClient();
        if(StringUtils.isNotBlank(sslContextService.getKeyStoreFile())) {
            final KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm(),
                    sslContext.getProvider());
            final KeyStore keyStore = KeyStore.getInstance(sslContextService.getKeyStoreType());
            try (final InputStream is = new FileInputStream(sslContextService.getKeyStoreFile())) {
                keyStore.load(is, sslContextService.getKeyStorePassword().toCharArray());
            }
            keyManagerFactory.init(keyStore, sslContextService.getKeyStorePassword().toCharArray());
            sslContextBuilder.keyManager(keyManagerFactory);
        }

        if(StringUtils.isNotBlank(sslContextService.getTrustStoreFile())) {
            final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm(),
                    sslContext.getProvider());
            final KeyStore trustStore = KeyStore.getInstance(sslContextService.getTrustStoreType());
            try (final InputStream is = new FileInputStream(sslContextService.getTrustStoreFile())) {
                trustStore.load(is, sslContextService.getTrustStorePassword().toCharArray());
            }
            trustManagerFactory.init(trustStore);
            sslContextBuilder.trustManager(trustManagerFactory);
        }
        nettyChannelBuilder.sslContext(sslContextBuilder.build());

    } else {
        nettyChannelBuilder.usePlaintext(true);
    }

    final ManagedChannel channel = nettyChannelBuilder.build();
    final FlowFileServiceGrpc.FlowFileServiceBlockingStub blockingStub = FlowFileServiceGrpc.newBlockingStub(channel);
    channelReference.set(channel);
    blockingStubReference.set(blockingStub);
}
 
Example 14
Source File: ClientBuilder.java    From jetcd with Apache License 2.0 3 votes vote down vote up
/**
 * Configure SSL/TLS context create through {@link GrpcSslContexts#forClient} to use.
 *
 * @param  consumer     the SslContextBuilder consumer
 * @return              this builder
 * @throws SSLException if the SslContextBuilder fails
 */
public ClientBuilder sslContext(Consumer<SslContextBuilder> consumer) throws SSLException {
    SslContextBuilder builder = GrpcSslContexts.forClient();
    consumer.accept(builder);

    return sslContext(builder.build());
}