forked from canonical/lxd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
storage.go
664 lines (569 loc) · 17.8 KB
/
storage.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
package main
import (
"encoding/json"
"fmt"
"io"
"os"
"reflect"
"sync"
"sync/atomic"
"syscall"
"github.com/gorilla/websocket"
"github.com/lxc/lxd/shared"
"github.com/lxc/lxd/shared/api"
"github.com/lxc/lxd/shared/ioprogress"
"github.com/lxc/lxd/shared/logger"
)
// lxdStorageLockMap is a hashmap that allows functions to check whether the
// operation they are about to perform is already in progress. If it is the
// channel can be used to wait for the operation to finish. If it is not, the
// function that wants to perform the operation should store its code in the
// hashmap.
// Note that any access to this map must be done while holding a lock.
var lxdStorageOngoingOperationMap = map[string]chan bool{}
// lxdStorageMapLock is used to access lxdStorageOngoingOperationMap.
var lxdStorageMapLock sync.Mutex
// The following functions are used to construct simple operation codes that are
// unique.
func getPoolMountLockID(poolName string) string {
return fmt.Sprintf("mount/pool/%s", poolName)
}
func getPoolUmountLockID(poolName string) string {
return fmt.Sprintf("umount/pool/%s", poolName)
}
func getImageCreateLockID(poolName string, fingerprint string) string {
return fmt.Sprintf("create/image/%s/%s", poolName, fingerprint)
}
func getContainerMountLockID(poolName string, containerName string) string {
return fmt.Sprintf("mount/container/%s/%s", poolName, containerName)
}
func getContainerUmountLockID(poolName string, containerName string) string {
return fmt.Sprintf("umount/container/%s/%s", poolName, containerName)
}
func getCustomMountLockID(poolName string, volumeName string) string {
return fmt.Sprintf("mount/custom/%s/%s", poolName, volumeName)
}
func getCustomUmountLockID(poolName string, volumeName string) string {
return fmt.Sprintf("umount/custom/%s/%s", poolName, volumeName)
}
// Simply cache used to storage the activated drivers on this LXD instance. This
// allows us to avoid querying the database everytime and API call is made.
var storagePoolDriversCacheInitialized bool
var storagePoolDriversCacheVal atomic.Value
var storagePoolDriversCacheLock sync.Mutex
func readStoragePoolDriversCache() []string {
drivers := storagePoolDriversCacheVal.Load()
if drivers == nil {
return []string{}
}
return drivers.([]string)
}
// Filesystem magic numbers
const (
filesystemSuperMagicTmpfs = 0x01021994
filesystemSuperMagicExt4 = 0xEF53
filesystemSuperMagicXfs = 0x58465342
filesystemSuperMagicNfs = 0x6969
filesystemSuperMagicZfs = 0x2fc12fc1
)
// filesystemDetect returns the filesystem on which the passed-in path sits.
func filesystemDetect(path string) (string, error) {
fs := syscall.Statfs_t{}
err := syscall.Statfs(path, &fs)
if err != nil {
return "", err
}
switch fs.Type {
case filesystemSuperMagicBtrfs:
return "btrfs", nil
case filesystemSuperMagicZfs:
return "zfs", nil
case filesystemSuperMagicTmpfs:
return "tmpfs", nil
case filesystemSuperMagicExt4:
return "ext4", nil
case filesystemSuperMagicXfs:
return "xfs", nil
case filesystemSuperMagicNfs:
return "nfs", nil
default:
logger.Debugf("Unknown backing filesystem type: 0x%x", fs.Type)
return string(fs.Type), nil
}
}
// storageType defines the type of a storage
type storageType int
const (
storageTypeBtrfs storageType = iota
storageTypeZfs
storageTypeLvm
storageTypeDir
storageTypeMock
)
var supportedStoragePoolDrivers = []string{"btrfs", "dir", "lvm", "zfs"}
func storageTypeToString(sType storageType) (string, error) {
switch sType {
case storageTypeBtrfs:
return "btrfs", nil
case storageTypeZfs:
return "zfs", nil
case storageTypeLvm:
return "lvm", nil
case storageTypeMock:
return "mock", nil
case storageTypeDir:
return "dir", nil
}
return "", fmt.Errorf("invalid storage type")
}
func storageStringToType(sName string) (storageType, error) {
switch sName {
case "btrfs":
return storageTypeBtrfs, nil
case "zfs":
return storageTypeZfs, nil
case "lvm":
return storageTypeLvm, nil
case "mock":
return storageTypeMock, nil
case "dir":
return storageTypeDir, nil
}
return -1, fmt.Errorf("invalid storage type name")
}
// The storage interface defines the functions needed to implement a storage
// backend for a given storage driver.
type storage interface {
// Functions dealing with basic driver properties only.
StorageCoreInit() error
GetStorageType() storageType
GetStorageTypeName() string
GetStorageTypeVersion() string
// Functions dealing with storage pools.
StoragePoolInit() error
StoragePoolCheck() error
StoragePoolCreate() error
StoragePoolDelete() error
StoragePoolMount() (bool, error)
StoragePoolUmount() (bool, error)
StoragePoolUpdate(writable *api.StoragePoolPut, changedConfig []string) error
GetStoragePoolWritable() api.StoragePoolPut
SetStoragePoolWritable(writable *api.StoragePoolPut)
// Functions dealing with custom storage volumes.
StoragePoolVolumeCreate() error
StoragePoolVolumeDelete() error
StoragePoolVolumeMount() (bool, error)
StoragePoolVolumeUmount() (bool, error)
StoragePoolVolumeUpdate(changedConfig []string) error
GetStoragePoolVolumeWritable() api.StorageVolumePut
SetStoragePoolVolumeWritable(writable *api.StorageVolumePut)
// Functions dealing with container storage volumes.
// ContainerCreate creates an empty container (no rootfs/metadata.yaml)
ContainerCreate(container container) error
// ContainerCreateFromImage creates a container from a image.
ContainerCreateFromImage(container container, imageFingerprint string) error
ContainerCanRestore(container container, sourceContainer container) error
ContainerDelete(container container) error
ContainerCopy(target container, source container, containerOnly bool) error
ContainerMount(c container) (bool, error)
ContainerUmount(name string, path string) (bool, error)
ContainerRename(container container, newName string) error
ContainerRestore(container container, sourceContainer container) error
ContainerSetQuota(container container, size int64) error
ContainerGetUsage(container container) (int64, error)
GetContainerPoolInfo() (int64, string)
ContainerStorageReady(name string) bool
ContainerSnapshotCreate(snapshotContainer container, sourceContainer container) error
ContainerSnapshotDelete(snapshotContainer container) error
ContainerSnapshotRename(snapshotContainer container, newName string) error
ContainerSnapshotStart(container container) (bool, error)
ContainerSnapshotStop(container container) (bool, error)
// For use in migrating snapshots.
ContainerSnapshotCreateEmpty(snapshotContainer container) error
// Functions dealing with image storage volumes.
ImageCreate(fingerprint string) error
ImageDelete(fingerprint string) error
ImageMount(fingerprint string) (bool, error)
ImageUmount(fingerprint string) (bool, error)
// Functions dealing with migration.
MigrationType() MigrationFSType
// Does this storage backend preserve inodes when it is moved across LXD
// hosts?
PreservesInodes() bool
// Get the pieces required to migrate the source. This contains a list
// of the "object" (i.e. container or snapshot, depending on whether or
// not it is a snapshot name) to be migrated in order, and a channel
// for arguments of the specific migration command. We use a channel
// here so we don't have to invoke `zfs send` or `rsync` or whatever
// and keep its stdin/stdout open for each snapshot during the course
// of migration, we can do it lazily.
//
// N.B. that the order here important: e.g. in btrfs/zfs, snapshots
// which are parents of other snapshots should be sent first, to save
// as much transfer as possible. However, the base container is always
// sent as the first object, since that is the grandparent of every
// snapshot.
//
// We leave sending containers which are snapshots of other containers
// already present on the target instance as an exercise for the
// enterprising developer.
MigrationSource(container container, containerOnly bool) (MigrationStorageSourceDriver, error)
MigrationSink(live bool, container container, objects []*Snapshot, conn *websocket.Conn, srcIdmap *shared.IdmapSet, op *operation, containerOnly bool) error
}
func storageCoreInit(driver string) (storage, error) {
sType, err := storageStringToType(driver)
if err != nil {
return nil, err
}
switch sType {
case storageTypeBtrfs:
btrfs := storageBtrfs{}
err = btrfs.StorageCoreInit()
if err != nil {
return nil, err
}
return &btrfs, nil
case storageTypeDir:
dir := storageDir{}
err = dir.StorageCoreInit()
if err != nil {
return nil, err
}
return &dir, nil
case storageTypeLvm:
lvm := storageLvm{}
err = lvm.StorageCoreInit()
if err != nil {
return nil, err
}
return &lvm, nil
case storageTypeMock:
mock := storageMock{}
err = mock.StorageCoreInit()
if err != nil {
return nil, err
}
return &mock, nil
case storageTypeZfs:
zfs := storageZfs{}
err = zfs.StorageCoreInit()
if err != nil {
return nil, err
}
return &zfs, nil
}
return nil, fmt.Errorf("invalid storage type")
}
func storageInit(d *Daemon, poolName string, volumeName string, volumeType int) (storage, error) {
// Load the storage pool.
poolID, pool, err := dbStoragePoolGet(d.db, poolName)
if err != nil {
return nil, err
}
driver := pool.Driver
if driver == "" {
// This shouldn't actually be possible but better safe than
// sorry.
return nil, fmt.Errorf("no storage driver was provided")
}
// Load the storage volume.
volume := &api.StorageVolume{}
if volumeName != "" && volumeType >= 0 {
_, volume, err = dbStoragePoolVolumeGetType(d.db, volumeName, volumeType, poolID)
if err != nil {
return nil, err
}
}
sType, err := storageStringToType(driver)
if err != nil {
return nil, err
}
switch sType {
case storageTypeBtrfs:
btrfs := storageBtrfs{}
btrfs.poolID = poolID
btrfs.pool = pool
btrfs.volume = volume
btrfs.d = d
err = btrfs.StoragePoolInit()
if err != nil {
return nil, err
}
return &btrfs, nil
case storageTypeDir:
dir := storageDir{}
dir.poolID = poolID
dir.pool = pool
dir.volume = volume
dir.d = d
err = dir.StoragePoolInit()
if err != nil {
return nil, err
}
return &dir, nil
case storageTypeLvm:
lvm := storageLvm{}
lvm.poolID = poolID
lvm.pool = pool
lvm.volume = volume
lvm.d = d
err = lvm.StoragePoolInit()
if err != nil {
return nil, err
}
return &lvm, nil
case storageTypeMock:
mock := storageMock{}
mock.poolID = poolID
mock.pool = pool
mock.volume = volume
mock.d = d
err = mock.StoragePoolInit()
if err != nil {
return nil, err
}
return &mock, nil
case storageTypeZfs:
zfs := storageZfs{}
zfs.poolID = poolID
zfs.pool = pool
zfs.volume = volume
zfs.d = d
err = zfs.StoragePoolInit()
if err != nil {
return nil, err
}
return &zfs, nil
}
return nil, fmt.Errorf("invalid storage type")
}
func storagePoolInit(d *Daemon, poolName string) (storage, error) {
return storageInit(d, poolName, "", -1)
}
func storagePoolVolumeInit(d *Daemon, poolName string, volumeName string, volumeType int) (storage, error) {
// No need to detect storage here, its a new container.
return storageInit(d, poolName, volumeName, volumeType)
}
func storagePoolVolumeImageInit(d *Daemon, poolName string, imageFingerprint string) (storage, error) {
return storagePoolVolumeInit(d, poolName, imageFingerprint, storagePoolVolumeTypeImage)
}
func storagePoolVolumeContainerCreateInit(d *Daemon, poolName string, containerName string) (storage, error) {
return storagePoolVolumeInit(d, poolName, containerName, storagePoolVolumeTypeContainer)
}
func storagePoolVolumeContainerLoadInit(d *Daemon, containerName string) (storage, error) {
// Get the storage pool of a given container.
poolName, err := dbContainerPool(d.db, containerName)
if err != nil {
return nil, err
}
return storagePoolVolumeInit(d, poolName, containerName, storagePoolVolumeTypeContainer)
}
// {LXD_DIR}/storage-pools/<pool>
func getStoragePoolMountPoint(poolName string) string {
return shared.VarPath("storage-pools", poolName)
}
// ${LXD_DIR}/storage-pools/<pool>containers/<container_name>
func getContainerMountPoint(poolName string, containerName string) string {
return shared.VarPath("storage-pools", poolName, "containers", containerName)
}
// ${LXD_DIR}/storage-pools/<pool>/snapshots/<snapshot_name>
func getSnapshotMountPoint(poolName string, snapshotName string) string {
return shared.VarPath("storage-pools", poolName, "snapshots", snapshotName)
}
// ${LXD_DIR}/storage-pools/<pool>/images/<fingerprint>
func getImageMountPoint(poolName string, fingerprint string) string {
return shared.VarPath("storage-pools", poolName, "images", fingerprint)
}
// ${LXD_DIR}/storage-pools/<pool>/custom/<storage_volume>
func getStoragePoolVolumeMountPoint(poolName string, volumeName string) string {
return shared.VarPath("storage-pools", poolName, "custom", volumeName)
}
func createContainerMountpoint(mountPoint string, mountPointSymlink string, privileged bool) error {
var mode os.FileMode
if privileged {
mode = 0700
} else {
mode = 0755
}
mntPointSymlinkExist := shared.PathExists(mountPointSymlink)
mntPointSymlinkTargetExist := shared.PathExists(mountPoint)
var err error
if !mntPointSymlinkTargetExist {
err = os.MkdirAll(mountPoint, 0755)
if err != nil {
return err
}
}
err = os.Chmod(mountPoint, mode)
if err != nil {
return err
}
if !mntPointSymlinkExist {
err := os.Symlink(mountPoint, mountPointSymlink)
if err != nil {
return err
}
}
return nil
}
func deleteContainerMountpoint(mountPoint string, mountPointSymlink string, storageTypeName string) error {
mntPointSuffix := storageTypeName
oldStyleMntPointSymlink := fmt.Sprintf("%s.%s", mountPointSymlink, mntPointSuffix)
if shared.PathExists(mountPointSymlink) {
err := os.Remove(mountPointSymlink)
if err != nil {
return err
}
}
if shared.PathExists(oldStyleMntPointSymlink) {
err := os.Remove(oldStyleMntPointSymlink)
if err != nil {
return err
}
}
if shared.PathExists(mountPoint) {
err := os.Remove(mountPoint)
if err != nil {
return err
}
}
return nil
}
func renameContainerMountpoint(oldMountPoint string, oldMountPointSymlink string, newMountPoint string, newMountPointSymlink string) error {
if shared.PathExists(oldMountPoint) {
err := os.Rename(oldMountPoint, newMountPoint)
if err != nil {
return err
}
}
// Rename the symlink target.
if shared.PathExists(oldMountPointSymlink) {
err := os.Remove(oldMountPointSymlink)
if err != nil {
return err
}
}
// Create the new symlink.
err := os.Symlink(newMountPoint, newMountPointSymlink)
if err != nil {
return err
}
return nil
}
func createSnapshotMountpoint(snapshotMountpoint string, snapshotsSymlinkTarget string, snapshotsSymlink string) error {
snapshotMntPointExists := shared.PathExists(snapshotMountpoint)
mntPointSymlinkExist := shared.PathExists(snapshotsSymlink)
if !snapshotMntPointExists {
err := os.MkdirAll(snapshotMountpoint, 0711)
if err != nil {
return err
}
}
if !mntPointSymlinkExist {
err := os.Symlink(snapshotsSymlinkTarget, snapshotsSymlink)
if err != nil {
return err
}
}
return nil
}
func deleteSnapshotMountpoint(snapshotMountpoint string, snapshotsSymlinkTarget string, snapshotsSymlink string) error {
if shared.PathExists(snapshotMountpoint) {
err := os.Remove(snapshotMountpoint)
if err != nil {
return err
}
}
couldRemove := false
if shared.PathExists(snapshotsSymlinkTarget) {
err := os.Remove(snapshotsSymlinkTarget)
if err == nil {
couldRemove = true
}
}
if couldRemove && shared.PathExists(snapshotsSymlink) {
err := os.Remove(snapshotsSymlink)
if err != nil {
return err
}
}
return nil
}
// ShiftIfNecessary sets the volatile.last_state.idmap key to the idmap last
// used by the container.
func ShiftIfNecessary(container container, srcIdmap *shared.IdmapSet) error {
dstIdmap, err := container.IdmapSet()
if err != nil {
return err
}
if dstIdmap == nil {
dstIdmap = new(shared.IdmapSet)
}
if !reflect.DeepEqual(srcIdmap, dstIdmap) {
var jsonIdmap string
if srcIdmap != nil {
idmapBytes, err := json.Marshal(srcIdmap.Idmap)
if err != nil {
return err
}
jsonIdmap = string(idmapBytes)
} else {
jsonIdmap = "[]"
}
err := container.ConfigKeySet("volatile.last_state.idmap", jsonIdmap)
if err != nil {
return err
}
}
return nil
}
func progressWrapperRender(op *operation, key string, description string, progressInt int64, speedInt int64) {
meta := op.metadata
if meta == nil {
meta = make(map[string]interface{})
}
progress := fmt.Sprintf("%s (%s/s)", shared.GetByteSizeString(progressInt, 2), shared.GetByteSizeString(speedInt, 2))
if description != "" {
progress = fmt.Sprintf("%s: %s (%s/s)", description, shared.GetByteSizeString(progressInt, 2), shared.GetByteSizeString(speedInt, 2))
}
if meta[key] != progress {
meta[key] = progress
op.UpdateMetadata(meta)
}
}
// StorageProgressReader reports the read progress.
func StorageProgressReader(op *operation, key string, description string) func(io.ReadCloser) io.ReadCloser {
return func(reader io.ReadCloser) io.ReadCloser {
if op == nil {
return reader
}
progress := func(progressInt int64, speedInt int64) {
progressWrapperRender(op, key, description, progressInt, speedInt)
}
readPipe := &ioprogress.ProgressReader{
ReadCloser: reader,
Tracker: &ioprogress.ProgressTracker{
Handler: progress,
},
}
return readPipe
}
}
// StorageProgressWriter reports the write progress.
func StorageProgressWriter(op *operation, key string, description string) func(io.WriteCloser) io.WriteCloser {
return func(writer io.WriteCloser) io.WriteCloser {
if op == nil {
return writer
}
progress := func(progressInt int64, speedInt int64) {
progressWrapperRender(op, key, description, progressInt, speedInt)
}
writePipe := &ioprogress.ProgressWriter{
WriteCloser: writer,
Tracker: &ioprogress.ProgressTracker{
Handler: progress,
},
}
return writePipe
}
}