-
Notifications
You must be signed in to change notification settings - Fork 13
/
consumerinstance.go
463 lines (392 loc) · 15.5 KB
/
consumerinstance.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
package apic
import (
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"net/http"
"strconv"
"github.com/Axway/agent-sdk/pkg/util"
coreapi "github.com/Axway/agent-sdk/pkg/api"
apiv1 "github.com/Axway/agent-sdk/pkg/apic/apiserver/models/api/v1"
management "github.com/Axway/agent-sdk/pkg/apic/apiserver/models/management/v1alpha1"
defs "github.com/Axway/agent-sdk/pkg/apic/definitions"
corecfg "github.com/Axway/agent-sdk/pkg/config"
utilerrors "github.com/Axway/agent-sdk/pkg/util/errors"
"github.com/Axway/agent-sdk/pkg/util/log"
"github.com/gabriel-vasile/mimetype"
)
// TODO - this file should be able to be removed once Unified Catalog support has been removed
func (c *ServiceClient) buildConsumerInstanceSpec(serviceBody *ServiceBody, doc string, categories []string) management.ConsumerInstanceSpec {
subscriptionDefinitionName := serviceBody.SubscriptionName
autoSubscribe := false
if c.cfg.GetSubscriptionConfig().GetSubscriptionApprovalMode() == corecfg.AutoApproval {
autoSubscribe = true
}
// Set default state to published
if serviceBody.State == "" {
serviceBody.State = PublishedState
}
enableSubscription := c.enableSubscription(serviceBody)
owningTeam := c.cfg.GetTeamName()
// If there is an organizationName in the serviceBody, try to find a match in the map of Central teams.
// If found, use that as the owningTeam for the service. Otherwise, use the configured default team.
if serviceBody.TeamName != "" {
if _, found := c.getTeamFromCache(serviceBody.TeamName); found {
owningTeam = serviceBody.TeamName
} else {
teamForMsg := "the default team"
if owningTeam != "" {
teamForMsg = fmt.Sprintf("team %s", owningTeam)
}
log.Infof("Amplify Central does not contain a team named %s for API %s. The Catalog Item will be assigned to %s.",
serviceBody.TeamName, serviceBody.APIName, teamForMsg)
}
}
return management.ConsumerInstanceSpec{
Name: serviceBody.NameToPush,
ApiServiceInstance: serviceBody.serviceContext.instanceName,
Description: serviceBody.Description,
Visibility: "RESTRICTED",
Version: serviceBody.Version,
State: serviceBody.State,
Status: serviceBody.Status,
Tags: mapToTagsArray(serviceBody.Tags, c.cfg.GetTagsToPublish()),
Documentation: doc,
OwningTeam: owningTeam,
Subscription: management.ConsumerInstanceSpecSubscription{
Enabled: enableSubscription,
AutoSubscribe: autoSubscribe,
SubscriptionDefinition: subscriptionDefinitionName,
},
UnstructuredDataProperties: c.buildUnstructuredDataProperties(serviceBody),
Categories: categories,
}
}
// buildUnstructuredDataProperties - creates the unstructured data properties portion of the consumer instance
func (c *ServiceClient) buildUnstructuredDataProperties(serviceBody *ServiceBody) management.ConsumerInstanceSpecUnstructuredDataProperties {
if serviceBody.ResourceType != Unstructured {
return management.ConsumerInstanceSpecUnstructuredDataProperties{}
}
const defType = "Asset"
unstructuredDataProperties := management.ConsumerInstanceSpecUnstructuredDataProperties{
Type: defType,
ContentType: mimetype.Detect(serviceBody.SpecDefinition).String(),
Label: defType,
FileName: serviceBody.APIName,
Data: base64.StdEncoding.EncodeToString(serviceBody.SpecDefinition),
}
if serviceBody.UnstructuredProps.AssetType != "" {
unstructuredDataProperties.Type = serviceBody.UnstructuredProps.AssetType
// Set the label to the same as the asset type
unstructuredDataProperties.Label = serviceBody.UnstructuredProps.AssetType
}
if serviceBody.UnstructuredProps.ContentType != "" {
unstructuredDataProperties.ContentType = serviceBody.UnstructuredProps.ContentType
}
if serviceBody.UnstructuredProps.Label != "" {
unstructuredDataProperties.Label = serviceBody.UnstructuredProps.Label
if serviceBody.UnstructuredProps.AssetType == "" {
unstructuredDataProperties.Type = serviceBody.UnstructuredProps.Label
}
}
if serviceBody.UnstructuredProps.Filename != "" {
unstructuredDataProperties.FileName = serviceBody.UnstructuredProps.Filename
}
return unstructuredDataProperties
}
func (c *ServiceClient) enableSubscription(serviceBody *ServiceBody) bool {
if len(serviceBody.authPolicies) > 0 {
serviceBody.AuthPolicy = serviceBody.authPolicies[0] // use the first auth policy
}
enableSubscription := serviceBody.AuthPolicy != Passthrough
// if there isn't a registered subscription schema, do not enable subscriptions,
// or if the status is not PUBLISHED, do not enable subscriptions
if serviceBody.Status != PublishedStatus || serviceBody.SubscriptionName == "" {
enableSubscription = false
}
if enableSubscription {
log.Debugf("Subscriptions will be enabled for '%s'", serviceBody.APIName)
} else {
log.Debugf("Subscriptions will be disabled for '%s', either because the authPolicy is pass-through or there is not a registered subscription schema", serviceBody.APIName)
}
return enableSubscription
}
func (c *ServiceClient) buildConsumerInstance(serviceBody *ServiceBody, name string, doc string) *management.ConsumerInstance {
owner, _ := c.getOwnerObject(serviceBody, false) // owner, _ := at this point, we don't need to validate error on getOwnerObject. This is used for subresource status update
ci := &management.ConsumerInstance{
ResourceMeta: apiv1.ResourceMeta{
GroupVersionKind: management.ConsumerInstanceGVK(),
Name: name,
Title: serviceBody.NameToPush,
Attributes: util.CheckEmptyMapStringString(serviceBody.InstanceAttributes),
Tags: mapToTagsArray(serviceBody.Tags, c.cfg.GetTagsToPublish()),
Metadata: apiv1.Metadata{
Scope: apiv1.MetadataScope{
Kind: management.EnvironmentGVK().Kind,
Name: c.cfg.GetEnvironmentName(),
},
},
},
Spec: c.buildConsumerInstanceSpec(serviceBody, doc, serviceBody.categoryNames),
Owner: owner,
}
ciDetails := util.MergeMapStringInterface(serviceBody.ServiceAgentDetails, serviceBody.InstanceAgentDetails)
agentDetails := buildAgentDetailsSubResource(serviceBody, false, ciDetails)
util.SetAgentDetails(ci, agentDetails)
return ci
}
func (c *ServiceClient) updateConsumerInstance(serviceBody *ServiceBody, ci *management.ConsumerInstance, doc string) {
ci.GroupVersionKind = management.ConsumerInstanceGVK()
ci.Metadata.ResourceVersion = ""
ci.Title = serviceBody.NameToPush
ci.Tags = mapToTagsArray(serviceBody.Tags, c.cfg.GetTagsToPublish())
ci.Owner, _ = c.getOwnerObject(serviceBody, false)
ci.Attributes = util.CheckEmptyMapStringString(serviceBody.InstanceAttributes)
ciDetails := util.MergeMapStringInterface(serviceBody.ServiceAgentDetails, serviceBody.InstanceAgentDetails)
agentDetails := buildAgentDetailsSubResource(serviceBody, false, ciDetails)
util.SetAgentDetails(ci, agentDetails)
// use existing categories only if mappings have not been configured
categories := ci.Spec.Categories
if corecfg.IsMappingConfigured() {
// use only mapping categories if mapping was configured
categories = serviceBody.categoryNames
}
ci.Spec = c.buildConsumerInstanceSpec(serviceBody, doc, categories)
}
// processConsumerInstance - deal with either a create or update of a consumerInstance
func (c *ServiceClient) processConsumerInstance(serviceBody *ServiceBody) error {
// Before attempting to create the consumer instance ensure all categories exist
for _, categoryTitle := range serviceBody.categoryTitles {
categoryName := c.GetOrCreateCategory(categoryTitle)
// only add categories that exist on central
if categoryName != "" {
serviceBody.categoryNames = append(serviceBody.categoryNames, categoryName)
}
}
// Allow catalog asset to be created. However, set to pass-through so subscriptions aren't enabled
if !isValidAuthPolicy(serviceBody.AuthPolicy) {
log.Warnf("'%s' has an inbound policy of (%s) and is not supported. Catalog asset will be created with a pass-through inbound policy. ", serviceBody.APIName, serviceBody.AuthPolicy)
serviceBody.AuthPolicy = Passthrough
serviceBody.Status = UnidentifiedInboundPolicy
}
var doc = ""
if serviceBody.Documentation != nil {
var err error
doc, err = strconv.Unquote(string(serviceBody.Documentation))
if err != nil {
return err
}
}
consumerInstanceName := serviceBody.serviceContext.serviceName
if serviceBody.Stage != "" {
consumerInstanceName = sanitizeAPIName(fmt.Sprintf("%s-%s", serviceBody.serviceContext.serviceName, serviceBody.Stage))
}
httpMethod := http.MethodPost
consumerInstanceURL := c.cfg.GetConsumerInstancesURL()
var instance *management.ConsumerInstance
var err error
if serviceBody.serviceContext.serviceAction == updateAPI {
instance, err = c.getConsumerInstanceByName(consumerInstanceName)
if err != nil {
return err
}
}
if instance != nil {
httpMethod = http.MethodPut
consumerInstanceURL += "/" + consumerInstanceName
c.updateConsumerInstance(serviceBody, instance, doc)
} else {
instance = c.buildConsumerInstance(serviceBody, consumerInstanceName, doc)
}
return c.deployAPI(instance, httpMethod, consumerInstanceURL, serviceBody, consumerInstanceName)
}
func (c *ServiceClient) deployAPI(instance *management.ConsumerInstance, httpMethod, consumerInstanceURL string, serviceBody *ServiceBody, consumerInstanceName string) error {
buffer, err := json.Marshal(instance)
if err != nil {
return err
}
_, err = c.apiServiceDeployAPI(httpMethod, consumerInstanceURL, buffer)
if err != nil && serviceBody.serviceContext.serviceAction == addAPI {
return c.rollback(serviceBody.serviceContext.serviceName, err)
}
if err == nil && len(instance.SubResources) > 0 {
if xAgentDetail, ok := instance.SubResources[defs.XAgentDetails]; ok {
subResources := map[string]interface{}{
defs.XAgentDetails: xAgentDetail,
}
err = c.CreateSubResource(instance.ResourceMeta, subResources)
if err != nil {
return c.rollback(serviceBody.serviceContext.serviceName, err)
}
return err
}
}
serviceBody.serviceContext.consumerInstanceName = consumerInstanceName
return nil
}
func (c *ServiceClient) rollback(serviceName string, err error) error {
if err != nil {
_, rollbackErr := c.rollbackAPIService(serviceName)
if rollbackErr != nil {
return errors.New(err.Error() + rollbackErr.Error())
}
}
return err
}
// getAPIServerConsumerInstance -
func (c *ServiceClient) getAPIServerConsumerInstance(name string, query map[string]string) (*management.ConsumerInstance, error) {
headers, err := c.createHeader()
if err != nil {
return nil, err
}
consumerInstanceURL := c.cfg.GetConsumerInstancesURL() + "/" + name
request := coreapi.Request{
Method: coreapi.GET,
URL: consumerInstanceURL,
Headers: headers,
QueryParams: query,
}
response, err := c.apiClient.Send(request)
if err != nil {
return nil, err
}
if response.Code != http.StatusOK {
if response.Code != http.StatusNotFound {
responseErr := readResponseErrors(response.Code, response.Body)
return nil, utilerrors.Wrap(ErrRequestQuery, responseErr)
}
return nil, nil
}
consumerInstance := new(management.ConsumerInstance)
err = json.Unmarshal(response.Body, consumerInstance)
return consumerInstance, err
}
// UpdateConsumerInstanceSubscriptionDefinition -
func (c *ServiceClient) UpdateConsumerInstanceSubscriptionDefinition(externalAPIID, subscriptionDefinitionName string) error {
consumerInstance, err := c.getConsumerInstancesByExternalAPIID(externalAPIID)
if err != nil {
return err
}
// Update the subscription definition
if consumerInstance[0].Spec.Subscription.SubscriptionDefinition == subscriptionDefinitionName {
return nil // no updates to be made
}
consumerInstance[0].Metadata.ResourceVersion = ""
consumerInstance[0].Spec.Subscription.SubscriptionDefinition = subscriptionDefinitionName
consumerInstanceURL := c.cfg.GetConsumerInstancesURL() + "/" + consumerInstance[0].Name
buffer, err := json.Marshal(consumerInstance)
if err != nil {
return err
}
_, err = c.apiServiceDeployAPI(http.MethodPut, consumerInstanceURL, buffer)
return err
}
// getConsumerInstancesByExternalAPIID gets consumer instances.
func (c *ServiceClient) getConsumerInstancesByExternalAPIID(externalAPIID string) ([]*management.ConsumerInstance, error) {
headers, err := c.createHeader()
if err != nil {
return nil, err
}
svc := c.caches.GetAPIServiceWithAPIID(externalAPIID)
if svc == nil {
return nil, fmt.Errorf("api service with external api id %s not found in the cache", externalAPIID)
}
log.Tracef("Get consumer instance by external api id: %s", externalAPIID)
params := map[string]string{
"query": fmt.Sprintf("metadata.references.name==%s", svc.Name),
}
request := coreapi.Request{
Method: coreapi.GET,
URL: c.cfg.GetConsumerInstancesURL(),
Headers: headers,
QueryParams: params,
}
response, err := c.apiClient.Send(request)
if err != nil {
return nil, err
}
if response.Code != http.StatusOK {
responseErr := readResponseErrors(response.Code, response.Body)
return nil, utilerrors.Wrap(ErrRequestQuery, responseErr)
}
consumerInstances := make([]*management.ConsumerInstance, 0)
err = json.Unmarshal(response.Body, &consumerInstances)
if err != nil {
return nil, err
}
if len(consumerInstances) == 0 {
return nil, errors.New("Unable to find consumerInstance using external api id: " + externalAPIID)
}
return consumerInstances, nil
}
// getConsumerInstanceByID
func (c *ServiceClient) getConsumerInstanceByID(instanceID string) (*management.ConsumerInstance, error) {
headers, err := c.createHeader()
if err != nil {
return nil, err
}
log.Tracef("Get consumer instance by id: %s", instanceID)
params := map[string]string{
"query": fmt.Sprintf("metadata.id==%s", instanceID),
}
request := coreapi.Request{
Method: coreapi.GET,
URL: c.cfg.GetConsumerInstancesURL(),
Headers: headers,
QueryParams: params,
}
response, err := c.apiClient.Send(request)
if err != nil {
return nil, err
}
if response.Code != http.StatusOK {
responseErr := readResponseErrors(response.Code, response.Body)
return nil, utilerrors.Wrap(ErrRequestQuery, responseErr)
}
consumerInstances := make([]*management.ConsumerInstance, 0)
err = json.Unmarshal(response.Body, &consumerInstances)
if len(consumerInstances) == 0 {
return nil, errors.New("Unable to find consumerInstance using instanceID " + instanceID)
}
return consumerInstances[0], err
}
// getConsumerInstanceByName
func (c *ServiceClient) getConsumerInstanceByName(name string) (*management.ConsumerInstance, error) {
headers, err := c.createHeader()
if err != nil {
return nil, err
}
log.Tracef("Get consumer instance by name: %s", name)
params := map[string]string{
"query": fmt.Sprintf("name==%s", name),
}
request := coreapi.Request{
Method: coreapi.GET,
URL: c.cfg.GetConsumerInstancesURL(),
Headers: headers,
QueryParams: params,
}
response, err := c.apiClient.Send(request)
if err != nil {
return nil, err
}
if response.Code != http.StatusOK {
responseErr := readResponseErrors(response.Code, response.Body)
return nil, utilerrors.Wrap(ErrRequestQuery, responseErr)
}
consumerInstances := make([]*management.ConsumerInstance, 0)
err = json.Unmarshal(response.Body, &consumerInstances)
if len(consumerInstances) == 0 {
return nil, nil
}
return consumerInstances[0], err
}
// deleteConsumerInstance -
func (c *ServiceClient) deleteConsumerInstance(name string) error {
_, err := c.apiServiceDeployAPI(http.MethodDelete, c.cfg.GetConsumerInstancesURL()+"/"+name, nil)
if err != nil && err.Error() != strconv.Itoa(http.StatusNotFound) {
return err
}
return nil
}