-
Notifications
You must be signed in to change notification settings - Fork 781
/
Copy pathclient_set.go
523 lines (442 loc) · 12.9 KB
/
client_set.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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
package dependency
import (
"context"
"crypto/tls"
"fmt"
"log"
"net"
"net/http"
"sync"
"time"
consulapi "github.com/hashicorp/consul/api"
rootcerts "github.com/hashicorp/go-rootcerts"
nomadapi "github.com/hashicorp/nomad/api"
vaultapi "github.com/hashicorp/vault/api"
)
// ClientSet is a collection of clients that dependencies use to communicate
// with remote services like Consul or Vault.
type ClientSet struct {
sync.RWMutex
vault *vaultClient
consul *consulClient
nomad *nomadClient
}
// consulClient is a wrapper around a real Consul API client.
type consulClient struct {
client *consulapi.Client
transport *http.Transport
}
// vaultClient is a wrapper around a real Vault API client.
type vaultClient struct {
client *vaultapi.Client
httpClient *http.Client
}
// nomadClient is a wrapper around a real Nomad API client.
type nomadClient struct {
client *nomadapi.Client
httpClient *http.Client
}
// TransportDialer is an interface that allows passing a custom dialer function
// to an HTTP client's transport config
type TransportDialer interface {
// Dial is intended to match https://pkg.go.dev/net#Dialer.Dial
Dial(network, address string) (net.Conn, error)
// DialContext is intended to match https://pkg.go.dev/net#Dialer.DialContext
DialContext(ctx context.Context, network, address string) (net.Conn, error)
}
// CreateConsulClientInput is used as input to the CreateConsulClient function.
type CreateConsulClientInput struct {
Address string
Namespace string
Token string
TokenFile string
AuthEnabled bool
AuthUsername string
AuthPassword string
SSLEnabled bool
SSLVerify bool
SSLCert string
SSLKey string
SSLCACert string
SSLCAPath string
ServerName string
TransportDialKeepAlive time.Duration
TransportDialTimeout time.Duration
TransportDisableKeepAlives bool
TransportIdleConnTimeout time.Duration
TransportMaxIdleConns int
TransportMaxIdleConnsPerHost int
TransportTLSHandshakeTimeout time.Duration
}
// CreateVaultClientInput is used as input to the CreateVaultClient function.
type CreateVaultClientInput struct {
Address string
Namespace string
Token string
UnwrapToken bool
SSLEnabled bool
SSLVerify bool
SSLCert string
SSLKey string
SSLCACert string
SSLCAPath string
ServerName string
TransportCustomDialer TransportDialer
TransportDialKeepAlive time.Duration
TransportDialTimeout time.Duration
TransportDisableKeepAlives bool
TransportIdleConnTimeout time.Duration
TransportMaxIdleConns int
TransportMaxIdleConnsPerHost int
TransportTLSHandshakeTimeout time.Duration
}
// CreateNomadClientInput is used as input to the CreateNomadClient function.
type CreateNomadClientInput struct {
Address string
Namespace string
Token string
AuthUsername string
AuthPassword string
SSLEnabled bool
SSLVerify bool
SSLCert string
SSLKey string
SSLCACert string
SSLCAPath string
ServerName string
TransportCustomDialer TransportDialer
TransportDialKeepAlive time.Duration
TransportDialTimeout time.Duration
TransportDisableKeepAlives bool
TransportIdleConnTimeout time.Duration
TransportMaxIdleConns int
TransportMaxIdleConnsPerHost int
TransportTLSHandshakeTimeout time.Duration
}
// NewClientSet creates a new client set that is ready to accept clients.
func NewClientSet() *ClientSet {
return &ClientSet{}
}
// CreateConsulClient creates a new Consul API client from the given input.
func (c *ClientSet) CreateConsulClient(i *CreateConsulClientInput) error {
consulConfig := consulapi.DefaultConfig()
if i.Address != "" {
consulConfig.Address = i.Address
}
if i.Namespace != "" {
consulConfig.Namespace = i.Namespace
}
if i.Token != "" {
consulConfig.Token = i.Token
}
if i.TokenFile != "" {
consulConfig.TokenFile = i.TokenFile
}
if i.AuthEnabled {
consulConfig.HttpAuth = &consulapi.HttpBasicAuth{
Username: i.AuthUsername,
Password: i.AuthPassword,
}
}
// This transport will attempt to keep connections open to the Consul server.
transport := &http.Transport{
Proxy: http.ProxyFromEnvironment,
Dial: (&net.Dialer{
Timeout: i.TransportDialTimeout,
KeepAlive: i.TransportDialKeepAlive,
}).Dial,
DisableKeepAlives: i.TransportDisableKeepAlives,
MaxIdleConns: i.TransportMaxIdleConns,
IdleConnTimeout: i.TransportIdleConnTimeout,
MaxIdleConnsPerHost: i.TransportMaxIdleConnsPerHost,
TLSHandshakeTimeout: i.TransportTLSHandshakeTimeout,
}
// Configure SSL
if i.SSLEnabled {
consulConfig.Scheme = "https"
var tlsConfig tls.Config
// Custom certificate or certificate and key
if i.SSLCert != "" && i.SSLKey != "" {
cert, err := tls.LoadX509KeyPair(i.SSLCert, i.SSLKey)
if err != nil {
return fmt.Errorf("client set: consul: %s", err)
}
tlsConfig.Certificates = []tls.Certificate{cert}
} else if i.SSLCert != "" {
cert, err := tls.LoadX509KeyPair(i.SSLCert, i.SSLCert)
if err != nil {
return fmt.Errorf("client set: consul: %s", err)
}
tlsConfig.Certificates = []tls.Certificate{cert}
}
// Custom CA certificate
if i.SSLCACert != "" || i.SSLCAPath != "" {
rootConfig := &rootcerts.Config{
CAFile: i.SSLCACert,
CAPath: i.SSLCAPath,
}
if err := rootcerts.ConfigureTLS(&tlsConfig, rootConfig); err != nil {
return fmt.Errorf("client set: consul configuring TLS failed: %s", err)
}
}
// Construct all the certificates now
tlsConfig.BuildNameToCertificate()
// SSL verification
if i.ServerName != "" {
tlsConfig.ServerName = i.ServerName
tlsConfig.InsecureSkipVerify = false
}
if !i.SSLVerify {
log.Printf("[WARN] (clients) disabling consul SSL verification")
tlsConfig.InsecureSkipVerify = true
}
// Save the TLS config on our transport
transport.TLSClientConfig = &tlsConfig
}
// Setup the new transport
consulConfig.Transport = transport
// Create the API client
client, err := consulapi.NewClient(consulConfig)
if err != nil {
return fmt.Errorf("client set: consul: %s", err)
}
// Save the data on ourselves
c.Lock()
c.consul = &consulClient{
client: client,
transport: transport,
}
c.Unlock()
return nil
}
func (c *ClientSet) CreateVaultClient(i *CreateVaultClientInput) error {
vaultConfig := vaultapi.DefaultConfig()
if i.Address != "" {
vaultConfig.Address = i.Address
}
// This transport will attempt to keep connections open to the Vault server.
var dialer TransportDialer
dialer = &net.Dialer{
Timeout: i.TransportDialTimeout,
KeepAlive: i.TransportDialKeepAlive,
}
if i.TransportCustomDialer != nil {
dialer = i.TransportCustomDialer
}
transport := &http.Transport{
Proxy: http.ProxyFromEnvironment,
Dial: dialer.Dial,
DisableKeepAlives: i.TransportDisableKeepAlives,
MaxIdleConns: i.TransportMaxIdleConns,
IdleConnTimeout: i.TransportIdleConnTimeout,
MaxIdleConnsPerHost: i.TransportMaxIdleConnsPerHost,
TLSHandshakeTimeout: i.TransportTLSHandshakeTimeout,
}
// Configure SSL
if i.SSLEnabled {
var tlsConfig tls.Config
// Custom certificate or certificate and key
if i.SSLCert != "" && i.SSLKey != "" {
cert, err := tls.LoadX509KeyPair(i.SSLCert, i.SSLKey)
if err != nil {
return fmt.Errorf("client set: vault: %s", err)
}
tlsConfig.Certificates = []tls.Certificate{cert}
} else if i.SSLCert != "" {
cert, err := tls.LoadX509KeyPair(i.SSLCert, i.SSLCert)
if err != nil {
return fmt.Errorf("client set: vault: %s", err)
}
tlsConfig.Certificates = []tls.Certificate{cert}
}
// Custom CA certificate
if i.SSLCACert != "" || i.SSLCAPath != "" {
rootConfig := &rootcerts.Config{
CAFile: i.SSLCACert,
CAPath: i.SSLCAPath,
}
if err := rootcerts.ConfigureTLS(&tlsConfig, rootConfig); err != nil {
return fmt.Errorf("client set: vault configuring TLS failed: %s", err)
}
}
// Construct all the certificates now
tlsConfig.BuildNameToCertificate()
// SSL verification
if i.ServerName != "" {
tlsConfig.ServerName = i.ServerName
tlsConfig.InsecureSkipVerify = false
}
if !i.SSLVerify {
log.Printf("[WARN] (clients) disabling vault SSL verification")
tlsConfig.InsecureSkipVerify = true
}
// Save the TLS config on our transport
transport.TLSClientConfig = &tlsConfig
}
// Setup the new transport
vaultConfig.HttpClient.Transport = transport
// Create the client
client, err := vaultapi.NewClient(vaultConfig)
if err != nil {
return fmt.Errorf("client set: vault: %s", err)
}
// Set the namespace if given.
if i.Namespace != "" {
client.SetNamespace(i.Namespace)
}
// Set the token if given
if i.Token != "" {
client.SetToken(i.Token)
}
// Check if we are unwrapping
if i.UnwrapToken {
secret, err := client.Logical().Unwrap(i.Token)
if err != nil {
return fmt.Errorf("client set: vault unwrap: %s", err)
}
if secret == nil {
return fmt.Errorf("client set: vault unwrap: no secret")
}
if secret.Auth == nil {
return fmt.Errorf("client set: vault unwrap: no secret auth")
}
if secret.Auth.ClientToken == "" {
return fmt.Errorf("client set: vault unwrap: no token returned")
}
client.SetToken(secret.Auth.ClientToken)
}
// Save the data on ourselves
c.Lock()
c.vault = &vaultClient{
client: client,
httpClient: vaultConfig.HttpClient,
}
c.Unlock()
return nil
}
// CreateNomadClient creates a new Nomad API client from the given input.
func (c *ClientSet) CreateNomadClient(i *CreateNomadClientInput) error {
conf := nomadapi.DefaultConfig()
if i.Address != "" {
conf.Address = i.Address
}
if i.Namespace != "" {
conf.Namespace = i.Namespace
}
if i.Token != "" {
conf.SecretID = i.Token
}
if i.AuthUsername != "" || i.AuthPassword != "" {
conf.HttpAuth = &nomadapi.HttpBasicAuth{
Username: i.AuthUsername,
Password: i.AuthPassword,
}
}
// This transport will attempt to keep connections open to the Vault server.
var dialer TransportDialer
dialer = &net.Dialer{
Timeout: i.TransportDialTimeout,
KeepAlive: i.TransportDialKeepAlive,
}
if i.TransportCustomDialer != nil {
dialer = i.TransportCustomDialer
}
transport := &http.Transport{
Proxy: http.ProxyFromEnvironment,
Dial: dialer.Dial,
DisableKeepAlives: i.TransportDisableKeepAlives,
MaxIdleConns: i.TransportMaxIdleConns,
IdleConnTimeout: i.TransportIdleConnTimeout,
MaxIdleConnsPerHost: i.TransportMaxIdleConnsPerHost,
TLSHandshakeTimeout: i.TransportTLSHandshakeTimeout,
}
// Configure SSL
if i.SSLEnabled {
var tlsConfig tls.Config
// Custom certificate or certificate and key
if i.SSLCert != "" && i.SSLKey != "" {
cert, err := tls.LoadX509KeyPair(i.SSLCert, i.SSLKey)
if err != nil {
return fmt.Errorf("client set: nomad: %s", err)
}
tlsConfig.Certificates = []tls.Certificate{cert}
} else if i.SSLCert != "" {
cert, err := tls.LoadX509KeyPair(i.SSLCert, i.SSLCert)
if err != nil {
return fmt.Errorf("client set: nomad: %s", err)
}
tlsConfig.Certificates = []tls.Certificate{cert}
}
// Custom CA certificate
if i.SSLCACert != "" || i.SSLCAPath != "" {
rootConfig := &rootcerts.Config{
CAFile: i.SSLCACert,
CAPath: i.SSLCAPath,
}
if err := rootcerts.ConfigureTLS(&tlsConfig, rootConfig); err != nil {
return fmt.Errorf("client set: nomad configuring TLS failed: %s", err)
}
}
// Construct all the certificates now
tlsConfig.BuildNameToCertificate()
// SSL verification
if i.ServerName != "" {
tlsConfig.ServerName = i.ServerName
tlsConfig.InsecureSkipVerify = false
}
if !i.SSLVerify {
log.Printf("[WARN] (clients) disabling nomad SSL verification")
tlsConfig.InsecureSkipVerify = true
}
// Save the TLS config on our transport
transport.TLSClientConfig = &tlsConfig
}
conf.HttpClient = &http.Client{
Transport: transport,
}
// Create the API client
client, err := nomadapi.NewClient(conf)
if err != nil {
return fmt.Errorf("client set: nomad: %w", err)
}
// Save the data on ourselves
c.Lock()
c.nomad = &nomadClient{
client: client,
httpClient: conf.HttpClient,
}
c.Unlock()
return nil
}
// Consul returns the Consul client for this set.
func (c *ClientSet) Consul() *consulapi.Client {
c.RLock()
defer c.RUnlock()
return c.consul.client
}
// Vault returns the Vault client for this set.
func (c *ClientSet) Vault() *vaultapi.Client {
c.RLock()
defer c.RUnlock()
return c.vault.client
}
// Nomad returns the Nomad client for this set.
func (c *ClientSet) Nomad() *nomadapi.Client {
c.RLock()
defer c.RUnlock()
return c.nomad.client
}
// Stop closes all idle connections for any attached clients.
func (c *ClientSet) Stop() {
c.Lock()
defer c.Unlock()
if c.consul != nil {
c.consul.transport.CloseIdleConnections()
}
if c.vault != nil {
c.vault.httpClient.Transport.(*http.Transport).CloseIdleConnections()
}
if c.nomad != nil {
c.nomad.httpClient.Transport.(*http.Transport).CloseIdleConnections()
}
}