-
Notifications
You must be signed in to change notification settings - Fork 11
/
group_mgmt_client.go
459 lines (406 loc) · 12.4 KB
/
group_mgmt_client.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
// Copyright 2020-2021 Hewlett Packard Enterprise Development LP
package client
import (
"crypto/tls"
"encoding/json"
"fmt"
"strings"
"time"
"github.com/go-resty/resty/v2"
"github.com/hpe-storage/nimble-golang-sdk/pkg/client/v1/nimbleos"
"github.com/hpe-storage/nimble-golang-sdk/pkg/param"
)
const (
groupURIFmtTenant = "https://%s:443/api/tenant/%s"
groupURIFmt = "https://%s:5392/%s"
clientTimeout = time.Minute
maxLoginRetries = 1
jobTimeout = 5 * time.Minute
jobPollInterval = 5 * time.Second
smAsyncJobId = "SM_async_job_id"
)
// GroupMgmtClient :
type GroupMgmtClient struct {
URL string
Client *resty.Client
SessionToken string
WaitOnJob bool
Username string
Password string
isTenant bool
}
// DataWrapper is used to represent a generic JSON API payload
type DataWrapper struct {
Data interface{} `json:"data"`
StartRow *int `json:"startRow,omitempty"`
EndRow *int `json:"endRow,omitempty"`
PageSize *int `json:"pageSize,omitempty"`
TotalRows *int `json:"totalRows,omitempty"`
OperationType *string `json:"operationType,omitempty"`
}
// ErrorResponse is a serializer struct for representing a valid JSON API errors payload.
type ErrorResponse struct {
Messages []*Message `json:"messages"`
}
// Message is an `Error` implementation as well as an implementation of the JSON API error object.
type Message struct {
Code string `json:"code,omitempty"`
Text string `json:"text,omitempty"`
Severity string `json:"severity,omitempty"`
Arguments Argument `json:"arguments,omitempty"`
}
type Argument struct {
JobId string `json:"job_id,omitempty"`
}
func newGroupMgmtClient(ipAddress, username, password, apiVersion string, waitOnJobs, isTenant bool) *GroupMgmtClient {
// Get new resty()
restyClient := resty.New()
restyClient.SetTLSClientConfig(&tls.Config{
InsecureSkipVerify: true,
})
// Create GroupMgmt Client
groupMgmtClient := &GroupMgmtClient{
Client: restyClient,
WaitOnJob: waitOnJobs,
Username: username,
Password: password,
isTenant: isTenant,
}
if groupMgmtClient.isTenant {
groupMgmtClient.URL = fmt.Sprintf(groupURIFmtTenant, ipAddress, apiVersion)
} else {
groupMgmtClient.URL = fmt.Sprintf(groupURIFmt, ipAddress, apiVersion)
}
return groupMgmtClient
}
// NewClient instantiates a new client to communicate with the Nimble group
func NewClient(ipAddress, username, password, apiVersion string, waitOnJobs, isTenant bool) (*GroupMgmtClient, error) {
if apiVersion != "v1" {
return nil, fmt.Errorf("API version \"%s\" is not recognized", apiVersion)
}
// Get resty client
groupMgmtClient := newGroupMgmtClient(ipAddress, username, password, apiVersion, waitOnJobs, isTenant)
// Get session token
sessionToken, err := groupMgmtClient.login(username, password)
if err != nil {
return nil, err
}
groupMgmtClient.SessionToken = sessionToken
// Add retryCondition
// This flag is set during a relogin attempt to prevent retry recursion
reloginInProgress := false
// Add a retry condition to perform a relogin if the session has expired
groupMgmtClient.Client.
AddRetryCondition(
func(resp *resty.Response, err error) bool {
// Attempt relogin on an authorization error if relogin is not already in progress
if err == nil && resp.StatusCode() == 401 && !reloginInProgress {
reloginInProgress = true
sessionToken, err = groupMgmtClient.login(username, password)
reloginInProgress = false
if err != nil {
return false
}
// replace the original client session token with new session token
groupMgmtClient.SessionToken = sessionToken
resp.Request.SetHeader("X-Auth-Token", groupMgmtClient.SessionToken)
return true
}
return false
},
).SetRetryCount(maxLoginRetries)
return groupMgmtClient, nil
}
// EnableDebug : enables debug logging of client request/response
func (client *GroupMgmtClient) EnableDebug() {
client.Client.SetDebug(true)
}
func (client *GroupMgmtClient) login(username, password string) (string, error) {
// Construct Payload
appName := "Go sdkv1 client"
token := &nimbleos.Token{
Username: &username,
Password: &password,
AppName: &appName,
}
token, err := client.GetTokenObjectSet().CreateObject(token)
if err != nil {
return "", err
}
return *token.SessionToken, err
}
// Post :
func (client *GroupMgmtClient) Post(path string, payload interface{}, respHolder interface{}) (interface{}, error) {
// build the url
url := fmt.Sprintf("%s/%s", client.URL, path)
// post it
response, err := client.Client.R().
SetHeader("X-Auth-Token", client.SessionToken).
SetBody(&DataWrapper{
Data: payload,
}).
Post(url)
if err != nil {
return nil, err
}
return processResponse(client, response, path, respHolder, nil)
}
// Put
func (client *GroupMgmtClient) Put(path, id string, payload interface{}, respHolder interface{}) (interface{}, error) {
// build the url
url := fmt.Sprintf("%s/%s/%s", client.URL, path, id)
// Put it
response, err := client.Client.R().
SetHeader("X-Auth-Token", client.SessionToken).
SetBody(&DataWrapper{
Data: payload,
}).
Put(url)
if err != nil {
return nil, err
}
return processResponse(client, response, path, respHolder, nil)
}
// Get : Only used to get a single object with the given ID
func (client *GroupMgmtClient) Get(path string, id string, respHolder interface{}) (interface{}, error) {
// build the url
url := fmt.Sprintf("%s/%s/%s", client.URL, path, id)
// Get it
response, err := client.Client.R().
SetHeader("X-Auth-Token", client.SessionToken).
Get(url)
if err != nil {
return nil, err
}
// convert a 404 (not found) to nil response
if response.StatusCode() == 404 {
return nil, nil
}
return processResponse(client, response, path, respHolder, nil)
}
// Delete :
func (client *GroupMgmtClient) Delete(path string, id string) error {
// build the url
url := fmt.Sprintf("%s/%s/%s", client.URL, path, id)
// delete it
response, err := client.Client.R().
SetHeader("X-Auth-Token", client.SessionToken).
Delete(url)
if err != nil {
return err
}
_, err = processResponse(client, response, path, nil, nil)
return err
}
// List without any params
func (client *GroupMgmtClient) List(path string) (interface{}, error) {
listResp, err := client.ListFromParams(path, nil)
if err != nil {
return nil, err
}
return listResp, nil
}
// ListFromParams :
func (client *GroupMgmtClient) ListFromParams(path string, params *param.GetParams) (interface{}, error) {
wrapper, err := client.listGetOrPost(path, params)
if err != nil {
return nil, err
}
return wrapper, nil
}
func (client *GroupMgmtClient) listGetOrPost(path string, params *param.GetParams) (interface{}, error) {
if params == nil {
return client.listGet(path, nil, nil)
}
// load the url query parameters
queryParams, err := params.BuildQueryParts()
if err != nil {
return nil, err
}
// check if advanced criteria post is required
if params.Filter != nil {
simpleMap, _ := params.Filter.AsSimpleMap()
if simpleMap == nil {
fetch := "fetch"
wrapper := &DataWrapper{
Data: params.Filter,
OperationType: &fetch,
}
if params.Page != nil {
wrapper.StartRow = params.Page.StartRow
wrapper.EndRow = params.Page.EndRow
}
// complex filter, need to POST it
postResp, err := client.listPost(path, wrapper, queryParams, params)
if err != nil {
return nil, err
}
return postResp, nil
} else {
// get request
getResp, err := client.listGet(path, queryParams, params)
if err != nil {
return nil, err
}
return getResp, nil
}
} else {
// get request
getResp, err := client.listGet(path, queryParams, params)
if err != nil {
return nil, err
}
return getResp, nil
}
}
// listPost uses a post request to get all objects on the path using an advanced criteria
func (client *GroupMgmtClient) listPost(
path string,
payload *DataWrapper,
queryParams map[string]string,
params *param.GetParams,
) (interface{}, error) {
// build the url
url := fmt.Sprintf("%s/%s/detail", client.URL, path)
// Post it
response, err := client.Client.R().
SetQueryParams(queryParams).
SetHeader("X-Auth-Token", client.SessionToken).
SetBody(payload).
Post(url)
if err != nil {
return nil, err
}
return processResponse(client, response, path, nil, params)
}
// listGet uses a get request to get all objects on the path
func (client *GroupMgmtClient) listGet(
path string,
queryParams map[string]string,
params *param.GetParams,
) (interface{}, error) {
// build the url
url := fmt.Sprintf("%s/%s/detail", client.URL, path)
response, err := client.Client.R().
SetQueryParams(queryParams).
SetHeader("X-Auth-Token", client.SessionToken).
Get(url)
if err != nil {
return nil, err
}
return processResponse(client, response, path, nil, params)
}
// unwrapData
func unwrapData(body []byte, payload interface{}) (interface{}, *int, error) {
// unmarshal the response
wrapper := &DataWrapper{
Data: payload,
}
err := json.Unmarshal(body, wrapper)
if err != nil {
return nil, nil, err
}
// return it
return wrapper.Data, wrapper.TotalRows, nil
}
//processResponse
func processResponse(client *GroupMgmtClient, response *resty.Response, path string, respHolder interface{}, params *param.GetParams) (interface{}, error) {
// process successfull response
if response.IsSuccess() {
// http code 202, handle async job
if response.StatusCode() == 202 {
id, err := processAsyncResponse(client, response.Body())
if id != nil {
// action rpc may contain different path.
// extract Get uri path from original path.
newPath := strings.Split(path, "/")
return client.Get(newPath[0], id.(string), respHolder)
} else {
return nil, err
}
}
// unmarshall response data
dataIntf, totalRows, err := unwrapData(response.Body(), respHolder)
if params != nil && params.Page != nil && totalRows != nil {
params.Page.TotalRows = totalRows
}
return dataIntf, err
} else {
// error response
return nil, processError(response.StatusCode(), response.Body())
}
}
// process error response
func processError(httpCode int, body []byte) error {
errResp := ""
wrapper := &ErrorResponse{}
err := json.Unmarshal(body, wrapper)
if err != nil {
return err
}
for _, emsg := range wrapper.Messages {
errResp += fmt.Sprintf("%+v", *emsg)
}
return fmt.Errorf("error: http status(%d), messages: %v", httpCode, errResp)
}
//unwrap error response
func unwrapError(body []byte) (string, error) {
errResp := ""
wrapper := &ErrorResponse{}
err := json.Unmarshal(body, wrapper)
if err != nil {
return errResp, err
}
for _, emsg := range wrapper.Messages {
errResp += fmt.Sprintf("%+v", *emsg)
}
return errResp, nil
}
// processAsyncResponse: process http code 202 response
func processAsyncResponse(client *GroupMgmtClient, body []byte) (interface{}, error) {
errResp, _ := unwrapError(body)
if client.WaitOnJob { // check sync flag
unwrapMessage := &ErrorResponse{}
err := json.Unmarshal(body, unwrapMessage)
if err != nil {
return nil, err
}
var jobId string
for _, msg := range unwrapMessage.Messages {
if msg.Code == smAsyncJobId {
jobId = msg.Arguments.JobId
}
}
if len(jobId) == 0 {
return nil, fmt.Errorf("http response error: status (202), but no job ID returned, messages: %v", errResp)
}
id, err := waitForJobResult(jobId, client)
if err != nil {
return nil, fmt.Errorf("http response error: status (202), messages: %v", err.Error())
}
return id, nil
}
return nil, fmt.Errorf("http response error: status (202), messages: %v", errResp)
}
//waitForJobResult : it monitors jobId periodically until job completion or timed out
func waitForJobResult(jobId string, client *GroupMgmtClient) (interface{}, error) {
// Loop over job ids periodically unitl 300 sec timeout or unitl completion of jobs.
intervalChan := time.Tick(jobPollInterval) // control the fequency of GetObject() API call.
timeoutChan := time.After(jobTimeout) // timeout setting, 300 Seconds
for {
select {
case <-intervalChan:
job, err := client.GetJobObjectSet().GetObject(jobId)
if err != nil {
fmt.Printf("Warning : failed to get %s jobId info, err : %s\n", jobId, err.Error())
} else {
var objectId = *job.ObjectId
if string(*job.State) == string(*nimbleos.NsJobStatusDone) {
return objectId, nil
}
}
case <-timeoutChan:
return nil, fmt.Errorf("waitForJobResult: job with ID %v timed out after %v seconds.", jobId, jobTimeout)
}
}
}