device.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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. "fmt"
  17. "net"
  18. "os"
  19. "syscall"
  20. "time"
  21. log "github.com/coreos/flannel/Godeps/_workspace/src/github.com/golang/glog"
  22. "github.com/coreos/flannel/Godeps/_workspace/src/github.com/vishvananda/netlink"
  23. "github.com/coreos/flannel/Godeps/_workspace/src/github.com/vishvananda/netlink/nl"
  24. "github.com/coreos/flannel/pkg/ip"
  25. )
  26. type vxlanDeviceAttrs struct {
  27. vni uint32
  28. name string
  29. vtepIndex int
  30. vtepAddr net.IP
  31. vtepPort int
  32. }
  33. type vxlanDevice struct {
  34. link *netlink.Vxlan
  35. }
  36. func sysctlSet(path, value string) error {
  37. f, err := os.Create(path)
  38. if err != nil {
  39. return err
  40. }
  41. defer f.Close()
  42. _, err = f.Write([]byte(value))
  43. return err
  44. }
  45. func newVXLANDevice(devAttrs *vxlanDeviceAttrs) (*vxlanDevice, error) {
  46. link := &netlink.Vxlan{
  47. LinkAttrs: netlink.LinkAttrs{
  48. Name: devAttrs.name,
  49. },
  50. VxlanId: int(devAttrs.vni),
  51. VtepDevIndex: devAttrs.vtepIndex,
  52. SrcAddr: devAttrs.vtepAddr,
  53. Port: devAttrs.vtepPort,
  54. Learning: true,
  55. Proxy: true,
  56. L2miss: true,
  57. }
  58. link, err := ensureLink(link)
  59. if err != nil {
  60. return nil, err
  61. }
  62. // this enables ARP requests being sent to userspace via netlink
  63. sysctlPath := fmt.Sprintf("/proc/sys/net/ipv4/neigh/%s/app_solicit", devAttrs.name)
  64. sysctlSet(sysctlPath, "3")
  65. return &vxlanDevice{
  66. link: link,
  67. }, nil
  68. }
  69. func ensureLink(vxlan *netlink.Vxlan) (*netlink.Vxlan, error) {
  70. err := netlink.LinkAdd(vxlan)
  71. if err == syscall.EEXIST {
  72. // it's ok if the device already exists as long as config is similar
  73. existing, err := netlink.LinkByName(vxlan.Name)
  74. if err != nil {
  75. return nil, err
  76. }
  77. incompat := vxlanLinksIncompat(vxlan, existing)
  78. if incompat == "" {
  79. return existing.(*netlink.Vxlan), nil
  80. }
  81. // delete existing
  82. log.Warningf("%q already exists with incompatable configuration: %v; recreating device", vxlan.Name, incompat)
  83. if err = netlink.LinkDel(existing); err != nil {
  84. return nil, fmt.Errorf("failed to delete interface: %v", err)
  85. }
  86. // create new
  87. if err = netlink.LinkAdd(vxlan); err != nil {
  88. return nil, fmt.Errorf("failed to create vxlan interface: %v", err)
  89. }
  90. } else if err != nil {
  91. return nil, err
  92. }
  93. ifindex := vxlan.Index
  94. link, err := netlink.LinkByIndex(vxlan.Index)
  95. if err != nil {
  96. return nil, fmt.Errorf("can't locate created vxlan device with index %v", ifindex)
  97. }
  98. var ok bool
  99. if vxlan, ok = link.(*netlink.Vxlan); !ok {
  100. return nil, fmt.Errorf("created vxlan device with index %v is not vxlan", ifindex)
  101. }
  102. return vxlan, nil
  103. }
  104. func (dev *vxlanDevice) Configure(ipn ip.IP4Net) error {
  105. setAddr4(dev.link, ipn.ToIPNet())
  106. if err := netlink.LinkSetUp(dev.link); err != nil {
  107. return fmt.Errorf("failed to set interface %s to UP state: %s", dev.link.Attrs().Name, err)
  108. }
  109. // explicitly add a route since there might be a route for a subnet already
  110. // installed by Docker and then it won't get auto added
  111. route := netlink.Route{
  112. LinkIndex: dev.link.Attrs().Index,
  113. Scope: netlink.SCOPE_UNIVERSE,
  114. Dst: ipn.Network().ToIPNet(),
  115. }
  116. if err := netlink.RouteAdd(&route); err != nil && err != syscall.EEXIST {
  117. return fmt.Errorf("failed to add route (%s -> %s): %v", ipn.Network().String(), dev.link.Attrs().Name, err)
  118. }
  119. return nil
  120. }
  121. func (dev *vxlanDevice) Destroy() {
  122. netlink.LinkDel(dev.link)
  123. }
  124. func (dev *vxlanDevice) MACAddr() net.HardwareAddr {
  125. return dev.link.HardwareAddr
  126. }
  127. func (dev *vxlanDevice) MTU() int {
  128. return dev.link.MTU
  129. }
  130. func (dev *vxlanDevice) MonitorMisses(misses chan *netlink.Neigh) {
  131. nlsock, err := nl.Subscribe(syscall.NETLINK_ROUTE, syscall.RTNLGRP_NEIGH)
  132. if err != nil {
  133. log.Error("Failed to subscribe to netlink RTNLGRP_NEIGH messages")
  134. return
  135. }
  136. for {
  137. msgs, err := nlsock.Receive()
  138. if err != nil {
  139. log.Errorf("Failed to receive from netlink: %v ", err)
  140. // wait 1 sec before retrying but honor the cancel channel
  141. time.Sleep(1 * time.Second)
  142. continue
  143. }
  144. for _, msg := range msgs {
  145. dev.processNeighMsg(msg, misses)
  146. }
  147. }
  148. }
  149. func isNeighResolving(state int) bool {
  150. return (state & (netlink.NUD_INCOMPLETE | netlink.NUD_STALE | netlink.NUD_DELAY | netlink.NUD_PROBE)) != 0
  151. }
  152. func (dev *vxlanDevice) processNeighMsg(msg syscall.NetlinkMessage, misses chan *netlink.Neigh) {
  153. neigh, err := netlink.NeighDeserialize(msg.Data)
  154. if err != nil {
  155. log.Error("Failed to deserialize netlink ndmsg: %v", err)
  156. return
  157. }
  158. if int(neigh.LinkIndex) != dev.link.Index {
  159. return
  160. }
  161. if msg.Header.Type != syscall.RTM_GETNEIGH && msg.Header.Type != syscall.RTM_NEWNEIGH {
  162. return
  163. }
  164. if !isNeighResolving(neigh.State) {
  165. // misses come with NUD_STALE bit set
  166. return
  167. }
  168. misses <- neigh
  169. }
  170. func (dev *vxlanDevice) AddL2(mac net.HardwareAddr, vtep net.IP) error {
  171. neigh := netlink.Neigh{
  172. LinkIndex: dev.link.Index,
  173. State: netlink.NUD_REACHABLE,
  174. Family: syscall.AF_BRIDGE,
  175. Flags: netlink.NTF_SELF,
  176. IP: vtep,
  177. HardwareAddr: mac,
  178. }
  179. log.Infof("calling NeighAdd: %v, %v", vtep, mac)
  180. return netlink.NeighAdd(&neigh)
  181. }
  182. func (dev *vxlanDevice) DelL2(mac net.HardwareAddr, vtep net.IP) error {
  183. neigh := netlink.Neigh{
  184. LinkIndex: dev.link.Index,
  185. Family: syscall.AF_BRIDGE,
  186. Flags: netlink.NTF_SELF,
  187. IP: vtep,
  188. HardwareAddr: mac,
  189. }
  190. log.Infof("calling NeighDel: %v, %v", vtep, mac)
  191. return netlink.NeighDel(&neigh)
  192. }
  193. func (dev *vxlanDevice) AddL3(ip net.IP, mac net.HardwareAddr) error {
  194. neigh := netlink.Neigh{
  195. LinkIndex: dev.link.Index,
  196. State: netlink.NUD_REACHABLE,
  197. Type: syscall.RTN_UNICAST,
  198. IP: ip,
  199. HardwareAddr: mac,
  200. }
  201. log.Infof("calling NeighSet: %v, %v", ip, mac)
  202. return netlink.NeighSet(&neigh)
  203. }
  204. func vxlanLinksIncompat(l1, l2 netlink.Link) string {
  205. if l1.Type() != l2.Type() {
  206. return fmt.Sprintf("link type: %v vs %v", l1.Type(), l2.Type())
  207. }
  208. v1 := l1.(*netlink.Vxlan)
  209. v2 := l2.(*netlink.Vxlan)
  210. if v1.VxlanId != v2.VxlanId {
  211. return fmt.Sprintf("vni: %v vs %v", v1.VxlanId, v2.VxlanId)
  212. }
  213. if v1.VtepDevIndex > 0 && v2.VtepDevIndex > 0 && v1.VtepDevIndex != v2.VtepDevIndex {
  214. return fmt.Sprintf("vtep (external) interface: %v vs %v", v1.VtepDevIndex, v2.VtepDevIndex)
  215. }
  216. if len(v1.SrcAddr) > 0 && len(v2.SrcAddr) > 0 && !v1.SrcAddr.Equal(v2.SrcAddr) {
  217. return fmt.Sprintf("vtep (external) IP: %v vs %v", v1.SrcAddr, v2.SrcAddr)
  218. }
  219. if len(v1.Group) > 0 && len(v2.Group) > 0 && !v1.Group.Equal(v2.Group) {
  220. return fmt.Sprintf("group address: %v vs %v", v1.Group, v2.Group)
  221. }
  222. if v1.L2miss != v2.L2miss {
  223. return fmt.Sprintf("l2miss: %v vs %v", v1.L2miss, v2.L2miss)
  224. }
  225. if v1.Port > 0 && v2.Port > 0 && v1.Port != v2.Port {
  226. return fmt.Sprintf("port: %v vs %v", v1.Port, v2.Port)
  227. }
  228. return ""
  229. }
  230. // sets IP4 addr on link removing any existing ones first
  231. func setAddr4(link *netlink.Vxlan, ipn *net.IPNet) error {
  232. addrs, err := netlink.AddrList(link, syscall.AF_INET)
  233. if err != nil {
  234. return err
  235. }
  236. for _, addr := range addrs {
  237. if err = netlink.AddrDel(link, &addr); err != nil {
  238. return fmt.Errorf("failed to delete IPv4 addr %s from %s", addr.String(), link.Attrs().Name)
  239. }
  240. }
  241. addr := netlink.Addr{ipn, ""}
  242. if err = netlink.AddrAdd(link, &addr); err != nil {
  243. return fmt.Errorf("failed to add IP address %s to %s: %s", ipn.String(), link.Attrs().Name, err)
  244. }
  245. return nil
  246. }