-
Notifications
You must be signed in to change notification settings - Fork 2
/
dial.go
75 lines (69 loc) 路 2.2 KB
/
dial.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package cloudclient
import (
"context"
"crypto/x509"
"fmt"
"strconv"
"strings"
"time"
"golang.org/x/oauth2"
"google.golang.org/api/idtoken"
"google.golang.org/api/option"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/credentials/oauth"
"google.golang.org/grpc/keepalive"
)
// DialService dials another Cloud Run gRPC service with the default service account's RPC credentials.
func DialService(ctx context.Context, target string, opts ...grpc.DialOption) (*grpc.ClientConn, error) {
tokenSource, err := newTokenSource(ctx, target)
if err != nil {
return nil, err
}
systemCertPool, err := x509.SystemCertPool()
if err != nil {
return nil, fmt.Errorf("dial %s: %w", target, err)
}
defaultOpts := []grpc.DialOption{
grpc.WithPerRPCCredentials(&oauth.TokenSource{TokenSource: tokenSource}),
grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(systemCertPool, "")),
// Enable connection keepalive to mitigate "connection reset by peer".
// https://cloud.google.com/run/docs/troubleshooting
// For details on keepalive settings, see:
// https://github.com/grpc/grpc-go/blob/master/Documentation/keepalive.md
grpc.WithKeepaliveParams(keepalive.ClientParameters{
Time: 1 * time.Minute,
Timeout: 10 * time.Second,
PermitWithoutStream: true,
}),
}
conn, err := grpc.DialContext(ctx, withDefaultPort(target, 443), append(defaultOpts, opts...)...)
if err != nil {
return nil, fmt.Errorf("dial %s: %w", target, err)
}
return conn, nil
}
func trimPort(target string) string {
parts := strings.Split(target, ":")
if len(parts) == 1 {
return target
}
return strings.Join(parts[:len(parts)-1], ":")
}
func withDefaultPort(target string, port int) string {
parts := strings.Split(target, ":")
if len(parts) == 1 {
return target + ":" + strconv.Itoa(port)
}
return target
}
func newTokenSource(ctx context.Context, target string) (_ oauth2.TokenSource, err error) {
defer func() {
if err != nil {
err = fmt.Errorf("new token source: %w", err)
}
}()
audience := "https://" + trimPort(target)
idTokenSource, err := idtoken.NewTokenSource(ctx, audience, option.WithAudiences(audience))
return idTokenSource, err
}