forked from canonical/lxd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
patches.go
2870 lines (2509 loc) · 86.6 KB
/
patches.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 main
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"syscall"
"github.com/lxc/lxd/lxd/db"
"github.com/lxc/lxd/shared"
"github.com/lxc/lxd/shared/logger"
log "github.com/lxc/lxd/shared/log15"
)
/* Patches are one-time actions that are sometimes needed to update
existing container configuration or move things around on the
filesystem.
Those patches are applied at startup time after the database schema
has been fully updated. Patches can therefore assume a working database.
At the time the patches are applied, the containers aren't started
yet and the daemon isn't listening to requests.
DO NOT use this mechanism for database update. Schema updates must be
done through the separate schema update mechanism.
Only append to the patches list, never remove entries and never re-order them.
*/
var patches = []patch{
{name: "invalid_profile_names", run: patchInvalidProfileNames},
{name: "leftover_profile_config", run: patchLeftoverProfileConfig},
{name: "network_permissions", run: patchNetworkPermissions},
{name: "storage_api", run: patchStorageApi},
{name: "storage_api_v1", run: patchStorageApiV1},
{name: "storage_api_dir_cleanup", run: patchStorageApiDirCleanup},
{name: "storage_api_lvm_keys", run: patchStorageApiLvmKeys},
{name: "storage_api_keys", run: patchStorageApiKeys},
{name: "storage_api_update_storage_configs", run: patchStorageApiUpdateStorageConfigs},
{name: "storage_api_lxd_on_btrfs", run: patchStorageApiLxdOnBtrfs},
{name: "storage_api_lvm_detect_lv_size", run: patchStorageApiDetectLVSize},
{name: "storage_api_insert_zfs_driver", run: patchStorageApiInsertZfsDriver},
{name: "storage_zfs_noauto", run: patchStorageZFSnoauto},
{name: "storage_zfs_volume_size", run: patchStorageZFSVolumeSize},
{name: "network_dnsmasq_hosts", run: patchNetworkDnsmasqHosts},
{name: "storage_api_dir_bind_mount", run: patchStorageApiDirBindMount},
{name: "fix_uploaded_at", run: patchFixUploadedAt},
{name: "storage_api_ceph_size_remove", run: patchStorageApiCephSizeRemove},
{name: "devices_new_naming_scheme", run: patchDevicesNewNamingScheme},
}
type patch struct {
name string
run func(name string, d *Daemon) error
}
func (p *patch) apply(d *Daemon) error {
logger.Debugf("Applying patch: %s", p.name)
err := p.run(p.name, d)
if err != nil {
return err
}
err = d.db.PatchesMarkApplied(p.name)
if err != nil {
return err
}
return nil
}
// Return the names of all available patches.
func patchesGetNames() []string {
names := make([]string, len(patches))
for i, patch := range patches {
names[i] = patch.name
}
return names
}
func patchesApplyAll(d *Daemon) error {
appliedPatches, err := d.db.Patches()
if err != nil {
return err
}
for _, patch := range patches {
if shared.StringInSlice(patch.name, appliedPatches) {
continue
}
err := patch.apply(d)
if err != nil {
return err
}
}
return nil
}
// Patches begin here
func patchLeftoverProfileConfig(name string, d *Daemon) error {
return d.db.ProfileCleanupLeftover()
}
func patchInvalidProfileNames(name string, d *Daemon) error {
profiles, err := d.db.Profiles()
if err != nil {
return err
}
for _, profile := range profiles {
if strings.Contains(profile, "/") || shared.StringInSlice(profile, []string{".", ".."}) {
logger.Info("Removing unreachable profile (invalid name)", log.Ctx{"name": profile})
err := d.db.ProfileDelete(profile)
if err != nil {
return err
}
}
}
return nil
}
func patchNetworkPermissions(name string, d *Daemon) error {
// Get the list of networks
networks, err := d.db.Networks()
if err != nil {
return err
}
// Fix the permissions
err = os.Chmod(shared.VarPath("networks"), 0711)
if err != nil {
return err
}
for _, network := range networks {
if !shared.PathExists(shared.VarPath("networks", network)) {
continue
}
err = os.Chmod(shared.VarPath("networks", network), 0711)
if err != nil {
return err
}
if shared.PathExists(shared.VarPath("networks", network, "dnsmasq.hosts")) {
err = os.Chmod(shared.VarPath("networks", network, "dnsmasq.hosts"), 0644)
if err != nil {
return err
}
}
}
return nil
}
func patchStorageApi(name string, d *Daemon) error {
lvmVgName := daemonConfig["storage.lvm_vg_name"].Get()
zfsPoolName := daemonConfig["storage.zfs_pool_name"].Get()
defaultPoolName := "default"
preStorageApiStorageType := storageTypeDir
if lvmVgName != "" {
preStorageApiStorageType = storageTypeLvm
defaultPoolName = lvmVgName
} else if zfsPoolName != "" {
preStorageApiStorageType = storageTypeZfs
defaultPoolName = zfsPoolName
} else if d.os.BackingFS == "btrfs" {
preStorageApiStorageType = storageTypeBtrfs
} else {
// Dir storage pool.
}
defaultStorageTypeName, err := storageTypeToString(preStorageApiStorageType)
if err != nil {
return err
}
// In case we detect that an lvm name or a zfs name exists it makes
// sense to create a storage pool in the database, independent of
// whether anything currently exists on that pool. We can still probably
// safely assume that the user at least once used that pool.
// However, when we detect {dir, btrfs}, we can't rely on that guess
// since the daemon doesn't record any name for the pool anywhere. So
// in the {dir, btrfs} case we check whether anything exists on the
// pool, if not, then we don't create a default pool. The user will then
// be forced to run lxd init again and can start from a pristine state.
// Check if this LXD instace currently has any containers, snapshots, or
// images configured. If so, we create a default storage pool in the
// database. Otherwise, the user will have to run LXD init.
cRegular, err := d.db.ContainersList(db.CTypeRegular)
if err != nil {
return err
}
// Get list of existing snapshots.
cSnapshots, err := d.db.ContainersList(db.CTypeSnapshot)
if err != nil {
return err
}
// Get list of existing public images.
imgPublic, err := d.db.ImagesGet(true)
if err != nil {
return err
}
// Get list of existing private images.
imgPrivate, err := d.db.ImagesGet(false)
if err != nil {
return err
}
// Nothing exists on the pool so we're not creating a default one,
// thereby forcing the user to run lxd init.
if len(cRegular) == 0 && len(cSnapshots) == 0 && len(imgPublic) == 0 && len(imgPrivate) == 0 {
return nil
}
// If any of these are actually called, there's no way back.
poolName := defaultPoolName
switch preStorageApiStorageType {
case storageTypeBtrfs:
err = upgradeFromStorageTypeBtrfs(name, d, defaultPoolName, defaultStorageTypeName, cRegular, cSnapshots, imgPublic, imgPrivate)
case storageTypeDir:
err = upgradeFromStorageTypeDir(name, d, defaultPoolName, defaultStorageTypeName, cRegular, cSnapshots, imgPublic, imgPrivate)
case storageTypeLvm:
err = upgradeFromStorageTypeLvm(name, d, defaultPoolName, defaultStorageTypeName, cRegular, cSnapshots, imgPublic, imgPrivate)
case storageTypeZfs:
// The user is using a zfs dataset. This case needs to be
// handled with care:
// - The pool name that is used in the storage backends needs
// to be set to a sane name that doesn't contain a slash "/".
// This is what this snippet is for.
// - The full dataset name <pool_name>/<volume_name> needs to be
// set as the source value.
if strings.Contains(defaultPoolName, "/") {
poolName = "default"
}
err = upgradeFromStorageTypeZfs(name, d, defaultPoolName, defaultStorageTypeName, cRegular, []string{}, imgPublic, imgPrivate)
default: // Shouldn't happen.
return fmt.Errorf("Invalid storage type. Upgrading not possible.")
}
if err != nil {
return err
}
// The new storage api enforces that the default storage pool on which
// containers are created is set in the default profile. If it isn't
// set, then LXD will refuse to create a container until either an
// appropriate device including a pool is added to the default profile
// or the user explicitly passes the pool the container's storage volume
// is supposed to be created on.
allcontainers := append(cRegular, cSnapshots...)
err = updatePoolPropertyForAllObjects(d, poolName, allcontainers)
if err != nil {
return err
}
// Unset deprecated storage keys.
daemonConfig["storage.lvm_fstype"].Set(d, "")
daemonConfig["storage.lvm_mount_options"].Set(d, "")
daemonConfig["storage.lvm_thinpool_name"].Set(d, "")
daemonConfig["storage.lvm_vg_name"].Set(d, "")
daemonConfig["storage.lvm_volume_size"].Set(d, "")
daemonConfig["storage.zfs_pool_name"].Set(d, "")
daemonConfig["storage.zfs_remove_snapshots"].Set(d, "")
daemonConfig["storage.zfs_use_refquota"].Set(d, "")
return SetupStorageDriver(d.State(), true)
}
func upgradeFromStorageTypeBtrfs(name string, d *Daemon, defaultPoolName string, defaultStorageTypeName string, cRegular []string, cSnapshots []string, imgPublic []string, imgPrivate []string) error {
poolConfig := map[string]string{}
poolSubvolumePath := getStoragePoolMountPoint(defaultPoolName)
poolConfig["source"] = poolSubvolumePath
err := storagePoolValidateConfig(defaultPoolName, defaultStorageTypeName, poolConfig, nil)
if err != nil {
return err
}
err = storagePoolFillDefault(defaultPoolName, defaultStorageTypeName, poolConfig)
if err != nil {
return err
}
poolID := int64(-1)
pools, err := d.db.StoragePools()
if err == nil { // Already exist valid storage pools.
// Check if the storage pool already has a db entry.
if shared.StringInSlice(defaultPoolName, pools) {
logger.Warnf("Database already contains a valid entry for the storage pool: %s.", defaultPoolName)
}
// Get the pool ID as we need it for storage volume creation.
// (Use a tmp variable as Go's scoping is freaking me out.)
tmp, pool, err := d.db.StoragePoolGet(defaultPoolName)
if err != nil {
logger.Errorf("Failed to query database: %s.", err)
return err
}
poolID = tmp
// Update the pool configuration on a post LXD 2.9.1 instance
// that still runs this upgrade code because of a partial
// upgrade.
if pool.Config == nil {
pool.Config = poolConfig
}
err = d.db.StoragePoolUpdate(defaultPoolName, "", pool.Config)
if err != nil {
return err
}
} else if err == db.NoSuchObjectError { // Likely a pristine upgrade.
tmp, err := dbStoragePoolCreateAndUpdateCache(d.db, defaultPoolName, "", defaultStorageTypeName, poolConfig)
if err != nil {
return err
}
poolID = tmp
s, err := storagePoolInit(d.State(), defaultPoolName)
if err != nil {
return err
}
err = s.StoragePoolCreate()
if err != nil {
return err
}
} else { // Shouldn't happen.
logger.Errorf("Failed to query database: %s.", err)
return err
}
if len(cRegular) > 0 {
// ${LXD_DIR}/storage-pools/<name>
containersSubvolumePath := getContainerMountPoint(defaultPoolName, "")
if !shared.PathExists(containersSubvolumePath) {
err := os.MkdirAll(containersSubvolumePath, 0711)
if err != nil {
return err
}
}
}
// Get storage pool from the db after having updated it above.
_, defaultPool, err := d.db.StoragePoolGet(defaultPoolName)
if err != nil {
return err
}
for _, ct := range cRegular {
// Initialize empty storage volume configuration for the
// container.
containerPoolVolumeConfig := map[string]string{}
err = storageVolumeFillDefault(ct, containerPoolVolumeConfig, defaultPool)
if err != nil {
return err
}
_, err = d.db.StoragePoolVolumeGetTypeID(ct, storagePoolVolumeTypeContainer, poolID)
if err == nil {
logger.Warnf("Storage volumes database already contains an entry for the container.")
err := d.db.StoragePoolVolumeUpdate(ct, storagePoolVolumeTypeContainer, poolID, "", containerPoolVolumeConfig)
if err != nil {
return err
}
} else if err == db.NoSuchObjectError {
// Insert storage volumes for containers into the database.
_, err := d.db.StoragePoolVolumeCreate(ct, "", storagePoolVolumeTypeContainer, poolID, containerPoolVolumeConfig)
if err != nil {
logger.Errorf("Could not insert a storage volume for container \"%s\".", ct)
return err
}
} else {
logger.Errorf("Failed to query database: %s", err)
return err
}
// Rename the btrfs subvolume and making it a
// subvolume of the subvolume of the storage pool:
// mv ${LXD_DIR}/containers/<container_name> ${LXD_DIR}/storage-pools/<pool>/<container_name>
oldContainerMntPoint := shared.VarPath("containers", ct)
newContainerMntPoint := getContainerMountPoint(defaultPoolName, ct)
if shared.PathExists(oldContainerMntPoint) && !shared.PathExists(newContainerMntPoint) {
err = os.Rename(oldContainerMntPoint, newContainerMntPoint)
if err != nil {
err := btrfsSubVolumeCreate(newContainerMntPoint)
if err != nil {
return err
}
output, err := rsyncLocalCopy(oldContainerMntPoint, newContainerMntPoint, "")
if err != nil {
logger.Errorf("Failed to rsync: %s: %s.", output, err)
return err
}
btrfsSubVolumesDelete(oldContainerMntPoint)
if shared.PathExists(oldContainerMntPoint) {
err = os.RemoveAll(oldContainerMntPoint)
if err != nil {
return err
}
}
}
}
// Create a symlink to the mountpoint of the container:
// ${LXD_DIR}/containers/<container_name> ->
// ${LXD_DIR}/storage-pools/<pool>/containers/<container_name>
doesntMatter := false
err = createContainerMountpoint(newContainerMntPoint, oldContainerMntPoint, doesntMatter)
if err != nil {
return err
}
// Check if we need to account for snapshots for this container.
ctSnapshots, err := d.db.ContainerGetSnapshots(ct)
if err != nil {
return err
}
if len(ctSnapshots) > 0 {
// Create the snapshots directory in
// the new storage pool:
// ${LXD_DIR}/storage-pools/<pool>/snapshots
newSnapshotsMntPoint := getSnapshotMountPoint(defaultPoolName, ct)
if !shared.PathExists(newSnapshotsMntPoint) {
err := os.MkdirAll(newSnapshotsMntPoint, 0700)
if err != nil {
return err
}
}
}
for _, cs := range ctSnapshots {
// Insert storage volumes for snapshots into the
// database. Note that snapshots have already been moved
// and symlinked above. So no need to do any work here.
// Initialize empty storage volume configuration for the
// container.
snapshotPoolVolumeConfig := map[string]string{}
err = storageVolumeFillDefault(cs, snapshotPoolVolumeConfig, defaultPool)
if err != nil {
return err
}
_, err = d.db.StoragePoolVolumeGetTypeID(cs, storagePoolVolumeTypeContainer, poolID)
if err == nil {
logger.Warnf("Storage volumes database already contains an entry for the snapshot.")
err := d.db.StoragePoolVolumeUpdate(cs, storagePoolVolumeTypeContainer, poolID, "", snapshotPoolVolumeConfig)
if err != nil {
return err
}
} else if err == db.NoSuchObjectError {
// Insert storage volumes for containers into the database.
_, err := d.db.StoragePoolVolumeCreate(cs, "", storagePoolVolumeTypeContainer, poolID, snapshotPoolVolumeConfig)
if err != nil {
logger.Errorf("Could not insert a storage volume for snapshot \"%s\".", cs)
return err
}
} else {
logger.Errorf("Failed to query database: %s", err)
return err
}
// We need to create a new snapshot since we can't move
// readonly snapshots.
oldSnapshotMntPoint := shared.VarPath("snapshots", cs)
newSnapshotMntPoint := getSnapshotMountPoint(defaultPoolName, cs)
if shared.PathExists(oldSnapshotMntPoint) && !shared.PathExists(newSnapshotMntPoint) {
err = btrfsSnapshot(oldSnapshotMntPoint, newSnapshotMntPoint, true)
if err != nil {
err := btrfsSubVolumeCreate(newSnapshotMntPoint)
if err != nil {
return err
}
output, err := rsyncLocalCopy(oldSnapshotMntPoint, newSnapshotMntPoint, "")
if err != nil {
logger.Errorf("Failed to rsync: %s: %s.", output, err)
return err
}
btrfsSubVolumesDelete(oldSnapshotMntPoint)
if shared.PathExists(oldSnapshotMntPoint) {
err = os.RemoveAll(oldSnapshotMntPoint)
if err != nil {
return err
}
}
} else {
// Delete the old subvolume.
err = btrfsSubVolumesDelete(oldSnapshotMntPoint)
if err != nil {
return err
}
}
}
}
if len(ctSnapshots) > 0 {
// Create a new symlink from the snapshots directory of
// the container to the snapshots directory on the
// storage pool:
// ${LXD_DIR}/snapshots/<container_name> -> ${LXD_DIR}/storage-pools/<pool>/snapshots/<container_name>
snapshotsPath := shared.VarPath("snapshots", ct)
newSnapshotMntPoint := getSnapshotMountPoint(defaultPoolName, ct)
os.Remove(snapshotsPath)
if !shared.PathExists(snapshotsPath) {
err := os.Symlink(newSnapshotMntPoint, snapshotsPath)
if err != nil {
return err
}
}
}
}
// Insert storage volumes for images into the database. Images don't
// move. The tarballs remain in their original location.
images := append(imgPublic, imgPrivate...)
for _, img := range images {
imagePoolVolumeConfig := map[string]string{}
err = storageVolumeFillDefault(img, imagePoolVolumeConfig, defaultPool)
if err != nil {
return err
}
_, err = d.db.StoragePoolVolumeGetTypeID(img, storagePoolVolumeTypeImage, poolID)
if err == nil {
logger.Warnf("Storage volumes database already contains an entry for the image.")
err := d.db.StoragePoolVolumeUpdate(img, storagePoolVolumeTypeImage, poolID, "", imagePoolVolumeConfig)
if err != nil {
return err
}
} else if err == db.NoSuchObjectError {
// Insert storage volumes for containers into the database.
_, err := d.db.StoragePoolVolumeCreate(img, "", storagePoolVolumeTypeImage, poolID, imagePoolVolumeConfig)
if err != nil {
logger.Errorf("Could not insert a storage volume for image \"%s\".", img)
return err
}
} else {
logger.Errorf("Failed to query database: %s", err)
return err
}
imagesMntPoint := getImageMountPoint(defaultPoolName, "")
if !shared.PathExists(imagesMntPoint) {
err := os.MkdirAll(imagesMntPoint, 0700)
if err != nil {
return err
}
}
oldImageMntPoint := shared.VarPath("images", img+".btrfs")
newImageMntPoint := getImageMountPoint(defaultPoolName, img)
if shared.PathExists(oldImageMntPoint) && !shared.PathExists(newImageMntPoint) {
err := os.Rename(oldImageMntPoint, newImageMntPoint)
if err != nil {
return err
}
}
}
return nil
}
func upgradeFromStorageTypeDir(name string, d *Daemon, defaultPoolName string, defaultStorageTypeName string, cRegular []string, cSnapshots []string, imgPublic []string, imgPrivate []string) error {
poolConfig := map[string]string{}
poolConfig["source"] = shared.VarPath("storage-pools", defaultPoolName)
err := storagePoolValidateConfig(defaultPoolName, defaultStorageTypeName, poolConfig, nil)
if err != nil {
return err
}
err = storagePoolFillDefault(defaultPoolName, defaultStorageTypeName, poolConfig)
if err != nil {
return err
}
poolID := int64(-1)
pools, err := d.db.StoragePools()
if err == nil { // Already exist valid storage pools.
// Check if the storage pool already has a db entry.
if shared.StringInSlice(defaultPoolName, pools) {
logger.Warnf("Database already contains a valid entry for the storage pool: %s.", defaultPoolName)
}
// Get the pool ID as we need it for storage volume creation.
// (Use a tmp variable as Go's scoping is freaking me out.)
tmp, pool, err := d.db.StoragePoolGet(defaultPoolName)
if err != nil {
logger.Errorf("Failed to query database: %s.", err)
return err
}
poolID = tmp
// Update the pool configuration on a post LXD 2.9.1 instance
// that still runs this upgrade code because of a partial
// upgrade.
if pool.Config == nil {
pool.Config = poolConfig
}
err = d.db.StoragePoolUpdate(defaultPoolName, pool.Description, pool.Config)
if err != nil {
return err
}
} else if err == db.NoSuchObjectError { // Likely a pristine upgrade.
tmp, err := dbStoragePoolCreateAndUpdateCache(d.db, defaultPoolName, "", defaultStorageTypeName, poolConfig)
if err != nil {
return err
}
poolID = tmp
s, err := storagePoolInit(d.State(), defaultPoolName)
if err != nil {
return err
}
err = s.StoragePoolCreate()
if err != nil {
return err
}
} else { // Shouldn't happen.
logger.Errorf("Failed to query database: %s.", err)
return err
}
// Get storage pool from the db after having updated it above.
_, defaultPool, err := d.db.StoragePoolGet(defaultPoolName)
if err != nil {
return err
}
// Insert storage volumes for containers into the database.
for _, ct := range cRegular {
// Initialize empty storage volume configuration for the
// container.
containerPoolVolumeConfig := map[string]string{}
err = storageVolumeFillDefault(ct, containerPoolVolumeConfig, defaultPool)
if err != nil {
return err
}
_, err = d.db.StoragePoolVolumeGetTypeID(ct, storagePoolVolumeTypeContainer, poolID)
if err == nil {
logger.Warnf("Storage volumes database already contains an entry for the container.")
err := d.db.StoragePoolVolumeUpdate(ct, storagePoolVolumeTypeContainer, poolID, "", containerPoolVolumeConfig)
if err != nil {
return err
}
} else if err == db.NoSuchObjectError {
// Insert storage volumes for containers into the database.
_, err := d.db.StoragePoolVolumeCreate(ct, "", storagePoolVolumeTypeContainer, poolID, containerPoolVolumeConfig)
if err != nil {
logger.Errorf("Could not insert a storage volume for container \"%s\".", ct)
return err
}
} else {
logger.Errorf("Failed to query database: %s", err)
return err
}
// Create the new path where containers will be located on the
// new storage api.
containersMntPoint := getContainerMountPoint(defaultPoolName, "")
if !shared.PathExists(containersMntPoint) {
err := os.MkdirAll(containersMntPoint, 0711)
if err != nil {
return err
}
}
// Simply rename the container when they are directories.
oldContainerMntPoint := shared.VarPath("containers", ct)
newContainerMntPoint := getContainerMountPoint(defaultPoolName, ct)
if shared.PathExists(oldContainerMntPoint) && !shared.PathExists(newContainerMntPoint) {
// First try to rename.
err := os.Rename(oldContainerMntPoint, newContainerMntPoint)
if err != nil {
output, err := rsyncLocalCopy(oldContainerMntPoint, newContainerMntPoint, "")
if err != nil {
logger.Errorf("Failed to rsync: %s: %s.", output, err)
return err
}
err = os.RemoveAll(oldContainerMntPoint)
if err != nil {
return err
}
}
}
doesntMatter := false
err = createContainerMountpoint(newContainerMntPoint, oldContainerMntPoint, doesntMatter)
if err != nil {
return err
}
// Check if we need to account for snapshots for this container.
oldSnapshotMntPoint := shared.VarPath("snapshots", ct)
if !shared.PathExists(oldSnapshotMntPoint) {
continue
}
// If the snapshots directory for that container is empty,
// remove it.
isEmpty, _ := shared.PathIsEmpty(oldSnapshotMntPoint)
if isEmpty {
os.Remove(oldSnapshotMntPoint)
continue
}
// Create the new path where snapshots will be located on the
// new storage api.
snapshotsMntPoint := shared.VarPath("storage-pools", defaultPoolName, "snapshots")
if !shared.PathExists(snapshotsMntPoint) {
err := os.MkdirAll(snapshotsMntPoint, 0711)
if err != nil {
return err
}
}
// Now simply rename the snapshots directory as well.
newSnapshotMntPoint := getSnapshotMountPoint(defaultPoolName, ct)
if shared.PathExists(oldSnapshotMntPoint) && !shared.PathExists(newSnapshotMntPoint) {
err := os.Rename(oldSnapshotMntPoint, newSnapshotMntPoint)
if err != nil {
output, err := rsyncLocalCopy(oldSnapshotMntPoint, newSnapshotMntPoint, "")
if err != nil {
logger.Errorf("Failed to rsync: %s: %s.", output, err)
return err
}
err = os.RemoveAll(oldSnapshotMntPoint)
if err != nil {
return err
}
}
}
// Create a symlink for this container. snapshots.
err = createSnapshotMountpoint(newSnapshotMntPoint, newSnapshotMntPoint, oldSnapshotMntPoint)
if err != nil {
return err
}
}
// Insert storage volumes for snapshots into the database. Note that
// snapshots have already been moved and symlinked above. So no need to
// do any work here.
for _, cs := range cSnapshots {
// Insert storage volumes for snapshots into the
// database. Note that snapshots have already been moved
// and symlinked above. So no need to do any work here.
// Initialize empty storage volume configuration for the
// container.
snapshotPoolVolumeConfig := map[string]string{}
err = storageVolumeFillDefault(cs, snapshotPoolVolumeConfig, defaultPool)
if err != nil {
return err
}
_, err = d.db.StoragePoolVolumeGetTypeID(cs, storagePoolVolumeTypeContainer, poolID)
if err == nil {
logger.Warnf("Storage volumes database already contains an entry for the snapshot.")
err := d.db.StoragePoolVolumeUpdate(cs, storagePoolVolumeTypeContainer, poolID, "", snapshotPoolVolumeConfig)
if err != nil {
return err
}
} else if err == db.NoSuchObjectError {
// Insert storage volumes for containers into the database.
_, err := d.db.StoragePoolVolumeCreate(cs, "", storagePoolVolumeTypeContainer, poolID, snapshotPoolVolumeConfig)
if err != nil {
logger.Errorf("Could not insert a storage volume for snapshot \"%s\".", cs)
return err
}
} else {
logger.Errorf("Failed to query database: %s", err)
return err
}
}
// Insert storage volumes for images into the database. Images don't
// move. The tarballs remain in their original location.
images := append(imgPublic, imgPrivate...)
for _, img := range images {
imagePoolVolumeConfig := map[string]string{}
err = storageVolumeFillDefault(img, imagePoolVolumeConfig, defaultPool)
if err != nil {
return err
}
_, err = d.db.StoragePoolVolumeGetTypeID(img, storagePoolVolumeTypeImage, poolID)
if err == nil {
logger.Warnf("Storage volumes database already contains an entry for the image.")
err := d.db.StoragePoolVolumeUpdate(img, storagePoolVolumeTypeImage, poolID, "", imagePoolVolumeConfig)
if err != nil {
return err
}
} else if err == db.NoSuchObjectError {
// Insert storage volumes for containers into the database.
_, err := d.db.StoragePoolVolumeCreate(img, "", storagePoolVolumeTypeImage, poolID, imagePoolVolumeConfig)
if err != nil {
logger.Errorf("Could not insert a storage volume for image \"%s\".", img)
return err
}
} else {
logger.Errorf("Failed to query database: %s", err)
return err
}
}
return nil
}
func upgradeFromStorageTypeLvm(name string, d *Daemon, defaultPoolName string, defaultStorageTypeName string, cRegular []string, cSnapshots []string, imgPublic []string, imgPrivate []string) error {
poolConfig := map[string]string{}
poolConfig["source"] = defaultPoolName
// Set it only if it is not the default value.
fsType := daemonConfig["storage.lvm_fstype"].Get()
if fsType != "" && fsType != "ext4" {
poolConfig["volume.block.filesystem"] = fsType
}
// Set it only if it is not the default value.
fsMntOpts := daemonConfig["storage.lvm_mount_options"].Get()
if fsMntOpts != "" && fsMntOpts != "discard" {
poolConfig["volume.block.mount_options"] = fsMntOpts
}
poolConfig["lvm.thinpool_name"] = daemonConfig["storage.lvm_thinpool_name"].Get()
if poolConfig["lvm.thinpool_name"] == "" {
// If empty we need to set it to the old default.
poolConfig["lvm.thinpool_name"] = "LXDPool"
}
poolConfig["lvm.vg_name"] = daemonConfig["storage.lvm_vg_name"].Get()
poolConfig["volume.size"] = daemonConfig["storage.lvm_volume_size"].Get()
if poolConfig["volume.size"] != "" {
// In case stuff like GiB is used which
// share.dParseByteSizeString() doesn't handle.
if strings.Contains(poolConfig["volume.size"], "i") {
poolConfig["volume.size"] = strings.Replace(poolConfig["volume.size"], "i", "", 1)
}
}
// On previous upgrade versions, "size" was set instead of
// "volume.size", so unset it.
poolConfig["size"] = ""
err := storagePoolValidateConfig(defaultPoolName, defaultStorageTypeName, poolConfig, nil)
if err != nil {
return err
}
err = storagePoolFillDefault(defaultPoolName, defaultStorageTypeName, poolConfig)
if err != nil {
return err
}
// Activate volume group
err = storageVGActivate(defaultPoolName)
if err != nil {
logger.Errorf("Could not activate volume group \"%s\". Manual intervention needed.", defaultPoolName)
return err
}
// Peek into the storage pool database to see whether any storage pools
// are already configured. If so, we can assume that a partial upgrade
// has been performed and can skip the next steps.
poolID := int64(-1)
pools, err := d.db.StoragePools()
if err == nil { // Already exist valid storage pools.
// Check if the storage pool already has a db entry.
if shared.StringInSlice(defaultPoolName, pools) {
logger.Warnf("Database already contains a valid entry for the storage pool: %s.", defaultPoolName)
}
// Get the pool ID as we need it for storage volume creation.
// (Use a tmp variable as Go's scoping is freaking me out.)
tmp, pool, err := d.db.StoragePoolGet(defaultPoolName)
if err != nil {
logger.Errorf("Failed to query database: %s.", err)
return err
}
poolID = tmp
// Update the pool configuration on a post LXD 2.9.1 instance
// that still runs this upgrade code because of a partial
// upgrade.
if pool.Config == nil {
pool.Config = poolConfig
}
err = d.db.StoragePoolUpdate(defaultPoolName, pool.Description, pool.Config)
if err != nil {
return err
}
} else if err == db.NoSuchObjectError { // Likely a pristine upgrade.
tmp, err := dbStoragePoolCreateAndUpdateCache(d.db, defaultPoolName, "", defaultStorageTypeName, poolConfig)
if err != nil {
return err
}
poolID = tmp
} else { // Shouldn't happen.
logger.Errorf("Failed to query database: %s.", err)
return err
}
// Create pool mountpoint if it doesn't already exist.
poolMntPoint := getStoragePoolMountPoint(defaultPoolName)
if !shared.PathExists(poolMntPoint) {
err = os.MkdirAll(poolMntPoint, 0711)
if err != nil {
logger.Warnf("Failed to create pool mountpoint: %s", poolMntPoint)
}
}
if len(cRegular) > 0 {
// Create generic containers folder on the storage pool.
newContainersMntPoint := getContainerMountPoint(defaultPoolName, "")
if !shared.PathExists(newContainersMntPoint) {
err = os.MkdirAll(newContainersMntPoint, 0711)
if err != nil {
logger.Warnf("Failed to create containers mountpoint: %s", newContainersMntPoint)
}
}
}
// Get storage pool from the db after having updated it above.
_, defaultPool, err := d.db.StoragePoolGet(defaultPoolName)
if err != nil {
return err
}
// Insert storage volumes for containers into the database.
for _, ct := range cRegular {
// Initialize empty storage volume configuration for the
// container.
containerPoolVolumeConfig := map[string]string{}
err = storageVolumeFillDefault(ct, containerPoolVolumeConfig, defaultPool)
if err != nil {
return err
}
_, err = d.db.StoragePoolVolumeGetTypeID(ct, storagePoolVolumeTypeContainer, poolID)
if err == nil {
logger.Warnf("Storage volumes database already contains an entry for the container.")
err := d.db.StoragePoolVolumeUpdate(ct, storagePoolVolumeTypeContainer, poolID, "", containerPoolVolumeConfig)
if err != nil {
return err
}
} else if err == db.NoSuchObjectError {
// Insert storage volumes for containers into the database.
_, err := d.db.StoragePoolVolumeCreate(ct, "", storagePoolVolumeTypeContainer, poolID, containerPoolVolumeConfig)
if err != nil {
logger.Errorf("Could not insert a storage volume for container \"%s\".", ct)
return err
}
} else {
logger.Errorf("Failed to query database: %s", err)
return err
}
// Unmount the logical volume.
oldContainerMntPoint := shared.VarPath("containers", ct)
if shared.IsMountPoint(oldContainerMntPoint) {
err := tryUnmount(oldContainerMntPoint, syscall.MNT_DETACH)
if err != nil {
logger.Errorf("Failed to unmount LVM logical volume \"%s\": %s.", oldContainerMntPoint, err)
return err
}
}
// Create the new path where containers will be located on the
// new storage api. We do os.Rename() here to preserve
// permissions and ownership.
newContainerMntPoint := getContainerMountPoint(defaultPoolName, ct)
ctLvName := containerNameToLVName(ct)
newContainerLvName := fmt.Sprintf("%s_%s", storagePoolVolumeAPIEndpointContainers, ctLvName)
containerLvDevPath := getLvmDevPath(defaultPoolName, storagePoolVolumeAPIEndpointContainers, ctLvName)
if !shared.PathExists(containerLvDevPath) {
oldLvDevPath := fmt.Sprintf("/dev/%s/%s", defaultPoolName, ctLvName)
// If the old LVM device path for the logical volume
// exists we call lvrename. Otherwise this is likely a
// mixed-storage LXD instance which we need to deal
// with.