forked from canonical/lxd
/
update.go
2962 lines (2709 loc) · 92.8 KB
/
update.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 cluster
import (
"context"
"database/sql"
"fmt"
"strconv"
"strings"
"time"
"github.com/lxc/lxd/lxd/db/query"
"github.com/lxc/lxd/lxd/db/schema"
"github.com/lxc/lxd/shared"
log "github.com/lxc/lxd/shared/log15"
"github.com/lxc/lxd/shared/logger"
"github.com/lxc/lxd/shared/osarch"
"github.com/pkg/errors"
)
// Schema for the cluster database.
func Schema() *schema.Schema {
schema := schema.NewFromMap(updates)
schema.Fresh(freshSchema)
return schema
}
// FreshSchema returns the fresh schema definition of the global database.
func FreshSchema() string {
return freshSchema
}
// SchemaDotGo refreshes the schema.go file in this package, using the updates
// defined here.
func SchemaDotGo() error {
return schema.DotGo(updates, "schema")
}
// SchemaVersion is the current version of the cluster database schema.
var SchemaVersion = len(updates)
var updates = map[int]schema.Update{
1: updateFromV0,
2: updateFromV1,
3: updateFromV2,
4: updateFromV3,
5: updateFromV4,
6: updateFromV5,
7: updateFromV6,
8: updateFromV7,
9: updateFromV8,
10: updateFromV9,
11: updateFromV10,
12: updateFromV11,
13: updateFromV12,
14: updateFromV13,
15: updateFromV14,
16: updateFromV15,
17: updateFromV16,
18: updateFromV17,
19: updateFromV18,
20: updateFromV19,
21: updateFromV20,
22: updateFromV21,
23: updateFromV22,
24: updateFromV23,
25: updateFromV24,
26: updateFromV25,
27: updateFromV26,
28: updateFromV27,
29: updateFromV28,
30: updateFromV29,
31: updateFromV30,
32: updateFromV31,
33: updateFromV32,
34: updateFromV33,
35: updateFromV34,
36: updateFromV35,
37: updateFromV36,
38: updateFromV37,
39: updateFromV38,
40: updateFromV39,
41: updateFromV40,
42: updateFromV41,
43: updateFromV42,
44: updateFromV43,
45: updateFromV44,
46: updateFromV45,
47: updateFromV46,
}
// updateFromV46 adds support for restricting certificates to projects
func updateFromV46(tx *sql.Tx) error {
_, err := tx.Exec(`
ALTER TABLE certificates ADD COLUMN restricted INTEGER NOT NULL DEFAULT 0;
CREATE TABLE certificates_projects (
certificate_id INTEGER NOT NULL,
project_id INTEGER NOT NULL,
FOREIGN KEY (certificate_id) REFERENCES certificates (id) ON DELETE CASCADE,
FOREIGN KEY (project_id) REFERENCES projects (id) ON DELETE CASCADE,
UNIQUE (certificate_id, project_id)
);
CREATE VIEW certificates_projects_ref (fingerprint, value) AS
SELECT certificates.fingerprint, projects.name FROM certificates_projects
JOIN certificates ON certificates.id=certificates_projects.certificate_id
JOIN projects ON projects.id=certificates_projects.project_id
ORDER BY projects.name;
`)
if err != nil {
return errors.Wrap(err, "Failed extending certificates to support project restrictions")
}
return nil
}
// updateFromV45 updates projects_used_by_ref to include ceph volumes
func updateFromV45(tx *sql.Tx) error {
_, err := tx.Exec(`
DROP VIEW projects_used_by_ref;
CREATE VIEW projects_used_by_ref (name,
value) AS
SELECT projects.name,
printf('/1.0/instances/%s?project=%s',
"instances".name,
projects.name)
FROM "instances" JOIN projects ON project_id=projects.id UNION
SELECT projects.name,
printf('/1.0/images/%s?project=%s',
images.fingerprint,
projects.name)
FROM images JOIN projects ON project_id=projects.id UNION
SELECT projects.name,
printf('/1.0/storage-pools/%s/volumes/custom/%s?project=%s&target=%s',
storage_pools.name,
storage_volumes.name,
projects.name,
nodes.name)
FROM storage_volumes JOIN storage_pools ON storage_pool_id=storage_pools.id JOIN nodes ON node_id=nodes.id JOIN projects ON project_id=projects.id WHERE storage_volumes.type=2 UNION
SELECT projects.name,
printf('/1.0/storage-pools/%s/volumes/custom/%s?project=%s',
storage_pools.name,
storage_volumes.name,
projects.name)
FROM storage_volumes JOIN storage_pools ON storage_pool_id=storage_pools.id JOIN projects ON project_id=projects.id WHERE storage_volumes.type=2 AND storage_volumes.node_id IS NULL UNION
SELECT projects.name,
printf('/1.0/profiles/%s?project=%s',
profiles.name,
projects.name)
FROM profiles JOIN projects ON project_id=projects.id UNION
SELECT projects.name,
printf('/1.0/networks/%s?project=%s',
networks.name,
projects.name)
FROM networks JOIN projects ON project_id=projects.id UNION
SELECT projects.name,
printf('/1.0/network-acls/%s?project=%s',
networks_acls.name,
projects.name)
FROM networks_acls JOIN projects ON project_id=projects.id;
`)
if err != nil {
return errors.Wrap(err, "Failed to update projects_used_by_ref")
}
return nil
}
// updateFromV44 adds networks_acls table, and adds a foreign key relationship between networks and projects.
// API extension: network_acl
func updateFromV44(tx *sql.Tx) error {
_, err := tx.Exec(`
DROP VIEW projects_used_by_ref;
CREATE TABLE networks_new (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
project_id INTEGER NOT NULL,
name TEXT NOT NULL,
description TEXT,
state INTEGER NOT NULL DEFAULT 0,
type INTEGER NOT NULL DEFAULT 0,
UNIQUE (project_id, name),
FOREIGN KEY (project_id) REFERENCES projects (id) ON DELETE CASCADE
);
INSERT INTO networks_new (id, project_id, name, description, state, type)
SELECT id, project_id, name, description, state, type FROM networks;
CREATE TABLE networks_nodes_new (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
network_id INTEGER NOT NULL,
node_id INTEGER NOT NULL,
state INTEGER NOT NULL DEFAULT 0,
UNIQUE (network_id, node_id),
FOREIGN KEY (network_id) REFERENCES networks_new (id) ON DELETE CASCADE,
FOREIGN KEY (node_id) REFERENCES nodes (id) ON DELETE CASCADE
);
INSERT INTO networks_nodes_new (id, network_id, node_id, state)
SELECT id, network_id, node_id, state FROM networks_nodes;
CREATE TABLE networks_config_new (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
network_id INTEGER NOT NULL,
node_id INTEGER,
key TEXT NOT NULL,
value TEXT,
UNIQUE (network_id, node_id, key),
FOREIGN KEY (network_id) REFERENCES networks_new (id) ON DELETE CASCADE,
FOREIGN KEY (node_id) REFERENCES nodes (id) ON DELETE CASCADE
);
INSERT INTO networks_config_new (id, network_id, node_id, key, value)
SELECT id, network_id, node_id, key, value FROM networks_config;
DROP TABLE networks;
DROP TABLE networks_nodes;
DROP TABLE networks_config;
CREATE UNIQUE INDEX networks_unique_network_id_node_id_key ON networks_config_new (network_id, IFNULL(node_id, -1), key);
ALTER TABLE networks_new RENAME TO networks;
ALTER TABLE networks_nodes_new RENAME TO networks_nodes;
ALTER TABLE networks_config_new RENAME TO networks_config;
CREATE TABLE networks_acls (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
project_id INTEGER NOT NULL,
name TEXT NOT NULL,
description TEXT NOT NULL,
ingress TEXT NOT NULL,
egress TEXT NOT NULL,
UNIQUE (project_id, name),
FOREIGN KEY (project_id) REFERENCES projects (id) ON DELETE CASCADE
);
CREATE TABLE networks_acls_config (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
network_acl_id INTEGER NOT NULL,
key TEXT NOT NULL,
value TEXT,
UNIQUE (network_acl_id, key),
FOREIGN KEY (network_acl_id) REFERENCES networks_acls (id) ON DELETE CASCADE
);
CREATE VIEW projects_used_by_ref (name,
value) AS
SELECT projects.name,
printf('/1.0/instances/%s?project=%s',
"instances".name,
projects.name)
FROM "instances" JOIN projects ON project_id=projects.id UNION
SELECT projects.name,
printf('/1.0/images/%s?project=%s',
images.fingerprint,
projects.name)
FROM images JOIN projects ON project_id=projects.id UNION
SELECT projects.name,
printf('/1.0/storage-pools/%s/volumes/custom/%s?project=%s&target=%s',
storage_pools.name,
storage_volumes.name,
projects.name,
nodes.name)
FROM storage_volumes JOIN storage_pools ON storage_pool_id=storage_pools.id JOIN nodes ON node_id=nodes.id JOIN projects ON project_id=projects.id WHERE storage_volumes.type=2 UNION
SELECT projects.name,
printf('/1.0/profiles/%s?project=%s',
profiles.name,
projects.name)
FROM profiles JOIN projects ON project_id=projects.id UNION
SELECT projects.name,
printf('/1.0/networks/%s?project=%s',
networks.name,
projects.name)
FROM networks JOIN projects ON project_id=projects.id UNION
SELECT projects.name,
printf('/1.0/network-acls/%s?project=%s',
networks_acls.name,
projects.name)
FROM networks_acls JOIN projects ON project_id=projects.id;
`)
if err != nil {
return errors.Wrap(err, "Failed to add networks_acls and networks_acls_config tables, and update projects_used_by_ref view")
}
return nil
}
// updateFromV43 adds a unique index to the storage_pools_config and networks_config tables.
func updateFromV43(tx *sql.Tx) error {
_, err := tx.Exec(`CREATE UNIQUE INDEX storage_pools_unique_storage_pool_id_node_id_key ON storage_pools_config (storage_pool_id, IFNULL(node_id, -1), key);
CREATE UNIQUE INDEX networks_unique_network_id_node_id_key ON networks_config (network_id, IFNULL(node_id, -1), key);
`)
if err != nil {
return errors.Wrapf(err, "Failed adding unique index to storage_pools_config and networks_config tables")
}
return nil
}
// updateFromV42 removes any duplicated storage pool config rows that have the same value.
// This can occur when multiple create requests have been issued when setting up a clustered storage pool.
func updateFromV42(tx *sql.Tx) error {
// Find all duplicated config rows and return comma delimited list of affected row IDs for each dupe set.
stmt, err := tx.Prepare(`SELECT storage_pool_id, IFNULL(node_id, -1), key, value, COUNT(*) AS rowCount, GROUP_CONCAT(id, ",") AS dupeRowIDs
FROM storage_pools_config
GROUP BY storage_pool_id, node_id, key, value
HAVING rowCount > 1
`)
if err != nil {
return errors.Wrapf(err, "Failed preparing query")
}
defer stmt.Close()
rows, err := stmt.Query()
if err != nil {
return errors.Wrapf(err, "Failed running query")
}
defer rows.Close()
type dupeRow struct {
storagePoolID int64
nodeID int64
key string
value string
rowCount int64
dupeRowIDs string
}
var dupeRows []dupeRow
for rows.Next() {
r := dupeRow{}
err = rows.Scan(&r.storagePoolID, &r.nodeID, &r.key, &r.value, &r.rowCount, &r.dupeRowIDs)
if err != nil {
return errors.Wrapf(err, "Failed scanning rows")
}
dupeRows = append(dupeRows, r)
}
err = rows.Err()
if err != nil {
return errors.Wrap(err, "Got a row error")
}
for _, r := range dupeRows {
logger.Warn("Found duplicated storage pool config rows", log.Ctx{"storagePoolID": r.storagePoolID, "nodeID": r.nodeID, "key": r.key, "value": r.value, "rowCount": r.rowCount, "dupeRowIDs": r.dupeRowIDs})
rowIDs := strings.Split(r.dupeRowIDs, ",")
// Iterate and delete all but 1 of the rowIDs so we leave just one left.
for i := 0; i < len(rowIDs)-1; i++ {
rowID, err := strconv.Atoi(rowIDs[i])
if err != nil {
return errors.Wrapf(err, "Failed converting row ID")
}
_, err = tx.Exec("DELETE FROM storage_pools_config WHERE id = ?", rowID)
if err != nil {
return errors.Wrapf(err, "Failed deleting storage pool config row with ID %d", rowID)
}
logger.Warn("Deleted duplicated storage pool config row", log.Ctx{"storagePoolID": r.storagePoolID, "nodeID": r.nodeID, "key": r.key, "value": r.value, "rowCount": r.rowCount, "rowID": rowID})
}
}
return nil
}
// updateFromV41 removes any duplicated network config rows that have the same value.
// This can occur when multiple create requests have been issued when setting up a clustered network.
func updateFromV41(tx *sql.Tx) error {
// Find all duplicated config rows and return comma delimited list of affected row IDs for each dupe set.
stmt, err := tx.Prepare(`SELECT network_id, IFNULL(node_id, -1), key, value, COUNT(*) AS rowCount, GROUP_CONCAT(id, ",") AS dupeRowIDs
FROM networks_config
GROUP BY network_id, node_id, key, value
HAVING rowCount > 1
`)
if err != nil {
return errors.Wrapf(err, "Failed preparing query")
}
defer stmt.Close()
rows, err := stmt.Query()
if err != nil {
return errors.Wrapf(err, "Failed running query")
}
defer rows.Close()
type dupeRow struct {
networkID int64
nodeID int64
key string
value string
rowCount int64
dupeRowIDs string
}
var dupeRows []dupeRow
for rows.Next() {
r := dupeRow{}
err = rows.Scan(&r.networkID, &r.nodeID, &r.key, &r.value, &r.rowCount, &r.dupeRowIDs)
if err != nil {
return errors.Wrapf(err, "Failed scanning rows")
}
dupeRows = append(dupeRows, r)
}
err = rows.Err()
if err != nil {
return errors.Wrap(err, "Got a row error")
}
for _, r := range dupeRows {
logger.Warn("Found duplicated network config rows", log.Ctx{"networkID": r.networkID, "nodeID": r.nodeID, "key": r.key, "value": r.value, "rowCount": r.rowCount, "dupeRowIDs": r.dupeRowIDs})
rowIDs := strings.Split(r.dupeRowIDs, ",")
// Iterate and delete all but 1 of the rowIDs so we leave just one left.
for i := 0; i < len(rowIDs)-1; i++ {
rowID, err := strconv.Atoi(rowIDs[i])
if err != nil {
return errors.Wrapf(err, "Failed converting row ID")
}
_, err = tx.Exec("DELETE FROM networks_config WHERE id = ?", rowID)
if err != nil {
return errors.Wrapf(err, "Failed deleting network config row with ID %d", rowID)
}
logger.Warn("Deleted duplicated network config row", log.Ctx{"networkID": r.networkID, "nodeID": r.nodeID, "key": r.key, "value": r.value, "rowCount": r.rowCount, "rowID": rowID})
}
}
return nil
}
// Add state column to storage_pools_nodes tables. Set existing row's state to 1 ("created").
func updateFromV40(tx *sql.Tx) error {
stmt := `
ALTER TABLE storage_pools_nodes ADD COLUMN state INTEGER NOT NULL DEFAULT 0;
UPDATE storage_pools_nodes SET state = 1;
`
_, err := tx.Exec(stmt)
return err
}
// Add state column to networks_nodes tables. Set existing row's state to 1 ("created").
func updateFromV39(tx *sql.Tx) error {
stmt := `
ALTER TABLE networks_nodes ADD COLUMN state INTEGER NOT NULL DEFAULT 0;
UPDATE networks_nodes SET state = 1;
`
_, err := tx.Exec(stmt)
return err
}
// Add storage_volumes_backups table.
func updateFromV38(tx *sql.Tx) error {
stmt := `
CREATE TABLE storage_volumes_backups (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
storage_volume_id INTEGER NOT NULL,
name VARCHAR(255) NOT NULL,
creation_date DATETIME,
expiry_date DATETIME,
volume_only INTEGER NOT NULL default 0,
optimized_storage INTEGER NOT NULL default 0,
FOREIGN KEY (storage_volume_id) REFERENCES "storage_volumes" (id) ON DELETE CASCADE,
UNIQUE (storage_volume_id, name)
);
`
_, err := tx.Exec(stmt)
if err != nil {
return err
}
return nil
}
// Attempt to add missing project features.networks feature to default project.
func updateFromV37(tx *sql.Tx) error {
ids, err := query.SelectIntegers(tx, `SELECT id FROM projects WHERE name = "default" LIMIT 1`)
if err != nil {
return err
}
if len(ids) == 1 {
tx.Exec("INSERT INTO projects_config (project_id, key, value) VALUES (?, 'features.networks', 'true');", ids[0])
}
return nil
}
// Add networks to projects references.
func updateFromV36(tx *sql.Tx) error {
stmts := `
DROP VIEW projects_used_by_ref;
CREATE VIEW projects_used_by_ref (name,
value) AS
SELECT projects.name,
printf('/1.0/instances/%s?project=%s',
"instances".name,
projects.name)
FROM "instances" JOIN projects ON project_id=projects.id UNION
SELECT projects.name,
printf('/1.0/images/%s?project=%s',
images.fingerprint,
projects.name)
FROM images JOIN projects ON project_id=projects.id UNION
SELECT projects.name,
printf('/1.0/storage-pools/%s/volumes/custom/%s?project=%s&target=%s',
storage_pools.name,
storage_volumes.name,
projects.name,
nodes.name)
FROM storage_volumes JOIN storage_pools ON storage_pool_id=storage_pools.id JOIN nodes ON node_id=nodes.id JOIN projects ON project_id=projects.id WHERE storage_volumes.type=2 UNION
SELECT projects.name,
printf('/1.0/profiles/%s?project=%s',
profiles.name,
projects.name)
FROM profiles JOIN projects ON project_id=projects.id UNION
SELECT projects.name,
printf('/1.0/networks/%s?project=%s',
networks.name,
projects.name)
FROM networks JOIN projects ON project_id=projects.id;
`
_, err := tx.Exec(stmts)
return err
}
// This fixes node IDs of storage volumes on non-remote pools which were
// wrongly set to NULL.
func updateFromV35(tx *sql.Tx) error {
stmts := `
WITH storage_volumes_tmp (id, node_id)
AS (
SELECT storage_volumes.id, storage_pools_nodes.node_id
FROM storage_volumes
JOIN storage_pools_nodes ON storage_pools_nodes.storage_pool_id=storage_volumes.storage_pool_id
JOIN storage_pools ON storage_pools.id=storage_volumes.storage_pool_id
WHERE storage_pools.driver NOT IN ("ceph", "cephfs"))
UPDATE storage_volumes
SET node_id=(
SELECT storage_volumes_tmp.node_id
FROM storage_volumes_tmp
WHERE storage_volumes.id=storage_volumes_tmp.id)
WHERE id IN (SELECT id FROM storage_volumes_tmp) AND node_id IS NULL
`
_, err := tx.Exec(stmts)
if err != nil {
return err
}
return nil
}
// Remove multiple entries of the same volume when using remote storage.
// Also, allow node ID to be null for the instances and storage_volumes tables, and set it to null
// for instances and storage volumes using remote storage.
func updateFromV34(tx *sql.Tx) error {
stmts := `
SELECT storage_volumes.id, storage_volumes.name
FROM storage_volumes
JOIN storage_pools ON storage_pools.id=storage_volumes.storage_pool_id
WHERE storage_pools.driver IN ("ceph", "cephfs")
ORDER BY storage_volumes.name
`
// Get the total number of storage volume rows.
count, err := query.Count(tx, "storage_volumes JOIN storage_pools ON storage_pools.id=storage_volumes.storage_pool_id",
`storage_pools.driver IN ("ceph", "cephfs")`)
if err != nil {
return errors.Wrap(err, "Failed to get storage volumes count")
}
volumes := make([]struct {
ID int
Name string
}, count)
dest := func(i int) []interface{} {
return []interface{}{
&volumes[i].ID,
&volumes[i].Name,
}
}
stmt, err := tx.Prepare(stmts)
if err != nil {
return errors.Wrap(err, "Failed to prepary storage volume query")
}
err = query.SelectObjects(stmt, dest)
if err != nil {
return errors.Wrap(err, "Failed to fetch storage volumes with remote storage")
}
// Remove multiple entries of the same volume when using remote storage
for i := 1; i < count; i++ {
if volumes[i-1].Name == volumes[i].Name {
_, err = tx.Exec(`DELETE FROM storage_volumes WHERE id=?`, volumes[i-1].ID)
if err != nil {
return errors.Wrap(err, "Failed to delete row from storage_volumes")
}
}
}
stmts = `
CREATE TABLE storage_volumes_new (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
name TEXT NOT NULL,
storage_pool_id INTEGER NOT NULL,
node_id INTEGER,
type INTEGER NOT NULL,
description TEXT,
project_id INTEGER NOT NULL,
content_type INTEGER NOT NULL DEFAULT 0,
UNIQUE (storage_pool_id, node_id, project_id, name, type),
FOREIGN KEY (storage_pool_id) REFERENCES storage_pools (id) ON DELETE CASCADE,
FOREIGN KEY (node_id) REFERENCES nodes (id) ON DELETE CASCADE,
FOREIGN KEY (project_id) REFERENCES projects (id) ON DELETE CASCADE
);`
// Create new tables where node ID can be null.
_, err = tx.Exec(stmts)
if err != nil {
return err
}
// Copy rows from storage_volumes to storage_volumes_new
count, err = query.Count(tx, "storage_volumes", "")
if err != nil {
return errors.Wrap(err, "Failed to get storage_volumes count")
}
storageVolumes := make([]struct {
ID int
Name string
StoragePoolID int
NodeID string
Type int
Description string
ProjectID int
ContentType int
}, count)
dest = func(i int) []interface{} {
return []interface{}{
&storageVolumes[i].ID,
&storageVolumes[i].Name,
&storageVolumes[i].StoragePoolID,
&storageVolumes[i].NodeID,
&storageVolumes[i].Type,
&storageVolumes[i].Description,
&storageVolumes[i].ProjectID,
&storageVolumes[i].ContentType,
}
}
stmt, err = tx.Prepare(`
SELECT id, name, storage_pool_id, node_id, type, coalesce(description, ''), project_id, content_type
FROM storage_volumes`)
if err != nil {
return errors.Wrap(err, "Failed to prepare storage volumes query")
}
err = query.SelectObjects(stmt, dest)
if err != nil {
return errors.Wrap(err, "Failed to fetch storage volumes")
}
for _, storageVolume := range storageVolumes {
_, err = tx.Exec(`
INSERT INTO storage_volumes_new (id, name, storage_pool_id, node_id, type, description, project_id, content_type)
VALUES (?, ?, ?, ?, ?, ?, ?, ?);`,
storageVolume.ID, storageVolume.Name, storageVolume.StoragePoolID, storageVolume.NodeID,
storageVolume.Type, storageVolume.Description, storageVolume.ProjectID, storageVolume.ContentType)
if err != nil {
return err
}
}
// Store rows of storage_volumes_config as we need to re-add them at the end.
count, err = query.Count(tx, "storage_volumes_config", "")
if err != nil {
return errors.Wrap(err, "Failed to get storage_volumes_config count")
}
storageVolumeConfigs := make([]struct {
ID int
StorageVolumeID int
Key string
Value string
}, count)
dest = func(i int) []interface{} {
return []interface{}{
&storageVolumeConfigs[i].ID,
&storageVolumeConfigs[i].StorageVolumeID,
&storageVolumeConfigs[i].Key,
&storageVolumeConfigs[i].Value,
}
}
stmt, err = tx.Prepare(`SELECT * FROM storage_volumes_config;`)
if err != nil {
return errors.Wrap(err, "Failed to prepare storage volumes query")
}
err = query.SelectObjects(stmt, dest)
if err != nil {
return errors.Wrap(err, "Failed to fetch storage volume configs")
}
// Store rows of storage_volumes_snapshots as we need to re-add them at the end.
count, err = query.Count(tx, "storage_volumes_snapshots", "")
if err != nil {
return errors.Wrap(err, "Failed to get storage_volumes_snapshots count")
}
storageVolumeSnapshots := make([]struct {
ID int
StorageVolumeID int
Name string
Description string
ExpiryDate time.Time
}, count)
dest = func(i int) []interface{} {
return []interface{}{
&storageVolumeSnapshots[i].ID,
&storageVolumeSnapshots[i].StorageVolumeID,
&storageVolumeSnapshots[i].Name,
&storageVolumeSnapshots[i].Description,
&storageVolumeSnapshots[i].ExpiryDate,
}
}
stmt, err = tx.Prepare(`SELECT * FROM storage_volumes_snapshots;`)
if err != nil {
return errors.Wrap(err, "Failed to prepare storage volume snapshots query")
}
err = query.SelectObjects(stmt, dest)
if err != nil {
return errors.Wrap(err, "Failed to fetch storage volume snapshots")
}
// Store rows of storage_volumes_snapshots_config as we need to re-add them at the end.
count, err = query.Count(tx, "storage_volumes_snapshots_config", "")
if err != nil {
return errors.Wrap(err, "Failed to get storage_volumes_snapshots_config count")
}
storageVolumeSnapshotConfigs := make([]struct {
ID int
StorageVolumeSnapshotID int
Key string
Value string
}, count)
dest = func(i int) []interface{} {
return []interface{}{
&storageVolumeSnapshotConfigs[i].ID,
&storageVolumeSnapshotConfigs[i].StorageVolumeSnapshotID,
&storageVolumeSnapshotConfigs[i].Key,
&storageVolumeSnapshotConfigs[i].Value,
}
}
stmt, err = tx.Prepare(`SELECT * FROM storage_volumes_snapshots_config;`)
if err != nil {
return errors.Wrap(err, "Failed to prepare storage volume snapshots query")
}
err = query.SelectObjects(stmt, dest)
if err != nil {
return errors.Wrap(err, "Failed to fetch storage volume snapshot configs")
}
_, err = tx.Exec(`
PRAGMA foreign_keys = OFF;
PRAGMA legacy_alter_table = ON;
DROP TABLE storage_volumes;
ALTER TABLE storage_volumes_new RENAME TO storage_volumes;
UPDATE storage_volumes
SET node_id=null
WHERE storage_volumes.id IN (
SELECT storage_volumes.id FROM storage_volumes
JOIN storage_pools ON storage_volumes.storage_pool_id=storage_pools.id
WHERE storage_pools.driver IN ("ceph", "cephfs")
);
PRAGMA foreign_keys = ON;
PRAGMA legacy_alter_table = OFF;
CREATE TRIGGER storage_volumes_check_id
BEFORE INSERT ON storage_volumes
WHEN NEW.id IN (SELECT id FROM storage_volumes_snapshots)
BEGIN
SELECT RAISE(FAIL, "invalid ID");
END;
`)
if err != nil {
return err
}
// When we dropped the storage_volumes table earlier, all config entries
// were removed as well. Let's re-add them.
for _, storageVolumeConfig := range storageVolumeConfigs {
_, err = tx.Exec(`INSERT INTO storage_volumes_config (id, storage_volume_id, key, value) VALUES (?, ?, ?, ?);`, storageVolumeConfig.ID, storageVolumeConfig.StorageVolumeID, storageVolumeConfig.Key, storageVolumeConfig.Value)
if err != nil {
return err
}
}
// When we dropped the storage_volumes table earlier, all snapshot entries
// were removed as well. Let's re-add them.
for _, storageVolumeSnapshot := range storageVolumeSnapshots {
_, err = tx.Exec(`INSERT INTO storage_volumes_snapshots (id, storage_volume_id, name, description, expiry_date) VALUES (?, ?, ?, ?, ?);`, storageVolumeSnapshot.ID, storageVolumeSnapshot.StorageVolumeID, storageVolumeSnapshot.Name, storageVolumeSnapshot.Description, storageVolumeSnapshot.ExpiryDate)
if err != nil {
return err
}
}
// When we dropped the storage_volumes table earlier, all snapshot config entries
// were removed as well. Let's re-add them.
for _, storageVolumeSnapshotConfig := range storageVolumeSnapshotConfigs {
_, err = tx.Exec(`INSERT INTO storage_volumes_snapshots_config (id, storage_volume_snapshot_id, key, value) VALUES (?, ?, ?, ?);`, storageVolumeSnapshotConfig.ID, storageVolumeSnapshotConfig.StorageVolumeSnapshotID, storageVolumeSnapshotConfig.Key, storageVolumeSnapshotConfig.Value)
if err != nil {
return err
}
}
count, err = query.Count(tx, "storage_volumes_all", "")
if err != nil {
return errors.Wrap(err, "Failed to get storage_volumes count")
}
if count > 0 {
var maxID int64
row := tx.QueryRow("SELECT MAX(id) FROM storage_volumes_all LIMIT 1")
err = row.Scan(&maxID)
if err != nil {
return err
}
// Set sqlite_sequence to max(id)
_, err = tx.Exec("UPDATE sqlite_sequence SET seq = ? WHERE name = 'storage_volumes'", maxID)
if err != nil {
return errors.Wrap(err, "Increment storage volumes sequence")
}
}
return nil
}
// Add project_id field to networks, add unique index across project_id and name,
// and set existing networks to project_id 1.
// This is made a lot more complex because it requires re-creating the referenced tables as there is no way to
// disable foreign keys temporarily within a transaction.
func updateFromV33(tx *sql.Tx) error {
_, err := tx.Exec(`
CREATE TABLE networks_new (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
project_id INTEGER NOT NULL,
name TEXT NOT NULL,
description TEXT,
state INTEGER NOT NULL DEFAULT 0,
type INTEGER NOT NULL DEFAULT 0,
UNIQUE (project_id, name)
);
INSERT INTO networks_new (id, project_id, name, description, state, type)
SELECT id, 1, name, description, state, type FROM networks;
CREATE TABLE networks_nodes_new (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
network_id INTEGER NOT NULL,
node_id INTEGER NOT NULL,
UNIQUE (network_id, node_id),
FOREIGN KEY (network_id) REFERENCES networks_new (id) ON DELETE CASCADE,
FOREIGN KEY (node_id) REFERENCES nodes (id) ON DELETE CASCADE
);
INSERT INTO networks_nodes_new (id, network_id, node_id)
SELECT id, network_id, node_id FROM networks_nodes;
CREATE TABLE networks_config_new (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
network_id INTEGER NOT NULL,
node_id INTEGER,
key TEXT NOT NULL,
value TEXT,
UNIQUE (network_id, node_id, key),
FOREIGN KEY (network_id) REFERENCES networks_new (id) ON DELETE CASCADE,
FOREIGN KEY (node_id) REFERENCES nodes (id) ON DELETE CASCADE
);
INSERT INTO networks_config_new (id, network_id, node_id, key, value)
SELECT id, network_id, node_id, key, value FROM networks_config;
DROP TABLE networks;
DROP TABLE networks_nodes;
DROP TABLE networks_config;
ALTER TABLE networks_new RENAME TO networks;
ALTER TABLE networks_nodes_new RENAME TO networks_nodes;
ALTER TABLE networks_config_new RENAME TO networks_config;
`)
if err != nil {
return errors.Wrap(err, "Failed to add project_id column to networks table")
}
return nil
}
// Add type field to networks.
func updateFromV32(tx *sql.Tx) error {
_, err := tx.Exec("ALTER TABLE networks ADD COLUMN type INTEGER NOT NULL DEFAULT 0;")
if err != nil {
return errors.Wrap(err, "Failed to add type column to networks table")
}
return nil
}
// Add failure_domain column to nodes table.
func updateFromV31(tx *sql.Tx) error {
stmts := `
CREATE TABLE nodes_failure_domains (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
name TEXT NOT NULL,
UNIQUE (name)
);
ALTER TABLE nodes
ADD COLUMN failure_domain_id INTEGER DEFAULT NULL REFERENCES nodes_failure_domains (id) ON DELETE SET NULL;
`
_, err := tx.Exec(stmts)
if err != nil {
return err
}
return nil
}
// Add content type field to storage volumes
func updateFromV30(tx *sql.Tx) error {
stmts := `ALTER TABLE storage_volumes ADD COLUMN content_type INTEGER NOT NULL DEFAULT 0;
UPDATE storage_volumes SET content_type = 1 WHERE type = 3;
UPDATE storage_volumes SET content_type = 1 WHERE storage_volumes.id IN (
SELECT storage_volumes.id
FROM storage_volumes
JOIN images ON storage_volumes.name = images.fingerprint
WHERE images.type = 1
);
DROP VIEW storage_volumes_all;
CREATE VIEW storage_volumes_all (
id,
name,
storage_pool_id,
node_id,
type,
description,
project_id,
content_type) AS
SELECT id,
name,
storage_pool_id,
node_id,
type,
description,
project_id,
content_type
FROM storage_volumes UNION
SELECT storage_volumes_snapshots.id,
printf('%s/%s', storage_volumes.name, storage_volumes_snapshots.name),
storage_volumes.storage_pool_id,
storage_volumes.node_id,
storage_volumes.type,
storage_volumes_snapshots.description,
storage_volumes.project_id,
storage_volumes.content_type
FROM storage_volumes
JOIN storage_volumes_snapshots ON storage_volumes.id = storage_volumes_snapshots.storage_volume_id;
`
_, err := tx.Exec(stmts)
if err != nil {
return errors.Wrap(err, "Failed to add storage volume content type")
}
return nil
}
// Add storage volumes to projects references and fix images.
func updateFromV29(tx *sql.Tx) error {
stmts := `