github.com/demonoid81/moby@v0.0.0-20200517203328-62dd8e17c460/opts/address_pools.go (about)

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