address_pools.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package opts
  2. import (
  3. "encoding/csv"
  4. "encoding/json"
  5. "fmt"
  6. "strconv"
  7. "strings"
  8. types "github.com/docker/docker/libnetwork/ipamutils"
  9. )
  10. // PoolsOpt is a Value type for parsing the default address pools definitions
  11. type PoolsOpt struct {
  12. Values []*types.NetworkToSplit
  13. }
  14. // UnmarshalJSON fills values structure info from JSON input
  15. func (p *PoolsOpt) UnmarshalJSON(raw []byte) error {
  16. return json.Unmarshal(raw, &(p.Values))
  17. }
  18. // Set predefined pools
  19. func (p *PoolsOpt) Set(value string) error {
  20. csvReader := csv.NewReader(strings.NewReader(value))
  21. fields, err := csvReader.Read()
  22. if err != nil {
  23. return err
  24. }
  25. poolsDef := types.NetworkToSplit{}
  26. for _, field := range fields {
  27. // TODO(thaJeztah): this should not be case-insensitive.
  28. key, val, ok := strings.Cut(strings.ToLower(field), "=")
  29. if !ok {
  30. return fmt.Errorf("invalid field '%s' must be a key=value pair", field)
  31. }
  32. switch key {
  33. case "base":
  34. poolsDef.Base = val
  35. case "size":
  36. size, err := strconv.Atoi(val)
  37. if err != nil {
  38. return fmt.Errorf("invalid size value: %q (must be integer): %v", value, err)
  39. }
  40. poolsDef.Size = size
  41. default:
  42. return fmt.Errorf("unexpected key '%s' in '%s'", key, field)
  43. }
  44. }
  45. p.Values = append(p.Values, &poolsDef)
  46. return nil
  47. }
  48. // Type returns the type of this option
  49. func (p *PoolsOpt) Type() string {
  50. return "pool-options"
  51. }
  52. // String returns a string repr of this option
  53. func (p *PoolsOpt) String() string {
  54. var pools []string
  55. for _, pool := range p.Values {
  56. repr := fmt.Sprintf("%s %d", pool.Base, pool.Size)
  57. pools = append(pools, repr)
  58. }
  59. return strings.Join(pools, ", ")
  60. }
  61. // Value returns the mounts
  62. func (p *PoolsOpt) Value() []*types.NetworkToSplit {
  63. return p.Values
  64. }
  65. // Name returns the flag name of this option
  66. func (p *PoolsOpt) Name() string {
  67. return "default-address-pools"
  68. }