-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathtemplates.go
809 lines (703 loc) · 26.8 KB
/
templates.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
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
package dao
import (
"context"
"errors"
"fmt"
"net/url"
"regexp"
"strings"
"time"
"github.com/content-services/content-sources-backend/pkg/api"
"github.com/content-services/content-sources-backend/pkg/candlepin_client"
"github.com/content-services/content-sources-backend/pkg/config"
ce "github.com/content-services/content-sources-backend/pkg/errors"
"github.com/content-services/content-sources-backend/pkg/event"
"github.com/content-services/content-sources-backend/pkg/models"
"github.com/content-services/content-sources-backend/pkg/pulp_client"
"github.com/jackc/pgx/v5/pgconn"
"golang.org/x/exp/slices"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
type templateDaoImpl struct {
db *gorm.DB
pulpClient pulp_client.PulpClient
}
func GetTemplateDao(db *gorm.DB, pulpClient pulp_client.PulpClient) TemplateDao {
return &templateDaoImpl{
db: db,
pulpClient: pulpClient,
}
}
func TemplateDBToApiError(e error, uuid *string) *ce.DaoError {
var dupKeyName string
if e == nil {
return nil
}
pgError, ok := e.(*pgconn.PgError)
if ok {
if pgError.Code == "23505" {
switch pgError.ConstraintName {
case "name_org_id_not_deleted_unique":
dupKeyName = "name"
}
return &ce.DaoError{AlreadyExists: true, Message: "Template with this " + dupKeyName + " already belongs to organization"}
}
if pgError.Code == "22021" {
return &ce.DaoError{BadValidation: true, Message: "Request parameters contain invalid syntax"}
}
}
dbError, ok := e.(models.Error)
if ok {
daoError := ce.DaoError{BadValidation: dbError.Validation, Message: dbError.Message}
daoError.Wrap(e)
return &daoError
}
daoError := ce.DaoError{}
if errors.Is(e, gorm.ErrRecordNotFound) {
msg := "Template not found"
if uuid != nil {
msg = fmt.Sprintf("Template with UUID %s not found", *uuid)
}
daoError = ce.DaoError{
Message: msg,
NotFound: true,
}
} else {
daoError = ce.DaoError{
Message: e.Error(),
NotFound: ce.HttpCodeForDaoError(e) == 404, // Check if isNotFoundError
}
}
daoError.Wrap(e)
return &daoError
}
func (t templateDaoImpl) Create(ctx context.Context, reqTemplate api.TemplateRequest) (api.TemplateResponse, error) {
var resp api.TemplateResponse
var err error
_ = t.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
resp, err = t.create(ctx, tx, reqTemplate)
return err
})
return resp, err
}
func (t templateDaoImpl) create(ctx context.Context, tx *gorm.DB, reqTemplate api.TemplateRequest) (api.TemplateResponse, error) {
var modelTemplate models.Template
var respTemplate api.TemplateResponse
if err := t.validateRepositoryUUIDs(ctx, *reqTemplate.OrgID, reqTemplate.RepositoryUUIDS); err != nil {
return api.TemplateResponse{}, err
}
// Create a template
templatesCreateApiToModel(reqTemplate, &modelTemplate)
err := tx.Create(&modelTemplate).Error
if err != nil {
return api.TemplateResponse{}, TemplateDBToApiError(err, nil)
}
// Associate the template to repositories
if reqTemplate.RepositoryUUIDS == nil {
return api.TemplateResponse{}, &ce.DaoError{
Message: "template must include repository uuids",
BadValidation: true,
}
}
err = t.insertTemplateRepoConfigsAndSnapshots(tx, ctx, *reqTemplate.OrgID, modelTemplate, reqTemplate.RepositoryUUIDS)
if err != nil {
return api.TemplateResponse{}, err
}
templatesModelToApi(modelTemplate, &respTemplate)
respTemplate.RepositoryUUIDS = reqTemplate.RepositoryUUIDS
event.SendTemplateEvent(*reqTemplate.OrgID, event.TemplateCreated, []api.TemplateResponse{respTemplate})
return respTemplate, nil
}
func (t templateDaoImpl) validateRepositoryUUIDs(ctx context.Context, orgId string, uuids []string) error {
var count int64
resp := t.db.WithContext(ctx).Model(models.RepositoryConfiguration{}).Where("org_id = ? or org_id = ?", orgId, config.RedHatOrg).Where("uuid in ?", UuidifyStrings(uuids)).Count(&count)
if resp.Error != nil {
return fmt.Errorf("could not query repository uuids: %w", resp.Error)
}
if count != int64(len(uuids)) {
return &ce.DaoError{NotFound: true, Message: "One or more Repository UUIDs was invalid."}
}
var snapshotCount int64
resp = t.db.WithContext(ctx).Model(models.RepositoryConfiguration{}).
Where("org_id = ? or org_id = ?", orgId, config.RedHatOrg).
Where("uuid in ?", UuidifyStrings(uuids)).
Where("last_snapshot_uuid IS NOT NULL").
Count(&snapshotCount)
if resp.Error != nil {
return fmt.Errorf("could not query repository uuids: %w", resp.Error)
}
if snapshotCount != int64(len(uuids)) {
return &ce.DaoError{NotFound: true, Message: "One or more repositories does not have a snapshot."}
}
return nil
}
func (t templateDaoImpl) insertTemplateRepoConfigsAndSnapshots(tx *gorm.DB, ctx context.Context, orgId string, template models.Template, repoUUIDs []string) error {
templateRepoConfigs := make([]models.TemplateRepositoryConfiguration, len(repoUUIDs))
var templateDate time.Time
if template.UseLatest {
templateDate = time.Now()
} else {
templateDate = template.Date
}
sDao := snapshotDaoImpl{db: tx}
req := api.ListSnapshotByDateRequest{Date: templateDate, RepositoryUUIDS: repoUUIDs}
snapshots, err := sDao.FetchSnapshotsModelByDateAndRepository(ctx, orgId, req)
if err != nil {
return err
}
for i, repo := range repoUUIDs {
snapIndex := slices.IndexFunc(snapshots, func(s models.Snapshot) bool {
return s.RepositoryConfigurationUUID == repo
})
templateRepoConfigs[i].TemplateUUID = template.UUID
templateRepoConfigs[i].RepositoryConfigurationUUID = repo
templateRepoConfigs[i].SnapshotUUID = snapshots[snapIndex].UUID
}
err = tx.Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "template_uuid"}, {Name: "repository_configuration_uuid"}},
DoUpdates: clause.AssignmentColumns([]string{"deleted_at", "snapshot_uuid"}),
}).Create(&templateRepoConfigs).Error
if err != nil {
return TemplateDBToApiError(err, nil)
}
return nil
}
func (t templateDaoImpl) DeleteTemplateRepoConfigs(ctx context.Context, templateUUID string, keepRepoConfigUUIDs []string) error {
err := t.db.WithContext(ctx).Unscoped().Where("template_uuid = ? AND repository_configuration_uuid not in ?", UuidifyString(templateUUID), UuidifyStrings(keepRepoConfigUUIDs)).
Delete(models.TemplateRepositoryConfiguration{}).Error
if err != nil {
return TemplateDBToApiError(err, nil)
}
return nil
}
func (t templateDaoImpl) softDeleteTemplateRepoConfigs(tx *gorm.DB, templateUUID string, keepRepoConfigUUIDs []string) error {
err := tx.Debug().Where("template_uuid = ? AND repository_configuration_uuid not in ?", UuidifyString(templateUUID), UuidifyStrings(keepRepoConfigUUIDs)).
Delete(&models.TemplateRepositoryConfiguration{}).Error
if err != nil {
return TemplateDBToApiError(err, nil)
}
return nil
}
func (t templateDaoImpl) Fetch(ctx context.Context, orgID string, uuid string, includeSoftDel bool) (api.TemplateResponse, error) {
modelTemplate, err := t.fetch(ctx, orgID, uuid, includeSoftDel)
if err != nil {
return api.TemplateResponse{}, err
}
pulpContentPath := ""
if config.Get().Features.Snapshots.Enabled {
var err error
pulpContentPath, err = t.pulpClient.GetContentPath(ctx)
if err != nil {
return api.TemplateResponse{}, err
}
}
lastSnapshotUUIDs, err := t.fetchLatestSnapshotUUIDsForReposOfTemplates(ctx, []models.Template{modelTemplate})
if err != nil {
return api.TemplateResponse{}, TemplateDBToApiError(err, nil)
}
return templatesConvertToResponses([]models.Template{modelTemplate}, lastSnapshotUUIDs, pulpContentPath)[0], nil
}
func (t templateDaoImpl) fetch(ctx context.Context, orgID string, uuid string, includeSoftDel bool) (models.Template, error) {
var modelTemplate models.Template
query := t.db.WithContext(ctx)
if includeSoftDel {
query = query.Unscoped()
}
err := query.Where("uuid = ? AND org_id = ?", UuidifyString(uuid), orgID).
Preload("TemplateRepositoryConfigurations.Snapshot.RepositoryConfiguration").
Preload("LastUpdateTask").
First(&modelTemplate).Error
if err != nil {
return modelTemplate, TemplateDBToApiError(err, &uuid)
}
return modelTemplate, nil
}
func (t templateDaoImpl) Update(ctx context.Context, orgID string, uuid string, templParams api.TemplateUpdateRequest) (api.TemplateResponse, error) {
var resp api.TemplateResponse
var err error
err = t.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
return t.update(ctx, tx, orgID, uuid, templParams)
})
if err != nil {
return resp, err
}
resp, err = t.Fetch(ctx, orgID, uuid, false)
if err != nil {
return resp, err
}
event.SendTemplateEvent(orgID, event.TemplateUpdated, []api.TemplateResponse{resp})
return resp, err
}
func (t templateDaoImpl) update(ctx context.Context, tx *gorm.DB, orgID string, uuid string, templParams api.TemplateUpdateRequest) error {
dbTempl, err := t.fetch(ctx, orgID, uuid, false)
if err != nil {
return err
}
templatesUpdateApiToModel(templParams, &dbTempl)
// copy fields to validate before updating the template
validateTemplate := models.Template{
Name: dbTempl.Name,
OrgID: dbTempl.OrgID,
Arch: dbTempl.Arch,
UseLatest: dbTempl.UseLatest,
Version: dbTempl.Version,
Date: dbTempl.Date,
}
tx = tx.WithContext(ctx)
if err := tx.Model(&validateTemplate).Where("uuid = ?", UuidifyString(uuid)).Updates(dbTempl.MapForUpdate()).Error; err != nil {
return TemplateDBToApiError(err, &uuid)
}
var existingRepoConfigUUIDs []string
if err := tx.Model(&models.TemplateRepositoryConfiguration{}).Select("repository_configuration_uuid").Where("template_uuid = ?", dbTempl.UUID).Find(&existingRepoConfigUUIDs).Error; err != nil {
return RepositoryDBErrorToApi(err, nil)
}
if templParams.RepositoryUUIDS != nil {
if err := t.validateRepositoryUUIDs(ctx, orgID, templParams.RepositoryUUIDS); err != nil {
return err
}
err = t.softDeleteTemplateRepoConfigs(tx, uuid, templParams.RepositoryUUIDS)
if err != nil {
return fmt.Errorf("could not remove uneeded template repositories %w", err)
}
err = t.insertTemplateRepoConfigsAndSnapshots(tx, ctx, dbTempl.OrgID, dbTempl, templParams.RepositoryUUIDS)
if err != nil {
return fmt.Errorf("could not insert new template repositories %w", err)
}
}
return nil
}
func (t templateDaoImpl) List(ctx context.Context, orgID string, includeSoftDel bool, paginationData api.PaginationData, filterData api.TemplateFilterData) (api.TemplateCollectionResponse, int64, error) {
var totalTemplates int64
templates := make([]models.Template, 0)
filteredDB := t.filteredDbForList(orgID, t.db.WithContext(ctx), filterData)
if includeSoftDel {
filteredDB = filteredDB.Unscoped()
}
sortMap := map[string]string{
"name": "name",
"url": "url",
"arch": "arch",
"version": "version",
}
order := convertSortByToSQL(paginationData.SortBy, sortMap, "name asc")
// Get count
if filteredDB.
Model(&templates).
Distinct("uuid").
Count(&totalTemplates).Error != nil {
return api.TemplateCollectionResponse{}, totalTemplates, TemplateDBToApiError(filteredDB.Error, nil)
}
if filteredDB.
Distinct("templates.*").
Preload("TemplateRepositoryConfigurations").
Preload("LastUpdateTask").
Order(order).
Limit(paginationData.Limit).
Offset(paginationData.Offset).
Find(&templates).Error != nil {
return api.TemplateCollectionResponse{}, totalTemplates, TemplateDBToApiError(filteredDB.Error, nil)
}
pulpContentPath := ""
if config.Get().Features.Snapshots.Enabled {
var err error
pulpContentPath, err = t.pulpClient.GetContentPath(ctx)
if err != nil {
return api.TemplateCollectionResponse{}, 0, err
}
}
lastSnapshotUUIDs, err := t.fetchLatestSnapshotUUIDsForReposOfTemplates(ctx, templates)
if err != nil {
return api.TemplateCollectionResponse{}, totalTemplates, TemplateDBToApiError(err, nil)
}
responses := templatesConvertToResponses(templates, lastSnapshotUUIDs, pulpContentPath)
return api.TemplateCollectionResponse{Data: responses}, totalTemplates, nil
}
func (t templateDaoImpl) InternalOnlyFetchByName(ctx context.Context, name string) (models.Template, error) {
var modelTemplate models.Template
err := t.db.WithContext(ctx).
Where("name = ? ", name).
Preload("TemplateRepositoryConfigurations").First(&modelTemplate).Error
if err != nil {
return modelTemplate, TemplateDBToApiError(err, nil)
}
return modelTemplate, nil
}
func (t templateDaoImpl) filteredDbForList(orgID string, filteredDB *gorm.DB, filterData api.TemplateFilterData) *gorm.DB {
filteredDB = filteredDB.Where("org_id = ? ", orgID).Preload("TemplateRepositoryConfigurations.Snapshot.RepositoryConfiguration")
if filterData.Name != "" {
filteredDB = filteredDB.Where("name = ?", filterData.Name)
}
if filterData.Arch != "" {
filteredDB = filteredDB.Where("arch = ?", filterData.Arch)
}
if filterData.Version != "" {
filteredDB = filteredDB.Where("version = ?", filterData.Version)
}
if filterData.Search != "" {
containsSearch := "%" + filterData.Search + "%"
filteredDB = filteredDB.
Where("name LIKE ?", containsSearch)
}
if len(filterData.RepositoryUUIDs) > 0 || len(filterData.SnapshotUUIDs) > 0 {
filteredDB = filteredDB.
Joins("INNER JOIN templates_repository_configurations on templates_repository_configurations.template_uuid = templates.uuid")
}
if len(filterData.RepositoryUUIDs) > 0 && len(filterData.SnapshotUUIDs) > 0 {
filteredDB = filteredDB.
Where("templates_repository_configurations.repository_configuration_uuid in ?", UuidifyStrings(filterData.RepositoryUUIDs)).
Or("templates_repository_configurations.snapshot_uuid in ?", UuidifyStrings(filterData.SnapshotUUIDs))
} else if len(filterData.RepositoryUUIDs) > 0 {
filteredDB = filteredDB.
Where("templates_repository_configurations.repository_configuration_uuid in ?", UuidifyStrings(filterData.RepositoryUUIDs))
} else if len(filterData.SnapshotUUIDs) > 0 {
filteredDB = filteredDB.
Where("templates_repository_configurations.snapshot_uuid in ?", UuidifyStrings(filterData.SnapshotUUIDs))
}
if filterData.UseLatest {
filteredDB = filteredDB.Where("use_latest = ?", filterData.UseLatest)
}
return filteredDB
}
func (t templateDaoImpl) SoftDelete(ctx context.Context, orgID string, uuid string) error {
var modelTemplate models.Template
err := t.db.WithContext(ctx).Where("uuid = ? AND org_id = ?", UuidifyString(uuid), orgID).First(&modelTemplate).Error
if err != nil {
return TemplateDBToApiError(err, &uuid)
}
if err = t.db.WithContext(ctx).Delete(&modelTemplate).Error; err != nil {
return err
}
var resp api.TemplateResponse
templatesModelToApi(modelTemplate, &resp)
event.SendTemplateEvent(orgID, event.TemplateDeleted, []api.TemplateResponse{resp})
return nil
}
func (t templateDaoImpl) Delete(ctx context.Context, orgID string, uuid string) error {
var modelTemplate models.Template
err := t.db.WithContext(ctx).Unscoped().Where("uuid = ? AND org_id = ?", UuidifyString(uuid), orgID).First(&modelTemplate).Error
if err != nil {
return TemplateDBToApiError(err, &uuid)
}
if err = t.db.WithContext(ctx).Unscoped().Delete(&modelTemplate).Error; err != nil {
return err
}
return nil
}
func (t templateDaoImpl) ClearDeletedAt(ctx context.Context, orgID string, uuid string) error {
var modelTemplate models.Template
err := t.db.WithContext(ctx).Unscoped().Where("uuid = ? AND org_id = ?", UuidifyString(uuid), orgID).First(&modelTemplate).Error
if err != nil {
return err
}
err = t.db.WithContext(ctx).Unscoped().Model(&modelTemplate).Update("deleted_at", nil).Error
if err != nil {
return err
}
return nil
}
// GetRepoChanges given a template UUID and a slice of repo config uuids, returns the added/removed/unchanged/all between the existing and given repos
func (t templateDaoImpl) GetRepoChanges(ctx context.Context, templateUUID string, newRepoConfigUUIDs []string) ([]string, []string, []string, []string, error) {
var templateRepoConfigs []models.TemplateRepositoryConfiguration
if err := t.db.WithContext(ctx).Model(&models.TemplateRepositoryConfiguration{}).Unscoped().Where("template_uuid = ?", templateUUID).Find(&templateRepoConfigs).Error; err != nil {
return nil, nil, nil, nil, TemplateDBToApiError(err, nil)
}
// if the repo is being added, it's in the request and the distribution_href is nil
// if the repo is already part of the template, it's in request and distribution_href is not nil
// if the repo is being removed, it's not in request but is in the table
var added, unchanged, removed, all []string
for _, v := range templateRepoConfigs {
if v.DistributionHref == "" && slices.Contains(newRepoConfigUUIDs, v.RepositoryConfigurationUUID) {
added = append(added, v.RepositoryConfigurationUUID)
} else if slices.Contains(newRepoConfigUUIDs, v.RepositoryConfigurationUUID) {
unchanged = append(unchanged, v.RepositoryConfigurationUUID)
} else {
removed = append(removed, v.RepositoryConfigurationUUID)
}
all = append(all, v.RepositoryConfigurationUUID)
}
return added, removed, unchanged, all, nil
}
func (t templateDaoImpl) GetDistributionHref(ctx context.Context, templateUUID string, repoConfigUUID string) (string, error) {
var distributionHref string
err := t.db.WithContext(ctx).Model(&models.TemplateRepositoryConfiguration{}).Select("distribution_href").Unscoped().Where("template_uuid = ? AND repository_configuration_uuid = ?", templateUUID, repoConfigUUID).Find(&distributionHref).Error
if err != nil {
return "", err
}
return distributionHref, nil
}
func (t templateDaoImpl) UpdateDistributionHrefs(ctx context.Context, templateUUID string, repoUUIDs []string, snapshots []models.Snapshot, repoDistributionMap map[string]string) error {
templateRepoConfigs := make([]models.TemplateRepositoryConfiguration, len(repoUUIDs))
for i, repo := range repoUUIDs {
snapIndex := slices.IndexFunc(snapshots, func(s models.Snapshot) bool {
return s.RepositoryConfigurationUUID == repo
})
templateRepoConfigs[i].TemplateUUID = templateUUID
templateRepoConfigs[i].RepositoryConfigurationUUID = repo
templateRepoConfigs[i].SnapshotUUID = snapshots[snapIndex].UUID
if repoDistributionMap != nil {
templateRepoConfigs[i].DistributionHref = repoDistributionMap[repo]
}
}
err := t.db.WithContext(ctx).Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "template_uuid"}, {Name: "repository_configuration_uuid"}},
DoUpdates: clause.AssignmentColumns([]string{"distribution_href"}),
}).Create(&templateRepoConfigs).Error
if err != nil {
return TemplateDBToApiError(err, nil)
}
return nil
}
func (t templateDaoImpl) SetEnvironmentCreated(ctx context.Context, templateUUID string) error {
result := t.db.WithContext(ctx).Exec(`
UPDATE templates
SET rhsm_environment_created = true
WHERE uuid = ?`,
templateUUID,
)
if result.Error != nil {
return result.Error
}
return nil
}
func (t templateDaoImpl) UpdateLastUpdateTask(ctx context.Context, taskUUID string, orgID string, templateUUID string) error {
result := t.db.WithContext(ctx).Exec(`
UPDATE templates
SET last_update_task_uuid = ?
WHERE org_id = ?
AND uuid = ?`,
taskUUID,
orgID,
templateUUID,
)
if result.Error != nil {
return result.Error
}
return nil
}
func (t templateDaoImpl) UpdateLastError(ctx context.Context, orgID string, templateUUID string, lastUpdateSnapshotError string) error {
result := t.db.WithContext(ctx).Exec(`
UPDATE templates
SET last_update_snapshot_error = ?
WHERE org_id = ?
AND uuid = ?`,
lastUpdateSnapshotError,
orgID,
templateUUID,
)
if result.Error != nil {
return result.Error
}
return nil
}
func (t templateDaoImpl) UpdateSnapshots(ctx context.Context, templateUUID string, repoUUIDs []string, snapshots []models.Snapshot) error {
var templateRepoConfigs []models.TemplateRepositoryConfiguration
for _, repo := range repoUUIDs {
snapIndex := slices.IndexFunc(snapshots, func(s models.Snapshot) bool {
return s.RepositoryConfigurationUUID == repo
})
templateRepoConfigs = append(templateRepoConfigs, models.TemplateRepositoryConfiguration{
TemplateUUID: templateUUID,
RepositoryConfigurationUUID: repo,
SnapshotUUID: snapshots[snapIndex].UUID,
})
}
if len(templateRepoConfigs) > 0 {
err := t.db.WithContext(ctx).Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "template_uuid"}, {Name: "repository_configuration_uuid"}},
DoUpdates: clause.AssignmentColumns([]string{"snapshot_uuid"}),
}).Create(&templateRepoConfigs).Error
if err != nil {
return TemplateDBToApiError(err, nil)
}
}
return nil
}
func (t templateDaoImpl) DeleteTemplateSnapshot(ctx context.Context, snapshotUUID string) error {
err := t.db.WithContext(ctx).Unscoped().Where("snapshot_uuid = ?", UuidifyString(snapshotUUID)).
Delete(models.TemplateRepositoryConfiguration{}).Error
if err != nil {
return TemplateDBToApiError(err, nil)
}
return nil
}
func (t templateDaoImpl) GetRepositoryConfigurationFile(ctx context.Context, orgID, templateUUID string) (string, error) {
sDao := snapshotDaoImpl(t)
rcDao := repositoryConfigDaoImpl{db: t.db}
template, err := t.Fetch(ctx, orgID, templateUUID, false)
if err != nil {
return "", err
}
pc := t.pulpClient
contentPath, err := pc.GetContentPath(ctx)
if err != nil {
return "", err
}
var templateRepoConfigFile strings.Builder
for _, snap := range template.Snapshots {
repoConfig, err := rcDao.fetchRepoConfig(ctx, orgID, snap.RepositoryUUID, true)
if err != nil {
return "", err
}
repoConfigFile, err := sDao.GetRepositoryConfigurationFile(ctx, orgID, snap.UUID, false)
if err != nil {
return "", err
}
var contentURL string
domain := strings.Split(snap.RepositoryPath, "/")[0]
parsedRepoURL, err := url.Parse(repoConfig.Repository.URL)
if err != nil {
return "", err
}
path := parsedRepoURL.Path
if repoConfig.IsRedHat() {
contentURL = contentPath + domain + "/templates/" + templateUUID + path
} else {
contentURL = contentPath + domain + "/templates/" + templateUUID + "/" + snap.RepositoryUUID
}
// replace baseurl with the one specific to the template
re, err := regexp.Compile(`(?m)^baseurl=.*`)
if err != nil {
return "", err
}
if !re.MatchString(repoConfigFile) {
return "", fmt.Errorf("baseurl not found in config file")
}
repoConfigFile = re.ReplaceAllString(repoConfigFile, fmt.Sprintf("baseurl=%s", contentURL))
templateRepoConfigFile.WriteString(repoConfigFile)
templateRepoConfigFile.WriteString("\n")
}
return templateRepoConfigFile.String(), nil
}
func templatesCreateApiToModel(api api.TemplateRequest, model *models.Template) {
if api.Name != nil {
model.Name = *api.Name
}
if api.Description != nil {
model.Description = *api.Description
}
if api.Version != nil {
model.Version = *api.Version
}
if api.Arch != nil {
model.Arch = *api.Arch
}
if api.Date != nil {
model.Date = api.Date.AsTime().UTC()
}
if api.OrgID != nil {
model.OrgID = *api.OrgID
}
if api.User != nil {
model.CreatedBy = *api.User
model.LastUpdatedBy = *api.User
}
if api.UseLatest != nil {
model.UseLatest = *api.UseLatest
}
}
func templatesUpdateApiToModel(api api.TemplateUpdateRequest, model *models.Template) {
if api.Description != nil {
model.Description = *api.Description
}
if api.Date != nil {
model.Date = api.Date.AsTime().UTC()
}
if api.OrgID != nil {
model.OrgID = *api.OrgID
}
if api.User != nil {
model.LastUpdatedBy = *api.User
}
if api.Name != nil {
model.Name = *api.Name
}
if api.UseLatest != nil {
model.UseLatest = *api.UseLatest
}
}
func templatesModelToApi(model models.Template, apiTemplate *api.TemplateResponse) {
apiTemplate.UUID = model.UUID
apiTemplate.RHSMEnvironmentID = candlepin_client.GetEnvironmentID(model.UUID)
apiTemplate.RHSMEnvironmentCreated = model.RHSMEnvironmentCreated
apiTemplate.OrgID = model.OrgID
apiTemplate.Name = model.Name
apiTemplate.Description = model.Description
apiTemplate.Version = model.Version
apiTemplate.Arch = model.Arch
apiTemplate.Date = model.Date.UTC()
apiTemplate.CreatedBy = model.CreatedBy
apiTemplate.LastUpdatedBy = model.LastUpdatedBy
apiTemplate.CreatedAt = model.CreatedAt.UTC()
apiTemplate.UpdatedAt = model.UpdatedAt.UTC()
apiTemplate.UseLatest = model.UseLatest
apiTemplate.DeletedAt = model.DeletedAt
if model.LastUpdateSnapshotError != nil {
apiTemplate.LastUpdateSnapshotError = *model.LastUpdateSnapshotError
}
apiTemplate.LastUpdateTaskUUID = model.LastUpdateTaskUUID
if model.LastUpdateTask != nil {
apiTemplate.LastUpdateTask = &api.TaskInfoResponse{
UUID: model.LastUpdateTaskUUID,
Status: model.LastUpdateTask.Status,
Typename: model.LastUpdateTask.Typename,
OrgId: model.LastUpdateTask.OrgId,
ObjectType: config.ObjectTypeTemplate,
ObjectUUID: model.UUID,
ObjectName: model.Name,
}
if model.LastUpdateTask.Started != nil {
apiTemplate.LastUpdateTask.CreatedAt = model.LastUpdateTask.Started.Format(time.RFC3339)
}
if model.LastUpdateTask.Finished != nil {
apiTemplate.LastUpdateTask.EndedAt = model.LastUpdateTask.Finished.Format(time.RFC3339)
}
if model.LastUpdateTask.Error != nil {
apiTemplate.LastUpdateTask.Error = *model.LastUpdateTask.Error
}
}
}
func templatesConvertToResponses(templates []models.Template, lastSnapshotsUUIDs []string, pulpContentPath string) []api.TemplateResponse {
responses := make([]api.TemplateResponse, len(templates))
outdatedDate := time.Now().Add(-time.Duration((config.Get().Options.SnapshotRetainDaysLimit-14)*24) * time.Hour)
for i := 0; i < len(templates); i++ {
templatesModelToApi(templates[i], &responses[i])
// Add in associations (Repository Config UUIDs and Snapshots)
responses[i].RepositoryUUIDS = make([]string, 0) // prevent null responses
responses[i].ToBeDeletedSnapshots = make([]api.SnapshotResponse, 0)
for _, tRepoConfig := range templates[i].TemplateRepositoryConfigurations {
responses[i].RepositoryUUIDS = append(responses[i].RepositoryUUIDS, tRepoConfig.RepositoryConfigurationUUID)
snaps := snapshotConvertToResponses([]models.Snapshot{tRepoConfig.Snapshot}, pulpContentPath)
responses[i].Snapshots = append(responses[i].Snapshots, snaps[0])
}
for _, snap := range responses[i].Snapshots {
if snap.CreatedAt.Before(outdatedDate) && !slices.Contains(lastSnapshotsUUIDs, snap.UUID) {
responses[i].ToBeDeletedSnapshots = append(responses[i].ToBeDeletedSnapshots, snap)
}
}
}
return responses
}
func (t templateDaoImpl) fetchLatestSnapshotUUIDsForReposOfTemplates(ctx context.Context, templates []models.Template) ([]string, error) {
var repoUUIDs = make([]string, 0)
var repos []models.RepositoryConfiguration
var snapshotUUIDs = make([]string, 0)
for _, template := range templates {
for _, trc := range template.TemplateRepositoryConfigurations {
repoUUIDs = append(repoUUIDs, trc.RepositoryConfigurationUUID)
}
}
slices.Sort(repoUUIDs)
repoUUIDs = slices.Compact(repoUUIDs)
err := t.db.WithContext(ctx).
Where("uuid IN ? ", repoUUIDs).
Find(&repos).
Error
if err != nil {
return snapshotUUIDs, err
}
for _, repo := range repos {
snapshotUUIDs = append(snapshotUUIDs, repo.LastSnapshotUUID)
}
return snapshotUUIDs, nil
}