/
store.go
395 lines (349 loc) · 10.1 KB
/
store.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
// Copyright 2020 MongoDB Inc
//
// 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 store
//go:generate mockgen -destination=../mocks/mock_store.go -package=mocks github.com/mongodb/mongodb-atlas-cli/internal/store CredentialsGetter
import (
"context"
"errors"
"fmt"
"net"
"net/http"
"strings"
"time"
"github.com/mongodb-forks/digest"
"github.com/mongodb/mongodb-atlas-cli/internal/config"
"github.com/mongodb/mongodb-atlas-cli/internal/log"
atlasv2 "go.mongodb.org/atlas-sdk/v20231115007/admin"
atlasauth "go.mongodb.org/atlas/auth"
atlas "go.mongodb.org/atlas/mongodbatlas"
"go.mongodb.org/ops-manager/opsmngr"
)
const (
telemetryTimeout = 1 * time.Second
tlsHandshakeTimeout = 5 * time.Second
timeout = 5 * time.Second
keepAlive = 30 * time.Second
maxIdleConns = 5
maxIdleConnsPerHost = 4
idleConnTimeout = 30 * time.Second
expectContinueTimeout = 1 * time.Second
versionManifestStaticPath = "https://opsmanager.mongodb.com/"
cloudGovServiceURL = "https://cloud.mongodbgov.com/"
)
var errUnsupportedService = errors.New("unsupported service")
type Store struct {
service string
baseURL string
caCertificate string
skipVerify bool
telemetry bool
username string
password string
accessToken *atlasauth.Token
client interface{}
// Latest release of the autogenerated Atlas V2 API Client
clientv2 *atlasv2.APIClient
ctx context.Context
}
var defaultTransport = &http.Transport{
DialContext: (&net.Dialer{
Timeout: timeout,
KeepAlive: keepAlive,
}).DialContext,
MaxIdleConns: maxIdleConns,
MaxIdleConnsPerHost: maxIdleConnsPerHost,
Proxy: http.ProxyFromEnvironment,
IdleConnTimeout: idleConnTimeout,
ExpectContinueTimeout: expectContinueTimeout,
}
var telemetryTransport = &http.Transport{
DialContext: (&net.Dialer{
Timeout: telemetryTimeout,
KeepAlive: keepAlive,
}).DialContext,
MaxIdleConns: maxIdleConns,
MaxIdleConnsPerHost: maxIdleConnsPerHost,
Proxy: http.ProxyFromEnvironment,
IdleConnTimeout: idleConnTimeout,
ExpectContinueTimeout: expectContinueTimeout,
}
func (s *Store) httpClient(httpTransport http.RoundTripper) (*http.Client, error) {
if s.username != "" && s.password != "" {
t := &digest.Transport{
Username: s.username,
Password: s.password,
}
t.Transport = httpTransport
return t.Client()
}
if s.accessToken != nil {
tr := &Transport{
token: s.accessToken,
base: httpTransport,
}
return &http.Client{Transport: tr}, nil
}
return &http.Client{Transport: httpTransport}, nil
}
type Transport struct {
token *atlasauth.Token
base http.RoundTripper
}
func (tr *Transport) RoundTrip(req *http.Request) (*http.Response, error) {
tr.token.SetAuthHeader(req)
return tr.base.RoundTrip(req)
}
func (s *Store) transport() *http.Transport {
switch {
case s.telemetry:
return telemetryTransport
default:
return defaultTransport
}
}
// Option is any configuration for Store.
// New will take a list of Option and process them sequentially.
// The store package provides a list of pointers and preset set of Option you can use
// but you can implement your own.
type Option func(s *Store) error
// Options turns a list of Option instances into a single Option.
// This is a helper when combining multiple Option.
func Options(opts ...Option) Option {
return func(s *Store) error {
for _, opt := range opts {
if err := opt(s); err != nil {
return err
}
}
return nil
}
}
// Service configures the Store service, valid options are cloud, cloud-manager, and ops-manager.
func Service(service string) Option {
return func(s *Store) error {
s.service = service
return nil
}
}
// WithBaseURL sets the base URL for the underling HTTP client.
// the url should not contain any path, to add the public API path use WithPublicPathBaseURL.
func WithBaseURL(configURL string) Option {
return func(s *Store) error {
s.baseURL = configURL
return nil
}
}
// WithCACertificate enables the Store to use a custom CA certificate.
func WithCACertificate(caCertificate string) Option {
return func(s *Store) error {
s.caCertificate = caCertificate
return nil
}
}
// SkipVerify skips CA certificate verification, use at your own risk.
func SkipVerify() Option {
return func(s *Store) error {
s.skipVerify = true
return nil
}
}
func Telemetry() Option {
return func(s *Store) error {
s.telemetry = true
return nil
}
}
// CredentialsGetter interface for how to get credentials when Store must be authenticated.
type CredentialsGetter interface {
PublicAPIKey() string
PrivateAPIKey() string
Token() (*atlasauth.Token, error)
AuthType() config.AuthMechanism
}
// WithAuthentication sets the store credentials.
func WithAuthentication(c CredentialsGetter) Option {
return func(s *Store) error {
s.username = c.PublicAPIKey()
s.password = c.PrivateAPIKey()
if s.username == "" && s.password == "" {
t, err := c.Token()
if err != nil {
return err
}
s.accessToken = t
}
return nil
}
}
// WithContext sets the store context.
func WithContext(ctx context.Context) Option {
return func(s *Store) error {
s.ctx = ctx
return nil
}
}
// setAtlasClient sets the internal client to use an Atlas client and methods.
func (s *Store) setAtlasClient(client *http.Client) error {
opts := []atlas.ClientOpt{atlas.SetUserAgent(config.UserAgent)}
if s.baseURL != "" {
opts = append(opts, atlas.SetBaseURL(s.baseURL))
}
if log.IsDebugLevel() {
opts = append(opts, atlas.SetWithRaw())
}
c, err := atlas.New(client, opts...)
if err != nil {
return err
}
err = s.createV2Client(client)
if err != nil {
return err
}
c.OnResponseProcessed(func(resp *atlas.Response) {
respHeaders := ""
for key, value := range resp.Header {
respHeaders += fmt.Sprintf("%v: %v\n", key, strings.Join(value, " "))
}
_, _ = log.Debugf(`request:
%v %v
response:
%v %v
%v
%v
`, resp.Request.Method, resp.Request.URL.String(), resp.Proto, resp.Status, respHeaders, string(resp.Raw))
})
s.client = c
return nil
}
/**
* Creates client for v2 generated API.
*/
func (s *Store) createV2Client(client *http.Client) error {
opts := []atlasv2.ClientModifier{
atlasv2.UseHTTPClient(client),
atlasv2.UseUserAgent(config.UserAgent),
atlasv2.UseDebug(log.IsDebugLevel())}
if s.baseURL != "" {
opts = append(opts, atlasv2.UseBaseURL(s.baseURL))
}
c, err := atlasv2.NewClient(opts...)
if err != nil {
return err
}
s.clientv2 = c
return nil
}
// setOpsManagerClient sets the internal client to use an Ops Manager client and methods.
func (s *Store) setOpsManagerClient(client *http.Client) error {
opts := []opsmngr.ClientOpt{opsmngr.SetUserAgent(config.UserAgent)}
if s.baseURL != "" {
opts = append(opts, opsmngr.SetBaseURL(s.baseURL))
}
if log.IsDebugLevel() {
opts = append(opts, opsmngr.SetWithRaw())
}
c, err := opsmngr.New(client, opts...)
if err != nil {
return err
}
c.OnResponseProcessed(func(resp *atlas.Response) {
respHeaders := ""
for key, value := range resp.Header {
respHeaders += fmt.Sprintf("%v: %v\n", key, strings.Join(value, " "))
}
_, _ = log.Debugf(`request:
%v %v
response:
%v %v
%v
%v
`, resp.Request.Method, resp.Request.URL.String(), resp.Proto, resp.Status, respHeaders, string(resp.Raw))
})
s.client = c
return nil
}
// ServiceGetter is a basic interface for service and base url settings.
type ServiceGetter interface {
Service() string
OpsManagerURL() string
}
// AuthenticatedConfig an interface of the methods needed to set up a Store.
type AuthenticatedConfig interface {
CredentialsGetter
ServiceGetter
}
// AuthenticatedPreset is the default Option when connecting to the public API with authentication.
func AuthenticatedPreset(c AuthenticatedConfig) Option {
options := []Option{Service(c.Service()), WithAuthentication(c)}
if baseURLOpt := baseURLOption(c); baseURLOpt != nil {
options = append(options, baseURLOpt)
}
return Options(options...)
}
func baseURLOption(c ServiceGetter) Option {
if configURL := c.OpsManagerURL(); configURL != "" {
return WithBaseURL(configURL)
} else if c.Service() == config.CloudGovService {
return WithBaseURL(cloudGovServiceURL)
}
return nil
}
// UnauthenticatedPreset is the default Option when connecting to the public API without authentication.
func UnauthenticatedPreset(c ServiceGetter) Option {
options := []Option{Service(c.Service())}
if option := baseURLOption(c); option != nil {
options = append(options, option)
}
return Options(options...)
}
// New returns a new Store based on the given list of Option.
//
// Usage:
//
// // get a new Store for Atlas
// store := store.New(Service("cloud"))
//
// // get a new Store for the public API based on a Config interface
// store := store.New(AuthenticatedPreset(config))
//
// // get a new Store for the private API based on a Config interface
// store := store.New(PrivateAuthenticatedPreset(config))
func New(opts ...Option) (*Store, error) {
store := new(Store)
// apply the list of options to Server
for _, opt := range opts {
if err := opt(store); err != nil {
return nil, err
}
}
client, err := store.httpClient(store.transport())
if err != nil {
return nil, err
}
switch store.service {
case config.CloudService, config.CloudGovService:
err = store.setAtlasClient(client)
case config.CloudManagerService, config.OpsManagerService:
err = store.setOpsManagerClient(client)
default:
return nil, fmt.Errorf("%w: %s", errUnsupportedService, store.service)
}
if err != nil {
return nil, err
}
if store.ctx == nil {
store.ctx = context.Background()
}
return store, nil
}