config.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // Copyright 2015 CoreOS, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package subnet
  15. import (
  16. "encoding/json"
  17. "errors"
  18. "github.com/coreos/flannel/pkg/ip"
  19. )
  20. type Config struct {
  21. Network ip.IP4Net
  22. SubnetMin ip.IP4
  23. SubnetMax ip.IP4
  24. SubnetLen uint
  25. Backend json.RawMessage `json:",omitempty"`
  26. }
  27. func ParseConfig(s string) (*Config, error) {
  28. cfg := new(Config)
  29. err := json.Unmarshal([]byte(s), cfg)
  30. if err != nil {
  31. return nil, err
  32. }
  33. if cfg.SubnetLen > 0 {
  34. if cfg.SubnetLen < cfg.Network.PrefixLen {
  35. return nil, errors.New("HostSubnet is larger network than Network")
  36. }
  37. } else {
  38. // try to give each host a /24 but if the whole network
  39. // is /24 or smaller, half the network
  40. if cfg.Network.PrefixLen < 24 {
  41. cfg.SubnetLen = 24
  42. } else {
  43. cfg.SubnetLen = cfg.Network.PrefixLen + 1
  44. }
  45. }
  46. subnetSize := ip.IP4(1 << (32 - cfg.SubnetLen))
  47. if cfg.SubnetMin == ip.IP4(0) {
  48. // skip over the first subnet otherwise it causes problems. e.g.
  49. // if Network is 10.100.0.0/16, having an interface with 10.0.0.0
  50. // makes ping think it's a broadcast address (not sure why)
  51. cfg.SubnetMin = cfg.Network.IP + subnetSize
  52. } else if !cfg.Network.Contains(cfg.SubnetMin) {
  53. return nil, errors.New("SubnetMin is not in the range of the Network")
  54. }
  55. if cfg.SubnetMax == ip.IP4(0) {
  56. cfg.SubnetMax = cfg.Network.Next().IP - subnetSize
  57. } else if !cfg.Network.Contains(cfg.SubnetMax) {
  58. return nil, errors.New("SubnetMax is not in the range of the Network")
  59. }
  60. return cfg, nil
  61. }