vxlan.go 8.3 KB

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