-
Notifications
You must be signed in to change notification settings - Fork 13
/
subscription.go
445 lines (376 loc) · 14.3 KB
/
subscription.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
package apic
// TODO - this file should be able to be removed once Unified Catalog support has been removed
import (
"encoding/json"
"fmt"
"net/http"
coreapi "github.com/Axway/agent-sdk/pkg/api"
v1 "github.com/Axway/agent-sdk/pkg/apic/apiserver/models/api/v1"
defs "github.com/Axway/agent-sdk/pkg/apic/definitions"
uc "github.com/Axway/agent-sdk/pkg/apic/unifiedcatalog/models"
"github.com/Axway/agent-sdk/pkg/util"
agenterrors "github.com/Axway/agent-sdk/pkg/util/errors"
log "github.com/Axway/agent-sdk/pkg/util/log"
)
// SubscriptionState - Type definition for subscription state
type SubscriptionState string
// SubscriptionState
const (
SubscriptionApproved = SubscriptionState("APPROVED")
SubscriptionRequested = SubscriptionState("REQUESTED")
SubscriptionRejected = SubscriptionState("REJECTED")
SubscriptionActive = SubscriptionState("ACTIVE")
SubscriptionUnsubscribed = SubscriptionState("UNSUBSCRIBED")
SubscriptionUnsubscribeInitiated = SubscriptionState("UNSUBSCRIBE_INITIATED")
SubscriptionFailedToSubscribe = SubscriptionState("FAILED_TO_SUBSCRIBE")
SubscriptionFailedToUnsubscribe = SubscriptionState("FAILED_TO_UNSUBSCRIBE")
SubscriptionChangeRequested = SubscriptionState("CHANGE_REQUESTED")
AccessRequestProvisioning = SubscriptionState("provisioning")
AccessRequestProvisioned = SubscriptionState("provisioned")
AccessRequestFailedProvisioning = SubscriptionState("failedProvisioning")
AccessRequestDeprovisioning = SubscriptionState("deprovisioning")
AccessRequestDeprovisioned = SubscriptionState("deprovisioned")
AccessRequestFailedDeprovisioning = SubscriptionState("failedDeprovisioning")
)
var catalogToAccessRequestStateMap = map[SubscriptionState]SubscriptionState{
SubscriptionApproved: AccessRequestProvisioning,
SubscriptionRequested: AccessRequestFailedProvisioning,
SubscriptionRejected: AccessRequestFailedProvisioning,
SubscriptionActive: AccessRequestProvisioned,
SubscriptionUnsubscribed: AccessRequestDeprovisioned,
SubscriptionUnsubscribeInitiated: AccessRequestDeprovisioning,
SubscriptionFailedToSubscribe: AccessRequestFailedProvisioning,
SubscriptionFailedToUnsubscribe: AccessRequestFailedDeprovisioning,
}
// getAccessRequestState - gets the access request state equivalent from a subscription state
func (s SubscriptionState) getAccessRequestState() SubscriptionState {
if state, found := catalogToAccessRequestStateMap[s]; found {
return state
}
return s
}
// isUnifiedCatalogState - returns true is the state is a unified catalog state
func (s SubscriptionState) isUnifiedCatalogState() bool {
_, found := catalogToAccessRequestStateMap[s]
return found
}
const (
appNameKey = "appName"
subscriptionAppNameType = "string"
profileKey = "profile"
)
// Subscription -
type Subscription interface {
GetID() string
GetName() string
GetApicID() string
GetRemoteAPIAttributes() map[string]string
GetRemoteAPIID() string
GetRemoteAPIStage() string
GetCatalogItemID() string
GetCreatedUserID() string
GetState() SubscriptionState
GetPropertyValue(propertyKey string) string
GetPropertyValues(propertyKey string) []interface{}
UpdateState(newState SubscriptionState, description string) error
UpdateStateWithProperties(newState SubscriptionState, description string, properties map[string]interface{}) error
UpdateEnumProperty(key, value, dataType string) error
UpdateProperties(appName string) error
UpdatePropertyValues(values map[string]interface{}) error
setAPIResourceInfo(apiServerResource *v1.ResourceInstance)
}
// CentralSubscription -
type CentralSubscription struct {
Subscription
CatalogItemSubscription *uc.CatalogItemSubscription `json:"catalogItemSubscription"`
ApicID string `json:"-"`
RemoteAPIID string `json:"-"`
RemoteAPIStage string `json:"-"`
apicClient *ServiceClient
RemoteAPIAttributes map[string]string
}
// GetRemoteAPIAttributes - Returns the attributes from the API that the subscription is tied to.
func (s *CentralSubscription) GetRemoteAPIAttributes() map[string]string {
return s.RemoteAPIAttributes
}
// GetCreatedUserID - Returns ID of the user that created the subscription
func (s *CentralSubscription) GetCreatedUserID() string {
return s.CatalogItemSubscription.Metadata.CreateUserId
}
// GetID - Returns ID of the subscription
func (s *CentralSubscription) GetID() string {
return s.CatalogItemSubscription.Id
}
// GetName - Returns Name of the subscription
func (s *CentralSubscription) GetName() string {
return s.CatalogItemSubscription.Name
}
// GetApicID - Returns ID of the Catalog Item or API Service instance
func (s *CentralSubscription) GetApicID() string {
return s.ApicID
}
// GetRemoteAPIID - Returns ID of the API on remote gateway
func (s *CentralSubscription) GetRemoteAPIID() string {
return s.RemoteAPIID
}
// GetRemoteAPIStage - Returns the stage name of the API on remote gateway
func (s *CentralSubscription) GetRemoteAPIStage() string {
return s.RemoteAPIStage
}
// GetCatalogItemID - Returns ID of the Catalog Item
func (s *CentralSubscription) GetCatalogItemID() string {
return s.CatalogItemSubscription.CatalogItemId
}
// GetState - Returns subscription state
func (s *CentralSubscription) GetState() SubscriptionState {
return SubscriptionState(s.CatalogItemSubscription.State)
}
// GetPropertyValue - Returns subscription Property value based on the key
func (s *CentralSubscription) GetPropertyValue(propertyKey string) string {
if len(s.CatalogItemSubscription.Properties) > 0 {
subscriptionProperty := s.CatalogItemSubscription.Properties[0]
value, ok := subscriptionProperty.Value[propertyKey]
if ok {
return fmt.Sprintf("%v", value)
}
}
return ""
}
// GetPropertyValues - Returns subscription Property value based on the key
func (s *CentralSubscription) GetPropertyValues(propertyKey string) []interface{} {
if len(s.CatalogItemSubscription.Properties) > 0 {
subscriptionProperty := s.CatalogItemSubscription.Properties[0]
if valueI, ok := subscriptionProperty.Value[propertyKey]; ok {
if valueA, isArray := valueI.([]interface{}); isArray && len(valueA) > 0 {
return valueA
}
}
}
return nil
}
func (s *CentralSubscription) updateProperties(properties map[string]interface{}) error {
if len(properties) == 0 {
return nil
}
// keep existing properties
var profile map[string]interface{}
for _, p := range s.CatalogItemSubscription.Properties {
if p.Key == profileKey {
profile = p.Value
}
}
allProps := map[string]interface{}{}
// keep existing properties
for k, v := range profile {
allProps[k] = v
}
// override with new values
for k, v := range properties {
allProps[k] = v
}
return s.updatePropertyValue(profileKey, allProps)
}
func (s *CentralSubscription) updateCatalogSubscriptionState(newState SubscriptionState, description string) (*coreapi.Request, error) {
headers, err := s.getServiceClient().createHeader()
if err != nil {
return nil, err
}
// Catalog has a requirement for the description to be < 350 characters.
if len(description) > 350 {
log.Warnf("Truncating description. Description to update catalog subscription state is greater than the 350 allowable characters [%s]", description)
description = description[:350]
}
subState := uc.CatalogItemSubscriptionState{
Description: description,
State: string(newState),
}
statePostBody, err := json.Marshal(subState)
if err != nil {
return nil, err
}
return &coreapi.Request{
Method: coreapi.POST,
URL: s.getServiceClient().cfg.GetCatalogItemSubscriptionStatesURL(s.GetCatalogItemID(), s.GetID()),
QueryParams: nil,
Headers: headers,
Body: statePostBody,
}, nil
}
// UpdateStateWithProperties - Updates the state of subscription
func (s *CentralSubscription) UpdateStateWithProperties(newState SubscriptionState, description string, properties map[string]interface{}) error {
if err := s.updateProperties(properties); err != nil {
return err
}
request, err := s.updateCatalogSubscriptionState(newState, description)
if err != nil {
return err
}
if response, err := s.getServiceClient().apiClient.Send(*request); err != nil {
return agenterrors.Wrap(ErrSubscriptionQuery, err.Error())
} else if !(response.Code == http.StatusOK || response.Code == http.StatusCreated) {
readResponseErrors(response.Code, response.Body)
return ErrSubscriptionResp.FormatError(response.Code)
}
return nil
}
// UpdateState - Updates the state of subscription
func (s *CentralSubscription) UpdateState(newState SubscriptionState, description string) error {
return s.UpdateStateWithProperties(newState, description, map[string]interface{}{})
}
// getServiceClient - returns the apic client
func (s *CentralSubscription) getServiceClient() *ServiceClient {
return s.apicClient
}
// UpdateEnumProperty -
func (s *CentralSubscription) UpdateEnumProperty(key, newValue, dataType string) error {
catalogItemID := s.GetCatalogItemID()
// First need to get the subscriptionDefProperties for the catalog item
ss, err := s.getServiceClient().GetSubscriptionDefinitionPropertiesForCatalogItem(catalogItemID, profileKey)
if ss == nil || err != nil {
return agenterrors.Wrap(ErrGetSubscriptionDefProperties, err.Error())
}
// update the appName in the enum
prop := ss.GetProperty(key)
// first check that the property is unique
for _, ele := range prop.Enum {
if ele == newValue {
return nil
}
}
newOptions := append(prop.Enum, newValue)
ss.AddProperty(key, dataType, prop.Description, "", true, newOptions)
// note: there will be a small time window where the enum items might be out-of-order. The agent will eventually
// pick up the changes and update the schema, which will reorder them.
// update the the subscriptionDefProperties for the catalog item. This MUST be done before updating the subscription
err = s.getServiceClient().UpdateSubscriptionDefinitionPropertiesForCatalogItem(catalogItemID, profileKey, ss)
if err != nil {
return agenterrors.Wrap(ErrUpdateSubscriptionDefProperties, err.Error())
}
return nil
}
// UpdateProperties -
func (s *CentralSubscription) UpdateProperties(appName string) error {
err := s.UpdateEnumProperty(appNameKey, appName, subscriptionAppNameType)
if err != nil {
return err
}
// Now we can update the appname in the subscription itself
err = s.updatePropertyValue(profileKey, map[string]interface{}{appNameKey: appName})
if err != nil {
return agenterrors.Wrap(ErrUpdateSubscriptionDefProperties, err.Error())
}
return nil
}
// updatePropertyValue - Updates the property value of the subscription
func (s *CentralSubscription) updatePropertyValue(propertyKey string, value map[string]interface{}) error {
headers, err := s.getServiceClient().createHeader()
if err != nil {
return err
}
url := fmt.Sprintf("%s/%s", s.getServiceClient().cfg.GetCatalogItemSubscriptionPropertiesURL(s.GetCatalogItemID(), s.GetID()), propertyKey)
body, err := json.Marshal(value)
if err != nil {
return err
}
request := coreapi.Request{
Method: coreapi.PUT,
URL: url,
Headers: headers,
Body: body,
}
response, err := s.getServiceClient().apiClient.Send(request)
if err != nil {
return err
}
if response.Code != http.StatusOK {
readResponseErrors(response.Code, response.Body)
return ErrSubscriptionResp.FormatError(response.Code)
}
return nil
}
// UpdatePropertyValues - Updates the property values of the subscription
func (s *CentralSubscription) UpdatePropertyValues(values map[string]interface{}) error {
headers, err := s.getServiceClient().createHeader()
if err != nil {
return err
}
url := fmt.Sprintf("%s/%s", s.getServiceClient().cfg.GetCatalogItemSubscriptionPropertiesURL(s.GetCatalogItemID(), s.GetID()), profileKey)
body, err := json.Marshal(values)
if err != nil {
return err
}
request := coreapi.Request{
Method: coreapi.PUT,
URL: url,
Headers: headers,
Body: body,
}
response, err := s.getServiceClient().apiClient.Send(request)
if err != nil {
return err
}
if response.Code != http.StatusOK {
readResponseErrors(response.Code, response.Body)
return ErrSubscriptionResp.FormatError(response.Code)
}
return nil
}
func (s *CentralSubscription) setAPIResourceInfo(apiServerResource *v1.ResourceInstance) {
s.ApicID = apiServerResource.Metadata.ID
apiID, _ := util.GetAgentDetailsValue(apiServerResource, defs.AttrExternalAPIID)
stage, _ := util.GetAgentDetailsValue(apiServerResource, defs.AttrExternalAPIStage)
s.RemoteAPIID = apiID
s.RemoteAPIStage = stage
// get the x agent details for this, convert to map[string]string
s.RemoteAPIAttributes = util.MapStringInterfaceToStringString(util.GetAgentDetails(apiServerResource))
}
// getSubscriptions -
func (c *ServiceClient) getSubscriptions(states []string) ([]CentralSubscription, error) {
queryParams := make(map[string]string)
searchQuery := ""
for _, state := range states {
if searchQuery != "" {
searchQuery += ","
}
searchQuery += "state==" + state
}
queryParams["query"] = searchQuery
resBody, err := c.sendSubscriptionsRequest(c.cfg.GetSubscriptionURL(), queryParams)
if err != nil {
return nil, agenterrors.Wrap(ErrSubscriptionQuery, err.Error())
}
subscriptions := make([]uc.CatalogItemSubscription, 0)
json.Unmarshal(resBody, &subscriptions)
// build the Subscription from the UC ones
subs := make([]CentralSubscription, 0)
for i := range subscriptions {
sub := CentralSubscription{
CatalogItemSubscription: &subscriptions[i],
apicClient: c,
}
subs = append(subs, sub)
}
return subs, nil
}
func (c *ServiceClient) sendSubscriptionsRequest(url string, queryParams map[string]string) ([]byte, error) {
headers, err := c.createHeader()
if err != nil {
return nil, err
}
request := coreapi.Request{
Method: coreapi.GET,
URL: url,
QueryParams: queryParams,
Headers: headers,
Body: nil,
}
response, err := c.apiClient.Send(request)
if err != nil {
return nil, agenterrors.Wrap(ErrSubscriptionQuery, err.Error())
}
if response.Code != http.StatusOK && response.Code != http.StatusNotFound {
readResponseErrors(response.Code, response.Body)
return nil, ErrSubscriptionResp.FormatError(response.Code)
}
return response.Body, nil
}