client.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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. package main
  19. import (
  20. "flag"
  21. "net"
  22. "strconv"
  23. "google.golang.org/grpc"
  24. _ "google.golang.org/grpc/balancer/grpclb"
  25. "google.golang.org/grpc/credentials"
  26. "google.golang.org/grpc/credentials/alts"
  27. "google.golang.org/grpc/credentials/google"
  28. "google.golang.org/grpc/credentials/oauth"
  29. "google.golang.org/grpc/grpclog"
  30. "google.golang.org/grpc/interop"
  31. testpb "google.golang.org/grpc/interop/grpc_testing"
  32. "google.golang.org/grpc/resolver"
  33. "google.golang.org/grpc/testdata"
  34. )
  35. const (
  36. googleDefaultCredsName = "google_default_credentials"
  37. )
  38. var (
  39. caFile = flag.String("ca_file", "", "The file containning the CA root cert file")
  40. useTLS = flag.Bool("use_tls", false, "Connection uses TLS if true")
  41. useALTS = flag.Bool("use_alts", false, "Connection uses ALTS if true (this option can only be used on GCP)")
  42. customCredentialsType = flag.String("custom_credentials_type", "", "Custom creds to use, excluding TLS or ALTS")
  43. altsHSAddr = flag.String("alts_handshaker_service_address", "", "ALTS handshaker gRPC service address")
  44. testCA = flag.Bool("use_test_ca", false, "Whether to replace platform root CAs with test CA as the CA root")
  45. serviceAccountKeyFile = flag.String("service_account_key_file", "", "Path to service account json key file")
  46. oauthScope = flag.String("oauth_scope", "", "The scope for OAuth2 tokens")
  47. defaultServiceAccount = flag.String("default_service_account", "", "Email of GCE default service account")
  48. serverHost = flag.String("server_host", "localhost", "The server host name")
  49. serverPort = flag.Int("server_port", 10000, "The server port number")
  50. tlsServerName = flag.String("server_host_override", "", "The server name use to verify the hostname returned by TLS handshake if it is not empty. Otherwise, --server_host is used.")
  51. testCase = flag.String("test_case", "large_unary",
  52. `Configure different test cases. Valid options are:
  53. empty_unary : empty (zero bytes) request and response;
  54. large_unary : single request and (large) response;
  55. client_streaming : request streaming with single response;
  56. server_streaming : single request with response streaming;
  57. ping_pong : full-duplex streaming;
  58. empty_stream : full-duplex streaming with zero message;
  59. timeout_on_sleeping_server: fullduplex streaming on a sleeping server;
  60. compute_engine_creds: large_unary with compute engine auth;
  61. service_account_creds: large_unary with service account auth;
  62. jwt_token_creds: large_unary with jwt token auth;
  63. per_rpc_creds: large_unary with per rpc token;
  64. oauth2_auth_token: large_unary with oauth2 token auth;
  65. cancel_after_begin: cancellation after metadata has been sent but before payloads are sent;
  66. cancel_after_first_response: cancellation after receiving 1st message from the server;
  67. status_code_and_message: status code propagated back to client;
  68. special_status_message: Unicode and whitespace is correctly processed in status message;
  69. custom_metadata: server will echo custom metadata;
  70. unimplemented_method: client attempts to call unimplemented method;
  71. unimplemented_service: client attempts to call unimplemented service.`)
  72. )
  73. type credsMode uint8
  74. const (
  75. credsNone credsMode = iota
  76. credsTLS
  77. credsALTS
  78. credsGoogleDefaultCreds
  79. )
  80. func main() {
  81. flag.Parse()
  82. var useGDC bool // use google default creds
  83. if *customCredentialsType != "" {
  84. if *customCredentialsType != googleDefaultCredsName {
  85. grpclog.Fatalf("custom_credentials_type can only be set to %v or not set", googleDefaultCredsName)
  86. }
  87. useGDC = true
  88. }
  89. if (*useTLS && *useALTS) || (*useTLS && useGDC) || (*useALTS && useGDC) {
  90. grpclog.Fatalf("only one of TLS, ALTS and google default creds can be used")
  91. }
  92. var credsChosen credsMode
  93. switch {
  94. case *useTLS:
  95. credsChosen = credsTLS
  96. case *useALTS:
  97. credsChosen = credsALTS
  98. case useGDC:
  99. credsChosen = credsGoogleDefaultCreds
  100. }
  101. resolver.SetDefaultScheme("dns")
  102. serverAddr := net.JoinHostPort(*serverHost, strconv.Itoa(*serverPort))
  103. var opts []grpc.DialOption
  104. switch credsChosen {
  105. case credsTLS:
  106. var sn string
  107. if *tlsServerName != "" {
  108. sn = *tlsServerName
  109. }
  110. var creds credentials.TransportCredentials
  111. if *testCA {
  112. var err error
  113. if *caFile == "" {
  114. *caFile = testdata.Path("ca.pem")
  115. }
  116. creds, err = credentials.NewClientTLSFromFile(*caFile, sn)
  117. if err != nil {
  118. grpclog.Fatalf("Failed to create TLS credentials %v", err)
  119. }
  120. } else {
  121. creds = credentials.NewClientTLSFromCert(nil, sn)
  122. }
  123. opts = append(opts, grpc.WithTransportCredentials(creds))
  124. case credsALTS:
  125. altsOpts := alts.DefaultClientOptions()
  126. if *altsHSAddr != "" {
  127. altsOpts.HandshakerServiceAddress = *altsHSAddr
  128. }
  129. altsTC := alts.NewClientCreds(altsOpts)
  130. opts = append(opts, grpc.WithTransportCredentials(altsTC))
  131. case credsGoogleDefaultCreds:
  132. opts = append(opts, grpc.WithCredentialsBundle(google.NewDefaultCredentials()))
  133. default:
  134. opts = append(opts, grpc.WithInsecure())
  135. }
  136. if credsChosen == credsTLS || credsChosen == credsALTS {
  137. if *testCase == "compute_engine_creds" {
  138. opts = append(opts, grpc.WithPerRPCCredentials(oauth.NewComputeEngine()))
  139. } else if *testCase == "service_account_creds" {
  140. jwtCreds, err := oauth.NewServiceAccountFromFile(*serviceAccountKeyFile, *oauthScope)
  141. if err != nil {
  142. grpclog.Fatalf("Failed to create JWT credentials: %v", err)
  143. }
  144. opts = append(opts, grpc.WithPerRPCCredentials(jwtCreds))
  145. } else if *testCase == "jwt_token_creds" {
  146. jwtCreds, err := oauth.NewJWTAccessFromFile(*serviceAccountKeyFile)
  147. if err != nil {
  148. grpclog.Fatalf("Failed to create JWT credentials: %v", err)
  149. }
  150. opts = append(opts, grpc.WithPerRPCCredentials(jwtCreds))
  151. } else if *testCase == "oauth2_auth_token" {
  152. opts = append(opts, grpc.WithPerRPCCredentials(oauth.NewOauthAccess(interop.GetToken(*serviceAccountKeyFile, *oauthScope))))
  153. }
  154. }
  155. opts = append(opts, grpc.WithBlock())
  156. conn, err := grpc.Dial(serverAddr, opts...)
  157. if err != nil {
  158. grpclog.Fatalf("Fail to dial: %v", err)
  159. }
  160. defer conn.Close()
  161. tc := testpb.NewTestServiceClient(conn)
  162. switch *testCase {
  163. case "empty_unary":
  164. interop.DoEmptyUnaryCall(tc)
  165. grpclog.Infoln("EmptyUnaryCall done")
  166. case "large_unary":
  167. interop.DoLargeUnaryCall(tc)
  168. grpclog.Infoln("LargeUnaryCall done")
  169. case "client_streaming":
  170. interop.DoClientStreaming(tc)
  171. grpclog.Infoln("ClientStreaming done")
  172. case "server_streaming":
  173. interop.DoServerStreaming(tc)
  174. grpclog.Infoln("ServerStreaming done")
  175. case "ping_pong":
  176. interop.DoPingPong(tc)
  177. grpclog.Infoln("Pingpong done")
  178. case "empty_stream":
  179. interop.DoEmptyStream(tc)
  180. grpclog.Infoln("Emptystream done")
  181. case "timeout_on_sleeping_server":
  182. interop.DoTimeoutOnSleepingServer(tc)
  183. grpclog.Infoln("TimeoutOnSleepingServer done")
  184. case "compute_engine_creds":
  185. if credsChosen == credsNone {
  186. grpclog.Fatalf("Credentials (TLS, ALTS or google default creds) need to be set for compute_engine_creds test case.")
  187. }
  188. interop.DoComputeEngineCreds(tc, *defaultServiceAccount, *oauthScope)
  189. grpclog.Infoln("ComputeEngineCreds done")
  190. case "service_account_creds":
  191. if credsChosen == credsNone {
  192. grpclog.Fatalf("Credentials (TLS, ALTS or google default creds) need to be set for service_account_creds test case.")
  193. }
  194. interop.DoServiceAccountCreds(tc, *serviceAccountKeyFile, *oauthScope)
  195. grpclog.Infoln("ServiceAccountCreds done")
  196. case "jwt_token_creds":
  197. if credsChosen == credsNone {
  198. grpclog.Fatalf("Credentials (TLS, ALTS or google default creds) need to be set for jwt_token_creds test case.")
  199. }
  200. interop.DoJWTTokenCreds(tc, *serviceAccountKeyFile)
  201. grpclog.Infoln("JWTtokenCreds done")
  202. case "per_rpc_creds":
  203. if credsChosen == credsNone {
  204. grpclog.Fatalf("Credentials (TLS, ALTS or google default creds) need to be set for per_rpc_creds test case.")
  205. }
  206. interop.DoPerRPCCreds(tc, *serviceAccountKeyFile, *oauthScope)
  207. grpclog.Infoln("PerRPCCreds done")
  208. case "oauth2_auth_token":
  209. if credsChosen == credsNone {
  210. grpclog.Fatalf("Credentials (TLS, ALTS or google default creds) need to be set for oauth2_auth_token test case.")
  211. }
  212. interop.DoOauth2TokenCreds(tc, *serviceAccountKeyFile, *oauthScope)
  213. grpclog.Infoln("Oauth2TokenCreds done")
  214. case "cancel_after_begin":
  215. interop.DoCancelAfterBegin(tc)
  216. grpclog.Infoln("CancelAfterBegin done")
  217. case "cancel_after_first_response":
  218. interop.DoCancelAfterFirstResponse(tc)
  219. grpclog.Infoln("CancelAfterFirstResponse done")
  220. case "status_code_and_message":
  221. interop.DoStatusCodeAndMessage(tc)
  222. grpclog.Infoln("StatusCodeAndMessage done")
  223. case "special_status_message":
  224. interop.DoSpecialStatusMessage(tc)
  225. grpclog.Infoln("SpecialStatusMessage done")
  226. case "custom_metadata":
  227. interop.DoCustomMetadata(tc)
  228. grpclog.Infoln("CustomMetadata done")
  229. case "unimplemented_method":
  230. interop.DoUnimplementedMethod(conn)
  231. grpclog.Infoln("UnimplementedMethod done")
  232. case "unimplemented_service":
  233. interop.DoUnimplementedService(testpb.NewUnimplementedServiceClient(conn))
  234. grpclog.Infoln("UnimplementedService done")
  235. default:
  236. grpclog.Fatal("Unsupported test case: ", *testCase)
  237. }
  238. }