Skip to content

Commit

Permalink
Migrate users of ManagedChannelBuilder.{forTarget,forAddress} to Chan…
Browse files Browse the repository at this point in the history
…nelCredentials
  • Loading branch information
ejona86 committed Oct 7, 2020
1 parent f0ef2c2 commit 2076c4e
Show file tree
Hide file tree
Showing 9 changed files with 141 additions and 76 deletions.
Expand Up @@ -17,9 +17,12 @@
package io.grpc.android.integrationtest;

import android.support.annotation.Nullable;
import io.grpc.ChannelCredentials;
import io.grpc.Grpc;
import io.grpc.InsecureChannelCredentials;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.okhttp.OkHttpChannelBuilder;
import io.grpc.okhttp.SslSocketFactoryChannelCredentials;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.cert.CertificateFactory;
Expand All @@ -40,21 +43,23 @@ public static ManagedChannel build(
@Nullable String serverHostOverride,
boolean useTls,
@Nullable InputStream testCa) {
ManagedChannelBuilder<?> channelBuilder = ManagedChannelBuilder.forAddress(host, port)
.maxInboundMessageSize(16 * 1024 * 1024);
if (serverHostOverride != null) {
// Force the hostname to match the cert the server uses.
channelBuilder.overrideAuthority(serverHostOverride);
}
ChannelCredentials credentials;
if (useTls) {
try {
((OkHttpChannelBuilder) channelBuilder).useTransportSecurity();
((OkHttpChannelBuilder) channelBuilder).sslSocketFactory(getSslSocketFactory(testCa));
credentials = SslSocketFactoryChannelCredentials.create(getSslSocketFactory(testCa));
} catch (Exception e) {
throw new RuntimeException(e);
}
} else {
channelBuilder.usePlaintext();
credentials = InsecureChannelCredentials.create();
}

ManagedChannelBuilder<?> channelBuilder = Grpc.newChannelBuilderForAddress(
host, port, credentials)
.maxInboundMessageSize(16 * 1024 * 1024);
if (serverHostOverride != null) {
// Force the hostname to match the cert the server uses.
channelBuilder.overrideAuthority(serverHostOverride);
}
return channelBuilder.build();
}
Expand Down
Expand Up @@ -17,8 +17,9 @@
package io.grpc.testing.integration;

import com.google.protobuf.ByteString;
import io.grpc.Grpc;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.TlsChannelCredentials;
import io.grpc.testing.integration.Messages.Payload;
import io.grpc.testing.integration.Messages.SimpleRequest;
import io.grpc.testing.integration.Messages.SimpleResponse;
Expand All @@ -40,7 +41,7 @@
public final class LongLivedChannel extends HttpServlet {
private static final String INTEROP_TEST_ADDRESS = "grpc-test.sandbox.googleapis.com:443";
private final ManagedChannel channel =
ManagedChannelBuilder.forTarget(INTEROP_TEST_ADDRESS).build();
Grpc.newChannelBuilder(INTEROP_TEST_ADDRESS, TlsChannelCredentials.create()).build();

@Override
public void destroy() {
Expand Down
Expand Up @@ -19,7 +19,9 @@
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import io.grpc.Grpc;
import io.grpc.ManagedChannelBuilder;
import io.grpc.TlsChannelCredentials;
import io.grpc.netty.NettyChannelBuilder;
import java.io.IOException;
import java.io.PrintWriter;
Expand Down Expand Up @@ -131,7 +133,7 @@ protected ManagedChannelBuilder<?> createChannelBuilder() {
"1.8",
System.getProperty("java.specification.version"));
ManagedChannelBuilder<?> builder =
ManagedChannelBuilder.forTarget(INTEROP_TEST_ADDRESS)
Grpc.newChannelBuilder(INTEROP_TEST_ADDRESS, TlsChannelCredentials.create())
.maxInboundMessageSize(AbstractInteropTest.MAX_MESSAGE_SIZE);
assertTrue(builder instanceof NettyChannelBuilder);
((NettyChannelBuilder) builder)
Expand Down
Expand Up @@ -18,26 +18,30 @@

import com.google.common.annotations.VisibleForTesting;
import com.google.common.io.Files;
import io.grpc.ChannelCredentials;
import io.grpc.Grpc;
import io.grpc.InsecureChannelCredentials;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.alts.AltsChannelBuilder;
import io.grpc.alts.ComputeEngineChannelBuilder;
import io.grpc.alts.GoogleDefaultChannelBuilder;
import io.grpc.TlsChannelCredentials;
import io.grpc.alts.AltsChannelCredentials;
import io.grpc.alts.ComputeEngineChannelCredentials;
import io.grpc.alts.GoogleDefaultChannelCredentials;
import io.grpc.internal.GrpcUtil;
import io.grpc.internal.testing.TestUtils;
import io.grpc.netty.GrpcSslContexts;
import io.grpc.netty.InsecureFromHttp1ChannelCredentials;
import io.grpc.netty.InternalNettyChannelBuilder;
import io.grpc.netty.NegotiationType;
import io.grpc.netty.NettyChannelBuilder;
import io.grpc.netty.NettySslContextChannelCredentials;
import io.grpc.okhttp.InternalOkHttpChannelBuilder;
import io.grpc.okhttp.OkHttpChannelBuilder;
import io.grpc.okhttp.SslSocketFactoryChannelCredentials;
import io.grpc.okhttp.internal.Platform;
import io.netty.handler.ssl.SslContext;
import java.io.File;
import java.io.FileInputStream;
import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.SSLSocketFactory;

/**
* Application that starts a client for the {@link TestServiceGrpc.TestServiceImplBase} and runs
Expand Down Expand Up @@ -282,8 +286,8 @@ private void runTest(TestCases testCase) throws Exception {
break;

case COMPUTE_ENGINE_CHANNEL_CREDENTIALS: {
ManagedChannel channel = ComputeEngineChannelBuilder
.forAddress(serverHost, serverPort).build();
ManagedChannel channel = Grpc.newChannelBuilderForAddress(
serverHost, serverPort, ComputeEngineChannelCredentials.create()).build();
try {
TestServiceGrpc.TestServiceBlockingStub computeEngineStub =
TestServiceGrpc.newBlockingStub(channel);
Expand Down Expand Up @@ -323,8 +327,8 @@ private void runTest(TestCases testCase) throws Exception {
}

case GOOGLE_DEFAULT_CREDENTIALS: {
ManagedChannel channel = GoogleDefaultChannelBuilder.forAddress(
serverHost, serverPort).build();
ManagedChannel channel = Grpc.newChannelBuilderForAddress(
serverHost, serverPort, GoogleDefaultChannelCredentials.create()).build();
try {
TestServiceGrpc.TestServiceBlockingStub googleDefaultStub =
TestServiceGrpc.newBlockingStub(channel);
Expand Down Expand Up @@ -392,34 +396,56 @@ private void runTest(TestCases testCase) throws Exception {
private class Tester extends AbstractInteropTest {
@Override
protected ManagedChannelBuilder<?> createChannelBuilder() {
if (customCredentialsType != null
&& customCredentialsType.equals("google_default_credentials")) {
return GoogleDefaultChannelBuilder.forAddress(serverHost, serverPort);
}
if (customCredentialsType != null
&& customCredentialsType.equals("compute_engine_channel_creds")) {
return ComputeEngineChannelBuilder.forAddress(serverHost, serverPort);
}
if (useAlts) {
return AltsChannelBuilder.forAddress(serverHost, serverPort);
}
ChannelCredentials channelCredentials;
if (customCredentialsType != null) {
useOkHttp = false; // Retain old behavior; avoids erroring if incompatible
if (customCredentialsType.equals("google_default_credentials")) {
channelCredentials = GoogleDefaultChannelCredentials.create();
} else if (customCredentialsType.equals("compute_engine_channel_creds")) {
channelCredentials = ComputeEngineChannelCredentials.create();
} else {
throw new IllegalArgumentException(
"Unknown custom credentials: " + customCredentialsType);
}

if (!useOkHttp) {
SslContext sslContext = null;
if (useTestCa) {
} else if (useAlts) {
useOkHttp = false; // Retain old behavior; avoids erroring if incompatible
channelCredentials = AltsChannelCredentials.create();

} else if (useTls) {
if (!useTestCa) {
channelCredentials = TlsChannelCredentials.create();
} else {
try {
sslContext = GrpcSslContexts.forClient().trustManager(
TestUtils.loadCert("ca.pem")).build();
if (useOkHttp) {
channelCredentials = SslSocketFactoryChannelCredentials.create(
TestUtils.newSslSocketFactoryForCa(
Platform.get().getProvider(), TestUtils.loadCert("ca.pem")));
} else {
channelCredentials = NettySslContextChannelCredentials.create(
GrpcSslContexts.forClient().trustManager(
TestUtils.loadCert("ca.pem")).build());
}
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}

} else {
if (useH2cUpgrade) {
if (useOkHttp) {
throw new IllegalArgumentException("OkHttp does not support HTTP/1 upgrade");
} else {
channelCredentials = InsecureFromHttp1ChannelCredentials.create();
}
} else {
channelCredentials = InsecureChannelCredentials.create();
}
}
if (!useOkHttp) {
NettyChannelBuilder nettyBuilder =
NettyChannelBuilder.forAddress(serverHost, serverPort)
.flowControlWindow(AbstractInteropTest.TEST_FLOW_CONTROL_WINDOW)
.negotiationType(useTls ? NegotiationType.TLS :
(useH2cUpgrade ? NegotiationType.PLAINTEXT_UPGRADE : NegotiationType.PLAINTEXT))
.sslContext(sslContext);
NettyChannelBuilder.forAddress(serverHost, serverPort, channelCredentials)
.flowControlWindow(AbstractInteropTest.TEST_FLOW_CONTROL_WINDOW);
if (serverHostOverride != null) {
nettyBuilder.overrideAuthority(serverHostOverride);
}
Expand All @@ -431,25 +457,13 @@ protected ManagedChannelBuilder<?> createChannelBuilder() {
return nettyBuilder.intercept(createCensusStatsClientInterceptor());
}

OkHttpChannelBuilder okBuilder = OkHttpChannelBuilder.forAddress(serverHost, serverPort);
OkHttpChannelBuilder okBuilder =
OkHttpChannelBuilder.forAddress(serverHost, serverPort, channelCredentials);
if (serverHostOverride != null) {
// Force the hostname to match the cert the server uses.
okBuilder.overrideAuthority(
GrpcUtil.authorityFromHostAndPort(serverHostOverride, serverPort));
}
if (useTls) {
if (useTestCa) {
try {
SSLSocketFactory factory = TestUtils.newSslSocketFactoryForCa(
Platform.get().getProvider(), TestUtils.loadCert("ca.pem"));
okBuilder.sslSocketFactory(factory);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
} else {
okBuilder.usePlaintext();
}
if (fullStreamDecompression) {
okBuilder.enableFullStreamDecompression();
}
Expand Down
Expand Up @@ -35,8 +35,9 @@
import io.grpc.DecompressorRegistry;
import io.grpc.ForwardingClientCall.SimpleForwardingClientCall;
import io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener;
import io.grpc.Grpc;
import io.grpc.InsecureChannelCredentials;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.Metadata;
import io.grpc.MethodDescriptor;
import io.grpc.Server;
Expand Down Expand Up @@ -189,11 +190,11 @@ public void compression() throws Exception {
.build()
.start();

channel = ManagedChannelBuilder.forAddress("localhost", server.getPort())
channel = Grpc.newChannelBuilder(
"localhost:" + server.getPort(), InsecureChannelCredentials.create())
.decompressorRegistry(clientDecompressors)
.compressorRegistry(clientCompressors)
.intercept(new ClientCompressorInterceptor())
.usePlaintext()
.build();
stub = TestServiceGrpc.newBlockingStub(channel);

Expand Down
@@ -0,0 +1,36 @@
/*
* Copyright 2020 The gRPC Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package io.grpc.testing.integration;

import io.grpc.ManagedChannelBuilder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Tests for integration between {@link ManagedChannelBuilder} and providers. */
@RunWith(JUnit4.class)
public final class ManagedChannelBuilderSpiTest {
@Test
public void forAddress_isntObviouslyBroken() {
ManagedChannelBuilder.forAddress("localhost", 443).build().shutdownNow();
}

@Test
public void forTarget_isntObviouslyBroken() {
ManagedChannelBuilder.forTarget("localhost:443").build().shutdownNow();
}
}
Expand Up @@ -22,8 +22,9 @@
import static org.junit.Assert.assertTrue;

import com.google.common.collect.ImmutableList;
import io.grpc.Grpc;
import io.grpc.InsecureChannelCredentials;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.testing.integration.Metrics.EmptyMessage;
import io.grpc.testing.integration.Metrics.GaugeResponse;
import io.grpc.testing.integration.StressTestClient.TestCaseWeightPair;
Expand Down Expand Up @@ -128,8 +129,8 @@ public void gaugesShouldBeExported() throws Exception {
client.runStressTest();

// Connect to the metrics service
ManagedChannel ch = ManagedChannelBuilder.forAddress("localhost", client.getMetricServerPort())
.usePlaintext()
ManagedChannel ch = Grpc.newChannelBuilder(
"localhost:" + client.getMetricServerPort(), InsecureChannelCredentials.create())
.build();

MetricsServiceGrpc.MetricsServiceBlockingStub stub = MetricsServiceGrpc.newBlockingStub(ch);
Expand Down
21 changes: 12 additions & 9 deletions xds/src/main/java/io/grpc/xds/XdsChannelFactory.java
Expand Up @@ -17,9 +17,12 @@
package io.grpc.xds;

import com.google.common.annotations.VisibleForTesting;
import io.grpc.ChannelCredentials;
import io.grpc.Grpc;
import io.grpc.InsecureChannelCredentials;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.alts.GoogleDefaultChannelBuilder;
import io.grpc.TlsChannelCredentials;
import io.grpc.alts.GoogleDefaultChannelCredentials;
import io.grpc.xds.Bootstrapper.ChannelCreds;
import io.grpc.xds.Bootstrapper.ServerInfo;
import io.grpc.xds.XdsClient.XdsChannel;
Expand Down Expand Up @@ -50,33 +53,33 @@ XdsChannel createChannel(List<ServerInfo> servers) throws XdsInitializationExcep
String serverUri = serverInfo.getServerUri();
logger.log(XdsLogLevel.INFO, "Creating channel to {0}", serverUri);
List<ChannelCreds> channelCredsList = serverInfo.getChannelCredentials();
ManagedChannelBuilder<?> channelBuilder = null;
ChannelCredentials channelCreds = null;
// Use the first supported channel credentials configuration.
for (ChannelCreds creds : channelCredsList) {
switch (creds.getType()) {
case "google_default":
logger.log(XdsLogLevel.INFO, "Using channel credentials: google_default");
channelBuilder = GoogleDefaultChannelBuilder.forTarget(serverUri);
channelCreds = GoogleDefaultChannelCredentials.create();
break;
case "insecure":
logger.log(XdsLogLevel.INFO, "Using channel credentials: insecure");
channelBuilder = ManagedChannelBuilder.forTarget(serverUri).usePlaintext();
channelCreds = InsecureChannelCredentials.create();
break;
case "tls":
logger.log(XdsLogLevel.INFO, "Using channel credentials: tls");
channelBuilder = ManagedChannelBuilder.forTarget(serverUri);
channelCreds = TlsChannelCredentials.create();
break;
default:
}
if (channelBuilder != null) {
if (channelCreds != null) {
break;
}
}
if (channelBuilder == null) {
if (channelCreds == null) {
throw new XdsInitializationException("No server with supported channel creds found");
}

ManagedChannel channel = channelBuilder
ManagedChannel channel = Grpc.newChannelBuilder(serverUri, channelCreds)
.keepAliveTime(5, TimeUnit.MINUTES)
.build();
boolean useProtocolV3 = experimentalV3SupportEnvVar
Expand Down

0 comments on commit 2076c4e

Please sign in to comment.