vxlan.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. // Copyright 2015 flannel authors
  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. "bytes"
  17. "encoding/json"
  18. "fmt"
  19. "net"
  20. "sync"
  21. "time"
  22. log "github.com/coreos/flannel/Godeps/_workspace/src/github.com/golang/glog"
  23. "github.com/coreos/flannel/Godeps/_workspace/src/github.com/vishvananda/netlink"
  24. "github.com/coreos/flannel/Godeps/_workspace/src/golang.org/x/net/context"
  25. "github.com/coreos/flannel/backend"
  26. "github.com/coreos/flannel/pkg/ip"
  27. "github.com/coreos/flannel/subnet"
  28. )
  29. const (
  30. defaultVNI = 1
  31. )
  32. type VXLANBackend struct {
  33. sm subnet.Manager
  34. network string
  35. cfg struct {
  36. VNI int
  37. Port int
  38. }
  39. extIndex int
  40. extIaddr net.IP
  41. extEaddr net.IP
  42. lease *subnet.Lease
  43. dev *vxlanDevice
  44. rts routes
  45. }
  46. func New(sm subnet.Manager, extIface *net.Interface, extIaddr net.IP, extEaddr net.IP) (backend.Backend, error) {
  47. vb := &VXLANBackend{
  48. sm: sm,
  49. extIndex: extIface.Index,
  50. extIaddr: extIaddr,
  51. extEaddr: extEaddr,
  52. }
  53. vb.cfg.VNI = defaultVNI
  54. return vb, nil
  55. }
  56. func newSubnetAttrs(extEaddr 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(extEaddr),
  63. BackendType: "vxlan",
  64. BackendData: json.RawMessage(data),
  65. }, nil
  66. }
  67. func (vb *VXLANBackend) RegisterNetwork(ctx context.Context, network string, config *subnet.Config) (*backend.SubnetDef, error) {
  68. vb.network = network
  69. // Parse our configuration
  70. if len(config.Backend) > 0 {
  71. if err := json.Unmarshal(config.Backend, &vb.cfg); err != nil {
  72. return nil, fmt.Errorf("error decoding VXLAN backend config: %v", err)
  73. }
  74. }
  75. devAttrs := vxlanDeviceAttrs{
  76. vni: uint32(vb.cfg.VNI),
  77. name: fmt.Sprintf("flannel.%v", vb.cfg.VNI),
  78. vtepIndex: vb.extIndex,
  79. vtepAddr: vb.extIaddr,
  80. vtepPort: vb.cfg.Port,
  81. }
  82. var err error
  83. vb.dev, err = newVXLANDevice(&devAttrs)
  84. if err != nil {
  85. return nil, err
  86. }
  87. sa, err := newSubnetAttrs(vb.extEaddr, vb.dev.MACAddr())
  88. if err != nil {
  89. return nil, err
  90. }
  91. l, err := vb.sm.AcquireLease(ctx, vb.network, sa)
  92. switch err {
  93. case nil:
  94. vb.lease = l
  95. case context.Canceled, context.DeadlineExceeded:
  96. return nil, err
  97. default:
  98. return nil, fmt.Errorf("failed to acquire lease: %v", err)
  99. }
  100. // vxlan's subnet is that of the whole overlay network (e.g. /16)
  101. // and not that of the individual host (e.g. /24)
  102. vxlanNet := ip.IP4Net{
  103. IP: l.Subnet.IP,
  104. PrefixLen: config.Network.PrefixLen,
  105. }
  106. if err = vb.dev.Configure(vxlanNet); err != nil {
  107. return nil, err
  108. }
  109. return &backend.SubnetDef{
  110. Lease: l,
  111. MTU: vb.dev.MTU(),
  112. }, nil
  113. }
  114. func (vb *VXLANBackend) Run(ctx context.Context) {
  115. log.Info("Watching for L3 misses")
  116. misses := make(chan *netlink.Neigh, 100)
  117. // Unfrtunately MonitorMisses does not take a cancel channel
  118. // as there's no wait to interrupt netlink socket recv
  119. go vb.dev.MonitorMisses(misses)
  120. wg := sync.WaitGroup{}
  121. log.Info("Watching for new subnet leases")
  122. evts := make(chan []subnet.Event)
  123. wg.Add(1)
  124. go func() {
  125. subnet.WatchLeases(ctx, vb.sm, vb.network, vb.lease, evts)
  126. log.Info("WatchLeases exited")
  127. wg.Done()
  128. }()
  129. defer wg.Wait()
  130. initialEvtsBatch := <-evts
  131. for {
  132. err := vb.handleInitialSubnetEvents(initialEvtsBatch)
  133. if err == nil {
  134. break
  135. }
  136. log.Error(err, " About to retry")
  137. time.Sleep(time.Second)
  138. }
  139. for {
  140. select {
  141. case miss := <-misses:
  142. vb.handleMiss(miss)
  143. case evtBatch := <-evts:
  144. vb.handleSubnetEvents(evtBatch)
  145. case <-ctx.Done():
  146. return
  147. }
  148. }
  149. }
  150. func (vb *VXLANBackend) UnregisterNetwork(ctx context.Context, name string) {
  151. }
  152. // So we can make it JSON (un)marshalable
  153. type hardwareAddr net.HardwareAddr
  154. func (hw hardwareAddr) MarshalJSON() ([]byte, error) {
  155. return []byte(fmt.Sprintf("%q", net.HardwareAddr(hw))), nil
  156. }
  157. func (hw *hardwareAddr) UnmarshalJSON(b []byte) error {
  158. if len(b) < 2 || b[0] != '"' || b[len(b)-1] != '"' {
  159. return fmt.Errorf("error parsing hardware addr")
  160. }
  161. b = b[1 : len(b)-1]
  162. mac, err := net.ParseMAC(string(b))
  163. if err != nil {
  164. return err
  165. }
  166. *hw = hardwareAddr(mac)
  167. return nil
  168. }
  169. type vxlanLeaseAttrs struct {
  170. VtepMAC hardwareAddr
  171. }
  172. func (vb *VXLANBackend) handleSubnetEvents(batch []subnet.Event) {
  173. for _, evt := range batch {
  174. switch evt.Type {
  175. case subnet.EventAdded:
  176. log.Info("Subnet added: ", evt.Lease.Subnet)
  177. if evt.Lease.Attrs.BackendType != "vxlan" {
  178. log.Warningf("Ignoring non-vxlan subnet: type=%v", evt.Lease.Attrs.BackendType)
  179. continue
  180. }
  181. var attrs vxlanLeaseAttrs
  182. if err := json.Unmarshal(evt.Lease.Attrs.BackendData, &attrs); err != nil {
  183. log.Error("Error decoding subnet lease JSON: ", err)
  184. continue
  185. }
  186. vb.rts.set(evt.Lease.Subnet, net.HardwareAddr(attrs.VtepMAC))
  187. vb.dev.AddL2(neigh{IP: evt.Lease.Attrs.PublicIP, MAC: net.HardwareAddr(attrs.VtepMAC)})
  188. case subnet.EventRemoved:
  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. if len(attrs.VtepMAC) > 0 {
  200. vb.dev.DelL2(neigh{IP: evt.Lease.Attrs.PublicIP, MAC: net.HardwareAddr(attrs.VtepMAC)})
  201. }
  202. vb.rts.remove(evt.Lease.Subnet)
  203. default:
  204. log.Error("Internal error: unknown event type: ", int(evt.Type))
  205. }
  206. }
  207. }
  208. func (vb *VXLANBackend) handleInitialSubnetEvents(batch []subnet.Event) error {
  209. log.Infof("Handling initial subnet events")
  210. fdbTable, err := vb.dev.GetL2List()
  211. if err != nil {
  212. return fmt.Errorf("Error fetching L2 table: %v", err)
  213. }
  214. for _, fdbEntry := range fdbTable {
  215. log.Infof("fdb already populated with: %s %s ", fdbEntry.IP, fdbEntry.HardwareAddr)
  216. }
  217. evtMarker := make([]bool, len(batch))
  218. leaseAttrsList := make([]vxlanLeaseAttrs, len(batch))
  219. fdbEntryMarker := make([]bool, len(fdbTable))
  220. for i, evt := range batch {
  221. if evt.Lease.Attrs.BackendType != "vxlan" {
  222. log.Warningf("Ignoring non-vxlan subnet: type=%v", evt.Lease.Attrs.BackendType)
  223. evtMarker[i] = true
  224. continue
  225. }
  226. if err := json.Unmarshal(evt.Lease.Attrs.BackendData, &leaseAttrsList[i]); err != nil {
  227. log.Error("Error decoding subnet lease JSON: ", err)
  228. evtMarker[i] = true
  229. continue
  230. }
  231. for j, fdbEntry := range fdbTable {
  232. if evt.Lease.Attrs.PublicIP.ToIP().Equal(fdbEntry.IP) && bytes.Equal([]byte(leaseAttrsList[i].VtepMAC), []byte(fdbEntry.HardwareAddr)) {
  233. evtMarker[i] = true
  234. fdbEntryMarker[j] = true
  235. break
  236. }
  237. }
  238. vb.rts.set(evt.Lease.Subnet, net.HardwareAddr(leaseAttrsList[i].VtepMAC))
  239. }
  240. for j, marker := range fdbEntryMarker {
  241. if !marker && fdbTable[j].IP != nil {
  242. err := vb.dev.DelL2(neigh{IP: ip.FromIP(fdbTable[j].IP), MAC: fdbTable[j].HardwareAddr})
  243. if err != nil {
  244. log.Error("Delete L2 failed: ", err)
  245. }
  246. }
  247. }
  248. for i, marker := range evtMarker {
  249. if !marker {
  250. err := vb.dev.AddL2(neigh{IP: batch[i].Lease.Attrs.PublicIP, MAC: net.HardwareAddr(leaseAttrsList[i].VtepMAC)})
  251. if err != nil {
  252. log.Error("Add L2 failed: ", err)
  253. }
  254. }
  255. }
  256. return nil
  257. }
  258. func (vb *VXLANBackend) handleMiss(miss *netlink.Neigh) {
  259. switch {
  260. case len(miss.IP) == 0 && len(miss.HardwareAddr) == 0:
  261. log.Info("Ignoring nil miss")
  262. case len(miss.HardwareAddr) == 0:
  263. vb.handleL3Miss(miss)
  264. default:
  265. log.Infof("Ignoring not a miss: %v, %v", miss.HardwareAddr, miss.IP)
  266. }
  267. }
  268. func (vb *VXLANBackend) handleL3Miss(miss *netlink.Neigh) {
  269. log.Infof("L3 miss: %v", miss.IP)
  270. rt := vb.rts.findByNetwork(ip.FromIP(miss.IP))
  271. if rt == nil {
  272. log.Infof("Route for %v not found", miss.IP)
  273. return
  274. }
  275. if err := vb.dev.AddL3(neigh{IP: ip.FromIP(miss.IP), MAC: rt.vtepMAC}); err != nil {
  276. log.Errorf("AddL3 failed: %v", err)
  277. } else {
  278. log.Info("AddL3 succeeded")
  279. }
  280. }