hostgw_network_test.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. // +build !windows
  15. package hostgw
  16. import (
  17. "net"
  18. "runtime"
  19. "testing"
  20. "github.com/coreos/flannel/backend"
  21. "github.com/coreos/flannel/pkg/ip"
  22. "github.com/coreos/flannel/subnet"
  23. "github.com/vishvananda/netlink"
  24. "github.com/vishvananda/netns"
  25. )
  26. func TestRouteCache(t *testing.T) {
  27. runtime.LockOSThread()
  28. defer runtime.UnlockOSThread()
  29. origns, _ := netns.Get()
  30. defer origns.Close()
  31. newns, _ := netns.New()
  32. netns.Set(newns)
  33. defer newns.Close()
  34. lo, err := netlink.LinkByName("lo")
  35. if err != nil {
  36. t.Fatal(err)
  37. }
  38. if err := netlink.AddrAdd(lo, &netlink.Addr{IPNet: &net.IPNet{IP: net.ParseIP("127.0.0.1"), Mask: net.CIDRMask(32, 32)}}); err != nil {
  39. t.Fatal(err)
  40. }
  41. if err := netlink.LinkSetUp(lo); err != nil {
  42. t.Fatal(err)
  43. }
  44. nw := network{extIface: &backend.ExternalInterface{Iface: &net.Interface{Index: lo.Attrs().Index}}}
  45. gw1, gw2 := ip.FromIP(net.ParseIP("127.0.0.1")), ip.FromIP(net.ParseIP("127.0.0.2"))
  46. subnet1 := ip.IP4Net{IP: ip.FromIP(net.ParseIP("192.168.0.0")), PrefixLen: 24}
  47. nw.handleSubnetEvents([]subnet.Event{
  48. {Type: subnet.EventAdded, Lease: subnet.Lease{Subnet: subnet1, Attrs: subnet.LeaseAttrs{PublicIP: gw1, BackendType: "host-gw"}}},
  49. })
  50. if len(nw.rl) != 1 {
  51. t.Fatal(nw.rl)
  52. }
  53. if !routeEqual(nw.rl[0], netlink.Route{Dst: subnet1.ToIPNet(), Gw: gw1.ToIP()}) {
  54. t.Fatal(nw.rl[0])
  55. }
  56. // change gateway of previous route
  57. nw.handleSubnetEvents([]subnet.Event{
  58. {Type: subnet.EventAdded, Lease: subnet.Lease{
  59. Subnet: subnet1, Attrs: subnet.LeaseAttrs{PublicIP: gw2, BackendType: "host-gw"}}}})
  60. if len(nw.rl) != 1 {
  61. t.Fatal(nw.rl)
  62. }
  63. if !routeEqual(nw.rl[0], netlink.Route{Dst: subnet1.ToIPNet(), Gw: gw2.ToIP()}) {
  64. t.Fatal(nw.rl[0])
  65. }
  66. }