-
Notifications
You must be signed in to change notification settings - Fork 239
/
load.go
1858 lines (1619 loc) · 52 KB
/
load.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
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package sqlite
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"strings"
"github.com/blang/semver/v4"
_ "github.com/mattn/go-sqlite3"
utilerrors "k8s.io/apimachinery/pkg/util/errors"
libsemver "github.com/operator-framework/operator-registry/pkg/lib/semver"
"github.com/operator-framework/operator-registry/pkg/registry"
)
type sqlLoader struct {
db *sql.DB
migrator Migrator
enableAlpha bool
}
type MigratableLoader interface {
registry.Load
Migrate(context.Context) error
}
var _ MigratableLoader = &sqlLoader{}
// startDepth is the depth that channel heads should be assigned
// in the channel_entry table. This const exists so that all
// add modes (replaces, semver, and semver-skippatch) are
// consistent.
const startDepth = 0
func newSQLLoader(db *sql.DB, opts ...DbOption) (*sqlLoader, error) {
options := defaultDBOptions()
for _, o := range opts {
o(options)
}
if _, err := db.Exec("PRAGMA foreign_keys = ON"); err != nil {
return nil, err
}
migrator, err := options.MigratorBuilder(db)
if err != nil {
return nil, err
}
return &sqlLoader{db: db, migrator: migrator, enableAlpha: options.EnableAlpha}, nil
}
func NewSQLLiteLoader(db *sql.DB, opts ...DbOption) (MigratableLoader, error) {
return newSQLLoader(db, opts...)
}
func (s *sqlLoader) Migrate(ctx context.Context) error {
if s.migrator == nil {
return fmt.Errorf("no migrator configured")
}
return s.migrator.Migrate(ctx)
}
func (s *sqlLoader) AddOperatorBundle(bundle *registry.Bundle) error {
tx, err := s.db.Begin()
if err != nil {
return err
}
defer func() {
tx.Rollback()
}()
if err := s.addOperatorBundle(tx, bundle); err != nil {
return err
}
return tx.Commit()
}
func (s *sqlLoader) addOperatorBundle(tx *sql.Tx, bundle *registry.Bundle) error {
addBundle, err := tx.Prepare("insert into operatorbundle(name, csv, bundle, bundlepath, version, skiprange, replaces, skips, substitutesfor) values(?, ?, ?, ?, ?, ?, ?, ?, ?)")
if err != nil {
return err
}
defer addBundle.Close()
addImage, err := tx.Prepare("insert into related_image(image, operatorbundle_name) values(?,?)")
if err != nil {
return fmt.Errorf("failed to insert related image: %s", err)
}
defer addImage.Close()
csvName, bundleImage, csvBytes, bundleBytes, _, err := bundle.Serialize()
if err != nil {
return fmt.Errorf("unable to serialize the bundle : %s", err)
}
if csvName == "" {
return fmt.Errorf("csv name not found")
}
version, err := bundle.Version()
if err != nil {
return fmt.Errorf("unable to obtain bundle version : %s", err)
}
skiprange, err := bundle.SkipRange()
if err != nil {
return fmt.Errorf("unable to obtain skipRange : %s", err)
}
replaces, err := bundle.Replaces()
if err != nil {
return fmt.Errorf("unable to obtain replaces : %s", err)
}
skips, err := bundle.Skips()
if err != nil {
return fmt.Errorf("unable to obtain skips : %s", err)
}
substitutesFor, err := bundle.SubstitutesFor()
if err != nil {
return fmt.Errorf("unable to obtain substitutes : %s", err)
}
if substitutesFor != "" && !s.enableAlpha {
return fmt.Errorf("SubstitutesFor is an alpha-only feature. You must enable alpha features with the flag --enable-alpha in order to use this feature.")
}
if _, err := addBundle.Exec(csvName, csvBytes, bundleBytes, bundleImage, version, skiprange, replaces, strings.Join(skips, ","), substitutesFor); err != nil {
return fmt.Errorf("failed to add bundle %q: %s", csvName, err.Error())
}
imgs, err := bundle.Images()
if err != nil {
return fmt.Errorf("unable to obtain images : %s", err)
}
for img := range imgs {
if _, err := addImage.Exec(img, csvName); err != nil {
return fmt.Errorf("failed to add related images %q for bundle %q: %s", img, csvName, err.Error())
}
}
// Add dependencies information
err = s.addDependencies(tx, bundle)
if err != nil {
return fmt.Errorf("failed to add dependencies : %s", err)
}
err = s.addBundleProperties(tx, bundle)
if err != nil {
return fmt.Errorf("failed to add properties : %s", err)
}
if s.enableAlpha {
err = s.addSubstitutesFor(tx, bundle)
if err != nil {
return fmt.Errorf("failed to add substitutes : %s", err)
}
}
return s.addAPIs(tx, bundle)
}
func (s *sqlLoader) addSubstitutesFor(tx *sql.Tx, bundle *registry.Bundle) error {
updateBundleReplaces, err := tx.Prepare("update operatorbundle set replaces = ? where replaces = ?")
if err != nil {
return err
}
defer updateBundleReplaces.Close()
updateBundleSkips, err := tx.Prepare("update operatorbundle set skips = ? where name = ?")
if err != nil {
return err
}
defer updateBundleSkips.Close()
updateBundleSubstitutesFor, err := tx.Prepare("update operatorbundle set substitutesfor = ? where name = ?")
if err != nil {
return err
}
defer updateBundleSubstitutesFor.Close()
updateBundleReplacesSkips, err := tx.Prepare("update operatorbundle set replaces = ?, skips = ? where name = ?")
if err != nil {
return err
}
defer updateBundleReplacesSkips.Close()
csvName := bundle.Name
replaces, err := bundle.Replaces()
if err != nil {
return fmt.Errorf("failed to obtain replaces : %s", err)
}
skips, err := bundle.Skips()
if err != nil {
return fmt.Errorf("failed to obtain skips : %s", err)
}
version, err := bundle.Version()
if err != nil {
return fmt.Errorf("failed to obtain version : %s", err)
}
substitutesFor, err := bundle.SubstitutesFor()
if err != nil {
return fmt.Errorf("failed to obtain substitutes : %s", err)
}
if substitutesFor != "" {
// Update any replaces that reference the substituted-for bundle
_, err = updateBundleReplaces.Exec(csvName, substitutesFor)
if err != nil {
return err
}
// Check if any other bundle substitutes for the same bundle
otherSubstitutions, err := s.getBundlesThatSubstitutesFor(tx, substitutesFor)
if err != nil {
return err
}
for len(otherSubstitutions) > 0 {
// consume the slice of substitutions
otherSubstitution := otherSubstitutions[0]
otherSubstitutions = otherSubstitutions[1:]
if otherSubstitution != csvName {
// Another bundle is substituting for that same bundle
// Get other bundle's version
_, _, rawVersion, err := s.getBundleSkipsReplacesVersion(tx, otherSubstitution)
if err != nil {
return err
}
otherSubstitutionVersion, err := semver.Parse(rawVersion)
if err != nil {
return err
}
currentSubstitutionVersion, err := semver.Parse(version)
if err != nil {
return err
}
// Compare versions
c, err := libsemver.BuildIdCompare(otherSubstitutionVersion, currentSubstitutionVersion)
if err != nil {
return err
}
if c < 0 {
// Update the currentSubstitution substitutesFor to point to otherSubstitution
// since it is latest
_, err = updateBundleSubstitutesFor.Exec(otherSubstitution, csvName)
if err != nil {
return err
}
moreSubstitutions, err := s.getBundlesThatSubstitutesFor(tx, otherSubstitution)
if err != nil {
return err
}
otherSubstitutions = append(otherSubstitutions, moreSubstitutions...)
} else if c > 0 {
// Update the otherSubstitution's substitutesFor to point to csvName
// Since it is the latest
_, err = updateBundleSubstitutesFor.Exec(csvName, otherSubstitution)
if err != nil {
return err
}
// Update the otherSubstitution's skips to include csvName and its skips
err = s.appendSkips(tx, append(skips, csvName), otherSubstitution)
if err != nil {
return err
}
moreSubstitutions, err := s.getBundlesThatSubstitutesFor(tx, csvName)
if err != nil {
return err
}
if len(moreSubstitutions) > 1 {
return fmt.Errorf("programmer error: more than one substitution pointing to %s", csvName)
}
} else {
// the versions are equal
return fmt.Errorf("cannot determine latest substitution because of duplicate versions")
}
}
}
}
// Get latest substitutesFor value of the current bundle
substitutesFor, err = s.getBundleSubstitution(tx, csvName)
if err != nil {
return err
}
// If the substituted-for of the current bundle substitutes for another bundle
// it should also be added to the skips of the substitutesFor bundle
for substitutesFor != "" {
skips = append(skips, substitutesFor)
substitutesFor, err = s.getBundleSubstitution(tx, substitutesFor)
if err != nil {
return err
}
}
// If the substitution (or substitution of substitution) is added before the
// substituted for bundle, (i.e. the bundle being added is substituted for by
// another bundle) then transfer the skips from the substitutedFor bundle (this
// bundle) over to the substitution's skips
var substitutesFors []string
substitutesFors, err = s.getBundlesThatSubstitutesFor(tx, csvName)
if err != nil || len(substitutesFors) > 1 {
return err
}
for len(substitutesFors) > 0 {
err = s.appendSkips(tx, append(skips, csvName), substitutesFors[0])
if err != nil {
return err
}
substitutesFors, err = s.getBundlesThatSubstitutesFor(tx, substitutesFors[0])
if err != nil || len(substitutesFors) > 1 {
return err
}
}
// Bundles that skip a bundle that is substituted for
// should also skip the substituted-for bundle
if len(skips) != 0 {
// ensure slice of skips doesn't contain duplicates
substitutesSkips := make(map[string]struct{})
skipsOverwrite := []string{}
for _, skip := range skips {
substitutesSkips[skip] = struct{}{}
substitutesFors, err = s.getBundlesThatSubstitutesFor(tx, skip)
if err != nil || len(substitutesFors) > 1 {
return err
}
for len(substitutesFors) > 0 {
// consume the slice of substitutions
substitutesFor = substitutesFors[0]
substitutesFors = substitutesFors[1:]
// shouldn't skip yourself
if substitutesFor != csvName {
substitutesSkips[substitutesFor] = struct{}{}
substitutesFors, err = s.getBundlesThatSubstitutesFor(tx, substitutesFor)
if err != nil || len(substitutesFors) > 1 {
return err
}
}
}
}
for s := range substitutesSkips {
skipsOverwrite = append(skipsOverwrite, s)
}
skips = skipsOverwrite
}
// If the bundle being added replaces a bundle that is substituted for
// (for example it was the previous head of the channel), change
// the replaces to the substituted-for bundle
if replaces != "" {
substitutesFors, err = s.getBundlesThatSubstitutesFor(tx, replaces)
if err != nil {
return err
}
for len(substitutesFors) > 0 {
// update the replaces to a newer substitution
replaces = substitutesFors[0]
// try to get the substitution of the substitution
substitutesFors, err = s.getBundlesThatSubstitutesFor(tx, replaces)
if err != nil || len(substitutesFors) > 1 {
return err
}
}
}
_, err = updateBundleReplacesSkips.Exec(replaces, strings.Join(skips, ","), csvName)
if err != nil {
return err
}
return nil
}
func (s *sqlLoader) appendSkips(tx *sql.Tx, skips []string, csvName string) error {
updateSkips, err := tx.Prepare("update operatorbundle set skips = ? where name = ?")
if err != nil {
return err
}
defer updateSkips.Close()
_, currentSkips, _, err := s.getBundleSkipsReplacesVersion(tx, csvName)
if err != nil {
return err
}
// ensure slice of skips doesn't contain duplicates
skipsMap := make(map[string]struct{})
for _, skip := range currentSkips {
skipsMap[skip] = struct{}{}
}
for _, skip := range skips {
if _, ok := skipsMap[skip]; !ok {
currentSkips = append(currentSkips, skip)
}
}
_, err = updateSkips.Exec(strings.Join(currentSkips, ","), csvName)
return err
}
func (s *sqlLoader) AddPackageChannelsFromGraph(graph *registry.Package) error {
tx, err := s.db.Begin()
if err != nil {
return fmt.Errorf("unable to start a transaction: %s", err)
}
defer func() {
tx.Rollback()
}()
var errs []error
if err := addPackageIfNotExists(tx, graph.Name); err != nil {
errs = append(errs, err)
}
for name, channel := range graph.Channels {
if err := addOrUpdateChannel(tx, name, graph.Name, channel.Head.CsvName); err != nil {
errs = append(errs, err)
continue
}
}
if err := updateDefaultChannel(tx, graph.DefaultChannel, graph.Name); err != nil {
errs = append(errs, fmt.Errorf("the default channel (%s) does not exist: %s", graph.DefaultChannel, err))
}
// update each channel's graph
for channelName, channel := range graph.Channels {
currentNode := channel.Head
depth := startDepth
var previousNodeID int64
// first clear the current channel graph
err := truncChannelGraph(tx, channelName, graph.Name)
if err != nil {
errs = append(errs, err)
break
}
// iterate into the replacement chain of the channel to insert or update all entries
for {
// create real channel entry for node
id, err := addChannelEntry(tx, channelName, graph.Name, currentNode.CsvName, depth)
if err != nil {
errs = append(errs, err)
break
}
// If the previous node was created, use the entryId of the current node to update
// the replaces for the previous node
if previousNodeID != 0 {
err := addReplaces(tx, id, previousNodeID)
if err != nil {
errs = append(errs, err)
}
}
syntheticReplaces := make([]registry.BundleKey, 0) // for CSV skips
nextNode := registry.BundleKey{}
currentNodeReplaces := channel.Nodes[currentNode]
// Iterate over all replaces for the node in the graph
// It should only contain one real replacement, so let's find it and
// follow the chain. For the rest, they are fake entries and should be
// generated as synthetic replacements
for replace := range currentNodeReplaces {
if _, ok := channel.Nodes[replace]; !ok {
syntheticReplaces = append(syntheticReplaces, replace)
} else {
nextNode = replace
}
}
// create synthetic channel entries for nodes
// also create channel entry to replace that node
syntheticDepth := depth + 1
for _, synthetic := range syntheticReplaces {
syntheticReplacesID, err := addChannelEntry(tx, channelName, graph.Name, synthetic.CsvName, syntheticDepth)
if err != nil {
errs = append(errs, err)
break
}
syntheticNodeID, err := addChannelEntry(tx, channelName, graph.Name, currentNode.CsvName, syntheticDepth)
if err != nil {
errs = append(errs, err)
break
}
err = addReplaces(tx, syntheticReplacesID, syntheticNodeID)
if err != nil {
errs = append(errs, err)
}
syntheticDepth++
}
// we got to the end of the channel graph
if nextNode.IsEmpty() {
// expectedDepth is:
// <number-of-nodes> + <start-depth> - 1
// For example, if the number of nodes is 3 and the startDepth is 0, the expected depth is 2 (0, 1, 2)
// If the number of nodes is 5 and the startDepth is 3, the expected depth is 7 (3, 4, 5, 6, 7)
expectedDepth := len(channel.Nodes) + startDepth - 1
if expectedDepth != depth {
err := fmt.Errorf("Invalid graph: some (non-bottom) nodes defined in the graph were not mentioned as replacements of any node (%d != %d)", expectedDepth, depth)
errs = append(errs, err)
}
break
}
// increase depth and continue
currentNode = nextNode
previousNodeID = id
depth++
}
}
if err := tx.Commit(); err != nil {
errs = append(errs, err)
}
return utilerrors.NewAggregate(errs)
}
func (s *sqlLoader) AddPackageChannels(manifest registry.PackageManifest) error {
tx, err := s.db.Begin()
if err != nil {
return fmt.Errorf("unable to start a transaction: %s", err)
}
defer func() {
tx.Rollback()
}()
if err := s.rmPackage(tx, manifest.PackageName); err != nil {
return err
}
if err := s.addPackageChannels(tx, manifest); err != nil {
return err
}
return tx.Commit()
}
func (s *sqlLoader) addPackageChannels(tx *sql.Tx, manifest registry.PackageManifest) error {
addPackage, err := tx.Prepare("insert into package(name) values(?)")
if err != nil {
return err
}
defer addPackage.Close()
addDefaultChannel, err := tx.Prepare("update package set default_channel = ? where name = ?")
if err != nil {
return err
}
defer addDefaultChannel.Close()
addChannel, err := tx.Prepare("insert into channel(name, package_name, head_operatorbundle_name) values(?, ?, ?)")
if err != nil {
return err
}
defer addChannel.Close()
addChannelEntry, err := tx.Prepare("insert into channel_entry(channel_name, package_name, operatorbundle_name, depth) values(?, ?, ?, ?)")
if err != nil {
return err
}
defer addChannelEntry.Close()
addReplaces, err := tx.Prepare("update channel_entry set replaces = ? where entry_id = ?")
if err != nil {
return err
}
defer addReplaces.Close()
getReplaces, err := tx.Prepare(`
SELECT DISTINCT operatorbundle.csv
FROM operatorbundle
WHERE operatorbundle.name=? LIMIT 1`)
if err != nil {
return err
}
defer getReplaces.Close()
if _, err := addPackage.Exec(manifest.PackageName); err != nil {
return fmt.Errorf("failed to add package %q: %s", manifest.PackageName, err.Error())
}
var (
errs []error
channels []registry.PackageChannel
hasDefault bool
)
for _, c := range manifest.Channels {
if deprecated, err := s.deprecated(tx, c.CurrentCSVName); err != nil || deprecated {
// Elide channels that start with a deprecated bundle
continue
}
if _, err := addChannel.Exec(c.Name, manifest.PackageName, c.CurrentCSVName); err != nil {
errs = append(errs, fmt.Errorf("failed to add channel %q in package %q: %s", c.Name, manifest.PackageName, err.Error()))
continue
}
if c.IsDefaultChannel(manifest) {
hasDefault = true
if _, err := addDefaultChannel.Exec(c.Name, manifest.PackageName); err != nil {
errs = append(errs, fmt.Errorf("failed to add default channel %q in package %q: %s", c.Name, manifest.PackageName, err.Error()))
continue
}
}
channels = append(channels, c)
}
if !hasDefault {
errs = append(errs, fmt.Errorf("no default channel specified for %s", manifest.PackageName))
}
for _, c := range channels {
res, err := addChannelEntry.Exec(c.Name, manifest.PackageName, c.CurrentCSVName, startDepth)
if err != nil {
errs = append(errs, fmt.Errorf("failed to add channel %q in package %q: %s", c.Name, manifest.PackageName, err.Error()))
continue
}
currentID, err := res.LastInsertId()
if err != nil {
errs = append(errs, err)
continue
}
channelEntryCSVName := c.CurrentCSVName
// depth is set to `startDepth + 1` here because we already added the channel head
// with depth `startDepth` above.
depth := startDepth + 1
// Since this loop depends on following 'replaces', keep track of where it's been
replaceCycle := map[string]bool{channelEntryCSVName: true}
for {
// Get CSV for current entry
replaces, skips, version, err := s.getBundleSkipsReplacesVersion(tx, channelEntryCSVName)
if err != nil {
errs = append(errs, err)
break
}
bundlePath, err := s.getBundlePathIfExists(tx, channelEntryCSVName)
if err != nil {
// this should only happen on an SQL error, bundlepath just not being set is for backwards compatibility reasons
errs = append(errs, err)
break
}
if err := s.addPackageProperty(tx, channelEntryCSVName, manifest.PackageName, version, bundlePath); err != nil {
errs = append(errs, err)
break
}
deprecated, err := s.deprecated(tx, channelEntryCSVName)
if err != nil {
errs = append(errs, err)
break
}
if deprecated {
// The package is truncated below this point, we're done!
break
}
for _, skip := range skips {
// add dummy channel entry for the skipped version
skippedChannelEntry, err := addChannelEntry.Exec(c.Name, manifest.PackageName, skip, depth)
if err != nil {
errs = append(errs, fmt.Errorf("failed to add channel %q for skipped version %q in package %q: %s", c.Name, skip, manifest.PackageName, err.Error()))
continue
}
skippedID, err := skippedChannelEntry.LastInsertId()
if err != nil {
errs = append(errs, err)
continue
}
// add another channel entry for the parent, which replaces the skipped
synthesizedChannelEntry, err := addChannelEntry.Exec(c.Name, manifest.PackageName, channelEntryCSVName, depth)
if err != nil {
errs = append(errs, fmt.Errorf("failed to add channel %q for replaces %q in package %q: %s", c.Name, channelEntryCSVName, manifest.PackageName, err.Error()))
continue
}
synthesizedID, err := synthesizedChannelEntry.LastInsertId()
if err != nil {
errs = append(errs, err)
continue
}
if _, err = addReplaces.Exec(skippedID, synthesizedID); err != nil {
errs = append(errs, err)
continue
}
depth++
}
// create real replacement chain
if replaces == "" {
// we've walked the channel until there was no replacement
break
}
replacedChannelEntry, err := addChannelEntry.Exec(c.Name, manifest.PackageName, replaces, depth)
if err != nil {
errs = append(errs, fmt.Errorf("failed to add channel %q for replaces %q in package %q: %s", c.Name, replaces, manifest.PackageName, err.Error()))
break
}
// If we find 'replaces' in the circuit list then we've seen it already, break out
if _, ok := replaceCycle[replaces]; ok {
errs = append(errs, fmt.Errorf("Cycle detected, %s replaces %s", channelEntryCSVName, replaces))
break
}
replaceCycle[replaces] = true
replacedID, err := replacedChannelEntry.LastInsertId()
if err != nil {
errs = append(errs, err)
break
}
if _, err = addReplaces.Exec(replacedID, currentID); err != nil {
errs = append(errs, err)
break
}
if _, _, _, err := s.getBundleSkipsReplacesVersion(tx, replaces); err != nil {
errs = append(errs, fmt.Errorf("Invalid bundle %s, replaces nonexistent bundle %s", c.CurrentCSVName, replaces))
break
}
currentID = replacedID
channelEntryCSVName = replaces
depth++
}
}
return utilerrors.NewAggregate(errs)
}
func (s *sqlLoader) ClearNonHeadBundles() error {
tx, err := s.db.Begin()
if err != nil {
return err
}
defer func() {
tx.Rollback()
}()
removeNonHeadBundles, err := tx.Prepare(`
update operatorbundle set bundle = null, csv = null
where (bundlepath != null or bundlepath != "")
and name not in (
select operatorbundle.name from operatorbundle
join channel on channel.head_operatorbundle_name = operatorbundle.name
)
`)
if err != nil {
return err
}
defer removeNonHeadBundles.Close()
_, err = removeNonHeadBundles.Exec()
if err != nil {
return err
}
return tx.Commit()
}
func (s *sqlLoader) getBundleSkipsReplacesVersion(tx *sql.Tx, bundleName string) (replaces string, skips []string, version string, err error) {
getReplacesSkipsAndVersions, err := tx.Prepare(`
SELECT replaces, skips, version
FROM operatorbundle
WHERE operatorbundle.name=? LIMIT 1`)
if err != nil {
return
}
defer getReplacesSkipsAndVersions.Close()
rows, rerr := getReplacesSkipsAndVersions.Query(bundleName)
if err != nil {
err = rerr
return
}
defer rows.Close()
if !rows.Next() {
err = fmt.Errorf("no bundle found for bundlename %s", bundleName)
return
}
var replacesStringSQL sql.NullString
var skipsStringSQL sql.NullString
var versionStringSQL sql.NullString
if err = rows.Scan(&replacesStringSQL, &skipsStringSQL, &versionStringSQL); err != nil {
return
}
if replacesStringSQL.Valid {
replaces = replacesStringSQL.String
}
if skipsStringSQL.Valid && len(skipsStringSQL.String) > 0 {
skips = strings.Split(skipsStringSQL.String, ",")
}
if versionStringSQL.Valid {
version = versionStringSQL.String
}
return
}
func (s *sqlLoader) getBundlePathIfExists(tx *sql.Tx, bundleName string) (bundlePath string, err error) {
getBundlePath, err := tx.Prepare(`
SELECT bundlepath
FROM operatorbundle
WHERE operatorbundle.name=? LIMIT 1`)
if err != nil {
return
}
defer getBundlePath.Close()
rows, rerr := getBundlePath.Query(bundleName)
if err != nil {
err = rerr
return
}
defer rows.Close()
if !rows.Next() {
// no bundlepath set
return
}
var bundlePathSQL sql.NullString
if err = rows.Scan(&bundlePathSQL); err != nil {
return
}
if bundlePathSQL.Valid {
bundlePath = bundlePathSQL.String
}
return
}
func (s *sqlLoader) addAPIs(tx *sql.Tx, bundle *registry.Bundle) error {
if bundle.Name == "" {
return fmt.Errorf("cannot add apis for bundle with no name: %#v", bundle)
}
addAPI, err := tx.Prepare("insert or ignore into api(group_name, version, kind, plural) values(?, ?, ?, ?)")
if err != nil {
return err
}
defer addAPI.Close()
addAPIProvider, err := tx.Prepare("insert into api_provider(group_name, version, kind, operatorbundle_name, operatorbundle_version, operatorbundle_path) values(?, ?, ?, ?, ?, ?)")
if err != nil {
return err
}
defer addAPIProvider.Close()
addAPIRequirer, err := tx.Prepare("insert into api_requirer(group_name, version, kind, operatorbundle_name, operatorbundle_version, operatorbundle_path) values(?, ?, ?, ?, ?, ?)")
if err != nil {
return err
}
defer addAPIRequirer.Close()
providedApis, err := bundle.ProvidedAPIs()
if err != nil {
return err
}
requiredApis, err := bundle.RequiredAPIs()
if err != nil {
return err
}
bundleVersion, err := bundle.Version()
if err != nil {
return err
}
sqlString := func(s string) sql.NullString {
return sql.NullString{String: s, Valid: s != ""}
}
for api := range providedApis {
if _, err := addAPI.Exec(api.Group, api.Version, api.Kind, api.Plural); err != nil {
return err
}
if _, err := addAPIProvider.Exec(api.Group, api.Version, api.Kind, bundle.Name, sqlString(bundleVersion), sqlString(bundle.BundleImage)); err != nil {
return err
}
}
for api := range requiredApis {
if _, err := addAPI.Exec(api.Group, api.Version, api.Kind, api.Plural); err != nil {
return err
}
if _, err := addAPIRequirer.Exec(api.Group, api.Version, api.Kind, bundle.Name, sqlString(bundleVersion), sqlString(bundle.BundleImage)); err != nil {
return err
}
}
return nil
}
func (s *sqlLoader) getCSVNames(tx *sql.Tx, packageName string) ([]string, error) {
getID, err := tx.Prepare(`
SELECT DISTINCT channel_entry.operatorbundle_name
FROM channel_entry
WHERE channel_entry.package_name=?`)
if err != nil {
return nil, err
}
defer getID.Close()
rows, err := getID.Query(packageName)
if err != nil {
return nil, err
}
var csvName string
csvNames := []string{}
for rows.Next() {
err := rows.Scan(&csvName)
if err != nil {
if nerr := rows.Close(); nerr != nil {
return nil, nerr
}
return nil, err
}
csvNames = append(csvNames, csvName)
}
if err := rows.Close(); err != nil {
return nil, err
}
return csvNames, nil
}
func (s *sqlLoader) RemovePackage(packageName string) error {
if err := func() error {
tx, err := s.db.Begin()
if err != nil {
return err
}
defer func() {
tx.Rollback()
}()
csvNames, err := s.getCSVNames(tx, packageName)
if err != nil {
return err
}
if len(csvNames) == 0 {
return fmt.Errorf("no package found for packagename %s", packageName)
}
for _, csvName := range csvNames {
if err := s.rmBundle(tx, csvName); err != nil {
return err
}
}
deletePackage, err := tx.Prepare("DELETE FROM package WHERE package.name=?")
if err != nil {
return err
}
defer deletePackage.Close()
if _, err := deletePackage.Exec(packageName); err != nil {
return err
}
deleteChannel, err := tx.Prepare("DELETE FROM channel WHERE package_name = ?")
if err != nil {
return err
}
defer deleteChannel.Close()
if _, err := deleteChannel.Exec(packageName); err != nil {
return err
}
return tx.Commit()
}(); err != nil {
return err
}
// separate transaction so that we remove stranded bundles after the package has been cleared
return s.RemoveStrandedBundles()
}
func (s *sqlLoader) rmBundle(tx *sql.Tx, csvName string) error {
deleteBundle, err := tx.Prepare("DELETE FROM operatorbundle WHERE operatorbundle.name=?")
if err != nil {