hostgw_network_test.go 2.2 KB

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