-
Notifications
You must be signed in to change notification settings - Fork 263
/
Copy pathmarshaller.go
629 lines (575 loc) · 27.1 KB
/
marshaller.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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
package xds
import (
"encoding/json"
"fmt"
"github.com/wso2/product-microgateway/adapter/config"
logger "github.com/wso2/product-microgateway/adapter/internal/loggers"
"github.com/wso2/product-microgateway/adapter/pkg/discovery/api/wso2/discovery/config/enforcer"
"github.com/wso2/product-microgateway/adapter/pkg/discovery/api/wso2/discovery/keymgt"
"github.com/wso2/product-microgateway/adapter/pkg/discovery/api/wso2/discovery/subscription"
"github.com/wso2/product-microgateway/adapter/pkg/eventhub/types"
)
var (
// APIMetadataMap has the following mapping apiUUID -> API (Metadata)
APIMetadataMap map[string]*subscription.APIs
// SubscriptionMap contains the subscriptions recieved from API Manager Control Plane
SubscriptionMap map[int32]*subscription.Subscription
// ApplicationMap contains the applications recieved from API Manager Control Plane
ApplicationMap map[string]*subscription.Application
// ApplicationKeyMappingMap contains the application key mappings recieved from API Manager Control Plane
ApplicationKeyMappingMap map[string]*subscription.ApplicationKeyMapping
// ApplicationPolicyMap contains the application policies recieved from API Manager Control Plane
ApplicationPolicyMap map[int32]*subscription.ApplicationPolicy
// SubscriptionPolicyMap contains the subscription policies recieved from API Manager Control Plane
SubscriptionPolicyMap map[int32]*subscription.SubscriptionPolicy
)
// EventType is a enum to distinguish Create, Update and Delete Events
type EventType int
const (
// CreateEvent : enum
CreateEvent EventType = iota
// UpdateEvent : enum
UpdateEvent
// DeleteEvent : enum
DeleteEvent
)
// MarshalConfig will marshal a Config struct - read from the config toml - to
// enfocer's CDS resource representation.
func MarshalConfig(config *config.Config) *enforcer.Config {
issuers := []*enforcer.Issuer{}
urlGroups := []*enforcer.TMURLGroup{}
for _, issuer := range config.Enforcer.Security.TokenService {
claimMaps := []*enforcer.ClaimMapping{}
for _, claimMap := range issuer.ClaimMapping {
claim := &enforcer.ClaimMapping{
RemoteClaim: claimMap.RemoteClaim,
LocalClaim: claimMap.LocalClaim,
}
claimMaps = append(claimMaps, claim)
}
jwtConfig := &enforcer.Issuer{
CertificateAlias: issuer.CertificateAlias,
ConsumerKeyClaim: issuer.ConsumerKeyClaim,
Issuer: issuer.Issuer,
Name: issuer.Name,
ValidateSubscription: issuer.ValidateSubscription,
JwksURL: issuer.JwksURL,
CertificateFilePath: issuer.CertificateFilePath,
ClaimMapping: claimMaps,
}
issuers = append(issuers, jwtConfig)
}
jwtUsers := []*enforcer.JWTUser{}
for _, user := range config.Enforcer.JwtIssuer.JwtUser {
jwtUser := &enforcer.JWTUser{
Username: user.Username,
Password: user.Password,
}
jwtUsers = append(jwtUsers, jwtUser)
}
for _, urlGroup := range config.Enforcer.Throttling.Publisher.URLGroup {
group := &enforcer.TMURLGroup{
AuthURLs: urlGroup.AuthURLs,
ReceiverURLs: urlGroup.ReceiverURLs,
Type: urlGroup.Type,
}
urlGroups = append(urlGroups, group)
}
authService := &enforcer.Service{
KeepAliveTime: config.Enforcer.AuthService.KeepAliveTime,
MaxHeaderLimit: config.Enforcer.AuthService.MaxHeaderLimit,
MaxMessageSize: config.Enforcer.AuthService.MaxMessageSize,
Port: config.Enforcer.AuthService.Port,
ThreadPool: &enforcer.ThreadPool{
CoreSize: config.Enforcer.AuthService.ThreadPool.CoreSize,
KeepAliveTime: config.Enforcer.AuthService.ThreadPool.KeepAliveTime,
MaxSize: config.Enforcer.AuthService.ThreadPool.MaxSize,
QueueSize: config.Enforcer.AuthService.ThreadPool.QueueSize,
},
}
cache := &enforcer.Cache{
Enable: config.Enforcer.Cache.Enabled,
MaximumSize: config.Enforcer.Cache.MaximumSize,
ExpiryTime: config.Enforcer.Cache.ExpiryTime,
}
tracing := &enforcer.Tracing{
Enabled: config.Tracing.Enabled,
Type: config.Tracing.Type,
ConfigProperties: config.Tracing.ConfigProperties,
}
metrics := &enforcer.Metrics{
Enabled: config.Enforcer.Metrics.Enabled,
Type: config.Enforcer.Metrics.Type,
}
analytics := &enforcer.Analytics{
Enabled: config.Analytics.Enabled,
ConfigProperties: config.Analytics.Enforcer.ConfigProperties,
Service: &enforcer.Service{
Port: config.Analytics.Enforcer.LogReceiver.Port,
MaxHeaderLimit: config.Analytics.Enforcer.LogReceiver.MaxHeaderLimit,
KeepAliveTime: config.Analytics.Enforcer.LogReceiver.KeepAliveTime,
MaxMessageSize: config.Analytics.Enforcer.LogReceiver.MaxMessageSize,
ThreadPool: &enforcer.ThreadPool{
CoreSize: config.Analytics.Enforcer.LogReceiver.ThreadPool.CoreSize,
MaxSize: config.Analytics.Enforcer.LogReceiver.ThreadPool.MaxSize,
QueueSize: config.Analytics.Enforcer.LogReceiver.ThreadPool.QueueSize,
KeepAliveTime: config.Analytics.Enforcer.LogReceiver.ThreadPool.KeepAliveTime,
},
},
}
management := &enforcer.Management{
Username: config.Enforcer.Management.Username,
Password: config.Enforcer.Management.Password,
}
restServer := &enforcer.RestServer{
Enable: config.Enforcer.RestServer.Enabled,
}
filters := []*enforcer.Filter{}
for _, filterConfig := range config.Enforcer.Filters {
filter := &enforcer.Filter{
ClassName: filterConfig.ClassName,
Position: filterConfig.Position,
ConfigProperties: filterConfig.ConfigProperties,
}
filters = append(filters, filter)
}
return &enforcer.Config{
JwtGenerator: &enforcer.JWTGenerator{
Enable: config.Enforcer.JwtGenerator.Enabled,
Encoding: config.Enforcer.JwtGenerator.Encoding,
ClaimDialect: config.Enforcer.JwtGenerator.ClaimDialect,
ConvertDialect: config.Enforcer.JwtGenerator.ConvertDialect,
Header: config.Enforcer.JwtGenerator.Header,
SigningAlgorithm: config.Enforcer.JwtGenerator.SigningAlgorithm,
EnableUserClaims: config.Enforcer.JwtGenerator.EnableUserClaims,
GatewayGeneratorImpl: config.Enforcer.JwtGenerator.GatewayGeneratorImpl,
ClaimsExtractorImpl: config.Enforcer.JwtGenerator.ClaimsExtractorImpl,
PublicCertificatePath: config.Enforcer.JwtGenerator.PublicCertificatePath,
PrivateKeyPath: config.Enforcer.JwtGenerator.PrivateKeyPath,
},
JwtIssuer: &enforcer.JWTIssuer{
Enabled: config.Enforcer.JwtIssuer.Enabled,
Issuer: config.Enforcer.JwtIssuer.Issuer,
Encoding: config.Enforcer.JwtIssuer.Encoding,
ClaimDialect: config.Enforcer.JwtIssuer.ClaimDialect,
SigningAlgorithm: config.Enforcer.JwtIssuer.SigningAlgorithm,
PublicCertificatePath: config.Enforcer.JwtIssuer.PublicCertificatePath,
PrivateKeyPath: config.Enforcer.JwtIssuer.PrivateKeyPath,
ValidityPeriod: config.Enforcer.JwtIssuer.ValidityPeriod,
JwtUsers: jwtUsers,
},
AuthService: authService,
Security: &enforcer.Security{
TokenService: issuers,
AuthHeader: &enforcer.AuthHeader{
EnableOutboundAuthHeader: config.Enforcer.Security.AuthHeader.EnableOutboundAuthHeader,
AuthorizationHeader: config.Enforcer.Security.AuthHeader.AuthorizationHeader,
TestConsoleHeaderName: config.Enforcer.Security.AuthHeader.TestConsoleHeaderName,
},
},
Cache: cache,
Tracing: tracing,
Metrics: metrics,
Analytics: analytics,
Throttling: &enforcer.Throttling{
EnableGlobalEventPublishing: config.Enforcer.Throttling.EnableGlobalEventPublishing,
EnableHeaderConditions: config.Enforcer.Throttling.EnableHeaderConditions,
EnableQueryParamConditions: config.Enforcer.Throttling.EnableQueryParamConditions,
EnableJwtClaimConditions: config.Enforcer.Throttling.EnableJwtClaimConditions,
JmsConnectionInitialContextFactory: config.Enforcer.Throttling.JmsConnectionInitialContextFactory,
JmsConnectionProviderUrl: config.Enforcer.Throttling.JmsConnectionProviderURL,
Publisher: &enforcer.BinaryPublisher{
Username: config.Enforcer.Throttling.Publisher.Username,
Password: config.Enforcer.Throttling.Publisher.Password,
UrlGroup: urlGroups,
Pool: &enforcer.PublisherPool{
InitIdleObjectDataPublishingAgents: config.Enforcer.Throttling.Publisher.Pool.InitIdleObjectDataPublishingAgents,
MaxIdleDataPublishingAgents: config.Enforcer.Throttling.Publisher.Pool.MaxIdleDataPublishingAgents,
PublisherThreadPoolCoreSize: config.Enforcer.Throttling.Publisher.Pool.PublisherThreadPoolCoreSize,
PublisherThreadPoolKeepAliveTime: config.Enforcer.Throttling.Publisher.Pool.PublisherThreadPoolKeepAliveTime,
PublisherThreadPoolMaximumSize: config.Enforcer.Throttling.Publisher.Pool.PublisherThreadPoolMaximumSize,
},
Agent: &enforcer.ThrottleAgent{
BatchSize: config.Enforcer.Throttling.Publisher.Agent.BatchSize,
Ciphers: config.Enforcer.Throttling.Publisher.Agent.Ciphers,
CorePoolSize: config.Enforcer.Throttling.Publisher.Agent.CorePoolSize,
EvictionTimePeriod: config.Enforcer.Throttling.Publisher.Agent.EvictionTimePeriod,
KeepAliveTimeInPool: config.Enforcer.Throttling.Publisher.Agent.KeepAliveTimeInPool,
MaxIdleConnections: config.Enforcer.Throttling.Publisher.Agent.MaxIdleConnections,
MaxPoolSize: config.Enforcer.Throttling.Publisher.Agent.MaxPoolSize,
MaxTransportPoolSize: config.Enforcer.Throttling.Publisher.Agent.MaxTransportPoolSize,
MinIdleTimeInPool: config.Enforcer.Throttling.Publisher.Agent.MinIdleTimeInPool,
QueueSize: config.Enforcer.Throttling.Publisher.Agent.QueueSize,
ReconnectionInterval: config.Enforcer.Throttling.Publisher.Agent.ReconnectionInterval,
SecureEvictionTimePeriod: config.Enforcer.Throttling.Publisher.Agent.SecureEvictionTimePeriod,
SecureMaxIdleConnections: config.Enforcer.Throttling.Publisher.Agent.SecureMaxIdleConnections,
SecureMaxTransportPoolSize: config.Enforcer.Throttling.Publisher.Agent.SecureMaxTransportPoolSize,
SecureMinIdleTimeInPool: config.Enforcer.Throttling.Publisher.Agent.SecureMinIdleTimeInPool,
SocketTimeoutMS: config.Enforcer.Throttling.Publisher.Agent.SocketTimeoutMS,
SslEnabledProtocols: config.Enforcer.Throttling.Publisher.Agent.SslEnabledProtocols,
},
},
},
Management: management,
RestServer: restServer,
Filters: filters,
}
}
// marshalSubscriptionMapToList converts the data into SubscriptionList proto type
func marshalSubscriptionMapToList(subscriptionMap map[int32]*subscription.Subscription) *subscription.SubscriptionList {
subscriptions := []*subscription.Subscription{}
for _, sub := range subscriptionMap {
subscriptions = append(subscriptions, sub)
}
return &subscription.SubscriptionList{
List: subscriptions,
}
}
// marshalApplicationMapToList converts the data into ApplicationList proto type
func marshalApplicationMapToList(appMap map[string]*subscription.Application) *subscription.ApplicationList {
applications := []*subscription.Application{}
for _, app := range appMap {
applications = append(applications, app)
}
return &subscription.ApplicationList{
List: applications,
}
}
// marshalAPIListMapToList converts the data into APIList proto type
func marshalAPIListMapToList(apiMap map[string]*subscription.APIs) *subscription.APIList {
apis := []*subscription.APIs{}
for _, api := range apiMap {
apis = append(apis, api)
}
return &subscription.APIList{
List: apis,
}
}
// marshalApplicationPolicyMapToList converts the data into ApplicationPolicyList proto type
func marshalApplicationPolicyMapToList(appPolicyMap map[int32]*subscription.ApplicationPolicy) *subscription.ApplicationPolicyList {
applicationPolicies := []*subscription.ApplicationPolicy{}
for _, policy := range appPolicyMap {
applicationPolicies = append(applicationPolicies, policy)
}
return &subscription.ApplicationPolicyList{
List: applicationPolicies,
}
}
// marshalSubscriptionPolicyMapToList converts the data into SubscriptionPolicyList proto type
func marshalSubscriptionPolicyMapToList(subPolicyMap map[int32]*subscription.SubscriptionPolicy) *subscription.SubscriptionPolicyList {
subscriptionPolicies := []*subscription.SubscriptionPolicy{}
for _, policy := range subPolicyMap {
subscriptionPolicies = append(subscriptionPolicies, policy)
}
return &subscription.SubscriptionPolicyList{
List: subscriptionPolicies,
}
}
// marshalKeyMappingMapToList converts the data into ApplicationKeyMappingList proto type
func marshalKeyMappingMapToList(keyMappingMap map[string]*subscription.ApplicationKeyMapping) *subscription.ApplicationKeyMappingList {
applicationKeyMappings := []*subscription.ApplicationKeyMapping{}
for _, keyMapping := range keyMappingMap {
// TODO: (VirajSalaka) tenant domain check missing
applicationKeyMappings = append(applicationKeyMappings, keyMapping)
}
return &subscription.ApplicationKeyMappingList{
List: applicationKeyMappings,
}
}
// MarshalKeyManager converts the data into KeyManager proto type
func MarshalKeyManager(keyManager *types.KeyManager) *keymgt.KeyManagerConfig {
configList, err := json.Marshal(keyManager.Configuration)
configuration := string(configList)
if err == nil {
newKeyManager := &keymgt.KeyManagerConfig{
Name: keyManager.Name,
Type: keyManager.Type,
Enabled: keyManager.Enabled,
TenantDomain: keyManager.TenantDomain,
Configuration: configuration,
}
return newKeyManager
}
logger.LoggerXds.Debugf("Error happens while marshaling key manager data for " + fmt.Sprint(keyManager.Name))
return nil
}
// MarshalMultipleApplications is used to update the applicationList during the startup where
// multiple applications are pulled at once. And then it returns the ApplicationList.
func MarshalMultipleApplications(appList *types.ApplicationList) *subscription.ApplicationList {
resourceMap := make(map[string]*subscription.Application)
for _, application := range appList.List {
applicationSub := marshalApplication(&application)
resourceMap[application.UUID] = applicationSub
}
ApplicationMap = resourceMap
return marshalApplicationMapToList(ApplicationMap)
}
// MarshalApplicationEventAndReturnList handles the Application Event corresponding to the event received
// from message broker. And then it returns the ApplicationList.
func MarshalApplicationEventAndReturnList(application *types.Application,
eventType EventType) *subscription.ApplicationList {
if eventType == DeleteEvent {
delete(ApplicationMap, application.UUID)
logger.LoggerXds.Infof("Application %s is deleted.", application.UUID)
} else {
applicationSub := marshalApplication(application)
ApplicationMap[application.UUID] = applicationSub
if eventType == CreateEvent {
logger.LoggerXds.Infof("Application %s is added.", application.UUID)
} else {
logger.LoggerXds.Infof("Application %s is updated.", application.UUID)
}
}
return marshalApplicationMapToList(ApplicationMap)
}
// MarshalMultipleApplicationKeyMappings is used to update the application key mappings during the startup where
// multiple key mappings are pulled at once. And then it returns the ApplicationKeyMappingList.
func MarshalMultipleApplicationKeyMappings(keymappingList *types.ApplicationKeyMappingList) *subscription.ApplicationKeyMappingList {
resourceMap := make(map[string]*subscription.ApplicationKeyMapping)
for _, keyMapping := range keymappingList.List {
applicationKeyMappingReference := GetApplicationKeyMappingReference(&keyMapping)
keyMappingSub := marshalKeyMapping(&keyMapping)
resourceMap[applicationKeyMappingReference] = keyMappingSub
}
ApplicationKeyMappingMap = resourceMap
return marshalKeyMappingMapToList(ApplicationKeyMappingMap)
}
// MarshalApplicationKeyMappingEventAndReturnList handles the Application Key Mapping Event corresponding to the event received
// from message broker. And then it returns the ApplicationKeyMappingList.
func MarshalApplicationKeyMappingEventAndReturnList(keyMapping *types.ApplicationKeyMapping,
eventType EventType) *subscription.ApplicationKeyMappingList {
applicationKeyMappingReference := GetApplicationKeyMappingReference(keyMapping)
if eventType == DeleteEvent {
delete(ApplicationKeyMappingMap, applicationKeyMappingReference)
logger.LoggerXds.Infof("Application Key Mapping for the applicationKeyMappingReference %s is removed.",
applicationKeyMappingReference)
} else {
keyMappingSub := marshalKeyMapping(keyMapping)
ApplicationKeyMappingMap[applicationKeyMappingReference] = keyMappingSub
logger.LoggerXds.Infof("Application Key Mapping for the applicationKeyMappingReference %s is added.",
applicationKeyMappingReference)
}
return marshalKeyMappingMapToList(ApplicationKeyMappingMap)
}
// MarshalMultipleSubscriptions is used to update the subscriptions during the startup where
// multiple subscriptions are pulled at once. And then it returns the SubscriptionList.
func MarshalMultipleSubscriptions(subscriptionsList *types.SubscriptionList) *subscription.SubscriptionList {
resourceMap := make(map[int32]*subscription.Subscription)
for _, sb := range subscriptionsList.List {
resourceMap[sb.SubscriptionID] = marshalSubscription(&sb)
}
SubscriptionMap = resourceMap
return marshalSubscriptionMapToList(SubscriptionMap)
}
// MarshalSubscriptionEventAndReturnList handles the Subscription Event corresponding to the event received
// from message broker. And then it returns the SubscriptionList.
func MarshalSubscriptionEventAndReturnList(sub *types.Subscription, eventType EventType) *subscription.SubscriptionList {
if eventType == DeleteEvent {
delete(SubscriptionMap, sub.SubscriptionID)
logger.LoggerXds.Infof("Subscription for %s:%s is deleted.", sub.APIUUID, sub.ApplicationUUID)
} else {
subscriptionSub := marshalSubscription(sub)
SubscriptionMap[sub.SubscriptionID] = subscriptionSub
if eventType == UpdateEvent {
logger.LoggerXds.Infof("Subscription for %s:%s is updated.", sub.APIUUID, sub.ApplicationUUID)
} else {
logger.LoggerXds.Infof("Subscription for %s:%s is added.", sub.APIUUID, sub.ApplicationUUID)
}
}
return marshalSubscriptionMapToList(SubscriptionMap)
}
// MarshalMultipleApplicationPolicies is used to update the applicationPolicies during the startup where
// multiple application policies are pulled at once. And then it returns the ApplicationPolicyList.
func MarshalMultipleApplicationPolicies(policies *types.ApplicationPolicyList) *subscription.ApplicationPolicyList {
resourceMap := make(map[int32]*subscription.ApplicationPolicy)
for _, policy := range policies.List {
appPolicy := marshalApplicationPolicy(&policy)
resourceMap[policy.ID] = appPolicy
logger.LoggerXds.Infof("appPolicy Entry is added : %v", appPolicy)
}
ApplicationPolicyMap = resourceMap
return marshalApplicationPolicyMapToList(ApplicationPolicyMap)
}
// MarshalApplicationPolicyEventAndReturnList handles the Application Policy Event corresponding to the event received
// from message broker. And then it returns the ApplicationPolicyList.
func MarshalApplicationPolicyEventAndReturnList(policy *types.ApplicationPolicy, eventType EventType) *subscription.ApplicationPolicyList {
if eventType == DeleteEvent {
delete(ApplicationPolicyMap, policy.ID)
logger.LoggerXds.Infof("Application Policy: %s is deleted.", policy.Name)
} else {
appPolicy := marshalApplicationPolicy(policy)
ApplicationPolicyMap[policy.ID] = appPolicy
if eventType == UpdateEvent {
logger.LoggerInternalMsg.Infof("Application Policy: %s is updated.", appPolicy.Name)
} else {
logger.LoggerInternalMsg.Infof("Application Policy: %s is added.", appPolicy.Name)
}
}
return marshalApplicationPolicyMapToList(ApplicationPolicyMap)
}
// MarshalMultipleSubscriptionPolicies is used to update the subscriptionPolicies during the startup where
// multiple subscription policies are pulled at once. And then it returns the SubscriptionPolicyList.
func MarshalMultipleSubscriptionPolicies(policies *types.SubscriptionPolicyList) *subscription.SubscriptionPolicyList {
resourceMap := make(map[int32]*subscription.SubscriptionPolicy)
for _, policy := range policies.List {
resourceMap[policy.ID] = marshalSubscriptionPolicy(&policy)
}
SubscriptionPolicyMap = resourceMap
return marshalSubscriptionPolicyMapToList(SubscriptionPolicyMap)
}
// MarshalSubscriptionPolicyEventAndReturnList handles the Subscription Policy Event corresponding to the event received
// from message broker. And then it returns the subscriptionPolicyList.
func MarshalSubscriptionPolicyEventAndReturnList(policy *types.SubscriptionPolicy, eventType EventType) *subscription.SubscriptionPolicyList {
if eventType == DeleteEvent {
delete(ApplicationPolicyMap, policy.ID)
logger.LoggerXds.Infof("Application Policy: %s is deleted.", policy.Name)
} else {
subPolicy := marshalSubscriptionPolicy(policy)
SubscriptionPolicyMap[policy.ID] = subPolicy
if eventType == UpdateEvent {
logger.LoggerInternalMsg.Infof("Subscription Policy: %s is updated.", subPolicy.Name)
} else {
logger.LoggerInternalMsg.Infof("Subscription Policy: %s is added.", subPolicy.Name)
}
}
return marshalSubscriptionPolicyMapToList(SubscriptionPolicyMap)
}
// UpdateAPIMetataMapWithMultipleAPIs updates the internal APIMetadataMap and it needs to be called during the startup.
// The purpose here is to store default versioned APIs and blocked APIs.
// initialAPIUUIDListMap is assigned during startup when global adapter is associated. This would be empty otherwise.
func UpdateAPIMetataMapWithMultipleAPIs(apiList *types.APIList, initialAPIUUIDListMap map[string]int) {
if APIMetadataMap == nil {
APIMetadataMap = make(map[string]*subscription.APIs)
}
for _, api := range apiList.List {
// initialAPIUUIDListMap is not null if the adapter is running with global adapter enabled, and it is
// the first method invocation.
if initialAPIUUIDListMap != nil {
if _, ok := initialAPIUUIDListMap[api.UUID]; !ok {
continue
}
}
newAPI := marshalAPIMetadata(&api)
APIMetadataMap[api.UUID] = newAPI
}
}
// UpdateAPIMetataMapWithAPILCEvent updates the internal map's API instances lifecycle state only if
// stored API Instance's or input status event is a blocked event. If the API's state is changed to un-BLOCKED state,
// the record will be removed.
func UpdateAPIMetataMapWithAPILCEvent(apiUUID, status string) {
apiEntry, apiFound := APIMetadataMap[apiUUID]
if !apiFound {
// IF API is not stored within the metadata Map and the lifecycle state is something else other BLOCKED state, those are discarded.
if status != blockedStatus {
logger.LoggerXds.Debugf("API life cycle state change event is discarded for the API : %s", apiUUID)
return
}
// IF API is not available and state is BLOCKED, needs to create a new instance and store within the Map.
logger.LoggerXds.Debugf("No API Metadata for API ID: %s is available. Hence a new record is added.", apiUUID)
APIMetadataMap[apiUUID] = &subscription.APIs{
Uuid: apiUUID,
LcState: status,
}
logger.LoggerXds.Infof("API life cycle state change event with state %q is updated for the API : %s",
status, apiUUID)
return
}
// If the API is available in the metadata map it should be either a BLOCKED API and/or default versioned API.
// If the update for existing API entry is not "BLOCKED" then the API can be removed from the list.
// when the API is unavailable in the api metadata list received in the enforcer, it would be treated as
// an unblocked API.
// But if the API is not the default version, those records won't be stored.
if status != blockedStatus && !apiEntry.IsDefaultVersion {
delete(APIMetadataMap, apiUUID)
return
}
APIMetadataMap[apiUUID].LcState = status
logger.LoggerXds.Infof("API life cycle state change event with state %q is updated for the API : %s",
status, apiUUID)
}
func marshalSubscription(subscriptionInternal *types.Subscription) *subscription.Subscription {
sub := &subscription.Subscription{
SubscriptionId: fmt.Sprint(subscriptionInternal.SubscriptionID),
PolicyId: subscriptionInternal.PolicyID,
ApiId: subscriptionInternal.APIID,
AppId: subscriptionInternal.AppID,
SubscriptionState: subscriptionInternal.SubscriptionState,
TimeStamp: subscriptionInternal.TimeStamp,
TenantId: subscriptionInternal.TenantID,
TenantDomain: subscriptionInternal.TenantDomain,
SubscriptionUUID: subscriptionInternal.SubscriptionUUID,
ApiUUID: subscriptionInternal.APIUUID,
AppUUID: subscriptionInternal.ApplicationUUID,
}
if sub.TenantDomain == "" {
sub.TenantDomain = config.GetControlPlaneConnectedTenantDomain()
}
return sub
}
func marshalApplication(appInternal *types.Application) *subscription.Application {
app := &subscription.Application{
Uuid: appInternal.UUID,
Id: appInternal.ID,
Name: appInternal.Name,
SubId: appInternal.ID,
SubName: appInternal.SubName,
Policy: appInternal.Policy,
TokenType: appInternal.TokenType,
GroupIds: appInternal.GroupIds,
Attributes: appInternal.Attributes,
TenantId: appInternal.TenantID,
TenantDomain: appInternal.TenantDomain,
Timestamp: appInternal.TimeStamp,
}
if app.TenantDomain == "" {
app.TenantDomain = config.GetControlPlaneConnectedTenantDomain()
}
return app
}
func marshalKeyMapping(keyMappingInternal *types.ApplicationKeyMapping) *subscription.ApplicationKeyMapping {
return &subscription.ApplicationKeyMapping{
ConsumerKey: keyMappingInternal.ConsumerKey,
KeyType: keyMappingInternal.KeyType,
KeyManager: keyMappingInternal.KeyManager,
ApplicationId: keyMappingInternal.ApplicationID,
ApplicationUUID: keyMappingInternal.ApplicationUUID,
TenantId: keyMappingInternal.TenantID,
TenantDomain: keyMappingInternal.TenantDomain,
Timestamp: keyMappingInternal.TimeStamp,
}
}
func marshalAPIMetadata(api *types.API) *subscription.APIs {
return &subscription.APIs{
Uuid: api.UUID,
IsDefaultVersion: api.IsDefaultVersion,
LcState: api.APIStatus,
}
}
func marshalApplicationPolicy(policy *types.ApplicationPolicy) *subscription.ApplicationPolicy {
return &subscription.ApplicationPolicy{
Id: policy.ID,
TenantId: policy.TenantID,
Name: policy.Name,
QuotaType: policy.QuotaType,
}
}
func marshalSubscriptionPolicy(policy *types.SubscriptionPolicy) *subscription.SubscriptionPolicy {
return &subscription.SubscriptionPolicy{
Id: policy.ID,
Name: policy.Name,
QuotaType: policy.QuotaType,
GraphQLMaxComplexity: policy.GraphQLMaxComplexity,
GraphQLMaxDepth: policy.GraphQLMaxDepth,
RateLimitCount: policy.RateLimitCount,
RateLimitTimeUnit: policy.RateLimitTimeUnit,
StopOnQuotaReach: policy.StopOnQuotaReach,
TenantId: policy.TenantID,
TenantDomain: policy.TenantDomain,
Timestamp: policy.TimeStamp,
}
}
// GetApplicationKeyMappingReference returns unique reference for each key Mapping event.
// It is the combination of consumerKey:keyManager
func GetApplicationKeyMappingReference(keyMapping *types.ApplicationKeyMapping) string {
return keyMapping.ConsumerKey + ":" + keyMapping.KeyManager
}