-
Notifications
You must be signed in to change notification settings - Fork 907
/
driver_common.go
601 lines (489 loc) · 19.5 KB
/
driver_common.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
package drivers
import (
"fmt"
"io"
"net/url"
"os/exec"
"regexp"
"strings"
"github.com/canonical/lxd/lxd/backup"
"github.com/canonical/lxd/lxd/instancewriter"
"github.com/canonical/lxd/lxd/migration"
"github.com/canonical/lxd/lxd/operations"
"github.com/canonical/lxd/lxd/project"
"github.com/canonical/lxd/lxd/state"
"github.com/canonical/lxd/lxd/storage/filesystem"
"github.com/canonical/lxd/shared"
"github.com/canonical/lxd/shared/api"
"github.com/canonical/lxd/shared/logger"
"github.com/canonical/lxd/shared/revert"
)
type common struct {
name string
config map[string]string
getVolID func(volType VolumeType, volName string) (int64, error)
commonRules *Validators
state *state.State
logger logger.Logger
patches map[string]func() error
}
func (d *common) init(state *state.State, name string, config map[string]string, logger logger.Logger, volIDFunc func(volType VolumeType, volName string) (int64, error), commonRules *Validators) {
d.name = name
d.config = config
d.getVolID = volIDFunc
d.commonRules = commonRules
d.state = state
d.logger = logger
}
// isRemote returns false indicating this driver does not use remote storage.
func (d *common) isRemote() bool {
return false
}
// validatePool validates a pool config against common rules and optional driver specific rules.
func (d *common) validatePool(config map[string]string, driverRules map[string]func(value string) error, volumeRules map[string]func(value string) error) error {
checkedFields := map[string]struct{}{}
// Get rules common for all drivers.
rules := d.commonRules.PoolRules()
// Merge driver specific rules into common rules.
for field, validator := range driverRules {
rules[field] = validator
}
// Add to pool volume configuration options as volume.* options.
// These will be used as default configuration options for volume.
for volRule, volValidator := range volumeRules {
rules[fmt.Sprintf("volume.%s", volRule)] = volValidator
}
// Run the validator against each field.
for k, validator := range rules {
checkedFields[k] = struct{}{} // Mark field as checked.
err := validator(config[k])
if err != nil {
return fmt.Errorf("Invalid value for option %q: %w", k, err)
}
}
// Look for any unchecked fields, as these are unknown fields and validation should fail.
for k := range config {
_, checked := checkedFields[k]
if checked {
continue
}
// User keys are not validated.
if strings.HasPrefix(k, "user.") {
continue
}
return fmt.Errorf("Invalid option %q", k)
}
return nil
}
// fillVolumeConfig populates volume config with defaults from pool.
// excludeKeys allow exclude some keys from copying to volume config.
// Sometimes that can be useful when copying is dependant from specific conditions
// and shouldn't be done in generic way.
func (d *common) fillVolumeConfig(vol *Volume, excludedKeys ...string) error {
for k := range d.config {
if !strings.HasPrefix(k, "volume.") {
continue
}
volKey := strings.TrimPrefix(k, "volume.")
isExcluded := false
for _, excludedKey := range excludedKeys {
if excludedKey == volKey {
isExcluded = true
break
}
}
if isExcluded {
continue
}
// If volume type is not custom or bucket, don't copy "size" property to volume config.
if (vol.volType != VolumeTypeCustom && vol.volType != VolumeTypeBucket) && volKey == "size" {
continue
}
// security.shifted and security.unmapped are only relevant for custom filesystem volumes.
if (vol.Type() != VolumeTypeCustom || vol.ContentType() != ContentTypeFS) && (volKey == "security.shifted" || volKey == "security.unmapped") {
continue
}
if vol.config[volKey] == "" {
vol.config[volKey] = d.config[k]
}
}
return nil
}
// FillVolumeConfig populate volume with default config.
func (d *common) FillVolumeConfig(vol Volume) error {
return d.fillVolumeConfig(&vol)
}
// validateVolume validates a volume config against common rules and optional driver specific rules.
// This functions has a removeUnknownKeys option that if set to true will remove any unknown fields
// (excluding those starting with "user.") which can be used when translating a volume config to a
// different storage driver that has different options.
func (d *common) validateVolume(vol Volume, driverRules map[string]func(value string) error, removeUnknownKeys bool) error {
checkedFields := map[string]struct{}{}
// Get rules common for all drivers.
rules := d.commonRules.VolumeRules(vol)
// Merge driver specific rules into common rules.
for field, validator := range driverRules {
rules[field] = validator
}
// Run the validator against each field.
for k, validator := range rules {
checkedFields[k] = struct{}{} // Mark field as checked.
err := validator(vol.config[k])
if err != nil {
return fmt.Errorf("Invalid value for volume %q option %q: %w", vol.name, k, err)
}
}
// Look for any unchecked fields, as these are unknown fields and validation should fail.
for k := range vol.config {
_, checked := checkedFields[k]
if checked {
continue
}
// User keys are not validated.
if strings.HasPrefix(k, "user.") {
continue
}
if !removeUnknownKeys {
return fmt.Errorf("Invalid option for volume %q option %q", vol.name, k)
}
delete(vol.config, k)
}
// If volume type is not custom or bucket, don't allow "size" property.
if (vol.volType != VolumeTypeCustom && vol.volType != VolumeTypeBucket) && vol.config["size"] != "" {
return fmt.Errorf("Volume %q property is not valid for volume type", "size")
}
// Check that security.unmapped and security.shifted are not set together.
if shared.IsTrue(vol.config["security.unmapped"]) && shared.IsTrue(vol.config["security.shifted"]) {
return fmt.Errorf("security.unmapped and security.shifted are mutually exclusive")
}
return nil
}
// MigrationTypes returns the type of transfer methods to be used when doing migrations between pools
// in preference order.
func (d *common) MigrationTypes(contentType ContentType, refresh bool, copySnapshots bool) []migration.Type {
var transportType migration.MigrationFSType
var rsyncFeatures []string
// Do not pass compression argument to rsync if the associated
// config key, that is rsync.compression, is set to false.
if shared.IsFalse(d.Config()["rsync.compression"]) {
rsyncFeatures = []string{"xattrs", "delete", "bidirectional"}
} else {
rsyncFeatures = []string{"xattrs", "delete", "compress", "bidirectional"}
}
if IsContentBlock(contentType) {
transportType = migration.MigrationFSType_BLOCK_AND_RSYNC
} else {
transportType = migration.MigrationFSType_RSYNC
}
return []migration.Type{
{
FSType: transportType,
Features: rsyncFeatures,
},
}
}
// Name returns the pool name.
func (d *common) Name() string {
return d.name
}
// Logger returns the current logger.
func (d *common) Logger() logger.Logger {
return d.logger
}
// Config returns the storage pool config (as a copy, so not modifiable).
func (d *common) Config() map[string]string {
confCopy := make(map[string]string, len(d.config))
for k, v := range d.config {
confCopy[k] = v
}
return confCopy
}
// ApplyPatch looks for a suitable patch and runs it.
func (d *common) ApplyPatch(name string) error {
if d.patches == nil {
return fmt.Errorf("The patch mechanism isn't implemented on pool %q", d.name)
}
// Locate the patch.
patch, ok := d.patches[name]
if !ok {
return fmt.Errorf("Patch %q isn't implemented on pool %q", name, d.name)
}
// Handle cases where a patch isn't needed.
if patch == nil {
return nil
}
return patch()
}
// moveGPTAltHeader moves the GPT alternative header to the end of the disk device supplied.
// If the device supplied is not detected as not being a GPT disk then no action is taken and nil is returned.
// If the required sgdisk command is not available a warning is logged, but no error is returned, as really it is
// the job of the VM quest to ensure the partitions are resized to the size of the disk (as LXD does not dicatate
// what partition structure (if any) the disk should have. However we do attempt to move the GPT alternative
// header where possible so that the backup header is where it is expected in case of any corruption with the
// primary header.
func (d *common) moveGPTAltHeader(devPath string) error {
path, err := exec.LookPath("sgdisk")
if err != nil {
d.logger.Warn("Skipped moving GPT alternative header to end of disk as sgdisk command not found", logger.Ctx{"dev": devPath})
return nil
}
_, err = shared.RunCommand(path, "--move-second-header", devPath)
if err == nil {
d.logger.Debug("Moved GPT alternative header to end of disk", logger.Ctx{"dev": devPath})
return nil
}
runErr, ok := err.(shared.RunError)
if ok {
exitError, ok := runErr.Unwrap().(*exec.ExitError)
if ok {
// sgdisk manpage says exit status 3 means:
// "Non-GPT disk detected and no -g option, but operation requires a write action".
if exitError.ExitCode() == 3 {
return nil // Non-error as non-GPT disk specified.
}
}
}
return err
}
// runFiller runs the supplied filler, and setting the returned volume size back into filler.
func (d *common) runFiller(vol Volume, devPath string, filler *VolumeFiller, allowUnsafeResize bool) error {
if filler == nil || filler.Fill == nil {
return nil
}
vol.driver.Logger().Debug("Running filler function", logger.Ctx{"dev": devPath, "path": vol.MountPath()})
volSize, err := filler.Fill(vol, devPath, allowUnsafeResize)
if err != nil {
return err
}
filler.Size = volSize
return nil
}
// CreateVolume creates a new storage volume on disk.
func (d *common) CreateVolume(vol Volume, filler *VolumeFiller, op *operations.Operation) error {
return ErrNotSupported
}
// CreateVolumeFromBackup re-creates a volume from its exported state.
func (d *common) CreateVolumeFromBackup(vol VolumeCopy, srcBackup backup.Info, srcData io.ReadSeeker, op *operations.Operation) (VolumePostHook, revert.Hook, error) {
return nil, nil, ErrNotSupported
}
// CreateVolumeFromCopy copies an existing storage volume (with or without snapshots) into a new volume.
func (d *common) CreateVolumeFromCopy(vol VolumeCopy, srcVol VolumeCopy, allowInconsistent bool, op *operations.Operation) error {
return ErrNotSupported
}
// CreateVolumeFromMigration creates a new volume (with or without snapshots) from a migration data stream.
func (d *common) CreateVolumeFromMigration(vol VolumeCopy, conn io.ReadWriteCloser, volTargetArgs migration.VolumeTargetArgs, preFiller *VolumeFiller, op *operations.Operation) error {
return ErrNotSupported
}
// RefreshVolume updates an existing volume to match the state of another.
func (d *common) RefreshVolume(vol VolumeCopy, srcVol VolumeCopy, refreshSnapshots []string, allowInconsistent bool, op *operations.Operation) error {
return ErrNotSupported
}
// DeleteVolume destroys the on-disk state of a volume.
func (d *common) DeleteVolume(vol Volume, op *operations.Operation) error {
return ErrNotSupported
}
// HasVolume indicates whether a specific volume exists on the storage pool.
func (d *common) HasVolume(vol Volume) (bool, error) {
return false, ErrNotSupported
}
// ValidateVolume validates the supplied volume config. Optionally removes invalid keys from the volume's config.
func (d *common) ValidateVolume(vol Volume, removeUnknownKeys bool) error {
return ErrNotSupported
}
// UpdateVolume applies the driver specific changes of a volume configuration change.
func (d *common) UpdateVolume(vol Volume, changedConfig map[string]string) error {
return ErrNotSupported
}
// GetVolumeUsage returns the disk space usage of a volume.
func (d *common) GetVolumeUsage(vol Volume) (int64, error) {
return -1, ErrNotSupported
}
// SetVolumeQuota applies a size limit on volume.
func (d *common) SetVolumeQuota(vol Volume, size string, allowUnsafeResize bool, op *operations.Operation) error {
return ErrNotSupported
}
// GetVolumeDiskPath returns the location of a root disk block device.
func (d *common) GetVolumeDiskPath(vol Volume) (string, error) {
return "", ErrNotSupported
}
// ListVolumes returns a list of LXD volumes in storage pool.
func (d *common) ListVolumes() ([]Volume, error) {
return nil, ErrNotSupported
}
// MountVolume sets up the volume for use.
func (d *common) MountVolume(vol Volume, op *operations.Operation) error {
return ErrNotSupported
}
// UnmountVolume clears any runtime state for the volume.
// As driver doesn't have volumes to unmount it returns false indicating the volume was already unmounted.
func (d *common) UnmountVolume(vol Volume, keepBlockDev bool, op *operations.Operation) (bool, error) {
return false, ErrNotSupported
}
// CanDelegateVolume checks whether the volume can be delegated.
func (d *common) CanDelegateVolume(vol Volume) bool {
return false
}
// DelegateVolume delegates a volume.
func (d *common) DelegateVolume(vol Volume, pid int) error {
return nil
}
// RenameVolume renames the volume and all related filesystem entries.
func (d *common) RenameVolume(vol Volume, newVolName string, op *operations.Operation) error {
return ErrNotSupported
}
// MigrateVolume streams the volume (with or without snapshots).
func (d *common) MigrateVolume(vol VolumeCopy, conn io.ReadWriteCloser, volSrcArgs *migration.VolumeSourceArgs, op *operations.Operation) error {
return ErrNotSupported
}
// BackupVolume creates an exported version of a volume.
func (d *common) BackupVolume(vol VolumeCopy, tarWriter *instancewriter.InstanceTarWriter, optimized bool, snapshots []string, op *operations.Operation) error {
return ErrNotSupported
}
// CreateVolumeSnapshot creates a new snapshot.
func (d *common) CreateVolumeSnapshot(snapVol Volume, op *operations.Operation) error {
return ErrNotSupported
}
// DeleteVolumeSnapshot deletes a snapshot.
func (d *common) DeleteVolumeSnapshot(snapVol Volume, op *operations.Operation) error {
return ErrNotSupported
}
// MountVolumeSnapshot makes the snapshot available for use.
func (d *common) MountVolumeSnapshot(snapVol Volume, op *operations.Operation) error {
return ErrNotSupported
}
// UnmountVolumeSnapshot clears any runtime state for the snapshot.
func (d *common) UnmountVolumeSnapshot(snapVol Volume, op *operations.Operation) (bool, error) {
return false, ErrNotSupported
}
// VolumeSnapshots returns a list of snapshots for the volume (in no particular order).
func (d *common) VolumeSnapshots(vol Volume, op *operations.Operation) ([]string, error) {
return nil, ErrNotSupported
}
// CheckVolumeSnapshots checks that the volume's snapshots, according to the storage driver, match those provided.
func (d *common) CheckVolumeSnapshots(vol Volume, snapVols []Volume, op *operations.Operation) error {
// Use the volume's driver reference to pick the actual method as implemented by the driver.
storageSnapshotNames, err := vol.driver.VolumeSnapshots(vol, op)
if err != nil {
return err
}
// Create a list of all wanted snapshots.
wantedSnapshotNames := make([]string, 0, len(snapVols))
for _, snap := range snapVols {
_, snapName, _ := api.GetParentAndSnapshotName(snap.name)
wantedSnapshotNames = append(wantedSnapshotNames, snapName)
}
// Check if the provided list of volume snapshots matches the ones from storage.
for _, wantedSnapshotName := range wantedSnapshotNames {
if !shared.ValueInSlice(wantedSnapshotName, storageSnapshotNames) {
return fmt.Errorf("Snapshot %q expected but not in storage", wantedSnapshotName)
}
}
// Check if the snapshots in storage match the ones from the provided list.
for _, storageSnapshotName := range storageSnapshotNames {
if !shared.ValueInSlice(storageSnapshotName, wantedSnapshotNames) {
return fmt.Errorf("Snapshot %q in storage but not expected", storageSnapshotName)
}
}
return nil
}
// RestoreVolume resets a volume to its snapshotted state.
func (d *common) RestoreVolume(vol Volume, snapVol Volume, op *operations.Operation) error {
return ErrNotSupported
}
// RenameVolumeSnapshot renames a snapshot.
func (d *common) RenameVolumeSnapshot(snapVol Volume, newSnapshotName string, op *operations.Operation) error {
return ErrNotSupported
}
// ValidateBucket validates the supplied bucket name.
func (d *common) ValidateBucket(bucket Volume) error {
projectName, bucketName := project.StorageVolumeParts(bucket.name)
if projectName == "" {
return fmt.Errorf("Project prefix missing in bucket volume name")
}
match, err := regexp.MatchString(`^[a-z0-9][\-\.a-z0-9]{2,62}$`, bucketName)
if err != nil {
return err
}
if !match {
return fmt.Errorf("Bucket name must be between 3 and 63 lowercase letters, numbers, periods or hyphens and must start with a letter or number")
}
return nil
}
// GetBucketURL returns the URL of the specified bucket.
func (d *common) GetBucketURL(bucketName string) *url.URL {
return nil
}
// CreateBucket creates a new bucket.
func (d *common) CreateBucket(bucket Volume, op *operations.Operation) error {
return ErrNotSupported
}
// DeleteBucket deletes an existing bucket.
func (d *common) DeleteBucket(bucket Volume, op *operations.Operation) error {
return ErrNotSupported
}
// UpdateBucket updates an existing bucket.
func (d *common) UpdateBucket(bucket Volume, changedConfig map[string]string) error {
return ErrNotSupported
}
// ValidateBucketKey validates the supplied bucket key config.
func (d *common) ValidateBucketKey(keyName string, creds S3Credentials, roleName string) error {
if keyName == "" {
return fmt.Errorf("Key name is required")
}
validRoles := []string{"admin", "read-only"}
if !shared.ValueInSlice(roleName, validRoles) {
return fmt.Errorf("Invalid key role")
}
return nil
}
// CreateBucketKey create bucket key.
func (d *common) CreateBucketKey(bucket Volume, keyName string, creds S3Credentials, roleName string, op *operations.Operation) (*S3Credentials, error) {
return nil, ErrNotSupported
}
// UpdateBucketKey updates bucket key.
func (d *common) UpdateBucketKey(bucket Volume, keyName string, creds S3Credentials, roleName string, op *operations.Operation) (*S3Credentials, error) {
return nil, ErrNotSupported
}
// DeleteBucketKey deletes the bucket key.
func (d *common) DeleteBucketKey(bucket Volume, keyName string, op *operations.Operation) error {
return nil
}
// roundVolumeBlockSizeBytes returns size rounded to the nearest multiple of MinBlockBoundary bytes that is equal
// to or larger than sizeBytes.
func (d *common) roundVolumeBlockSizeBytes(sizeBytes int64) int64 {
// QEMU requires image files to be in traditional storage block boundaries.
// We use 8k here to ensure our images are compatible with all of our backend drivers.
if sizeBytes < MinBlockBoundary {
sizeBytes = MinBlockBoundary
}
roundedSizeBytes := int64(sizeBytes/MinBlockBoundary) * MinBlockBoundary
// Ensure the rounded size is at least the size specified in sizeBytes.
if roundedSizeBytes < sizeBytes {
roundedSizeBytes += MinBlockBoundary
}
return roundedSizeBytes
}
func (d *common) isBlockBacked(vol Volume) bool {
return vol.driver.Info().BlockBacking
}
// filesystemFreeze syncs and freezes a filesystem and returns an unfreeze function on success.
func (d *common) filesystemFreeze(path string) (func() error, error) {
err := filesystem.SyncFS(path)
if err != nil {
return nil, fmt.Errorf("Failed syncing filesystem %q: %w", path, err)
}
_, err = shared.RunCommand("fsfreeze", "--freeze", path)
if err != nil {
return nil, fmt.Errorf("Failed freezing filesystem %q: %w", path, err)
}
d.logger.Info("Filesystem frozen", logger.Ctx{"path": path})
unfreezeFS := func() error {
_, err := shared.RunCommand("fsfreeze", "--unfreeze", path)
if err != nil {
return fmt.Errorf("Failed unfreezing filesystem %q: %w", path, err)
}
d.logger.Info("Filesystem unfrozen", logger.Ctx{"path": path})
return nil
}
return unfreezeFS, nil
}