/
update.go
1976 lines (1839 loc) · 61.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"
"strings"
"time"
"github.com/lxc/lxd/lxd/db/query"
"github.com/lxc/lxd/lxd/db/schema"
"github.com/lxc/lxd/shared"
"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,
}
// Create new storage snapshot tables and migrate data to them.
func updateFromV25(tx *sql.Tx) error {
// Get the total number of snapshot rows in the storage_volumes table.
count, err := query.Count(tx, "storage_volumes", "snapshot=1")
if err != nil {
return errors.Wrap(err, "Failed to volume snapshot count")
}
// Fetch all snapshot rows in the storage_volumes table.
snapshots := make([]struct {
ID int
Name string
StoragePoolID int
NodeID int
Type int
Description string
ProjectID int
Config map[string]string
}, count)
dest := func(i int) []interface{} {
return []interface{}{
&snapshots[i].ID,
&snapshots[i].Name,
&snapshots[i].StoragePoolID,
&snapshots[i].NodeID,
&snapshots[i].Type,
&snapshots[i].Description,
&snapshots[i].ProjectID,
}
}
stmt, err := tx.Prepare(`
SELECT id, name, storage_pool_id, node_id, type, coalesce(description, ''), project_id
FROM storage_volumes
WHERE snapshot=1
`)
if err != nil {
return errors.Wrap(err, "Failed to prepare volume snapshot query")
}
err = query.SelectObjects(stmt, dest)
if err != nil {
return errors.Wrap(err, "Failed to fetch instances")
}
for i, snapshot := range snapshots {
config, err := query.SelectConfig(tx,
"storage_volumes_config", "storage_volume_id=?",
snapshot.ID)
if err != nil {
return errors.Wrap(err, "Failed to fetch volume snapshot config")
}
snapshots[i].Config = config
}
stmts := `
ALTER TABLE storage_volumes RENAME TO old_storage_volumes;
CREATE TABLE "storage_volumes" (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
name TEXT NOT NULL,
storage_pool_id INTEGER NOT NULL,
node_id INTEGER NOT NULL,
type INTEGER NOT NULL,
description TEXT,
project_id INTEGER NOT NULL,
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
);
ALTER TABLE storage_volumes_config RENAME TO old_storage_volumes_config;
CREATE TABLE storage_volumes_config (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
storage_volume_id INTEGER NOT NULL,
key TEXT NOT NULL,
value TEXT,
UNIQUE (storage_volume_id, key),
FOREIGN KEY (storage_volume_id) REFERENCES storage_volumes (id) ON DELETE CASCADE
);
INSERT INTO storage_volumes(id, name, storage_pool_id, node_id, type, description, project_id)
SELECT id, name, storage_pool_id, node_id, type, description, project_id FROM old_storage_volumes
WHERE snapshot=0;
INSERT INTO storage_volumes_config
SELECT * FROM old_storage_volumes_config
WHERE storage_volume_id IN (SELECT id FROM storage_volumes);
DROP TABLE old_storage_volumes;
DROP TABLE old_storage_volumes_config;
CREATE TABLE storage_volumes_snapshots (
id INTEGER NOT NULL,
storage_volume_id INTEGER NOT NULL,
name TEXT NOT NULL,
description TEXT,
UNIQUE (id),
UNIQUE (storage_volume_id, name),
FOREIGN KEY (storage_volume_id) REFERENCES storage_volumes (id) ON DELETE CASCADE
);
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;
CREATE TRIGGER storage_volumes_snapshots_check_id
BEFORE INSERT ON storage_volumes_snapshots
WHEN NEW.id IN (SELECT id FROM storage_volumes)
BEGIN
SELECT RAISE(FAIL, "invalid ID");
END;
CREATE TABLE storage_volumes_snapshots_config (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
storage_volume_snapshot_id INTEGER NOT NULL,
key TEXT NOT NULL,
value TEXT,
FOREIGN KEY (storage_volume_snapshot_id) REFERENCES storage_volumes_snapshots (id) ON DELETE CASCADE,
UNIQUE (storage_volume_snapshot_id, key)
);
CREATE VIEW storage_volumes_all (
id,
name,
storage_pool_id,
node_id,
type,
description,
project_id) AS
SELECT id,
name,
storage_pool_id,
node_id,
type,
description,
project_id
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
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 create storage snapshots tables")
}
// Migrate snapshots to the new tables.
for _, snapshot := range snapshots {
parts := strings.Split(snapshot.Name, shared.SnapshotDelimiter)
if len(parts) != 2 {
logger.Errorf("Invalid volume snapshot name: %s", snapshot.Name)
continue
}
volume := parts[0]
name := parts[1]
ids, err := query.SelectIntegers(tx, "SELECT id FROM storage_volumes WHERE name=?", volume)
if err != nil {
return err
}
if len(ids) != 1 {
logger.Errorf("Volume snapshot %s has no parent", snapshot.Name)
continue
}
volumeID := ids[0]
_, err = tx.Exec(`
INSERT INTO storage_volumes_snapshots(id, storage_volume_id, name, description) VALUES(?, ?, ?, ?)
`, snapshot.ID, volumeID, name, snapshot.Description)
if err != nil {
return err
}
for key, value := range snapshot.Config {
_, err = tx.Exec(`
INSERT INTO storage_volumes_snapshots_config(storage_volume_snapshot_id, key, value) VALUES(?, ?, ?)
`, snapshot.ID, key, value)
if err != nil {
return err
}
}
}
return nil
}
// The ceph.user.name config key is required for Ceph to function.
func updateFromV24(tx *sql.Tx) error {
// Fetch the IDs of all existing Ceph pools.
poolIDs, err := query.SelectIntegers(tx, `SELECT id FROM storage_pools WHERE driver='ceph'`)
if err != nil {
return errors.Wrap(err, "Failed to get IDs of current ceph pools")
}
for _, poolID := range poolIDs {
// Fetch the config for this Ceph pool.
config, err := query.SelectConfig(tx, "storage_pools_config", "storage_pool_id=?", poolID)
if err != nil {
return errors.Wrap(err, "Failed to fetch of ceph pool config")
}
// Check if already set.
_, ok := config["ceph.user.name"]
if ok {
continue
}
// Add ceph.user.name config entry.
_, err = tx.Exec("INSERT INTO storage_pools_config (storage_pool_id, key, value) VALUES (?, 'ceph.user.name', 'admin')", poolID)
if err != nil {
return errors.Wrap(err, "Failed to create ceph.user.name config")
}
}
return nil
}
// The lvm.vg_name config key is required for LVM to function.
func updateFromV23(tx *sql.Tx) error {
// Fetch the IDs of all existing nodes.
nodeIDs, err := query.SelectIntegers(tx, "SELECT id FROM nodes")
if err != nil {
return errors.Wrap(err, "Failed to get IDs of current nodes")
}
// Fetch the IDs of all existing lvm pools.
poolIDs, err := query.SelectIntegers(tx, `SELECT id FROM storage_pools WHERE driver='lvm'`)
if err != nil {
return errors.Wrap(err, "Failed to get IDs of current lvm pools")
}
for _, poolID := range poolIDs {
for _, nodeID := range nodeIDs {
// Fetch the config for this lvm pool.
config, err := query.SelectConfig(tx, "storage_pools_config", "storage_pool_id=? AND node_id=?", poolID, nodeID)
if err != nil {
return errors.Wrap(err, "Failed to fetch of lvm pool config")
}
// Check if already set.
_, ok := config["lvm.vg_name"]
if ok {
continue
}
// Add lvm.vg_name config entry.
_, err = tx.Exec(`
INSERT INTO storage_pools_config(storage_pool_id, node_id, key, value)
SELECT ?, ?, 'lvm.vg_name', name FROM storage_pools WHERE id=?
`, poolID, nodeID, poolID)
if err != nil {
return errors.Wrap(err, "Failed to create lvm.vg_name node config")
}
}
}
return nil
}
// The zfs.pool_name config key is required for ZFS to function.
func updateFromV22(tx *sql.Tx) error {
// Fetch the IDs of all existing nodes.
nodeIDs, err := query.SelectIntegers(tx, "SELECT id FROM nodes")
if err != nil {
return errors.Wrap(err, "Failed to get IDs of current nodes")
}
// Fetch the IDs of all existing zfs pools.
poolIDs, err := query.SelectIntegers(tx, `SELECT id FROM storage_pools WHERE driver='zfs'`)
if err != nil {
return errors.Wrap(err, "Failed to get IDs of current zfs pools")
}
for _, poolID := range poolIDs {
for _, nodeID := range nodeIDs {
// Fetch the config for this zfs pool.
config, err := query.SelectConfig(tx, "storage_pools_config", "storage_pool_id=? AND node_id=?", poolID, nodeID)
if err != nil {
return errors.Wrap(err, "Failed to fetch of zfs pool config")
}
// Check if already set.
_, ok := config["zfs.pool_name"]
if ok {
continue
}
// Add zfs.pool_name config entry
_, err = tx.Exec(`
INSERT INTO storage_pools_config(storage_pool_id, node_id, key, value)
SELECT ?, ?, 'zfs.pool_name', name FROM storage_pools WHERE id=?
`, poolID, nodeID, poolID)
if err != nil {
return errors.Wrap(err, "Failed to create zfs.pool_name node config")
}
}
}
return nil
}
// Fix "images_profiles" table (missing UNIQUE)
func updateFromV21(tx *sql.Tx) error {
stmts := `
ALTER TABLE images_profiles RENAME TO old_images_profiles;
CREATE TABLE images_profiles (
image_id INTEGER NOT NULL,
profile_id INTEGER NOT NULL,
FOREIGN KEY (image_id) REFERENCES images (id) ON DELETE CASCADE,
FOREIGN KEY (profile_id) REFERENCES profiles (id) ON DELETE CASCADE,
UNIQUE (image_id, profile_id)
);
INSERT INTO images_profiles SELECT * FROM old_images_profiles;
DROP TABLE old_images_profiles;
`
_, err := tx.Exec(stmts)
return err
}
// Add "images_profiles" table
func updateFromV20(tx *sql.Tx) error {
stmts := `
CREATE TABLE images_profiles (
image_id INTEGER NOT NULL,
profile_id INTEGER NOT NULL,
FOREIGN KEY (image_id) REFERENCES images (id) ON DELETE CASCADE,
FOREIGN KEY (profile_id) REFERENCES profiles (id) ON DELETE CASCADE,
UNIQUE (image_id, profile_id)
);
INSERT INTO images_profiles (image_id, profile_id)
SELECT images.id, profiles.id FROM images
JOIN profiles ON images.project_id = profiles.project_id
WHERE profiles.name = 'default';
INSERT INTO images_profiles (image_id, profile_id)
SELECT images.id, profiles.id FROM projects_config AS R
JOIN projects_config AS S ON R.project_id = S.project_id
JOIN images ON images.project_id = R.project_id
JOIN profiles ON profiles.project_id = 1 AND profiles.name = "default"
WHERE R.key = "features.images" AND S.key = "features.profiles" AND R.value = "true" AND S.value != "true";
INSERT INTO images_profiles (image_id, profile_id)
SELECT images.id, profiles.id FROM projects_config AS R
JOIN projects_config AS S ON R.project_id = S.project_id
JOIN profiles ON profiles.project_id = R.project_id
JOIN images ON images.project_id = 1
WHERE R.key = "features.images" AND S.key = "features.profiles" AND R.value != "true" AND S.value = "true"
AND profiles.name = "default";
`
_, err := tx.Exec(stmts)
return err
}
// Add a new "arch" column to the "nodes" table.
func updateFromV19(tx *sql.Tx) error {
// The column has a not-null constraint and a default value of
// 0. However, leaving the 0 default won't effectively be accepted when
// creating a new, due to the check constraint, so we are sure to end
// up with a valid value.
_, err := tx.Exec("ALTER TABLE nodes ADD COLUMN arch INTEGER NOT NULL DEFAULT 0 CHECK (arch > 0)")
if err != nil {
return err
}
arch, err := osarch.ArchitectureGetLocalID()
if err != nil {
return err
}
_, err = tx.Exec("UPDATE nodes SET arch = ?", arch)
if err != nil {
return err
}
return nil
}
// Rename 'containers' to 'instances' in *_used_by_ref views.
func updateFromV18(tx *sql.Tx) error {
stmts := `
DROP VIEW profiles_used_by_ref;
CREATE VIEW profiles_used_by_ref (project,
name,
value) AS
SELECT projects.name,
profiles.name,
printf('/1.0/instances/%s?project=%s',
"instances".name,
instances_projects.name)
FROM profiles
JOIN projects ON projects.id=profiles.project_id
JOIN "instances_profiles"
ON "instances_profiles".profile_id=profiles.id
JOIN "instances"
ON "instances".id="instances_profiles".instance_id
JOIN projects AS instances_projects
ON instances_projects.id="instances".project_id;
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',
images.fingerprint)
FROM images JOIN projects ON project_id=projects.id UNION
SELECT projects.name,
printf('/1.0/profiles/%s?project=%s',
profiles.name,
projects.name)
FROM profiles JOIN projects ON project_id=projects.id;
`
_, err := tx.Exec(stmts)
return err
}
// Add nodes_roles table
func updateFromV17(tx *sql.Tx) error {
stmts := `
CREATE TABLE nodes_roles (
node_id INTEGER NOT NULL,
role INTEGER NOT NULL,
FOREIGN KEY (node_id) REFERENCES nodes (id) ON DELETE CASCADE,
UNIQUE (node_id, role)
);
`
_, err := tx.Exec(stmts)
return err
}
// Add image type column
func updateFromV16(tx *sql.Tx) error {
_, err := tx.Exec("ALTER TABLE images ADD COLUMN type INTEGER NOT NULL DEFAULT 0;")
return err
}
// Create new snapshot tables and migrate data to them.
func updateFromV15(tx *sql.Tx) error {
stmts := `
CREATE TABLE instances_snapshots (
id INTEGER primary key AUTOINCREMENT NOT NULL,
instance_id INTEGER NOT NULL,
name TEXT NOT NULL,
creation_date DATETIME NOT NULL DEFAULT 0,
stateful INTEGER NOT NULL DEFAULT 0,
description TEXT,
expiry_date DATETIME,
UNIQUE (instance_id, name),
FOREIGN KEY (instance_id) REFERENCES instances (id) ON DELETE CASCADE
);
CREATE TABLE instances_snapshots_config (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
instance_snapshot_id INTEGER NOT NULL,
key TEXT NOT NULL,
value TEXT,
FOREIGN KEY (instance_snapshot_id) REFERENCES instances_snapshots (id) ON DELETE CASCADE,
UNIQUE (instance_snapshot_id, key)
);
CREATE TABLE instances_snapshots_devices (
id INTEGER primary key AUTOINCREMENT NOT NULL,
instance_snapshot_id INTEGER NOT NULL,
name TEXT NOT NULL,
type INTEGER NOT NULL default 0,
FOREIGN KEY (instance_snapshot_id) REFERENCES instances_snapshots (id) ON DELETE CASCADE,
UNIQUE (instance_snapshot_id, name)
);
CREATE TABLE instances_snapshots_devices_config (
id INTEGER primary key AUTOINCREMENT NOT NULL,
instance_snapshot_device_id INTEGER NOT NULL,
key TEXT NOT NULL,
value TEXT,
FOREIGN KEY (instance_snapshot_device_id) REFERENCES instances_snapshots_devices (id) ON DELETE CASCADE,
UNIQUE (instance_snapshot_device_id, key)
);
CREATE VIEW instances_snapshots_config_ref (
project,
instance,
name,
key,
value) AS
SELECT
projects.name,
instances.name,
instances_snapshots.name,
instances_snapshots_config.key,
instances_snapshots_config.value
FROM instances_snapshots_config
JOIN instances_snapshots ON instances_snapshots.id=instances_snapshots_config.instance_snapshot_id
JOIN instances ON instances.id=instances_snapshots.instance_id
JOIN projects ON projects.id=instances.project_id;
CREATE VIEW instances_snapshots_devices_ref (
project,
instance,
name,
device,
type,
key,
value) AS
SELECT
projects.name,
instances.name,
instances_snapshots.name,
instances_snapshots_devices.name,
instances_snapshots_devices.type,
coalesce(instances_snapshots_devices_config.key, ''),
coalesce(instances_snapshots_devices_config.value, '')
FROM instances_snapshots_devices
LEFT OUTER JOIN instances_snapshots_devices_config
ON instances_snapshots_devices_config.instance_snapshot_device_id=instances_snapshots_devices.id
JOIN instances ON instances.id=instances_snapshots.instance_id
JOIN projects ON projects.id=instances.project_id
JOIN instances_snapshots ON instances_snapshots.id=instances_snapshots_devices.instance_snapshot_id
`
_, err := tx.Exec(stmts)
if err != nil {
return errors.Wrap(err, "Failed to create snapshots tables")
}
// Get the total number of rows in the instances table.
count, err := query.Count(tx, "instances", "")
if err != nil {
return errors.Wrap(err, "Failed to count rows in instances table")
}
// Fetch all rows in the instances table.
instances := make([]struct {
ID int
Name string
Type int
CreationDate time.Time
Stateful bool
Description string
ExpiryDate time.Time
}, count)
dest := func(i int) []interface{} {
return []interface{}{
&instances[i].ID,
&instances[i].Name,
&instances[i].Type,
&instances[i].CreationDate,
&instances[i].Stateful,
&instances[i].Description,
&instances[i].ExpiryDate,
}
}
stmt, err := tx.Prepare(`
SELECT id, name, type, creation_date, stateful, coalesce(description, ''), expiry_date FROM instances
`)
if err != nil {
return errors.Wrap(err, "Failed to prepare instances query")
}
err = query.SelectObjects(stmt, dest)
if err != nil {
return errors.Wrap(err, "Failed to fetch instances")
}
// Create an index mapping instance names to their IDs.
instanceIDsByName := make(map[string]int)
for _, instance := range instances {
if instance.Type == 1 {
continue
}
instanceIDsByName[instance.Name] = instance.ID
}
// Fetch all rows in the instances_config table that references
// snapshots and index them by instance ID.
count, err = query.Count(
tx,
"instances_config JOIN instances ON instances_config.instance_id = instances.id",
"instances.type = 1")
if err != nil {
return errors.Wrap(err, "Failed to count rows in instances_config table")
}
configs := make([]struct {
ID int
InstanceID int
Key string
Value string
}, count)
dest = func(i int) []interface{} {
return []interface{}{
&configs[i].ID,
&configs[i].InstanceID,
&configs[i].Key,
&configs[i].Value,
}
}
stmt, err = tx.Prepare(`
SELECT instances_config.id, instance_id, key, value
FROM instances_config JOIN instances ON instances_config.instance_id = instances.id
WHERE instances.type = 1
`)
if err != nil {
return errors.Wrap(err, "Failed to prepare instances_config query")
}
err = query.SelectObjects(stmt, dest)
if err != nil {
return errors.Wrap(err, "Failed to fetch snapshots config")
}
configBySnapshotID := make(map[int]map[string]string)
for _, config := range configs {
c, ok := configBySnapshotID[config.InstanceID]
if !ok {
c = make(map[string]string)
configBySnapshotID[config.InstanceID] = c
}
c[config.Key] = config.Value
}
// Fetch all rows in the instances_devices table that references
// snapshots and index them by instance ID.
count, err = query.Count(
tx,
"instances_devices JOIN instances ON instances_devices.instance_id = instances.id",
"instances.type = 1")
if err != nil {
return errors.Wrap(err, "Failed to count rows in instances_devices table")
}
devices := make([]struct {
ID int
InstanceID int
Name string
Type int
}, count)
dest = func(i int) []interface{} {
return []interface{}{
&devices[i].ID,
&devices[i].InstanceID,
&devices[i].Name,
&devices[i].Type,
}
}
stmt, err = tx.Prepare(`
SELECT instances_devices.id, instance_id, instances_devices.name, instances_devices.type
FROM instances_devices JOIN instances ON instances_devices.instance_id = instances.id
WHERE instances.type = 1
`)
if err != nil {
return errors.Wrap(err, "Failed to prepare instances_devices query")
}
err = query.SelectObjects(stmt, dest)
if err != nil {
return errors.Wrap(err, "Failed to fetch snapshots devices")
}
devicesBySnapshotID := make(map[int]map[string]struct {
Type int
Config map[string]string
})
for _, device := range devices {
d, ok := devicesBySnapshotID[device.InstanceID]
if !ok {
d = make(map[string]struct {
Type int
Config map[string]string
})
devicesBySnapshotID[device.InstanceID] = d
}
// Fetch the config for this device.
config, err := query.SelectConfig(tx, "instances_devices_config", "instance_device_id = ?", device.ID)
if err != nil {
return errors.Wrap(err, "Failed to fetch snapshots devices config")
}
d[device.Name] = struct {
Type int
Config map[string]string
}{
Type: device.Type,
Config: config,
}
}
// Migrate all snapshots to the new tables.
for _, instance := range instances {
if instance.Type == 0 {
continue
}
// Figure out the instance and snapshot names.
parts := strings.SplitN(instance.Name, shared.SnapshotDelimiter, 2)
if len(parts) != 2 {
return fmt.Errorf("Snapshot %s has an invalid name", instance.Name)
}
instanceName := parts[0]
instanceID, ok := instanceIDsByName[instanceName]
if !ok {
return fmt.Errorf("Found snapshot %s with no associated instance", instance.Name)
}
snapshotName := parts[1]
// Insert a new row in instances_snapshots
columns := []string{
"instance_id",
"name",
"creation_date",
"stateful",
"description",
"expiry_date",
}
id, err := query.UpsertObject(
tx,
"instances_snapshots",
columns,
[]interface{}{
instanceID,
snapshotName,
instance.CreationDate,
instance.Stateful,
instance.Description,
instance.ExpiryDate,
},
)
if err != nil {
return errors.Wrapf(err, "Failed migrate snapshot %s", instance.Name)
}
// Migrate the snapshot config
for key, value := range configBySnapshotID[instance.ID] {
columns := []string{
"instance_snapshot_id",
"key",
"value",
}
_, err := query.UpsertObject(
tx,
"instances_snapshots_config",
columns,
[]interface{}{
id,
key,
value,
},
)
if err != nil {
return errors.Wrapf(err, "Failed migrate config %s/%s for snapshot %s", key, value, instance.Name)
}
}
// Migrate the snapshot devices
for name, device := range devicesBySnapshotID[instance.ID] {
columns := []string{
"instance_snapshot_id",
"name",
"type",
}
deviceID, err := query.UpsertObject(
tx,
"instances_snapshots_devices",
columns,
[]interface{}{
id,
name,
device.Type,
},
)
if err != nil {
return errors.Wrapf(err, "Failed migrate device %s for snapshot %s", name, instance.Name)
}
for key, value := range device.Config {
columns := []string{
"instance_snapshot_device_id",
"key",
"value",
}
_, err := query.UpsertObject(
tx,
"instances_snapshots_devices_config",
columns,
[]interface{}{
deviceID,
key,
value,
},
)
if err != nil {
return errors.Wrapf(err, "Failed migrate config %s/%s for device %s of snapshot %s", key, value, name, instance.Name)
}
}
}
deleted, err := query.DeleteObject(tx, "instances", int64(instance.ID))
if err != nil {
return errors.Wrapf(err, "Failed to delete snapshot %s", instance.Name)
}
if !deleted {
return fmt.Errorf("Expected to delete snapshot %s", instance.Name)
}
}
// Make sure that no snapshot is left in the instances table.
count, err = query.Count(tx, "instances", "type = 1")
if err != nil {
return errors.Wrap(err, "Failed to count leftover snapshot rows")
}
if count != 0 {
return fmt.Errorf("Found %d unexpected snapshots left in instances table", count)
}
return nil
}
// Rename all containers* tables to instances*/
func updateFromV14(tx *sql.Tx) error {
stmts := `
ALTER TABLE containers RENAME TO instances;
ALTER TABLE containers_backups RENAME COLUMN container_id TO instance_id;
ALTER TABLE containers_backups RENAME TO instances_backups;
ALTER TABLE containers_config RENAME COLUMN container_id TO instance_id;
ALTER TABLE containers_config RENAME TO instances_config;
DROP VIEW containers_config_ref;
CREATE VIEW instances_config_ref (project,
node,
name,
key,
value) AS
SELECT projects.name,
nodes.name,
instances.name,
instances_config.key,
instances_config.value
FROM instances_config
JOIN instances ON instances.id=instances_config.instance_id
JOIN projects ON projects.id=instances.project_id
JOIN nodes ON nodes.id=instances.node_id;
ALTER TABLE containers_devices RENAME COLUMN container_id TO instance_id;
ALTER TABLE containers_devices RENAME TO instances_devices;
ALTER TABLE containers_devices_config RENAME COLUMN container_device_id TO instance_device_id;
ALTER TABLE containers_devices_config RENAME TO instances_devices_config;
DROP VIEW containers_devices_ref;
CREATE VIEW instances_devices_ref (project,
node,
name,
device,
type,
key,
value) AS
SELECT projects.name,
nodes.name,
instances.name,
instances_devices.name,
instances_devices.type,
coalesce(instances_devices_config.key,
''),
coalesce(instances_devices_config.value,
'')
FROM instances_devices
LEFT OUTER JOIN instances_devices_config ON instances_devices_config.instance_device_id=instances_devices.id
JOIN instances ON instances.id=instances_devices.instance_id
JOIN projects ON projects.id=instances.project_id
JOIN nodes ON nodes.id=instances.node_id;
DROP INDEX containers_node_id_idx;
CREATE INDEX instances_node_id_idx ON instances (node_id);
ALTER TABLE containers_profiles RENAME COLUMN container_id TO instance_id;
ALTER TABLE containers_profiles RENAME TO instances_profiles;
DROP VIEW containers_profiles_ref;
CREATE VIEW instances_profiles_ref (project,
node,
name,
value) AS
SELECT projects.name,
nodes.name,
instances.name,
profiles.name
FROM instances_profiles
JOIN instances ON instances.id=instances_profiles.instance_id
JOIN profiles ON profiles.id=instances_profiles.profile_id
JOIN projects ON projects.id=instances.project_id
JOIN nodes ON nodes.id=instances.node_id
ORDER BY instances_profiles.apply_order;
DROP INDEX containers_project_id_and_name_idx;
DROP INDEX containers_project_id_and_node_id_and_name_idx;
DROP INDEX containers_project_id_and_node_id_idx;
DROP INDEX containers_project_id_idx;
CREATE INDEX instances_project_id_and_name_idx ON instances (project_id, name);
CREATE INDEX instances_project_id_and_node_id_and_name_idx ON instances (project_id, node_id, name);
CREATE INDEX instances_project_id_and_node_id_idx ON instances (project_id, node_id);
CREATE INDEX instances_project_id_idx ON instances (project_id);
DROP VIEW profiles_used_by_ref;
CREATE VIEW profiles_used_by_ref (project,
name,
value) AS
SELECT projects.name,
profiles.name,
printf('/1.0/containers/%s?project=%s',
"instances".name,
instances_projects.name)
FROM profiles
JOIN projects ON projects.id=profiles.project_id
JOIN "instances_profiles"
ON "instances_profiles".profile_id=profiles.id
JOIN "instances"
ON "instances".id="instances_profiles".instance_id
JOIN projects AS instances_projects
ON instances_projects.id="instances".project_id;
`
_, err := tx.Exec(stmts)
return err
}
func updateFromV13(tx *sql.Tx) error {
_, err := tx.Exec("ALTER TABLE containers ADD COLUMN expiry_date DATETIME;")
return err
}
func updateFromV12(tx *sql.Tx) error {
stmts := `
DROP VIEW profiles_used_by_ref;
CREATE VIEW profiles_used_by_ref (project,
name,
value) AS
SELECT projects.name,
profiles.name,
printf('/1.0/containers/%s?project=%s',
containers.name,
containers_projects.name)
FROM profiles
JOIN projects ON projects.id=profiles.project_id
JOIN containers_profiles
ON containers_profiles.profile_id=profiles.id
JOIN containers
ON containers.id=containers_profiles.container_id
JOIN projects AS containers_projects
ON containers_projects.id=containers.project_id;
`
_, err := tx.Exec(stmts)
return err
}