...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package grpctransport
16
17 import (
18 "context"
19 "net"
20 "os"
21 "strconv"
22 "strings"
23
24 "cloud.google.com/go/auth"
25 "cloud.google.com/go/compute/metadata"
26 "google.golang.org/grpc"
27 grpcgoogle "google.golang.org/grpc/credentials/google"
28 )
29
30 func isDirectPathEnabled(endpoint string, opts *Options) bool {
31 if opts.InternalOptions != nil && !opts.InternalOptions.EnableDirectPath {
32 return false
33 }
34 if !checkDirectPathEndPoint(endpoint) {
35 return false
36 }
37 if b, _ := strconv.ParseBool(os.Getenv(disableDirectPathEnvVar)); b {
38 return false
39 }
40 return true
41 }
42
43 func checkDirectPathEndPoint(endpoint string) bool {
44
45
46
47 if strings.Contains(endpoint, "://") && !strings.HasPrefix(endpoint, "dns:///") {
48 return false
49 }
50
51 if endpoint == "" {
52 return false
53 }
54
55 return true
56 }
57
58 func isTokenProviderDirectPathCompatible(tp auth.TokenProvider, _ *Options) bool {
59 if tp == nil {
60 return false
61 }
62 tok, err := tp.Token(context.Background())
63 if err != nil {
64 return false
65 }
66 if tok == nil {
67 return false
68 }
69 if source, _ := tok.Metadata["auth.google.tokenSource"].(string); source != "compute-metadata" {
70 return false
71 }
72 if acct, _ := tok.Metadata["auth.google.serviceAccount"].(string); acct != "default" {
73 return false
74 }
75 return true
76 }
77
78 func isDirectPathXdsUsed(o *Options) bool {
79
80 if b, _ := strconv.ParseBool(os.Getenv(enableDirectPathXdsEnvVar)); b {
81 return true
82 }
83
84 if o.InternalOptions != nil && o.InternalOptions.EnableDirectPathXds {
85 return true
86 }
87 return false
88 }
89
90
91
92
93 func configureDirectPath(grpcOpts []grpc.DialOption, opts *Options, endpoint string, creds *auth.Credentials) ([]grpc.DialOption, string) {
94 if isDirectPathEnabled(endpoint, opts) && metadata.OnGCE() && isTokenProviderDirectPathCompatible(creds, opts) {
95
96 grpcOpts = []grpc.DialOption{
97 grpc.WithCredentialsBundle(grpcgoogle.NewDefaultCredentialsWithOptions(grpcgoogle.DefaultCredentialsOptions{PerRPCCreds: &grpcCredentialsProvider{creds: creds}}))}
98 if timeoutDialerOption != nil {
99 grpcOpts = append(grpcOpts, timeoutDialerOption)
100 }
101
102 if isDirectPathXdsUsed(opts) {
103
104 if addr, _, err := net.SplitHostPort(endpoint); err == nil {
105 endpoint = "google-c2p:///" + addr
106 } else {
107 endpoint = "google-c2p:///" + endpoint
108 }
109 } else {
110 if !strings.HasPrefix(endpoint, "dns:///") {
111 endpoint = "dns:///" + endpoint
112 }
113 grpcOpts = append(grpcOpts,
114
115
116
117 grpc.WithDisableServiceConfig(),
118 grpc.WithDefaultServiceConfig(`{"loadBalancingConfig":[{"grpclb":{"childPolicy":[{"pick_first":{}}]}}]}`))
119 }
120
121 }
122 return grpcOpts, endpoint
123 }
124
View as plain text