...
1 package opts
2
3 import (
4 "fmt"
5 "strconv"
6 "strings"
7
8 "github.com/docker/docker/api/types/blkiodev"
9 )
10
11
12 type ValidatorWeightFctType func(val string) (*blkiodev.WeightDevice, error)
13
14
15 func ValidateWeightDevice(val string) (*blkiodev.WeightDevice, error) {
16 k, v, ok := strings.Cut(val, ":")
17 if !ok || k == "" {
18 return nil, fmt.Errorf("bad format: %s", val)
19 }
20
21 if !strings.HasPrefix(k, "/dev/") {
22 return nil, fmt.Errorf("bad format for device path: %s", val)
23 }
24 weight, err := strconv.ParseUint(v, 10, 16)
25 if err != nil {
26 return nil, fmt.Errorf("invalid weight for device: %s", val)
27 }
28 if weight > 0 && (weight < 10 || weight > 1000) {
29 return nil, fmt.Errorf("invalid weight for device: %s", val)
30 }
31
32 return &blkiodev.WeightDevice{
33 Path: k,
34 Weight: uint16(weight),
35 }, nil
36 }
37
38
39 type WeightdeviceOpt struct {
40 values []*blkiodev.WeightDevice
41 validator ValidatorWeightFctType
42 }
43
44
45 func NewWeightdeviceOpt(validator ValidatorWeightFctType) WeightdeviceOpt {
46 return WeightdeviceOpt{
47 values: []*blkiodev.WeightDevice{},
48 validator: validator,
49 }
50 }
51
52
53 func (opt *WeightdeviceOpt) Set(val string) error {
54 var value *blkiodev.WeightDevice
55 if opt.validator != nil {
56 v, err := opt.validator(val)
57 if err != nil {
58 return err
59 }
60 value = v
61 }
62 opt.values = append(opt.values, value)
63 return nil
64 }
65
66
67 func (opt *WeightdeviceOpt) String() string {
68 out := make([]string, 0, len(opt.values))
69 for _, v := range opt.values {
70 out = append(out, v.String())
71 }
72
73 return fmt.Sprintf("%v", out)
74 }
75
76
77 func (opt *WeightdeviceOpt) GetList() []*blkiodev.WeightDevice {
78 return opt.values
79 }
80
81
82 func (opt *WeightdeviceOpt) Type() string {
83 return "list"
84 }
85
View as plain text