You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

130 lines
4.2 KiB

  1. // Copyright 2015 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // Package grpc supports network connections to GRPC servers.
  15. // This package is not intended for use by end developers. Use the
  16. // google.golang.org/api/option package to configure API clients.
  17. package grpc
  18. import (
  19. "context"
  20. "errors"
  21. "log"
  22. "go.opencensus.io/plugin/ocgrpc"
  23. "google.golang.org/api/internal"
  24. "google.golang.org/api/option"
  25. "google.golang.org/grpc"
  26. "google.golang.org/grpc/credentials"
  27. "google.golang.org/grpc/credentials/oauth"
  28. )
  29. // Set at init time by dial_appengine.go. If nil, we're not on App Engine.
  30. var appengineDialerHook func(context.Context) grpc.DialOption
  31. // Dial returns a GRPC connection for use communicating with a Google cloud
  32. // service, configured with the given ClientOptions.
  33. func Dial(ctx context.Context, opts ...option.ClientOption) (*grpc.ClientConn, error) {
  34. return dial(ctx, false, opts)
  35. }
  36. // DialInsecure returns an insecure GRPC connection for use communicating
  37. // with fake or mock Google cloud service implementations, such as emulators.
  38. // The connection is configured with the given ClientOptions.
  39. func DialInsecure(ctx context.Context, opts ...option.ClientOption) (*grpc.ClientConn, error) {
  40. return dial(ctx, true, opts)
  41. }
  42. func dial(ctx context.Context, insecure bool, opts []option.ClientOption) (*grpc.ClientConn, error) {
  43. var o internal.DialSettings
  44. for _, opt := range opts {
  45. opt.Apply(&o)
  46. }
  47. if err := o.Validate(); err != nil {
  48. return nil, err
  49. }
  50. if o.HTTPClient != nil {
  51. return nil, errors.New("unsupported HTTP client specified")
  52. }
  53. if o.GRPCConn != nil {
  54. return o.GRPCConn, nil
  55. }
  56. grpcOpts := []grpc.DialOption{
  57. grpc.WithWaitForHandshake(),
  58. }
  59. if insecure {
  60. grpcOpts = []grpc.DialOption{grpc.WithInsecure()}
  61. } else if !o.NoAuth {
  62. if o.APIKey != "" {
  63. log.Print("API keys are not supported for gRPC APIs. Remove the WithAPIKey option from your client-creating call.")
  64. }
  65. creds, err := internal.Creds(ctx, &o)
  66. if err != nil {
  67. return nil, err
  68. }
  69. grpcOpts = []grpc.DialOption{
  70. grpc.WithPerRPCCredentials(grpcTokenSource{
  71. TokenSource: oauth.TokenSource{creds.TokenSource},
  72. quotaProject: o.QuotaProject,
  73. requestReason: o.RequestReason,
  74. }),
  75. grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")),
  76. }
  77. }
  78. if appengineDialerHook != nil {
  79. // Use the Socket API on App Engine.
  80. grpcOpts = append(grpcOpts, appengineDialerHook(ctx))
  81. }
  82. // Add tracing, but before the other options, so that clients can override the
  83. // gRPC stats handler.
  84. // This assumes that gRPC options are processed in order, left to right.
  85. grpcOpts = addOCStatsHandler(grpcOpts)
  86. grpcOpts = append(grpcOpts, o.GRPCDialOpts...)
  87. if o.UserAgent != "" {
  88. grpcOpts = append(grpcOpts, grpc.WithUserAgent(o.UserAgent))
  89. }
  90. return grpc.DialContext(ctx, o.Endpoint, grpcOpts...)
  91. }
  92. func addOCStatsHandler(opts []grpc.DialOption) []grpc.DialOption {
  93. return append(opts, grpc.WithStatsHandler(&ocgrpc.ClientHandler{}))
  94. }
  95. // grpcTokenSource supplies PerRPCCredentials from an oauth.TokenSource.
  96. type grpcTokenSource struct {
  97. oauth.TokenSource
  98. // Additional metadata attached as headers.
  99. quotaProject string
  100. requestReason string
  101. }
  102. // GetRequestMetadata gets the request metadata as a map from a grpcTokenSource.
  103. func (ts grpcTokenSource) GetRequestMetadata(ctx context.Context, uri ...string) (
  104. map[string]string, error) {
  105. metadata, err := ts.TokenSource.GetRequestMetadata(ctx, uri...)
  106. if err != nil {
  107. return nil, err
  108. }
  109. // Attach system parameters into the metadata
  110. if ts.quotaProject != "" {
  111. metadata["X-goog-user-project"] = ts.quotaProject
  112. }
  113. if ts.requestReason != "" {
  114. metadata["X-goog-request-reason"] = ts.requestReason
  115. }
  116. return metadata, nil
  117. }