-
-
Notifications
You must be signed in to change notification settings - Fork 278
/
Copy pathbackend.go
7524 lines (6106 loc) · 249 KB
/
backend.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 storage
import (
"archive/zip"
"bytes"
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"net/http"
"net/url"
"os"
"path/filepath"
"slices"
"strings"
"sync"
"time"
"unicode"
"github.com/minio/minio-go/v7"
"golang.org/x/sync/errgroup"
"gopkg.in/yaml.v2"
incus "github.com/lxc/incus/v6/client"
internalInstance "github.com/lxc/incus/v6/internal/instance"
"github.com/lxc/incus/v6/internal/instancewriter"
internalIO "github.com/lxc/incus/v6/internal/io"
"github.com/lxc/incus/v6/internal/linux"
"github.com/lxc/incus/v6/internal/migration"
"github.com/lxc/incus/v6/internal/server/backup"
backupConfig "github.com/lxc/incus/v6/internal/server/backup/config"
"github.com/lxc/incus/v6/internal/server/cluster/request"
"github.com/lxc/incus/v6/internal/server/db"
"github.com/lxc/incus/v6/internal/server/db/cluster"
deviceConfig "github.com/lxc/incus/v6/internal/server/device/config"
"github.com/lxc/incus/v6/internal/server/instance"
"github.com/lxc/incus/v6/internal/server/instance/instancetype"
"github.com/lxc/incus/v6/internal/server/lifecycle"
"github.com/lxc/incus/v6/internal/server/locking"
localMigration "github.com/lxc/incus/v6/internal/server/migration"
"github.com/lxc/incus/v6/internal/server/operations"
"github.com/lxc/incus/v6/internal/server/project"
"github.com/lxc/incus/v6/internal/server/response"
"github.com/lxc/incus/v6/internal/server/state"
"github.com/lxc/incus/v6/internal/server/storage/drivers"
"github.com/lxc/incus/v6/internal/server/storage/memorypipe"
"github.com/lxc/incus/v6/internal/server/storage/s3"
"github.com/lxc/incus/v6/internal/server/storage/s3/miniod"
localUtil "github.com/lxc/incus/v6/internal/server/util"
internalUtil "github.com/lxc/incus/v6/internal/util"
"github.com/lxc/incus/v6/shared/api"
"github.com/lxc/incus/v6/shared/ioprogress"
"github.com/lxc/incus/v6/shared/logger"
"github.com/lxc/incus/v6/shared/revert"
"github.com/lxc/incus/v6/shared/units"
"github.com/lxc/incus/v6/shared/util"
)
var (
unavailablePools = make(map[string]struct{})
unavailablePoolsMu = sync.Mutex{}
)
// ConnectIfInstanceIsRemote is a reference to cluster.ConnectIfInstanceIsRemote.
//
//nolint:typecheck
var ConnectIfInstanceIsRemote func(s *state.State, projectName string, instName string, r *http.Request, instanceType instancetype.Type) (incus.InstanceServer, error)
// instanceDiskVolumeEffectiveFields fields from the instance disks that are applied to the volume's effective
// config (but not stored in the disk's volume database record).
var instanceDiskVolumeEffectiveFields = []string{
"size",
"size.state",
}
type backend struct {
driver drivers.Driver
id int64
db api.StoragePool
name string
state *state.State
logger logger.Logger
nodes map[int64]db.StoragePoolNode
}
// ID returns the storage pool ID.
func (b *backend) ID() int64 {
return b.id
}
// Name returns the storage pool name.
func (b *backend) Name() string {
return b.name
}
// Description returns the storage pool description.
func (b *backend) Description() string {
return b.db.Description
}
// ValidateName validates the provided name, and returns an error if it's not a valid storage name.
func (b *backend) ValidateName(value string) error {
if strings.Contains(value, "/") {
return fmt.Errorf(`Storage name cannot contain "/"`)
}
for _, r := range value {
if unicode.IsSpace(r) {
return fmt.Errorf(`Storage name cannot contain white space`)
}
}
return nil
}
// Validate storage pool config.
func (b *backend) Validate(config map[string]string) error {
return b.Driver().Validate(config)
}
// Status returns the storage pool status.
func (b *backend) Status() string {
return b.db.Status
}
// LocalStatus returns storage pool status of the local cluster member.
func (b *backend) LocalStatus() string {
// Check if pool is unavailable locally and replace status if so.
// But don't modify b.db.Status as the status may be recovered later so we don't want to persist it here.
if !IsAvailable(b.name) {
return api.StoragePoolStatusUnvailable
}
node, exists := b.nodes[b.state.DB.Cluster.GetNodeID()]
if !exists {
return api.StoragePoolStatusUnknown
}
return db.StoragePoolStateToAPIStatus(node.State)
}
// isStatusReady returns an error if pool is not ready for use on this server.
func (b *backend) isStatusReady() error {
if b.Status() == api.StoragePoolStatusPending {
return fmt.Errorf("Specified pool is not fully created")
}
if b.LocalStatus() == api.StoragePoolStatusUnvailable {
return api.StatusErrorf(http.StatusServiceUnavailable, "Storage pool is unavailable on this server")
}
return nil
}
// ToAPI returns the storage pool as an API representation.
func (b *backend) ToAPI() api.StoragePool {
return b.db
}
// Driver returns the storage pool driver.
func (b *backend) Driver() drivers.Driver {
return b.driver
}
// MigrationTypes returns the migration transport method preferred when sending a migration, based
// on the migration method requested by the driver's ability. The copySnapshots argument indicates
// whether snapshots are migrated as well. clusterMove determines whether the migration is done
// within a cluster and storageMove determines whether the storage pool is changed by the migration.
// This method is used to determine whether to use optimized migration.
func (b *backend) MigrationTypes(contentType drivers.ContentType, refresh bool, copySnapshots bool, clusterMove bool, storageMove bool) []localMigration.Type {
return b.driver.MigrationTypes(contentType, refresh, copySnapshots, clusterMove, storageMove)
}
// Create creates the storage pool layout on the storage device.
// localOnly is used for clustering where only a single node should do remote storage setup.
func (b *backend) Create(clientType request.ClientType, op *operations.Operation) error {
l := b.logger.AddContext(logger.Ctx{"config": b.db.Config, "description": b.db.Description, "clientType": clientType})
l.Debug("Create started")
defer l.Debug("Create finished")
// Validate name.
err := b.ValidateName(b.name)
if err != nil {
return err
}
// Validate config.
err = b.driver.Validate(b.db.Config)
if err != nil {
return err
}
revert := revert.New()
defer revert.Fail()
path := drivers.GetPoolMountPath(b.name)
if internalUtil.IsDir(path) {
return fmt.Errorf("Storage pool directory %q already exists", path)
}
// Create the storage path.
err = os.MkdirAll(path, 0o711)
if err != nil {
return fmt.Errorf("Failed to create storage pool directory %q: %w", path, err)
}
revert.Add(func() { _ = os.RemoveAll(path) })
if b.driver.Info().Remote && clientType != request.ClientTypeNormal {
if !b.driver.Info().MountedRoot {
// Create the directory structure.
err = b.createStorageStructure(path)
if err != nil {
return err
}
}
// Dealing with a remote storage pool, we're done now.
revert.Success()
return nil
}
// Create the storage pool on the storage device.
err = b.driver.Create()
if err != nil {
return err
}
revert.Add(func() { _ = b.driver.Delete(op) })
// Mount the storage pool.
ourMount, err := b.driver.Mount()
if err != nil {
return err
}
// We expect the caller of create to mount the pool if needed, so we should unmount after
// storage struct has been created.
if ourMount {
defer func() { _, _ = b.driver.Unmount() }()
}
// Create the directory structure.
err = b.createStorageStructure(path)
if err != nil {
return err
}
revert.Success()
return nil
}
// GetVolume returns a drivers.Volume containing copies of the supplied volume config and the pools config.
func (b *backend) GetVolume(volType drivers.VolumeType, contentType drivers.ContentType, volName string, volConfig map[string]string) drivers.Volume {
return drivers.NewVolume(b.driver, b.name, volType, contentType, volName, volConfig, b.db.Config).Clone()
}
// GetResources returns utilisation information about the pool.
func (b *backend) GetResources() (*api.ResourcesStoragePool, error) {
l := b.logger.AddContext(nil)
l.Debug("GetResources started")
defer l.Debug("GetResources finished")
if b.Status() == api.StoragePoolStatusPending {
return nil, errors.New("The pool is in pending state")
}
return b.driver.GetResources()
}
// IsUsed returns whether the storage pool is used by any volumes or profiles (excluding image volumes).
func (b *backend) IsUsed() (bool, error) {
usedBy, err := UsedBy(context.TODO(), b.state, b, true, true, db.StoragePoolVolumeTypeNameImage)
if err != nil {
return false, err
}
return len(usedBy) > 0, nil
}
// Update updates the pool config.
func (b *backend) Update(clientType request.ClientType, newDesc string, newConfig map[string]string, op *operations.Operation) error {
l := b.logger.AddContext(logger.Ctx{"newDesc": newDesc, "newConfig": newConfig})
l.Debug("Update started")
defer l.Debug("Update finished")
// Validate config.
err := b.driver.Validate(newConfig)
if err != nil {
return err
}
// Diff the configurations.
changedConfig, userOnly := b.detectChangedConfig(b.db.Config, newConfig)
// Check if the pool source is being changed that the local state is still pending, otherwise prevent it.
_, sourceChanged := changedConfig["source"]
if sourceChanged && b.LocalStatus() != api.StoragePoolStatusPending {
return fmt.Errorf("Pool source cannot be changed when not in pending state")
}
// Prevent shrinking the storage pool.
newSize, sizeChanged := changedConfig["size"]
if sizeChanged {
oldSizeBytes, _ := units.ParseByteSizeString(b.db.Config["size"])
newSizeBytes, _ := units.ParseByteSizeString(newSize)
if newSizeBytes < oldSizeBytes {
return fmt.Errorf("Pool cannot be shrunk")
}
}
// Apply changes to local member if both global pool and node are not pending and non-user config changed.
// Otherwise just apply changes to DB (below) ready for the actual global create request to be initiated.
if len(changedConfig) > 0 && b.Status() != api.StoragePoolStatusPending && b.LocalStatus() != api.StoragePoolStatusPending && !userOnly {
err = b.driver.Update(changedConfig)
if err != nil {
return err
}
}
// Update the database if something changed and we're in ClientTypeNormal mode.
if clientType == request.ClientTypeNormal && (len(changedConfig) > 0 || newDesc != b.db.Description) {
err = b.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
return tx.UpdateStoragePool(ctx, b.name, newDesc, newConfig)
})
if err != nil {
return err
}
}
return nil
}
// warningsDelete deletes any persistent warnings for the pool.
func (b *backend) warningsDelete() error {
err := b.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
return cluster.DeleteWarnings(ctx, tx.Tx(), cluster.TypeStoragePool, int(b.ID()))
})
if err != nil {
return fmt.Errorf("Failed deleting persistent warnings: %w", err)
}
return nil
}
// Delete removes the pool.
func (b *backend) Delete(clientType request.ClientType, op *operations.Operation) error {
l := b.logger.AddContext(logger.Ctx{"clientType": clientType})
l.Debug("Delete started")
defer l.Debug("Delete finished")
// Delete any persistent warnings for pool.
err := b.warningsDelete()
if err != nil {
return err
}
// If completely gone, just return
path := internalUtil.VarPath("storage-pools", b.name)
if !util.PathExists(path) {
return nil
}
if clientType != request.ClientTypeNormal && b.driver.Info().Remote {
if b.driver.Info().Deactivate || b.driver.Info().MountedRoot {
_, err := b.driver.Unmount()
if err != nil {
return err
}
}
if !b.driver.Info().MountedRoot {
// Remote storage may have leftover entries caused by
// volumes that were moved or delete while a particular system was offline.
err := os.RemoveAll(path)
if err != nil {
return err
}
}
} else {
// Remove any left over image volumes.
// This can occur during partial image unpack or if the storage pool has been recovered from an
// instance backup file and the image volume DB records were not restored.
// If non-image volumes exist, we don't delete the, even if they can then prevent the storage pool
// from being deleted, because they should not exist by this point and we don't want to end up
// removing an instance or custom volume accidentally.
// Errors listing volumes are ignored, as we should still try and delete the storage pool.
vols, _ := b.driver.ListVolumes()
for _, vol := range vols {
if vol.Type() == drivers.VolumeTypeImage {
err := b.driver.DeleteVolume(vol, op)
if err != nil {
return fmt.Errorf("Failed deleting left over image volume %q (%s): %w", vol.Name(), vol.ContentType(), err)
}
l.Warn("Deleted left over image volume", logger.Ctx{"volName": vol.Name(), "contentType": vol.ContentType()})
}
}
// Delete the low-level storage.
err := b.driver.Delete(op)
if err != nil {
return err
}
}
// Delete the mountpoint.
err = os.Remove(path)
if err != nil && !errors.Is(err, fs.ErrNotExist) {
return fmt.Errorf("Failed to remove directory %q: %w", path, err)
}
unavailablePoolsMu.Lock()
delete(unavailablePools, b.Name())
unavailablePoolsMu.Unlock()
return nil
}
// Mount mounts the storage pool.
func (b *backend) Mount() (bool, error) {
b.logger.Debug("Mount started")
defer b.logger.Debug("Mount finished")
revert := revert.New()
defer revert.Fail()
revert.Add(func() {
unavailablePoolsMu.Lock()
unavailablePools[b.Name()] = struct{}{}
unavailablePoolsMu.Unlock()
})
path := drivers.GetPoolMountPath(b.name)
// Create the storage path if needed.
if !internalUtil.IsDir(path) {
err := os.MkdirAll(path, 0o711)
if err != nil {
return false, fmt.Errorf("Failed to create storage pool directory %q: %w", path, err)
}
}
ourMount, err := b.driver.Mount()
if err != nil {
return false, err
}
if ourMount {
revert.Add(func() { _, _ = b.Unmount() })
}
// Create the directory structure (if needed) after mounted.
err = b.createStorageStructure(path)
if err != nil {
return false, err
}
revert.Success()
// Ensure pool is marked as available now its mounted.
unavailablePoolsMu.Lock()
delete(unavailablePools, b.Name())
unavailablePoolsMu.Unlock()
return ourMount, nil
}
// Unmount unmounts the storage pool.
func (b *backend) Unmount() (bool, error) {
b.logger.Debug("Unmount started")
defer b.logger.Debug("Unmount finished")
return b.driver.Unmount()
}
// ApplyPatch runs the requested patch at both backend and driver level.
func (b *backend) ApplyPatch(name string) error {
b.logger.Info("Applying patch", logger.Ctx{"name": name})
// Run early backend patches.
patch, ok := earlyPatches[name]
if ok {
err := patch(b)
if err != nil {
return err
}
}
// Run the driver patch itself.
err := b.driver.ApplyPatch(name)
if err != nil {
return err
}
// Run late backend patches.
patch, ok = latePatches[name]
if ok {
err := patch(b)
if err != nil {
return err
}
}
return nil
}
// ensureInstanceSymlink creates a symlink in the instance directory to the instance's mount path
// if doesn't exist already.
func (b *backend) ensureInstanceSymlink(instanceType instancetype.Type, projectName string, instanceName string, mountPath string) error {
if internalInstance.IsSnapshot(instanceName) {
return fmt.Errorf("Instance must not be snapshot")
}
symlinkPath := InstancePath(instanceType, projectName, instanceName, false)
// Remove any old symlinks left over by previous bugs that may point to a different pool.
if util.PathExists(symlinkPath) {
err := os.Remove(symlinkPath)
if err != nil {
return fmt.Errorf("Failed to remove symlink %q: %w", symlinkPath, err)
}
}
// Create new symlink.
err := os.Symlink(mountPath, symlinkPath)
if err != nil {
return fmt.Errorf("Failed to create symlink from %q to %q: %w", mountPath, symlinkPath, err)
}
return nil
}
// removeInstanceSymlink removes a symlink in the instance directory to the instance's mount path.
func (b *backend) removeInstanceSymlink(instanceType instancetype.Type, projectName string, instanceName string) error {
symlinkPath := InstancePath(instanceType, projectName, instanceName, false)
if util.PathExists(symlinkPath) {
err := os.Remove(symlinkPath)
if err != nil {
return fmt.Errorf("Failed to remove symlink %q: %w", symlinkPath, err)
}
}
return nil
}
// ensureInstanceSnapshotSymlink creates a symlink in the snapshot directory to the instance's
// snapshot path if doesn't exist already.
func (b *backend) ensureInstanceSnapshotSymlink(instanceType instancetype.Type, projectName string, instanceName string) error {
// Check we can convert the instance to the volume type needed.
volType, err := InstanceTypeToVolumeType(instanceType)
if err != nil {
return err
}
parentName, _, _ := api.GetParentAndSnapshotName(instanceName)
snapshotSymlink := InstancePath(instanceType, projectName, parentName, true)
volStorageName := project.Instance(projectName, parentName)
snapshotTargetPath := drivers.GetVolumeSnapshotDir(b.name, volType, volStorageName)
// Remove any old symlinks left over by previous bugs that may point to a different pool.
if util.PathExists(snapshotSymlink) {
err = os.Remove(snapshotSymlink)
if err != nil {
return fmt.Errorf("Failed to remove symlink %q: %w", snapshotSymlink, err)
}
}
// Create new symlink.
err = os.Symlink(snapshotTargetPath, snapshotSymlink)
if err != nil {
return fmt.Errorf("Failed to create symlink from %q to %q: %w", snapshotTargetPath, snapshotSymlink, err)
}
return nil
}
// removeInstanceSnapshotSymlinkIfUnused removes the symlink in the snapshot directory to the
// instance's snapshot path if the snapshot path is missing. It is expected that the driver will
// remove the instance's snapshot path after the last snapshot is removed or the volume is deleted.
func (b *backend) removeInstanceSnapshotSymlinkIfUnused(instanceType instancetype.Type, projectName string, instanceName string) error {
// Check we can convert the instance to the volume type needed.
volType, err := InstanceTypeToVolumeType(instanceType)
if err != nil {
return err
}
parentName, _, _ := api.GetParentAndSnapshotName(instanceName)
snapshotSymlink := InstancePath(instanceType, projectName, parentName, true)
volStorageName := project.Instance(projectName, parentName)
snapshotTargetPath := drivers.GetVolumeSnapshotDir(b.name, volType, volStorageName)
// If snapshot parent directory doesn't exist, remove symlink.
if !util.PathExists(snapshotTargetPath) {
if util.PathExists(snapshotSymlink) {
err := os.Remove(snapshotSymlink)
if err != nil {
return fmt.Errorf("Failed to remove symlink %q: %w", snapshotSymlink, err)
}
}
}
return nil
}
// applyInstanceRootDiskOverrides applies the instance's root disk config to the volume's config.
func (b *backend) applyInstanceRootDiskOverrides(inst instance.Instance, vol *drivers.Volume) error {
_, rootDiskConf, err := internalInstance.GetRootDiskDevice(inst.ExpandedDevices().CloneNative())
if err != nil {
return err
}
for _, k := range instanceDiskVolumeEffectiveFields {
if rootDiskConf[k] != "" {
switch k {
case "size":
vol.SetConfigSize(rootDiskConf[k])
case "size.state":
vol.SetConfigStateSize(rootDiskConf[k])
default:
return fmt.Errorf("Unsupported instance disk volume override field %q", k)
}
}
}
return nil
}
// applyInstanceRootDiskInitialValues applies the instance's root disk initial config to the volume's config.
func (b *backend) applyInstanceRootDiskInitialValues(inst instance.Instance, volConfig map[string]string) error {
_, rootDiskConf, err := internalInstance.GetRootDiskDevice(inst.ExpandedDevices().CloneNative())
if err != nil {
return err
}
for k, v := range rootDiskConf {
prefix, newKey, found := strings.Cut(k, "initial.")
if found && prefix == "" {
volConfig[newKey] = v
}
}
return nil
}
// CreateInstance creates an empty instance.
func (b *backend) CreateInstance(inst instance.Instance, op *operations.Operation) error {
l := b.logger.AddContext(logger.Ctx{"project": inst.Project().Name, "instance": inst.Name()})
l.Debug("CreateInstance started")
defer l.Debug("CreateInstance finished")
err := b.isStatusReady()
if err != nil {
return err
}
volType, err := InstanceTypeToVolumeType(inst.Type())
if err != nil {
return err
}
contentType := InstanceContentType(inst)
revert := revert.New()
defer revert.Fail()
volumeConfig := make(map[string]string)
err = b.applyInstanceRootDiskInitialValues(inst, volumeConfig)
if err != nil {
return err
}
// Validate config and create database entry for new storage volume.
err = VolumeDBCreate(b, inst.Project().Name, inst.Name(), "", volType, false, volumeConfig, inst.CreationDate(), time.Time{}, contentType, true, false)
if err != nil {
return err
}
revert.Add(func() { _ = VolumeDBDelete(b, inst.Project().Name, inst.Name(), volType) })
// Record new volume with authorizer.
err = b.state.Authorizer.AddStoragePoolVolume(b.state.ShutdownCtx, inst.Project().Name, b.Name(), volType.Singular(), inst.Name(), "")
if err != nil {
logger.Error("Failed to add storage volume to authorizer", logger.Ctx{"name": inst.Name(), "type": volType, "pool": b.Name(), "project": inst.Project().Name, "error": err})
}
revert.Add(func() {
_ = b.state.Authorizer.DeleteStoragePoolVolume(b.state.ShutdownCtx, inst.Project().Name, b.Name(), volType.Singular(), inst.Name(), "")
})
// Generate the effective root device volume for instance.
volStorageName := project.Instance(inst.Project().Name, inst.Name())
vol := b.GetVolume(volType, contentType, volStorageName, volumeConfig)
err = b.applyInstanceRootDiskOverrides(inst, &vol)
if err != nil {
return err
}
var filler *drivers.VolumeFiller
if inst.Type() == instancetype.Container {
filler = &drivers.VolumeFiller{
Fill: func(vol drivers.Volume, rootBlockPath string, allowUnsafeResize bool) (int64, error) {
// Create an empty rootfs.
err := os.Mkdir(filepath.Join(vol.MountPath(), "rootfs"), 0o755)
if err != nil && !os.IsExist(err) {
return 0, err
}
return 0, nil
},
}
}
err = b.driver.CreateVolume(vol, filler, op)
if err != nil {
return err
}
revert.Add(func() { _ = b.DeleteInstance(inst, op) })
err = b.ensureInstanceSymlink(inst.Type(), inst.Project().Name, inst.Name(), vol.MountPath())
if err != nil {
return err
}
err = inst.DeferTemplateApply(instance.TemplateTriggerCreate)
if err != nil {
return err
}
revert.Success()
return nil
}
// CreateInstanceFromBackup restores a backup file onto the storage device. Because the backup file
// is unpacked and restored onto the storage device before the instance is created in the database
// it is necessary to return two functions; a post hook that can be run once the instance has been
// created in the database to run any storage layer finalisations, and a revert hook that can be
// run if the instance database load process fails that will remove anything created thus far.
func (b *backend) CreateInstanceFromBackup(srcBackup backup.Info, srcData io.ReadSeeker, op *operations.Operation) (func(instance.Instance) error, revert.Hook, error) {
l := b.logger.AddContext(logger.Ctx{"project": srcBackup.Project, "instance": srcBackup.Name, "snapshots": srcBackup.Snapshots, "optimizedStorage": *srcBackup.OptimizedStorage})
l.Debug("CreateInstanceFromBackup started")
defer l.Debug("CreateInstanceFromBackup finished")
// Get the volume name on storage.
volStorageName := project.Instance(srcBackup.Project, srcBackup.Name)
// Get the instance type.
instanceType, err := instancetype.New(string(srcBackup.Type))
if err != nil {
return nil, nil, err
}
// Get the volume type.
volType, err := InstanceTypeToVolumeType(instanceType)
if err != nil {
return nil, nil, err
}
contentType := drivers.ContentTypeFS
if volType == drivers.VolumeTypeVM {
contentType = drivers.ContentTypeBlock
}
var volumeConfig map[string]string
if srcBackup.Config != nil && srcBackup.Config.Volume != nil {
volumeConfig = srcBackup.Config.Volume.Config
}
// Get instance root size information.
if srcBackup.Config != nil && srcBackup.Config.Container != nil {
_, rootConfig, err := internalInstance.GetRootDiskDevice(srcBackup.Config.Container.ExpandedDevices)
if err == nil && rootConfig["size"] != "" {
if volumeConfig == nil {
volumeConfig = map[string]string{}
}
volumeConfig["size"] = rootConfig["size"]
}
}
vol := b.GetVolume(volType, contentType, volStorageName, volumeConfig)
importRevert := revert.New()
defer importRevert.Fail()
// Unpack the backup into the new storage volume(s).
volPostHook, revertHook, err := b.driver.CreateVolumeFromBackup(vol, srcBackup, srcData, op)
if err != nil {
return nil, nil, err
}
if revertHook != nil {
importRevert.Add(revertHook)
}
err = b.ensureInstanceSymlink(instanceType, srcBackup.Project, srcBackup.Name, vol.MountPath())
if err != nil {
return nil, nil, err
}
importRevert.Add(func() {
_ = b.removeInstanceSymlink(instanceType, srcBackup.Project, srcBackup.Name)
})
if len(srcBackup.Snapshots) > 0 {
err = b.ensureInstanceSnapshotSymlink(instanceType, srcBackup.Project, srcBackup.Name)
if err != nil {
return nil, nil, err
}
importRevert.Add(func() {
_ = b.removeInstanceSnapshotSymlinkIfUnused(instanceType, srcBackup.Project, srcBackup.Name)
})
}
// Make sure the size isn't part of the instance volume after initial creation.
if volumeConfig != nil {
delete(volumeConfig, "size")
}
// Update information in the backup.yaml file.
err = vol.MountTask(func(mountPath string, op *operations.Operation) error {
return backup.UpdateInstanceConfig(b.state.DB.Cluster, srcBackup, mountPath)
}, op)
if err != nil {
return nil, nil, fmt.Errorf("Error updating backup file: %w", err)
}
// Create a post hook function that will use the instance (that will be created) to setup a new volume
// containing the instance's root disk device's config so that the driver's post hook function can access
// that config to perform any post instance creation setup.
postHook := func(inst instance.Instance) error {
l.Debug("CreateInstanceFromBackup post hook started")
defer l.Debug("CreateInstanceFromBackup post hook finished")
postHookRevert := revert.New()
defer postHookRevert.Fail()
// Create database entry for new storage volume.
var volumeDescription string
var volumeConfig map[string]string
volumeCreationDate := inst.CreationDate()
if srcBackup.Config != nil && srcBackup.Config.Volume != nil {
// If the backup restore interface provides volume config use it, otherwise use
// default volume config for the storage pool.
volumeDescription = srcBackup.Config.Volume.Description
volumeConfig = srcBackup.Config.Volume.Config
// Use volume's creation date if available.
if !srcBackup.Config.Volume.CreatedAt.IsZero() {
volumeCreationDate = srcBackup.Config.Volume.CreatedAt
}
}
// Validate config and create database entry for new storage volume.
// Strip unsupported config keys (in case the export was made from a different type of storage pool).
err = VolumeDBCreate(b, inst.Project().Name, inst.Name(), volumeDescription, volType, false, volumeConfig, volumeCreationDate, time.Time{}, contentType, true, true)
if err != nil {
return err
}
postHookRevert.Add(func() { _ = VolumeDBDelete(b, inst.Project().Name, inst.Name(), volType) })
// Record new volume with authorizer.
err = b.state.Authorizer.AddStoragePoolVolume(b.state.ShutdownCtx, inst.Project().Name, b.Name(), volType.Singular(), inst.Name(), "")
if err != nil {
logger.Error("Failed to add storage volume to authorizer", logger.Ctx{"name": inst.Name(), "type": volType, "pool": b.Name(), "project": inst.Project().Name, "error": err})
}
postHookRevert.Add(func() {
_ = b.state.Authorizer.DeleteStoragePoolVolume(b.state.ShutdownCtx, inst.Project().Name, b.Name(), volType.Singular(), inst.Name(), "")
})
for i, backupFileSnap := range srcBackup.Snapshots {
var volumeSnapDescription string
var volumeSnapConfig map[string]string
var volumeSnapExpiryDate time.Time
var volumeSnapCreationDate time.Time
// Check if snapshot volume config is available for restore and matches snapshot name.
if srcBackup.Config != nil {
if len(srcBackup.Config.Snapshots) >= i-1 && srcBackup.Config.Snapshots[i] != nil && srcBackup.Config.Snapshots[i].Name == backupFileSnap {
// Use instance snapshot's creation date if snap info available.
volumeSnapCreationDate = srcBackup.Config.Snapshots[i].CreatedAt
}
if len(srcBackup.Config.VolumeSnapshots) >= i-1 && srcBackup.Config.VolumeSnapshots[i] != nil && srcBackup.Config.VolumeSnapshots[i].Name == backupFileSnap {
// If the backup restore interface provides volume snapshot config use it,
// otherwise use default volume config for the storage pool.
volumeSnapDescription = srcBackup.Config.VolumeSnapshots[i].Description
volumeSnapConfig = srcBackup.Config.VolumeSnapshots[i].Config
if srcBackup.Config.VolumeSnapshots[i].ExpiresAt != nil {
volumeSnapExpiryDate = *srcBackup.Config.VolumeSnapshots[i].ExpiresAt
}
// Use volume's creation date if available.
if !srcBackup.Config.VolumeSnapshots[i].CreatedAt.IsZero() {
volumeSnapCreationDate = srcBackup.Config.VolumeSnapshots[i].CreatedAt
}
}
}
newSnapshotName := drivers.GetSnapshotVolumeName(inst.Name(), backupFileSnap)
// Validate config and create database entry for new storage volume.
// Strip unsupported config keys (in case the export was made from a different type of storage pool).
err = VolumeDBCreate(b, inst.Project().Name, newSnapshotName, volumeSnapDescription, volType, true, volumeSnapConfig, volumeSnapCreationDate, volumeSnapExpiryDate, contentType, true, true)
if err != nil {
return err
}
postHookRevert.Add(func() { _ = VolumeDBDelete(b, inst.Project().Name, newSnapshotName, volType) })
}
// Generate the effective root device volume for instance.
volStorageName := project.Instance(inst.Project().Name, inst.Name())
vol := b.GetVolume(volType, contentType, volStorageName, volumeConfig)
err = b.applyInstanceRootDiskOverrides(inst, &vol)
if err != nil {
return err
}
// Save any changes that have occurred to the instance's config to the on-disk backup.yaml file.
err = b.UpdateInstanceBackupFile(inst, false, op)
if err != nil {
return fmt.Errorf("Failed updating backup file: %w", err)
}
// If the driver returned a post hook, run it now.
if volPostHook != nil {
// Initialize new volume containing root disk config supplied in instance.
err = volPostHook(vol)
if err != nil {
return err
}
}
rootDiskConf := vol.Config()
// Apply quota config from root device if its set. Should be done after driver's post hook if set
// so that any volume initialisation has been completed first.
if rootDiskConf["size"] != "" {
size := rootDiskConf["size"]
l.Debug("Applying volume quota from root disk config", logger.Ctx{"size": size})
allowUnsafeResize := false
if vol.Type() == drivers.VolumeTypeContainer {
// Enable allowUnsafeResize for container imports so that filesystem resize
// safety checks are avoided in order to allow more imports to succeed when
// otherwise the pre-resize estimated checks of resize2fs would prevent
// import. If there is truly insufficient size to complete the import the
// resize will still fail, but its OK as we will then delete the volume
// rather than leaving it in a corrupted state. We don't need to do this
// for non-container volumes (nor should we) because block volumes won't
// error if we shrink them too much, and custom volumes can be created at
// the correct size immediately and don't need a post-import resize step.
allowUnsafeResize = true
}
err = b.driver.SetVolumeQuota(vol, size, allowUnsafeResize, op)
if err != nil {
// The restored volume can end up being larger than the root disk config's size
// property due to the block boundary rounding some storage drivers use. As such
// if the restored volume is larger than the config's size and it cannot be shrunk
// to the equivalent size on the target storage driver, don't fail as the backup
// has still been restored successfully.
if errors.Is(err, drivers.ErrCannotBeShrunk) {
l.Warn("Could not apply volume quota from root disk config as restored volume cannot be shrunk", logger.Ctx{"size": size})
} else {
return fmt.Errorf("Failed applying volume quota to root disk: %w", err)
}
}
// Apply the filesystem volume quota (only when main volume is block).
if vol.IsVMBlock() {
vmStateSize := rootDiskConf["size.state"]
// Apply default VM config filesystem size if main volume size is specified and
// no custom vmStateSize is specified. This way if the main volume size is empty
// (i.e removing quota) then this will also pass empty quota for the config
// filesystem volume as well, allowing a former quota to be removed from both
// volumes.
if vmStateSize == "" && size != "" {
vmStateSize = b.driver.Info().DefaultVMBlockFilesystemSize
}
l.Debug("Applying filesystem volume quota from root disk config", logger.Ctx{"size.state": vmStateSize})