123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118 |
- package subnet
- import (
- "encoding/json"
- "errors"
- "fmt"
- "github.com/coreos/flannel/pkg/ip"
- )
- type Config struct {
- Network ip.IP4Net
- SubnetMin ip.IP4
- SubnetMax ip.IP4
- SubnetLen uint
- BackendType string `json:"-"`
- Backend json.RawMessage `json:",omitempty"`
- }
- func parseBackendType(be json.RawMessage) (string, error) {
- var bt struct {
- Type string
- }
- if len(be) == 0 {
- return "udp", nil
- } else if err := json.Unmarshal(be, &bt); err != nil {
- return "", fmt.Errorf("error decoding Backend property of config: %v", err)
- }
- return bt.Type, nil
- }
- func ParseConfig(s string) (*Config, error) {
- cfg := new(Config)
- err := json.Unmarshal([]byte(s), cfg)
- if err != nil {
- return nil, err
- }
- if cfg.SubnetLen > 0 {
-
- if cfg.SubnetLen > 30 {
- return nil, errors.New("SubnetLen must be less than /31")
- }
-
-
- if cfg.SubnetLen < cfg.Network.PrefixLen+2 {
- return nil, errors.New("Network must be able to accommodate at least four subnets")
- }
- } else {
-
-
-
- if cfg.Network.PrefixLen > 28 {
-
-
-
- return nil, errors.New("Network is too small. Minimum useful network prefix is /28")
- } else if cfg.Network.PrefixLen <= 22 {
-
- cfg.SubnetLen = 24
- } else {
-
- cfg.SubnetLen = cfg.Network.PrefixLen + 2
- }
- }
- subnetSize := ip.IP4(1 << (32 - cfg.SubnetLen))
- if cfg.SubnetMin == ip.IP4(0) {
-
-
-
- cfg.SubnetMin = cfg.Network.IP + subnetSize
- } else if !cfg.Network.Contains(cfg.SubnetMin) {
- return nil, errors.New("SubnetMin is not in the range of the Network")
- }
- if cfg.SubnetMax == ip.IP4(0) {
- cfg.SubnetMax = cfg.Network.Next().IP - subnetSize
- } else if !cfg.Network.Contains(cfg.SubnetMax) {
- return nil, errors.New("SubnetMax is not in the range of the Network")
- }
-
- mask := ip.IP4(0xFFFFFFFF << (32 - cfg.SubnetLen))
- if cfg.SubnetMin != cfg.SubnetMin&mask {
- return nil, fmt.Errorf("SubnetMin is not on a SubnetLen boundary: %v", cfg.SubnetMin)
- }
- if cfg.SubnetMax != cfg.SubnetMax&mask {
- return nil, fmt.Errorf("SubnetMax is not on a SubnetLen boundary: %v", cfg.SubnetMax)
- }
- bt, err := parseBackendType(cfg.Backend)
- if err != nil {
- return nil, err
- }
- cfg.BackendType = bt
- return cfg, nil
- }
|