vxlan.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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 vxlan
  15. import (
  16. "encoding/json"
  17. "fmt"
  18. "net"
  19. "sync"
  20. "time"
  21. log "github.com/coreos/flannel/Godeps/_workspace/src/github.com/golang/glog"
  22. "github.com/coreos/flannel/Godeps/_workspace/src/golang.org/x/net/context"
  23. "github.com/coreos/flannel/backend"
  24. "github.com/coreos/flannel/pkg/ip"
  25. "github.com/coreos/flannel/subnet"
  26. )
  27. const (
  28. defaultVNI = 1
  29. )
  30. type VXLANBackend struct {
  31. sm subnet.Manager
  32. network string
  33. config *subnet.Config
  34. cfg struct {
  35. VNI int
  36. Port int
  37. }
  38. lease *subnet.Lease
  39. dev *vxlanDevice
  40. ctx context.Context
  41. cancel context.CancelFunc
  42. wg sync.WaitGroup
  43. }
  44. func New(sm subnet.Manager, network string, config *subnet.Config) backend.Backend {
  45. ctx, cancel := context.WithCancel(context.Background())
  46. vb := &VXLANBackend{
  47. sm: sm,
  48. network: network,
  49. config: config,
  50. ctx: ctx,
  51. cancel: cancel,
  52. }
  53. vb.cfg.VNI = defaultVNI
  54. return vb
  55. }
  56. func newSubnetAttrs(pubIP net.IP, mac net.HardwareAddr) (*subnet.LeaseAttrs, error) {
  57. data, err := json.Marshal(&vxlanLeaseAttrs{hardwareAddr(mac)})
  58. if err != nil {
  59. return nil, err
  60. }
  61. return &subnet.LeaseAttrs{
  62. PublicIP: ip.FromIP(pubIP),
  63. BackendType: "vxlan",
  64. BackendData: json.RawMessage(data),
  65. }, nil
  66. }
  67. func (vb *VXLANBackend) Init(extIface *net.Interface, extIP net.IP) (*backend.SubnetDef, error) {
  68. // Parse our configuration
  69. if len(vb.config.Backend) > 0 {
  70. if err := json.Unmarshal(vb.config.Backend, &vb.cfg); err != nil {
  71. return nil, fmt.Errorf("error decoding VXLAN backend config: %v", err)
  72. }
  73. }
  74. devAttrs := vxlanDeviceAttrs{
  75. vni: uint32(vb.cfg.VNI),
  76. name: fmt.Sprintf("flannel.%v", vb.cfg.VNI),
  77. vtepIndex: extIface.Index,
  78. vtepAddr: extIP,
  79. vtepPort: vb.cfg.Port,
  80. }
  81. var err error
  82. for {
  83. vb.dev, err = newVXLANDevice(&devAttrs)
  84. if err == nil {
  85. break
  86. } else {
  87. log.Error("VXLAN init: ", err)
  88. log.Info("Retrying in 1 second...")
  89. // wait 1 sec before retrying
  90. time.Sleep(1 * time.Second)
  91. }
  92. }
  93. sa, err := newSubnetAttrs(extIP, vb.dev.MACAddr())
  94. if err != nil {
  95. return nil, err
  96. }
  97. l, err := vb.sm.AcquireLease(vb.ctx, vb.network, sa)
  98. switch err {
  99. case nil:
  100. vb.lease = l
  101. case context.Canceled, context.DeadlineExceeded:
  102. return nil, err
  103. default:
  104. return nil, fmt.Errorf("failed to acquire lease: %v", err)
  105. }
  106. // vxlan's subnet is that of the whole overlay network (e.g. /16)
  107. // and not that of the individual host (e.g. /24)
  108. vxlanNet := ip.IP4Net{
  109. IP: l.Subnet.IP,
  110. PrefixLen: vb.config.Network.PrefixLen,
  111. }
  112. if err = vb.dev.Configure(vxlanNet); err != nil {
  113. return nil, err
  114. }
  115. return &backend.SubnetDef{
  116. Net: l.Subnet,
  117. MTU: vb.dev.MTU(),
  118. }, nil
  119. }
  120. func (vb *VXLANBackend) Run() {
  121. vb.wg.Add(1)
  122. go func() {
  123. subnet.LeaseRenewer(vb.ctx, vb.sm, vb.network, vb.lease)
  124. log.Info("LeaseRenewer exited")
  125. vb.wg.Done()
  126. }()
  127. log.Info("Watching for new subnet leases")
  128. evts := make(chan []subnet.Event)
  129. vb.wg.Add(1)
  130. go func() {
  131. subnet.WatchLeases(vb.ctx, vb.sm, vb.network, evts)
  132. log.Info("WatchLeases exited")
  133. vb.wg.Done()
  134. }()
  135. defer vb.wg.Wait()
  136. for {
  137. select {
  138. case evtBatch := <-evts:
  139. vb.handleSubnetEvents(evtBatch)
  140. case <-vb.ctx.Done():
  141. return
  142. }
  143. }
  144. }
  145. func (vb *VXLANBackend) Stop() {
  146. vb.cancel()
  147. }
  148. func (vb *VXLANBackend) Name() string {
  149. return "VXLAN"
  150. }
  151. // So we can make it JSON (un)marshalable
  152. type hardwareAddr net.HardwareAddr
  153. func (hw hardwareAddr) MarshalJSON() ([]byte, error) {
  154. return []byte(fmt.Sprintf("%q", net.HardwareAddr(hw))), nil
  155. }
  156. func (hw *hardwareAddr) UnmarshalJSON(b []byte) error {
  157. if len(b) < 2 || b[0] != '"' || b[len(b)-1] != '"' {
  158. return fmt.Errorf("error parsing hardware addr")
  159. }
  160. b = b[1 : len(b)-1]
  161. mac, err := net.ParseMAC(string(b))
  162. if err != nil {
  163. return err
  164. }
  165. *hw = hardwareAddr(mac)
  166. return nil
  167. }
  168. type vxlanLeaseAttrs struct {
  169. VtepMAC hardwareAddr
  170. }
  171. func (vb *VXLANBackend) handleSubnetEvents(batch []subnet.Event) {
  172. for _, evt := range batch {
  173. switch evt.Type {
  174. case subnet.SubnetAdded:
  175. log.Info("Subnet added: ", evt.Lease.Subnet)
  176. if evt.Lease.Attrs.BackendType != "vxlan" {
  177. log.Warningf("Ignoring non-vxlan subnet: type=%v", evt.Lease.Attrs.BackendType)
  178. continue
  179. }
  180. var attrs vxlanLeaseAttrs
  181. if err := json.Unmarshal(evt.Lease.Attrs.BackendData, &attrs); err != nil {
  182. log.Error("Error decoding subnet lease JSON: ", err)
  183. continue
  184. }
  185. vb.dev.AddL2(neigh{IP: evt.Lease.Attrs.PublicIP, MAC: net.HardwareAddr(attrs.VtepMAC)})
  186. vb.dev.AddL3(neigh{IP: evt.Lease.Subnet.IP, MAC: net.HardwareAddr(attrs.VtepMAC)})
  187. vb.dev.AddRoute(evt.Lease.Subnet)
  188. case subnet.SubnetRemoved:
  189. log.Info("Subnet removed: ", evt.Lease.Subnet)
  190. if evt.Lease.Attrs.BackendType != "vxlan" {
  191. log.Warningf("Ignoring non-vxlan subnet: type=%v", evt.Lease.Attrs.BackendType)
  192. continue
  193. }
  194. var attrs vxlanLeaseAttrs
  195. if err := json.Unmarshal(evt.Lease.Attrs.BackendData, &attrs); err != nil {
  196. log.Error("Error decoding subnet lease JSON: ", err)
  197. continue
  198. }
  199. vb.dev.DelRoute(evt.Lease.Subnet)
  200. if len(attrs.VtepMAC) > 0 {
  201. vb.dev.DelL2(neigh{IP: evt.Lease.Attrs.PublicIP, MAC: net.HardwareAddr(attrs.VtepMAC)})
  202. vb.dev.DelL3(neigh{IP: evt.Lease.Subnet.IP, MAC: net.HardwareAddr(attrs.VtepMAC)})
  203. }
  204. default:
  205. log.Error("Internal error: unknown event type: ", int(evt.Type))
  206. }
  207. }
  208. }