-
Notifications
You must be signed in to change notification settings - Fork 84
/
loader.go
431 lines (364 loc) · 15.5 KB
/
loader.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
package systemfetcher
import (
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"reflect"
"strings"
"github.com/kyma-incubator/compass/components/director/pkg/str"
"github.com/kyma-incubator/compass/components/director/internal/domain/tenant"
"github.com/kyma-incubator/compass/components/director/internal/model"
"github.com/kyma-incubator/compass/components/director/pkg/apperrors"
"github.com/kyma-incubator/compass/components/director/pkg/log"
"github.com/kyma-incubator/compass/components/director/pkg/persistence"
"github.com/pkg/errors"
)
const (
applicationTemplatesDirectoryPath = "/data/templates/"
integrationSystemJSONKey = "intSystem"
integrationSystemNameJSONKey = "name"
integrationSystemDescriptionJSONKey = "description"
managedAppProvisioningLabelKey = "managed_app_provisioning"
integrationSystemIDLabelKey = "integrationSystemID"
)
//go:generate mockery --name=appTmplService --output=automock --outpkg=automock --case=underscore --exported=true --disable-version-string
type appTmplService interface {
GetByNameAndRegion(ctx context.Context, name string, region interface{}) (*model.ApplicationTemplate, error)
Create(ctx context.Context, in model.ApplicationTemplateInput) (string, error)
Update(ctx context.Context, id string, override bool, in model.ApplicationTemplateUpdateInput) error
}
//go:generate mockery --name=webhookService --output=automock --outpkg=automock --case=underscore --exported=true --disable-version-string
type webhookService interface {
ListForApplicationTemplate(ctx context.Context, applicationTemplateID string) ([]*model.Webhook, error)
Create(ctx context.Context, owningResourceID string, in model.WebhookInput, objectType model.WebhookReferenceObjectType) (string, error)
Update(ctx context.Context, id string, in model.WebhookInput, objectType model.WebhookReferenceObjectType) error
Delete(ctx context.Context, id string, objectType model.WebhookReferenceObjectType) error
}
//go:generate mockery --name=intSysSvc --output=automock --outpkg=automock --case=underscore --exported=true --disable-version-string
type intSysSvc interface {
Create(ctx context.Context, in model.IntegrationSystemInput) (string, error)
List(ctx context.Context, pageSize int, cursor string) (model.IntegrationSystemPage, error)
}
// DataLoader loads and creates all the necessary data needed by system-fetcher
type DataLoader struct {
transaction persistence.Transactioner
appTmplSvc appTmplService
webhookSvc webhookService
intSysSvc intSysSvc
cfg Config
}
// NewDataLoader creates new DataLoader
func NewDataLoader(tx persistence.Transactioner, cfg Config, appTmplSvc appTmplService, intSysSvc intSysSvc, webhookSvc webhookService) *DataLoader {
return &DataLoader{
transaction: tx,
appTmplSvc: appTmplSvc,
intSysSvc: intSysSvc,
webhookSvc: webhookSvc,
cfg: cfg,
}
}
// LoadData loads and creates all the necessary data needed by system-fetcher
func (d *DataLoader) LoadData(ctx context.Context, readDir func(dirname string) ([]os.DirEntry, error), readFile func(filename string) ([]byte, error)) error {
appTemplateInputsMap, err := d.loadAppTemplates(ctx, readDir, readFile)
if err != nil {
return errors.Wrap(err, "failed while loading application templates")
}
tx, err := d.transaction.Begin()
if err != nil {
return errors.Wrap(err, "Error while beginning transaction")
}
defer d.transaction.RollbackUnlessCommitted(ctx, tx)
ctxWithTx := persistence.SaveToContext(ctx, tx)
appTemplateInputs, err := d.createAppTemplatesDependentEntities(ctxWithTx, appTemplateInputsMap)
if err != nil {
return errors.Wrap(err, "failed while creating application templates dependent entities")
}
if err = d.upsertAppTemplates(ctxWithTx, appTemplateInputs); err != nil {
return errors.Wrap(err, "failed while upserting application templates")
}
if err := tx.Commit(); err != nil {
return errors.Wrap(err, "while committing transaction")
}
return nil
}
func (d *DataLoader) syncWebhooks(ctx context.Context, appTemplateID string, webhooksModel []*model.Webhook, webhooksInput []*model.WebhookInput) error {
webhooksModelMap := make(map[model.WebhookType]*model.Webhook)
for _, webhook := range webhooksModel {
webhooksModelMap[webhook.Type] = webhook
}
for _, webhookInput := range webhooksInput {
webhookModel, exists := webhooksModelMap[webhookInput.Type]
var err error
if exists {
log.C(ctx).Infof("Webhook of type %s exists. Will update it...", webhookInput.Type)
err = d.webhookSvc.Update(ctx, webhookModel.ID, *webhookInput, model.ApplicationTemplateWebhookReference)
delete(webhooksModelMap, webhookInput.Type) // remove the item from the map after updating
} else {
log.C(ctx).Infof("Webhook of type %s does not exist. Will create it...", webhookInput.Type)
_, err = d.webhookSvc.Create(ctx, appTemplateID, *webhookInput, model.ApplicationTemplateWebhookReference)
}
if err != nil {
return err
}
}
for _, webhookModel := range webhooksModelMap {
log.C(ctx).Infof("Webhook of type %s is missing in the input. Will delete it...", webhookModel.Type)
if err := d.webhookSvc.Delete(ctx, webhookModel.ID, model.ApplicationTemplateWebhookReference); err != nil {
return err
}
}
return nil
}
func (d *DataLoader) loadAppTemplates(ctx context.Context, readDir func(dirname string) ([]os.DirEntry, error), readFile func(filename string) ([]byte, error)) ([]map[string]interface{}, error) {
appTemplatesFileLocation := applicationTemplatesDirectoryPath
if len(d.cfg.TemplatesFileLocation) > 0 {
appTemplatesFileLocation = d.cfg.TemplatesFileLocation
}
files, err := readDir(appTemplatesFileLocation)
if err != nil {
return nil, errors.Wrapf(err, "while reading directory with application templates files [%s]", appTemplatesFileLocation)
}
var appTemplateInputs []map[string]interface{}
for _, f := range files {
log.C(ctx).Infof("Loading application templates from file: %s", f.Name())
if filepath.Ext(f.Name()) != ".json" {
return nil, apperrors.NewInternalError(fmt.Sprintf("unsupported file format %q, supported format: json", filepath.Ext(f.Name())))
}
bytes, err := readFile(appTemplatesFileLocation + f.Name())
if err != nil {
return nil, errors.Wrapf(err, "while reading application templates file %q", appTemplatesFileLocation+f.Name())
}
var templatesFromFile []map[string]interface{}
if err := json.Unmarshal(bytes, &templatesFromFile); err != nil {
return nil, errors.Wrapf(err, "while unmarshalling application templates from file %s", appTemplatesFileLocation+f.Name())
}
log.C(ctx).Infof("Successfully loaded application templates from file: %s", f.Name())
appTemplateInputs = append(appTemplateInputs, templatesFromFile...)
}
return appTemplateInputs, nil
}
func (d *DataLoader) createAppTemplatesDependentEntities(ctx context.Context, appTmplInputs []map[string]interface{}) ([]model.ApplicationTemplateInput, error) {
appTemplateInputs := make([]model.ApplicationTemplateInput, 0, len(appTmplInputs))
for _, appTmplInput := range appTmplInputs {
var input model.ApplicationTemplateInput
appTmplInputJSON, err := json.Marshal(appTmplInput)
if err != nil {
return nil, errors.Wrap(err, "while marshaling application template input")
}
if err = json.Unmarshal(appTmplInputJSON, &input); err != nil {
return nil, errors.Wrap(err, "while unmarshalling application template input")
}
intSystem, ok := appTmplInput[integrationSystemJSONKey]
if ok {
intSystemData, ok := intSystem.(map[string]interface{})
if !ok {
return nil, fmt.Errorf("the type of the integration system is %T instead of map[string]interface{}. %v", intSystem, intSystemData)
}
appTmplIntSystem, err := extractIntegrationSystem(intSystemData)
if err != nil {
return nil, err
}
intSystemsFromDB, err := d.listIntegrationSystems(ctx)
if err != nil {
return nil, err
}
var intSysID string
for _, is := range intSystemsFromDB {
if is.Name == appTmplIntSystem.Name && str.PtrStrToStr(is.Description) == str.PtrStrToStr(appTmplIntSystem.Description) {
intSysID = is.ID
break
}
}
if intSysID == "" {
id, err := d.intSysSvc.Create(ctx, *appTmplIntSystem)
if err != nil {
return nil, errors.Wrapf(err, "while creating integration system with name %s", appTmplIntSystem.Name)
}
intSysID = id
log.C(ctx).Infof("Successfully created integration system with id: %s", intSysID)
}
input.ApplicationInputJSON, err = enrichWithIntegrationSystemIDLabel(input.ApplicationInputJSON, intSysID)
if err != nil {
return nil, err
}
}
appTemplateInputs = append(appTemplateInputs, input)
}
return enrichApplicationTemplateInput(appTemplateInputs), nil
}
func (d *DataLoader) listIntegrationSystems(ctx context.Context) ([]*model.IntegrationSystem, error) {
pageSize := 200
pageCursor := ""
hasNextPage := true
var integrationSystems []*model.IntegrationSystem
for hasNextPage {
intSystemsPage, err := d.intSysSvc.List(ctx, pageSize, pageCursor)
if err != nil {
return nil, errors.Wrapf(err, "while listing integration systems")
}
integrationSystems = append(integrationSystems, intSystemsPage.Data...)
pageCursor = intSystemsPage.PageInfo.EndCursor
hasNextPage = intSystemsPage.PageInfo.HasNextPage
}
return integrationSystems, nil
}
func (d *DataLoader) upsertAppTemplates(ctx context.Context, appTemplateInputs []model.ApplicationTemplateInput) error {
for _, appTmplInput := range appTemplateInputs {
var region interface{}
region, err := retrieveRegion(appTmplInput.Labels)
if err != nil {
return err
}
if region == "" {
region = nil
}
log.C(ctx).Infof("Retrieving application template with name %q and region %s", appTmplInput.Name, region)
appTemplate, err := d.appTmplSvc.GetByNameAndRegion(ctx, appTmplInput.Name, region)
if err != nil {
if !strings.Contains(err.Error(), "Object not found") {
return errors.Wrapf(err, "error while getting application template with name %q and region %s", appTmplInput.Name, region)
}
log.C(ctx).Infof("Cannot find application template with name %q and region %s. Creation triggered...", appTmplInput.Name, region)
templateID, err := d.appTmplSvc.Create(ctx, appTmplInput)
if err != nil {
return errors.Wrapf(err, "error while creating application template with name %q and region %s", appTmplInput.Name, region)
}
log.C(ctx).Infof("Successfully created application template with id: %q", templateID)
continue
}
if !areAppTemplatesEqual(appTemplate, appTmplInput) {
log.C(ctx).Infof("Updating application template with id %q", appTemplate.ID)
appTemplateUpdateInput := model.ApplicationTemplateUpdateInput{
Name: appTmplInput.Name,
Description: appTmplInput.Description,
ApplicationNamespace: appTmplInput.ApplicationNamespace,
ApplicationInputJSON: appTmplInput.ApplicationInputJSON,
Placeholders: appTmplInput.Placeholders,
AccessLevel: appTmplInput.AccessLevel,
Labels: appTmplInput.Labels,
}
if err := d.appTmplSvc.Update(ctx, appTemplate.ID, false, appTemplateUpdateInput); err != nil {
return errors.Wrapf(err, "while updating application template with id %q", appTemplate.ID)
}
log.C(ctx).Infof("Successfully updated application template with id %q", appTemplate.ID)
}
webhooks, err := d.webhookSvc.ListForApplicationTemplate(ctx, appTemplate.ID)
if err != nil {
return err
}
if !areWebhooksEqual(webhooks, appTmplInput.Webhooks) {
if err := d.syncWebhooks(ctx, appTemplate.ID, webhooks, appTmplInput.Webhooks); err != nil {
return errors.Wrapf(err, "while updating webhooks for application tempate with id %q", appTemplate.ID)
}
log.C(ctx).Infof("Successfully updated the webhooks for application template with id %q", appTemplate.ID)
}
}
return nil
}
func enrichApplicationTemplateInput(appTemplateInputs []model.ApplicationTemplateInput) []model.ApplicationTemplateInput {
enriched := make([]model.ApplicationTemplateInput, 0, len(appTemplateInputs))
for _, appTemplateInput := range appTemplateInputs {
if appTemplateInput.Description == nil {
appTemplateInput.Description = str.Ptr(appTemplateInput.Name)
}
if appTemplateInput.Placeholders == nil || len(appTemplateInput.Placeholders) == 0 {
appTemplateInput.Placeholders = []model.ApplicationTemplatePlaceholder{
{
Name: "name",
Description: str.Ptr("Application’s technical name"),
JSONPath: str.Ptr("$.displayName"),
},
{
Name: "display-name",
Description: str.Ptr("Application’s display name"),
JSONPath: str.Ptr("$.displayName"),
},
}
}
if appTemplateInput.AccessLevel == "" {
appTemplateInput.AccessLevel = model.GlobalApplicationTemplateAccessLevel
}
if appTemplateInput.Labels == nil {
appTemplateInput.Labels = map[string]interface{}{managedAppProvisioningLabelKey: false}
}
enriched = append(enriched, appTemplateInput)
}
return enriched
}
func enrichWithIntegrationSystemIDLabel(applicationInputJSON, intSystemID string) (string, error) {
var appInput map[string]interface{}
if err := json.Unmarshal([]byte(applicationInputJSON), &appInput); err != nil {
return "", errors.Wrapf(err, "while unmarshaling application input json")
}
appInput[integrationSystemIDLabelKey] = intSystemID
inputJSON, err := json.Marshal(appInput)
if err != nil {
return "", errors.Wrapf(err, "while marshalling app input")
}
return string(inputJSON), nil
}
func extractIntegrationSystem(intSysMap map[string]interface{}) (*model.IntegrationSystemInput, error) {
intSysName, ok := intSysMap[integrationSystemNameJSONKey]
if !ok {
return nil, fmt.Errorf("integration system name is missing")
}
intSysNameValue, ok := intSysName.(string)
if !ok {
return nil, fmt.Errorf("integration system name value must be string")
}
intSysDesc, ok := intSysMap[integrationSystemDescriptionJSONKey]
if !ok {
return nil, fmt.Errorf("integration system description is missing")
}
intSysDescValue, ok := intSysDesc.(string)
if !ok {
return nil, fmt.Errorf("integration system description value must be string")
}
return &model.IntegrationSystemInput{
Name: intSysNameValue,
Description: str.Ptr(intSysDescValue),
}, nil
}
func retrieveRegion(labels map[string]interface{}) (string, error) {
if labels == nil {
return "", nil
}
region, exists := labels[tenant.RegionLabelKey]
if !exists {
return "", nil
}
regionValue, ok := region.(string)
if !ok {
return "", fmt.Errorf("%q label value must be string", tenant.RegionLabelKey)
}
return regionValue, nil
}
func areAppTemplatesEqual(appTemplate *model.ApplicationTemplate, appTemplateInput model.ApplicationTemplateInput) bool {
if appTemplate == nil {
return false
}
isAppInputJSONEqual := appTemplate.ApplicationInputJSON == appTemplateInput.ApplicationInputJSON
isLabelEqual := reflect.DeepEqual(appTemplate.Labels, appTemplateInput.Labels)
isPlaceholderEqual := reflect.DeepEqual(appTemplate.Placeholders, appTemplateInput.Placeholders)
if isAppInputJSONEqual && isLabelEqual && isPlaceholderEqual {
return true
}
return false
}
func areWebhooksEqual(webhooksModel []*model.Webhook, webhooksInput []*model.WebhookInput) bool {
if len(webhooksModel) != len(webhooksInput) {
return false
}
foundWebhooksCounter := 0
for _, whModel := range webhooksModel {
for _, whInput := range webhooksInput {
if reflect.DeepEqual(whModel, *whInput.ToWebhook(whModel.ID, whModel.ObjectID, whModel.ObjectType)) {
foundWebhooksCounter++
break
}
}
}
return foundWebhooksCounter == len(webhooksModel)
}