-
Notifications
You must be signed in to change notification settings - Fork 330
/
clients.go
368 lines (325 loc) · 12.7 KB
/
clients.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package rpc
import (
"context"
"crypto/tls"
"fmt"
"io/ioutil"
"net/http"
"net/http/httputil"
"net/url"
"os"
"strings"
"time"
grpc_logrus "github.com/grpc-ecosystem/go-grpc-middleware/logging/logrus"
"go.opencensus.io/plugin/ocgrpc"
grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
grpc_tracing "github.com/grpc-ecosystem/go-grpc-middleware/tracing/opentracing"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"go.opencensus.io/plugin/ochttp"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/keepalive"
"google.golang.org/grpc/resolver"
"open-match.dev/open-match/internal/config"
"open-match.dev/open-match/internal/logging"
"open-match.dev/open-match/internal/telemetry"
)
const (
// ConfigNameEnableRPCLogging is the config name for enabling RPC logging.
ConfigNameEnableRPCLogging = "logging.rpc"
// configNameClientTrustedCertificatePath is the same as the root CA cert that the server trusts.
configNameClientTrustedCertificatePath = configNameServerRootCertificatePath
)
var (
clientLogger = logrus.WithFields(logrus.Fields{
"app": "openmatch",
"component": "client",
})
)
// ClientParams contains the connection parameters to connect to an Open Match service.
type ClientParams struct {
Address string
TrustedCertificate []byte
EnableRPCLogging bool
EnableRPCPayloadLogging bool
EnableMetrics bool
}
// nolint:gochecknoinits
func init() {
// Using gRPC's DNS resolver to create clients.
// This is a workaround for load balancing gRPC applications under k8s environments.
// See https://kubernetes.io/blog/2018/11/07/grpc-load-balancing-on-kubernetes-without-tears/ for more details.
// https://godoc.org/google.golang.org/grpc/resolver#SetDefaultScheme
resolver.SetDefaultScheme("dns")
}
func (p *ClientParams) usingTLS() bool {
return len(p.TrustedCertificate) > 0
}
// GRPCClientFromConfig creates a gRPC client connection from a configuration.
func GRPCClientFromConfig(cfg config.View, prefix string) (*grpc.ClientConn, error) {
clientParams := &ClientParams{
Address: toAddress(cfg.GetString(prefix+".hostname"), cfg.GetInt(prefix+".grpcport")),
EnableRPCLogging: cfg.GetBool(ConfigNameEnableRPCLogging),
EnableRPCPayloadLogging: logging.IsDebugEnabled(cfg),
EnableMetrics: cfg.GetBool(telemetry.ConfigNameEnableMetrics),
}
// If TLS support is enabled in the config, fill in the trusted certificates for decrpting server certificate.
if cfg.GetString(configNameClientTrustedCertificatePath) != "" {
_, err := os.Stat(cfg.GetString(configNameClientTrustedCertificatePath))
if err != nil {
clientLogger.WithError(err).Error("trusted certificate file may not exists.")
return nil, err
}
clientParams.TrustedCertificate, err = ioutil.ReadFile(cfg.GetString(configNameClientTrustedCertificatePath))
if err != nil {
clientLogger.WithError(err).Error("failed to read tls trusted certificate to establish a secure grpc client.")
return nil, err
}
}
return GRPCClientFromParams(clientParams)
}
// GRPCClientFromEndpoint creates a gRPC client connection from endpoint.
func GRPCClientFromEndpoint(cfg config.View, address string) (*grpc.ClientConn, error) {
// TODO: investigate if it is possible to keep a cache of the certpool and transport credentials
grpcOptions := newGRPCDialOptions(cfg.GetBool(telemetry.ConfigNameEnableMetrics), cfg.GetBool(ConfigNameEnableRPCLogging), logging.IsDebugEnabled(cfg))
if cfg.GetString(configNameClientTrustedCertificatePath) != "" {
_, err := os.Stat(cfg.GetString(configNameClientTrustedCertificatePath))
if err != nil {
clientLogger.WithError(err).Error("trusted certificate file may not exists.")
return nil, err
}
trustedCertificate, err := ioutil.ReadFile(cfg.GetString(configNameClientTrustedCertificatePath))
if err != nil {
clientLogger.WithError(err).Error("failed to read tls trusted certificate to establish a secure grpc client.")
return nil, err
}
pool, err := trustedCertificateFromFileData(trustedCertificate)
if err != nil {
clientLogger.WithError(err).Error("failed to get transport credentials from file.")
return nil, errors.WithStack(err)
}
tc := credentials.NewClientTLSFromCert(pool, "")
grpcOptions = append(grpcOptions, grpc.WithTransportCredentials(tc))
} else {
grpcOptions = append(grpcOptions, grpc.WithTransportCredentials(insecure.NewCredentials()))
}
return grpc.Dial(address, grpcOptions...)
}
// GRPCClientFromParams creates a gRPC client connection from the parameters.
func GRPCClientFromParams(params *ClientParams) (*grpc.ClientConn, error) {
grpcOptions := newGRPCDialOptions(params.EnableMetrics, params.EnableRPCLogging, params.EnableRPCPayloadLogging)
if params.usingTLS() {
trustedCertPool, err := trustedCertificateFromFileData(params.TrustedCertificate)
if err != nil {
clientLogger.WithError(err).Error("failed to get transport credentials from file.")
return nil, errors.WithStack(err)
}
grpcOptions = append(grpcOptions, grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(trustedCertPool, "")))
} else {
grpcOptions = append(grpcOptions, grpc.WithTransportCredentials(insecure.NewCredentials()))
}
return grpc.Dial(params.Address, grpcOptions...)
}
// HTTPClientFromConfig creates a HTTP client from from a configuration.
func HTTPClientFromConfig(cfg config.View, prefix string) (*http.Client, string, error) {
clientParams := &ClientParams{
Address: toAddress(cfg.GetString(prefix+".hostname"), cfg.GetInt(prefix+".httpport")),
EnableRPCLogging: cfg.GetBool(ConfigNameEnableRPCLogging),
EnableRPCPayloadLogging: logging.IsDebugEnabled(cfg),
EnableMetrics: cfg.GetBool(telemetry.ConfigNameEnableMetrics),
}
// If TLS support is enabled in the config, fill in the trusted certificates for decrpting server certificate.
if cfg.GetString(configNameClientTrustedCertificatePath) != "" {
_, err := os.Stat(cfg.GetString(configNameClientTrustedCertificatePath))
if err != nil {
clientLogger.WithError(err).Error("trusted certificate file may not exists.")
return nil, "", err
}
clientParams.TrustedCertificate, err = ioutil.ReadFile(cfg.GetString(configNameClientTrustedCertificatePath))
if err != nil {
clientLogger.WithError(err).Error("failed to read tls trusted certificate to establish a secure grpc client.")
return nil, "", err
}
}
return HTTPClientFromParams(clientParams)
}
func sanitizeHTTPAddress(address string, preferHTTPS bool) (string, error) {
lca := strings.ToLower(address)
if !strings.HasPrefix(lca, "http://") && !strings.HasPrefix(lca, "https://") {
if preferHTTPS {
address = "https://" + address
} else {
address = "http://" + address
}
}
u, err := url.Parse(address)
if err != nil {
return "", errors.New(fmt.Sprintf("%s is not a valid HTTP(S) address", address))
}
return u.String(), nil
}
// HTTPClientFromEndpoint creates a HTTP client from from endpoint.
func HTTPClientFromEndpoint(cfg config.View, address string) (*http.Client, string, error) {
// TODO: investigate if it is possible to keep a cache of the certpool and transport credentials
params := &ClientParams{
Address: address,
EnableRPCLogging: cfg.GetBool(ConfigNameEnableRPCLogging),
EnableRPCPayloadLogging: logging.IsDebugEnabled(cfg),
EnableMetrics: cfg.GetBool(telemetry.ConfigNameEnableMetrics),
}
if cfg.GetString(configNameClientTrustedCertificatePath) != "" {
_, err := os.Stat(cfg.GetString(configNameClientTrustedCertificatePath))
if err != nil {
clientLogger.WithError(err).Error("trusted certificate file may not exists.")
return nil, "", err
}
trustedCertificate, err := ioutil.ReadFile(cfg.GetString(configNameClientTrustedCertificatePath))
if err != nil {
clientLogger.WithError(err).Error("failed to read tls trusted certificate to establish a secure grpc client.")
return nil, "", err
}
params.TrustedCertificate = trustedCertificate
}
return HTTPClientFromParams(params)
}
// HTTPClientFromParams creates a HTTP client from the parameters.
func HTTPClientFromParams(params *ClientParams) (*http.Client, string, error) {
// TODO: Make client Timeout configurable
httpClient := &http.Client{Timeout: time.Second * 3}
var baseURL string
if params.usingTLS() {
var err error
baseURL, err = sanitizeHTTPAddress(params.Address, true)
if err != nil {
clientLogger.WithError(err).Error("cannot parse address")
return nil, "", err
}
pool, err := trustedCertificateFromFileData(params.TrustedCertificate)
if err != nil {
clientLogger.WithError(err).Error("failed to get cert pool from file.")
return nil, "", err
}
httpClient.Transport = &http.Transport{
TLSClientConfig: &tls.Config{
ServerName: params.Address,
RootCAs: pool,
},
}
} else {
var err error
baseURL, err = sanitizeHTTPAddress(params.Address, false)
if err != nil {
clientLogger.WithError(err).Error("cannot parse address")
return nil, "", err
}
}
if params.EnableRPCLogging {
attachTransport(httpClient, func(transport http.RoundTripper) http.RoundTripper {
return &loggingHTTPClient{
transport: transport,
logPayloads: params.EnableRPCPayloadLogging,
}
})
}
if params.EnableMetrics {
attachTransport(httpClient, func(transport http.RoundTripper) http.RoundTripper {
return &ochttp.Transport{
Base: transport,
}
})
}
return httpClient, baseURL, nil
}
func newGRPCDialOptions(enableMetrics bool, enableRPCLogging bool, enableRPCPayloadLogging bool) []grpc.DialOption {
si := []grpc.StreamClientInterceptor{
grpc_tracing.StreamClientInterceptor(),
}
ui := []grpc.UnaryClientInterceptor{
grpc_tracing.UnaryClientInterceptor(),
}
if enableRPCLogging {
grpcLogger := logrus.WithFields(logrus.Fields{
"app": "openmatch",
"component": "grpc.client",
})
grpcLogger.Level = logrus.DebugLevel
if enableRPCPayloadLogging {
logEverythingFromClient := func(_ context.Context, _ string) bool {
return true
}
si = append(si, grpc_logrus.PayloadStreamClientInterceptor(grpcLogger, logEverythingFromClient))
ui = append(ui, grpc_logrus.PayloadUnaryClientInterceptor(grpcLogger, logEverythingFromClient))
} else {
si = append(si, grpc_logrus.StreamClientInterceptor(grpcLogger))
ui = append(ui, grpc_logrus.UnaryClientInterceptor(grpcLogger))
}
}
opts := []grpc.DialOption{
grpc.WithStreamInterceptor(grpc_middleware.ChainStreamClient(si...)),
grpc.WithUnaryInterceptor(grpc_middleware.ChainUnaryClient(ui...)),
grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy":"round_robin"}`),
grpc.WithKeepaliveParams(keepalive.ClientParameters{
Time: 20 * time.Second,
Timeout: 10 * time.Second,
PermitWithoutStream: true,
}),
}
if enableMetrics {
opts = append(opts, grpc.WithStatsHandler(new(ocgrpc.ClientHandler)))
}
return opts
}
func toAddress(hostname string, port int) string {
return fmt.Sprintf("%s:%d", hostname, port)
}
type loggingHTTPClient struct {
transport http.RoundTripper
logPayloads bool
}
func (c *loggingHTTPClient) RoundTrip(req *http.Request) (*http.Response, error) {
dumpReqLog, dumpReqErr := httputil.DumpRequest(req, c.logPayloads)
fields := logrus.Fields{
"method": req.Method,
"url": req.URL,
"proto": req.Proto,
}
if dumpReqErr == nil {
clientLogger.WithFields(fields).Debug(string(dumpReqLog))
} else {
clientLogger.WithError(dumpReqErr).WithFields(fields).Debug("cannot dump request")
}
resp, err := c.transport.RoundTrip(req)
if err == nil {
dumpRespLog, dumpRespErr := httputil.DumpResponse(resp, c.logPayloads)
if dumpRespErr == nil {
clientLogger.WithFields(fields).Debug(string(dumpRespLog))
} else {
clientLogger.WithError(dumpRespErr).WithFields(fields).Debug("request was successful but cannot dump response")
}
} else {
clientLogger.WithError(err).WithFields(fields).Debug("request failed")
}
return resp, err
}
func attachTransport(client *http.Client, wrapper func(http.RoundTripper) http.RoundTripper) {
transport := client.Transport
if transport == nil {
transport = http.DefaultTransport
}
client.Transport = wrapper(transport)
}