github.com/hxx258456/ccgo@v0.0.5-0.20230213014102-48b35f46f66f/grpc/interop/client/client.go (about) 1 /* 2 * 3 * Copyright 2014 gRPC authors. 4 * 5 * Licensed under the Apache License, Version 2.0 (the "License"); 6 * you may not use this file except in compliance with the License. 7 * You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 * 17 */ 18 19 // Binary client is an interop client. 20 package main 21 22 import ( 23 "flag" 24 "io/ioutil" 25 "net" 26 "strconv" 27 "time" 28 29 "github.com/hxx258456/ccgo/x509" 30 31 tls "github.com/hxx258456/ccgo/gmtls" 32 33 grpc "github.com/hxx258456/ccgo/grpc" 34 _ "github.com/hxx258456/ccgo/grpc/balancer/grpclb" 35 "github.com/hxx258456/ccgo/grpc/credentials" 36 "github.com/hxx258456/ccgo/grpc/credentials/alts" 37 "github.com/hxx258456/ccgo/grpc/credentials/google" 38 "github.com/hxx258456/ccgo/grpc/credentials/oauth" 39 "github.com/hxx258456/ccgo/grpc/grpclog" 40 "github.com/hxx258456/ccgo/grpc/interop" 41 "github.com/hxx258456/ccgo/grpc/resolver" 42 "github.com/hxx258456/ccgo/grpc/testdata" 43 _ "github.com/hxx258456/ccgo/grpc/xds/googledirectpath" 44 45 testgrpc "github.com/hxx258456/ccgo/grpc/interop/grpc_testing" 46 ) 47 48 const ( 49 googleDefaultCredsName = "google_default_credentials" 50 computeEngineCredsName = "compute_engine_channel_creds" 51 ) 52 53 var ( 54 caFile = flag.String("ca_file", "", "The file containning the CA root cert file") 55 useTLS = flag.Bool("use_tls", false, "Connection uses TLS if true") 56 useALTS = flag.Bool("use_alts", false, "Connection uses ALTS if true (this option can only be used on GCP)") 57 customCredentialsType = flag.String("custom_credentials_type", "", "Custom creds to use, excluding TLS or ALTS") 58 altsHSAddr = flag.String("alts_handshaker_service_address", "", "ALTS handshaker gRPC service address") 59 testCA = flag.Bool("use_test_ca", false, "Whether to replace platform root CAs with test CA as the CA root") 60 serviceAccountKeyFile = flag.String("service_account_key_file", "", "Path to service account json key file") 61 oauthScope = flag.String("oauth_scope", "", "The scope for OAuth2 tokens") 62 defaultServiceAccount = flag.String("default_service_account", "", "Email of GCE default service account") 63 serverHost = flag.String("server_host", "localhost", "The server host name") 64 serverPort = flag.Int("server_port", 10000, "The server port number") 65 serviceConfigJSON = flag.String("service_config_json", "", "Disables service config lookups and sets the provided string as the default service config.") 66 soakIterations = flag.Int("soak_iterations", 10, "The number of iterations to use for the two soak tests: rpc_soak and channel_soak") 67 soakMaxFailures = flag.Int("soak_max_failures", 0, "The number of iterations in soak tests that are allowed to fail (either due to non-OK status code or exceeding the per-iteration max acceptable latency).") 68 soakPerIterationMaxAcceptableLatencyMs = flag.Int("soak_per_iteration_max_acceptable_latency_ms", 1000, "The number of milliseconds a single iteration in the two soak tests (rpc_soak and channel_soak) should take.") 69 soakOverallTimeoutSeconds = flag.Int("soak_overall_timeout_seconds", 10, "The overall number of seconds after which a soak test should stop and fail, if the desired number of iterations have not yet completed.") 70 tlsServerName = flag.String("server_host_override", "", "The server name used to verify the hostname returned by TLS handshake if it is not empty. Otherwise, --server_host is used.") 71 testCase = flag.String("test_case", "large_unary", 72 `Configure different test cases. Valid options are: 73 empty_unary : empty (zero bytes) request and response; 74 large_unary : single request and (large) response; 75 client_streaming : request streaming with single response; 76 server_streaming : single request with response streaming; 77 ping_pong : full-duplex streaming; 78 empty_stream : full-duplex streaming with zero message; 79 timeout_on_sleeping_server: fullduplex streaming on a sleeping server; 80 compute_engine_creds: large_unary with compute engine auth; 81 service_account_creds: large_unary with service account auth; 82 jwt_token_creds: large_unary with jwt token auth; 83 per_rpc_creds: large_unary with per rpc token; 84 oauth2_auth_token: large_unary with oauth2 token auth; 85 google_default_credentials: large_unary with google default credentials 86 compute_engine_channel_credentials: large_unary with compute engine creds 87 cancel_after_begin: cancellation after metadata has been sent but before payloads are sent; 88 cancel_after_first_response: cancellation after receiving 1st message from the server; 89 status_code_and_message: status code propagated back to client; 90 special_status_message: Unicode and whitespace is correctly processed in status message; 91 custom_metadata: server will echo custom metadata; 92 unimplemented_method: client attempts to call unimplemented method; 93 unimplemented_service: client attempts to call unimplemented service; 94 pick_first_unary: all requests are sent to one server despite multiple servers are resolved.`) 95 96 logger = grpclog.Component("interop") 97 ) 98 99 type credsMode uint8 100 101 const ( 102 credsNone credsMode = iota 103 credsTLS 104 credsALTS 105 credsGoogleDefaultCreds 106 credsComputeEngineCreds 107 ) 108 109 func main() { 110 flag.Parse() 111 var useGDC bool // use google default creds 112 var useCEC bool // use compute engine creds 113 if *customCredentialsType != "" { 114 switch *customCredentialsType { 115 case googleDefaultCredsName: 116 useGDC = true 117 case computeEngineCredsName: 118 useCEC = true 119 default: 120 logger.Fatalf("If set, custom_credentials_type can only be set to one of %v or %v", 121 googleDefaultCredsName, computeEngineCredsName) 122 } 123 } 124 if (*useTLS && *useALTS) || (*useTLS && useGDC) || (*useALTS && useGDC) || (*useTLS && useCEC) || (*useALTS && useCEC) { 125 logger.Fatalf("only one of TLS, ALTS, google default creds, or compute engine creds can be used") 126 } 127 128 var credsChosen credsMode 129 switch { 130 case *useTLS: 131 credsChosen = credsTLS 132 case *useALTS: 133 credsChosen = credsALTS 134 case useGDC: 135 credsChosen = credsGoogleDefaultCreds 136 case useCEC: 137 credsChosen = credsComputeEngineCreds 138 } 139 140 resolver.SetDefaultScheme("dns") 141 serverAddr := *serverHost 142 if *serverPort != 0 { 143 serverAddr = net.JoinHostPort(*serverHost, strconv.Itoa(*serverPort)) 144 } 145 var opts []grpc.DialOption 146 switch credsChosen { 147 case credsTLS: 148 var roots *x509.CertPool 149 if *testCA { 150 if *caFile == "" { 151 *caFile = testdata.Path("ca.pem") 152 } 153 b, err := ioutil.ReadFile(*caFile) 154 if err != nil { 155 logger.Fatalf("Failed to read root certificate file %q: %v", *caFile, err) 156 } 157 roots = x509.NewCertPool() 158 if !roots.AppendCertsFromPEM(b) { 159 logger.Fatalf("Failed to append certificates: %s", string(b)) 160 } 161 } 162 var creds credentials.TransportCredentials 163 if *tlsServerName != "" { 164 creds = credentials.NewClientTLSFromCert(roots, *tlsServerName) 165 } else { 166 creds = credentials.NewTLS(&tls.Config{RootCAs: roots}) 167 } 168 opts = append(opts, grpc.WithTransportCredentials(creds)) 169 case credsALTS: 170 altsOpts := alts.DefaultClientOptions() 171 if *altsHSAddr != "" { 172 altsOpts.HandshakerServiceAddress = *altsHSAddr 173 } 174 altsTC := alts.NewClientCreds(altsOpts) 175 opts = append(opts, grpc.WithTransportCredentials(altsTC)) 176 case credsGoogleDefaultCreds: 177 opts = append(opts, grpc.WithCredentialsBundle(google.NewDefaultCredentials())) 178 case credsComputeEngineCreds: 179 opts = append(opts, grpc.WithCredentialsBundle(google.NewComputeEngineCredentials())) 180 case credsNone: 181 opts = append(opts, grpc.WithInsecure()) 182 default: 183 logger.Fatal("Invalid creds") 184 } 185 if credsChosen == credsTLS { 186 if *testCase == "compute_engine_creds" { 187 opts = append(opts, grpc.WithPerRPCCredentials(oauth.NewComputeEngine())) 188 } else if *testCase == "service_account_creds" { 189 jwtCreds, err := oauth.NewServiceAccountFromFile(*serviceAccountKeyFile, *oauthScope) 190 if err != nil { 191 logger.Fatalf("Failed to create JWT credentials: %v", err) 192 } 193 opts = append(opts, grpc.WithPerRPCCredentials(jwtCreds)) 194 } else if *testCase == "jwt_token_creds" { 195 jwtCreds, err := oauth.NewJWTAccessFromFile(*serviceAccountKeyFile) 196 if err != nil { 197 logger.Fatalf("Failed to create JWT credentials: %v", err) 198 } 199 opts = append(opts, grpc.WithPerRPCCredentials(jwtCreds)) 200 } else if *testCase == "oauth2_auth_token" { 201 opts = append(opts, grpc.WithPerRPCCredentials(oauth.NewOauthAccess(interop.GetToken(*serviceAccountKeyFile, *oauthScope)))) 202 } 203 } 204 if len(*serviceConfigJSON) > 0 { 205 opts = append(opts, grpc.WithDisableServiceConfig(), grpc.WithDefaultServiceConfig(*serviceConfigJSON)) 206 } 207 conn, err := grpc.Dial(serverAddr, opts...) 208 if err != nil { 209 logger.Fatalf("Fail to dial: %v", err) 210 } 211 defer conn.Close() 212 tc := testgrpc.NewTestServiceClient(conn) 213 switch *testCase { 214 case "empty_unary": 215 interop.DoEmptyUnaryCall(tc) 216 logger.Infoln("EmptyUnaryCall done") 217 case "large_unary": 218 interop.DoLargeUnaryCall(tc) 219 logger.Infoln("LargeUnaryCall done") 220 case "client_streaming": 221 interop.DoClientStreaming(tc) 222 logger.Infoln("ClientStreaming done") 223 case "server_streaming": 224 interop.DoServerStreaming(tc) 225 logger.Infoln("ServerStreaming done") 226 case "ping_pong": 227 interop.DoPingPong(tc) 228 logger.Infoln("Pingpong done") 229 case "empty_stream": 230 interop.DoEmptyStream(tc) 231 logger.Infoln("Emptystream done") 232 case "timeout_on_sleeping_server": 233 interop.DoTimeoutOnSleepingServer(tc) 234 logger.Infoln("TimeoutOnSleepingServer done") 235 case "compute_engine_creds": 236 if credsChosen != credsTLS { 237 logger.Fatalf("TLS credentials need to be set for compute_engine_creds test case.") 238 } 239 interop.DoComputeEngineCreds(tc, *defaultServiceAccount, *oauthScope) 240 logger.Infoln("ComputeEngineCreds done") 241 case "service_account_creds": 242 if credsChosen != credsTLS { 243 logger.Fatalf("TLS credentials need to be set for service_account_creds test case.") 244 } 245 interop.DoServiceAccountCreds(tc, *serviceAccountKeyFile, *oauthScope) 246 logger.Infoln("ServiceAccountCreds done") 247 case "jwt_token_creds": 248 if credsChosen != credsTLS { 249 logger.Fatalf("TLS credentials need to be set for jwt_token_creds test case.") 250 } 251 interop.DoJWTTokenCreds(tc, *serviceAccountKeyFile) 252 logger.Infoln("JWTtokenCreds done") 253 case "per_rpc_creds": 254 if credsChosen != credsTLS { 255 logger.Fatalf("TLS credentials need to be set for per_rpc_creds test case.") 256 } 257 interop.DoPerRPCCreds(tc, *serviceAccountKeyFile, *oauthScope) 258 logger.Infoln("PerRPCCreds done") 259 case "oauth2_auth_token": 260 if credsChosen != credsTLS { 261 logger.Fatalf("TLS credentials need to be set for oauth2_auth_token test case.") 262 } 263 interop.DoOauth2TokenCreds(tc, *serviceAccountKeyFile, *oauthScope) 264 logger.Infoln("Oauth2TokenCreds done") 265 case "google_default_credentials": 266 if credsChosen != credsGoogleDefaultCreds { 267 logger.Fatalf("GoogleDefaultCredentials need to be set for google_default_credentials test case.") 268 } 269 interop.DoGoogleDefaultCredentials(tc, *defaultServiceAccount) 270 logger.Infoln("GoogleDefaultCredentials done") 271 case "compute_engine_channel_credentials": 272 if credsChosen != credsComputeEngineCreds { 273 logger.Fatalf("ComputeEngineCreds need to be set for compute_engine_channel_credentials test case.") 274 } 275 interop.DoComputeEngineChannelCredentials(tc, *defaultServiceAccount) 276 logger.Infoln("ComputeEngineChannelCredentials done") 277 case "cancel_after_begin": 278 interop.DoCancelAfterBegin(tc) 279 logger.Infoln("CancelAfterBegin done") 280 case "cancel_after_first_response": 281 interop.DoCancelAfterFirstResponse(tc) 282 logger.Infoln("CancelAfterFirstResponse done") 283 case "status_code_and_message": 284 interop.DoStatusCodeAndMessage(tc) 285 logger.Infoln("StatusCodeAndMessage done") 286 case "special_status_message": 287 interop.DoSpecialStatusMessage(tc) 288 logger.Infoln("SpecialStatusMessage done") 289 case "custom_metadata": 290 interop.DoCustomMetadata(tc) 291 logger.Infoln("CustomMetadata done") 292 case "unimplemented_method": 293 interop.DoUnimplementedMethod(conn) 294 logger.Infoln("UnimplementedMethod done") 295 case "unimplemented_service": 296 interop.DoUnimplementedService(testgrpc.NewUnimplementedServiceClient(conn)) 297 logger.Infoln("UnimplementedService done") 298 case "pick_first_unary": 299 interop.DoPickFirstUnary(tc) 300 logger.Infoln("PickFirstUnary done") 301 case "rpc_soak": 302 interop.DoSoakTest(tc, serverAddr, opts, false /* resetChannel */, *soakIterations, *soakMaxFailures, time.Duration(*soakPerIterationMaxAcceptableLatencyMs)*time.Millisecond, time.Now().Add(time.Duration(*soakOverallTimeoutSeconds)*time.Second)) 303 logger.Infoln("RpcSoak done") 304 case "channel_soak": 305 interop.DoSoakTest(tc, serverAddr, opts, true /* resetChannel */, *soakIterations, *soakMaxFailures, time.Duration(*soakPerIterationMaxAcceptableLatencyMs)*time.Millisecond, time.Now().Add(time.Duration(*soakOverallTimeoutSeconds)*time.Second)) 306 logger.Infoln("ChannelSoak done") 307 default: 308 logger.Fatal("Unsupported test case: ", *testCase) 309 } 310 }