weightdevice.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package opts
  2. import (
  3. "fmt"
  4. "strconv"
  5. "strings"
  6. "github.com/docker/docker/api/types/blkiodev"
  7. )
  8. // ValidatorWeightFctType defines a validator function that returns a validated struct and/or an error.
  9. type ValidatorWeightFctType func(val string) (*blkiodev.WeightDevice, error)
  10. // ValidateWeightDevice validates that the specified string has a valid device-weight format.
  11. func ValidateWeightDevice(val string) (*blkiodev.WeightDevice, error) {
  12. split := strings.SplitN(val, ":", 2)
  13. if len(split) != 2 {
  14. return nil, fmt.Errorf("bad format: %s", val)
  15. }
  16. if !strings.HasPrefix(split[0], "/dev/") {
  17. return nil, fmt.Errorf("bad format for device path: %s", val)
  18. }
  19. weight, err := strconv.ParseUint(split[1], 10, 0)
  20. if err != nil {
  21. return nil, fmt.Errorf("invalid weight for device: %s", val)
  22. }
  23. if weight > 0 && (weight < 10 || weight > 1000) {
  24. return nil, fmt.Errorf("invalid weight for device: %s", val)
  25. }
  26. return &blkiodev.WeightDevice{
  27. Path: split[0],
  28. Weight: uint16(weight),
  29. }, nil
  30. }
  31. // WeightdeviceOpt defines a map of WeightDevices
  32. type WeightdeviceOpt struct {
  33. values []*blkiodev.WeightDevice
  34. validator ValidatorWeightFctType
  35. }
  36. // NewWeightdeviceOpt creates a new WeightdeviceOpt
  37. func NewWeightdeviceOpt(validator ValidatorWeightFctType) WeightdeviceOpt {
  38. values := []*blkiodev.WeightDevice{}
  39. return WeightdeviceOpt{
  40. values: values,
  41. validator: validator,
  42. }
  43. }
  44. // Set validates a WeightDevice and sets its name as a key in WeightdeviceOpt
  45. func (opt *WeightdeviceOpt) Set(val string) error {
  46. var value *blkiodev.WeightDevice
  47. if opt.validator != nil {
  48. v, err := opt.validator(val)
  49. if err != nil {
  50. return err
  51. }
  52. value = v
  53. }
  54. (opt.values) = append((opt.values), value)
  55. return nil
  56. }
  57. // String returns WeightdeviceOpt values as a string.
  58. func (opt *WeightdeviceOpt) String() string {
  59. var out []string
  60. for _, v := range opt.values {
  61. out = append(out, v.String())
  62. }
  63. return fmt.Sprintf("%v", out)
  64. }
  65. // GetList returns a slice of pointers to WeightDevices.
  66. func (opt *WeightdeviceOpt) GetList() []*blkiodev.WeightDevice {
  67. var weightdevice []*blkiodev.WeightDevice
  68. for _, v := range opt.values {
  69. weightdevice = append(weightdevice, v)
  70. }
  71. return weightdevice
  72. }
  73. // Type returns the option type
  74. func (opt *WeightdeviceOpt) Type() string {
  75. return "list"
  76. }