/
opsmngr.go
345 lines (302 loc) · 10.7 KB
/
opsmngr.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
// Copyright 2019 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 opsmngr // import "go.mongodb.org/ops-manager/opsmngr"
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"reflect"
"strings"
"github.com/google/go-querystring/query"
atlas "go.mongodb.org/atlas/mongodbatlas"
)
const (
cloudURL = "https://cloud.mongodb.com/"
defaultBaseURL = cloudURL + APIPublicV1Path
userAgent = "go-ops-manager"
jsonMediaType = "application/json"
gzipMediaType = "application/gzip"
// APIPublicV1Path specifies the v1 api path
APIPublicV1Path = "api/public/v1.0/"
)
// Client manages communication with Ops Manager API
type Client struct {
client *http.Client
BaseURL *url.URL
UserAgent string
Organizations OrganizationsService
Projects ProjectsService
Users UsersService
Teams TeamsService
Automation AutomationService
UnauthUsers UnauthUsersService
AlertConfigurations atlas.AlertConfigurationsService
Alerts atlas.AlertsService
ContinuousSnapshots atlas.ContinuousSnapshotsService
ContinuousRestoreJobs atlas.ContinuousRestoreJobsService
Events atlas.EventsService
OrganizationAPIKeys atlas.APIKeysService
ProjectAPIKeys atlas.ProjectAPIKeysService
WhitelistAPIKeys atlas.WhitelistAPIKeysService
Agents AgentsService
Checkpoints CheckpointsService
GlobalAlerts GlobalAlertsService
Deployments DeploymentsService
Measurements MeasurementsService
Clusters ClustersService
Logs LogsService
LogCollections LogCollectionService
Diagnostics DiagnosticsService
GlobalAPIKeys GlobalAPIKeysService
GlobalAPIKeysWhitelist GlobalAPIKeyWhitelistsService
MaintenanceWindows MaintenanceWindowsService
PerformanceAdvisor PerformanceAdvisorService
VersionManifest VersionManifestService
BackupConfigs BackupConfigsService
ProjectJobConfig ProjectJobConfigService
BlockstoreConfig BlockstoreConfigService
FileSystemStoreConfig FileSystemStoreConfigService
S3BlockstoreConfig S3BlockstoreConfigService
OplogStoreConfig OplogStoreConfigService
SyncStoreConfig SyncStoreConfigService
DaemonConfig DaemonConfigService
SnapshotSchedule SnapshotScheduleService
FeatureControlPolicies FeatureControlPoliciesService
ServerUsage ServerUsageService
ServerUsageReport ServerUsageReportService
onRequestCompleted atlas.RequestCompletionCallback
}
type service struct {
Client atlas.RequestDoer
}
// NewClient returns a new Ops Manager API client. If a nil httpClient is
// provided, a http.DefaultClient will be used. To use API methods which require
// authentication, provide an http.Client that will perform the authentication
// for you (such as that provided by the https://github.com/mongodb-forks/digest).
func NewClient(httpClient *http.Client) *Client {
if httpClient == nil {
httpClient = http.DefaultClient
}
baseURL, _ := url.Parse(defaultBaseURL)
c := &Client{
client: httpClient,
BaseURL: baseURL,
UserAgent: userAgent,
}
c.Organizations = &OrganizationsServiceOp{Client: c}
c.Projects = &ProjectsServiceOp{Client: c}
c.Users = &UsersServiceOp{Client: c}
c.Teams = &TeamsServiceOp{Client: c}
c.Automation = &AutomationServiceOp{Client: c}
c.AlertConfigurations = &atlas.AlertConfigurationsServiceOp{Client: c}
c.UnauthUsers = &UnauthUsersServiceOp{Client: c}
c.ContinuousSnapshots = &atlas.ContinuousSnapshotsServiceOp{Client: c}
c.ContinuousRestoreJobs = &atlas.ContinuousRestoreJobsServiceOp{Client: c}
c.Agents = &AgentsServiceOp{Client: c}
c.Checkpoints = &CheckpointsServiceOp{Client: c}
c.Alerts = &atlas.AlertsServiceOp{Client: c}
c.GlobalAlerts = &GlobalAlertsServiceOp{Client: c}
c.Events = &atlas.EventsServiceOp{Client: c}
c.Deployments = &DeploymentsServiceOp{Client: c}
c.Measurements = &MeasurementsServiceOp{Client: c}
c.Clusters = &ClustersServiceOp{Client: c}
c.Logs = &LogsServiceOp{Client: c}
c.LogCollections = &LogCollectionServiceOp{Client: c}
c.Diagnostics = &DiagnosticsServiceOp{Client: c}
c.OrganizationAPIKeys = &atlas.APIKeysServiceOp{Client: c}
c.ProjectAPIKeys = &atlas.ProjectAPIKeysOp{Client: c}
c.WhitelistAPIKeys = &atlas.WhitelistAPIKeysServiceOp{Client: c}
c.GlobalAPIKeys = &GlobalAPIKeysServiceOp{Client: c}
c.GlobalAPIKeysWhitelist = &GlobalAPIKeyWhitelistsServiceOp{Client: c}
c.MaintenanceWindows = &MaintenanceWindowsServiceOp{Client: c}
c.PerformanceAdvisor = &PerformanceAdvisorServiceOp{Client: c}
c.VersionManifest = &VersionManifestServiceOp{Client: c}
c.BackupConfigs = &BackupConfigsServiceOp{Client: c}
c.ProjectJobConfig = &ProjectJobConfigServiceOp{Client: c}
c.BlockstoreConfig = &BlockstoreConfigServiceOp{Client: c}
c.FileSystemStoreConfig = &FileSystemStoreConfigServiceOp{Client: c}
c.S3BlockstoreConfig = &S3BlockstoreConfigServiceOp{Client: c}
c.OplogStoreConfig = &OplogStoreConfigServiceOp{Client: c}
c.SyncStoreConfig = &SyncStoreConfigServiceOp{Client: c}
c.DaemonConfig = &DaemonConfigServiceOp{Client: c}
c.SnapshotSchedule = &SnapshotScheduleServiceOp{Client: c}
c.FeatureControlPolicies = &FeatureControlPoliciesServiceOp{Client: c}
c.ServerUsage = &ServerUsageServiceOp{Client: c}
c.ServerUsageReport = &ServerUsageReportServiceOp{Client: c}
return c
}
// ClientOpt are options for New.
type ClientOpt func(*Client) error
// New returns a new Ops Manager API client instance.
func New(httpClient *http.Client, opts ...ClientOpt) (*Client, error) {
c := NewClient(httpClient)
for _, opt := range opts {
if err := opt(c); err != nil {
return nil, err
}
}
return c, nil
}
// SetBaseURL is a client option for setting the base URL.
func SetBaseURL(bu string) ClientOpt {
return func(c *Client) error {
u, err := url.Parse(bu)
if err != nil {
return err
}
c.BaseURL = u
return nil
}
}
// SetUserAgent is a client option for setting the user agent.
func SetUserAgent(ua string) ClientOpt {
return func(c *Client) error {
c.UserAgent = fmt.Sprintf("%s %s", ua, c.UserAgent)
return nil
}
}
// NewRequest creates an API request. A relative URL can be provided in urlStr,
// in which case it is resolved relative to the BaseURL of the Client.
// Relative URLs should always be specified without a preceding slash. If
// specified, the value pointed to by body is JSON encoded and included as the
// request body.
func (c *Client) NewRequest(ctx context.Context, method, urlStr string, body interface{}) (*http.Request, error) {
if !strings.HasSuffix(c.BaseURL.Path, "/") {
return nil, fmt.Errorf("base URL must have a trailing slash, but %q does not", c.BaseURL)
}
u, err := c.BaseURL.Parse(urlStr)
if err != nil {
return nil, err
}
var buf io.ReadWriter
if body != nil {
buf = &bytes.Buffer{}
enc := json.NewEncoder(buf)
enc.SetEscapeHTML(false)
err = enc.Encode(body)
if err != nil {
return nil, err
}
}
req, err := http.NewRequest(method, u.String(), buf)
if err != nil {
return nil, err
}
if body != nil {
req.Header.Set("Content-Type", jsonMediaType)
}
req.Header.Add("Accept", jsonMediaType)
if c.UserAgent != "" {
req.Header.Set("User-Agent", c.UserAgent)
}
return req, nil
}
// NewGZipRequest creates an API gzip request. A relative URL can be provided in urlStr,
// in which case it is resolved relative to the BaseURL of the Client.
// Relative URLs should always be specified without a preceding slash. If
// specified, the value pointed to by body is JSON encoded and included as the
// request body.
func (c *Client) NewGZipRequest(ctx context.Context, method, urlStr string) (*http.Request, error) {
if !strings.HasSuffix(c.BaseURL.Path, "/") {
return nil, fmt.Errorf("base URL must have a trailing slash, but %q does not", c.BaseURL)
}
rel, err := url.Parse(urlStr)
if err != nil {
return nil, err
}
u := c.BaseURL.ResolveReference(rel)
req, err := http.NewRequest(method, u.String(), nil)
if err != nil {
return nil, err
}
req.Header.Add("Accept", gzipMediaType)
if c.UserAgent != "" {
req.Header.Set("User-Agent", c.UserAgent)
}
return req, nil
}
// OnRequestCompleted sets the DO API request completion callback
func (c *Client) OnRequestCompleted(rc atlas.RequestCompletionCallback) {
c.onRequestCompleted = rc
}
// Do sends an API request and returns the API response. The API response is JSON decoded and stored in the value
// pointed to by v, or returned as an error if an API error has occurred. If v implements the io.Writer interface,
// the raw response will be written to v, without attempting to decode it.
// The provided ctx must be non-nil, if it is nil an error is returned. If it is canceled or times out,
// ctx.Err() will be returned.
func (c *Client) Do(ctx context.Context, req *http.Request, v interface{}) (*atlas.Response, error) {
if ctx == nil {
return nil, errors.New("context must be non-nil")
}
req = req.WithContext(ctx)
resp, err := c.client.Do(req)
if err != nil {
// If we got an error, and the context has been canceled,
// the context's error is probably more useful.
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
}
return nil, err
}
if c.onRequestCompleted != nil {
c.onRequestCompleted(req, resp)
}
defer resp.Body.Close()
response := &atlas.Response{Response: resp}
err = atlas.CheckResponse(resp)
if err != nil {
return response, err
}
if v != nil {
if w, ok := v.(io.Writer); ok {
_, _ = io.Copy(w, resp.Body)
} else {
decErr := json.NewDecoder(resp.Body).Decode(v)
if decErr == io.EOF {
decErr = nil // ignore EOF errors caused by empty response body
}
if decErr != nil {
err = decErr
}
}
}
return response, err
}
func setQueryParams(s string, opt interface{}) (string, error) {
v := reflect.ValueOf(opt)
if v.Kind() == reflect.Ptr && v.IsNil() {
return s, nil
}
origURL, err := url.Parse(s)
if err != nil {
return s, err
}
origValues := origURL.Query()
newValues, err := query.Values(opt)
if err != nil {
return s, err
}
for k, v := range newValues {
origValues[k] = v
}
origURL.RawQuery = origValues.Encode()
return origURL.String(), nil
}