-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsize.go
522 lines (417 loc) · 11.9 KB
/
size.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
/*
Copyright 2024 The lvm2go Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package lvm2go
import (
"errors"
"fmt"
"log/slog"
"math"
"slices"
"strconv"
"strings"
"unicode"
)
var ErrInvalidSizeGEZero = errors.New("invalid size specified, must be greater than or equal to zero")
var ErrInvalidUnit = errors.New("invalid unit specified")
var ErrInvalidSizePrefix = fmt.Errorf("invalid size prefix specified, must be one of %v", prefixCandidates)
type SizePrefix rune
const (
SizePrefixNone SizePrefix = 0
SizePrefixMinus SizePrefix = '-'
SizePrefixPlus SizePrefix = '+'
)
var prefixCandidates = []SizePrefix{
SizePrefixMinus,
SizePrefixPlus,
}
const (
sizeArg = "--size"
metadataSizeArg = "--metadatasize"
poolMetadataSizeArg = "--poolmetadatasize"
virtualSizeArg = "--virtualsize"
chunkSizeArg = "--chunksize"
dataAlignmentArg = "--dataalignment"
dataAlignmentOffsetArg = "--dataalignmentoffset"
)
type Unit rune
func (unit Unit) String() string {
if unit == UnitUnknown {
return ""
}
return string(unit)
}
func (unit Unit) MarshalText() ([]byte, error) {
return []byte(unit.String()), nil
}
func (unit Unit) ApplyToArgs(args Arguments) error {
if unit == 0 {
return nil
}
if err := unit.Validate(); err != nil {
return err
}
args.AddOrReplace(fmt.Sprintf("--units=%s", unit.String()))
return nil
}
func (unit Unit) Validate() error {
var ok bool
for _, valid := range validUnits {
if valid == unit || strings.ToUpper(string(valid)) == string(unit) {
ok = true
}
}
if !ok {
return fmt.Errorf("%w: %s is not a valid unit", ErrInvalidUnit, unit)
}
return nil
}
func (unit Unit) ApplyToLVsOptions(opts *LVsOptions) {
opts.Unit = unit
}
func (unit Unit) ApplyToVGsOptions(opts *VGsOptions) {
opts.Unit = unit
}
func (unit Unit) ApplyToPVsOptions(opts *PVsOptions) {
opts.Unit = unit
}
const (
conversionFactor = 1024
UnitBytes Unit = 'b'
UnitKiB Unit = 'k'
UnitMiB Unit = 'm'
UnitGiB Unit = 'g'
UnitTiB Unit = 't'
UnitPiB Unit = 'p'
UnitEiB Unit = 'e'
UnitSector Unit = 's'
// UnitUnknown is used to represent the output unit when
// LVs or VGs are queried without specifying a unit. (--nosuffix)
UnitUnknown Unit = 0
)
var validUnits = []Unit{UnitBytes, UnitKiB, UnitMiB, UnitGiB, UnitTiB, UnitPiB, UnitEiB, UnitSector, UnitUnknown}
var InvalidSize = Size{Val: -1, Unit: UnitUnknown}
var InvalidPrefixedSize = PrefixedSize{SizePrefix: SizePrefixNone, Size: InvalidSize}
// IsUnitOrDigit returns true if the unit is a valid unit.
// a valid unit is defined as a unit that is a member of validUnits.
// if the unit is not part of a valid unit, IsUnitOrDigit checks if the unit is a digit.
func IsUnitOrDigit(unit Unit) bool {
for _, valid := range validUnits {
if valid == unit || strings.ToUpper(string(valid)) == string(unit) {
return true
}
}
return unicode.IsDigit(rune(unit))
}
// Size is an InputToParse number that accepts an optional unit.
// InputToParse units are always treated as base two values, regardless of capitalization, e.g.
// 'k' and 'K' both refer to 1024.
// The default InputToParse unit is specified by letter, followed by |UNIT.
// UNIT represents other possible InputToParse
// units: b is bytes, s is sectors of 512 bytes, k is KiB, m is MiB,
// g is GiB, t is TiB, p is PiB, e is EiB.
type Size struct {
Val float64
Unit
}
func (opt Size) Virtual() VirtualSize {
return VirtualSize(opt)
}
func (opt Size) ToPoolMetadata() PoolMetadataSize {
return PoolMetadataSize(opt)
}
func (opt Size) MarshalText() ([]byte, error) {
return []byte(opt.String()), nil
}
func (opt Size) ToExtents(extentSize uint64, percent ExtentPercent) (Extents, error) {
bytes, err := opt.ToUnit(UnitBytes)
if err != nil {
return Extents{}, err
}
extents := uint64(math.Ceil(bytes.Val / float64(extentSize)))
return NewExtents(extents, percent), nil
}
var conversionTable = map[Unit]float64{
UnitBytes: 0,
UnitKiB: 1,
UnitMiB: 2,
UnitGiB: 3,
UnitTiB: 4,
UnitPiB: 5,
UnitEiB: 6,
}
func convert(val float64, a, b Unit) float64 {
if a == UnitUnknown || b == UnitUnknown {
return val
}
if a == UnitSector {
val *= 512
a = UnitBytes
}
toSectorAtEnd := false
if b == UnitSector {
toSectorAtEnd = true
b = UnitBytes
}
if conversionTable[a] < conversionTable[b] {
val /= math.Pow(conversionFactor, conversionTable[b]-conversionTable[a])
} else {
val *= math.Pow(conversionFactor, conversionTable[a]-conversionTable[b])
}
if toSectorAtEnd {
val /= 512
}
return val
}
func (opt Size) IsEqualTo(other Size) (bool, error) {
if opt.Unit == other.Unit {
return opt.Val == other.Val, nil
}
optBytes, err := opt.ToUnit(UnitBytes)
if err != nil {
return false, err
}
otherBytes, err := other.ToUnit(UnitBytes)
if err != nil {
return false, err
}
return optBytes == otherBytes, nil
}
func (opt Size) ToUnit(unit Unit) (Size, error) {
if opt.Unit == unit {
return opt, nil
}
if !IsUnitOrDigit(unit) {
return InvalidSize, fmt.Errorf("%w: %s is neither a valid unit nor a digit", ErrInvalidUnit, unit)
}
if opt.Unit == UnitUnknown {
return InvalidSize, fmt.Errorf(
"%w: %q cannot be converted to %q, because the unit is unknown - a valid unit is required for conversion (if you meant to use bytes, specify the unit explicitly)",
ErrInvalidUnit,
opt,
unit,
)
}
return NewSize(convert(opt.Val, opt.Unit, unit), unit), nil
}
func (opt Size) String() string {
var precision int
if opt.Unit != UnitBytes {
precision = 2
}
val := strconv.FormatFloat(opt.Val, 'f', precision, 64)
if opt.Unit == UnitUnknown {
return val
}
return val + string(opt.Unit)
}
func MustParseSize(str string) Size {
size, err := ParseSize(str)
if err != nil {
panic(err)
}
return size
}
func ParseSizeLenient(str string) (Size, error) {
eval := strings.TrimSpace(str)
if len(eval) == 0 || eval == "0" {
return Size{Val: 0, Unit: UnitBytes}, nil
}
return ParseSize(str)
}
func ParseSize(str string) (Size, error) {
if len(str) == 0 {
return Size{Val: 0, Unit: UnitUnknown}, nil
}
var unit Unit
offset := 0
if len(str) > 1 && !unicode.IsDigit(rune(str[len(str)-1])) {
unit = Unit(unicode.ToLower(rune(str[len(str)-1])))
offset++
} else {
unit = UnitUnknown
}
if !IsUnitOrDigit(unit) {
return InvalidSize, fmt.Errorf("%w: %s is neither a valid unit nor a digit", ErrInvalidUnit, unit)
}
if prefix := str[0]; prefix == '<' || prefix == '>' {
slog.Warn("size string starts with '<' or '>', this is not supported by lvm2go without losing precision, specify the unit explicitly if possible", slog.String("size", str))
str = str[1:]
}
fval, err := strconv.ParseFloat(str[:len(str)-offset], 64)
if err != nil {
return InvalidSize, fmt.Errorf("the value of the size cannot be parsed: %w", err)
}
return NewSize(fval, unit), nil
}
func NewSize(value float64, unit Unit) Size {
return Size{
Val: value,
Unit: unit,
}
}
func (opt Size) Validate() error {
if opt.Val < 0 {
return ErrInvalidSizeGEZero
}
if !IsUnitOrDigit(opt.Unit) {
return ErrInvalidUnit
}
return nil
}
func (opt Size) ApplyToLVCreateOptions(opts *LVCreateOptions) {
opts.Size = opt
}
func (opt Size) ApplyToLVResizeOptions(opts *LVResizeOptions) {
opts.Size = opt
}
func (opt Size) ApplyToArgs(args Arguments) error {
return opt.applyToArgs(sizeArg, args)
}
func (opt Size) applyToArgs(arg string, args Arguments) error {
if err := opt.Validate(); err != nil {
return err
}
args.AddOrReplace(fmt.Sprintf("%s=%s", arg, opt.String()))
return nil
}
type PrefixedSize struct {
SizePrefix
Size
}
func MustParsePrefixedSize(str string) PrefixedSize {
opt, err := ParsePrefixedSize(str)
if err != nil {
panic(err)
}
return opt
}
func ParsePrefixedSize(str string) (PrefixedSize, error) {
if len(str) == 0 {
size, err := ParseSize(str)
if err != nil {
return InvalidPrefixedSize, err
}
return PrefixedSize{Size: size}, nil
}
prefix := SizePrefix(str[0])
if unicode.IsDigit(rune(prefix)) {
size, err := ParseSize(str)
if err != nil {
return InvalidPrefixedSize, err
}
return NewPrefixedSize(SizePrefixNone, size), nil
}
if !slices.Contains(prefixCandidates, prefix) {
return InvalidPrefixedSize, ErrInvalidSizePrefix
}
size, err := ParseSize(str[1:])
if err != nil {
return InvalidPrefixedSize, err
}
return NewPrefixedSize(prefix, size), nil
}
func NewPrefixedSize(prefix SizePrefix, size Size) PrefixedSize {
return PrefixedSize{
SizePrefix: prefix,
Size: size,
}
}
func (opt PrefixedSize) Validate() error {
if err := opt.Size.Validate(); err != nil {
return err
}
if opt.SizePrefix != 0 && !slices.Contains(prefixCandidates, opt.SizePrefix) {
return ErrInvalidSizePrefix
}
return nil
}
func (opt PrefixedSize) ApplyToArgs(args Arguments) error {
return opt.applyToArgs(sizeArg, args)
}
func (opt PrefixedSize) applyToArgs(arg string, args Arguments) error {
if err := opt.Validate(); err != nil {
return err
}
if opt.Val == 0 {
return nil
}
var sizeBuilder strings.Builder
if opt.SizePrefix != 0 {
sizeBuilder.WriteRune(rune(opt.SizePrefix))
}
sizeBuilder.WriteString(opt.Size.String())
args.AddOrReplace(fmt.Sprintf("%s=%s", arg, sizeBuilder.String()))
return nil
}
func (opt PrefixedSize) ApplyToLVResizeOptions(opts *LVResizeOptions) {
opts.PrefixedSize = opt
}
func (opt PrefixedSize) ApplyToLVExtendOptions(opts *LVExtendOptions) {
opts.PrefixedSize = opt
}
type PoolMetadataPrefixedSize PrefixedSize
func (opt PoolMetadataPrefixedSize) ApplyToArgs(args Arguments) error {
return PrefixedSize(opt).applyToArgs(poolMetadataSizeArg, args)
}
type PoolMetadataSize Size
func (opt PoolMetadataSize) ApplyToArgs(args Arguments) error {
return Size(opt).applyToArgs(poolMetadataSizeArg, args)
}
type VirtualSize Size
func (opt VirtualSize) ApplyToLVCreateOptions(opts *LVCreateOptions) {
opts.VirtualSize = opt
}
func (opt VirtualSize) ApplyToArgs(args Arguments) error {
return Size(opt).applyToArgs(virtualSizeArg, args)
}
type VirtualPrefixedSize PrefixedSize
func (opt VirtualPrefixedSize) ApplyToArgs(args Arguments) error {
return PrefixedSize(opt).applyToArgs(virtualSizeArg, args)
}
type ChunkSize Size
func (opt ChunkSize) ApplyToLVCreateOptions(opts *LVCreateOptions) {
opts.ChunkSize = opt
}
func (opt ChunkSize) ApplyToArgs(args Arguments) error {
return Size(opt).applyToArgs(chunkSizeArg, args)
}
type DataAlignment Size
func (opt DataAlignment) ApplyToArgs(args Arguments) error {
return Size(opt).applyToArgs(dataAlignmentArg, args)
}
func (opt DataAlignment) ApplyToVGCreateOptions(opts *VGCreateOptions) {
opts.DataAlignment = opt
}
func (opt DataAlignment) ApplyToPVCreateOptions(opts *PVCreateOptions) {
opts.DataAlignment = opt
}
type DataAlignmentOffset Size
func (opt DataAlignmentOffset) ApplyToArgs(args Arguments) error {
return Size(opt).applyToArgs(dataAlignmentOffsetArg, args)
}
func (opt DataAlignmentOffset) ApplyToVGCreateOptions(opts *VGCreateOptions) {
opts.DataAlignmentOffset = opt
}
func (opt DataAlignmentOffset) ApplyToPVCreateOptions(opts *PVCreateOptions) {
opts.DataAlignmentOffset = opt
}
type MetadataSize Size
func (opt MetadataSize) ApplyToArgs(args Arguments) error {
return Size(opt).applyToArgs(metadataSizeArg, args)
}
func (opt MetadataSize) ApplyToVGCreateOptions(opts *VGCreateOptions) {
opts.MetadataSize = opt
}
func (opt MetadataSize) ApplyToPVCreateOptions(opts *PVCreateOptions) {
opts.MetadataSize = opt
}