subnet_test.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  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 subnet
  15. import (
  16. "encoding/json"
  17. "reflect"
  18. "testing"
  19. "time"
  20. etcd "github.com/coreos/flannel/Godeps/_workspace/src/github.com/coreos/etcd/client"
  21. "github.com/coreos/flannel/Godeps/_workspace/src/github.com/jonboulle/clockwork"
  22. "github.com/coreos/flannel/Godeps/_workspace/src/golang.org/x/net/context"
  23. "github.com/coreos/flannel/pkg/ip"
  24. )
  25. func newDummyRegistry() *MockSubnetRegistry {
  26. attrs := LeaseAttrs{
  27. PublicIP: ip.MustParseIP4("1.1.1.1"),
  28. }
  29. exp := time.Time{}
  30. subnets := []Lease{
  31. {ip.IP4Net{ip.MustParseIP4("10.3.1.0"), 24}, attrs, exp, 10},
  32. {ip.IP4Net{ip.MustParseIP4("10.3.2.0"), 24}, attrs, exp, 11},
  33. {ip.IP4Net{ip.MustParseIP4("10.3.4.0"), 24}, attrs, exp, 12},
  34. {ip.IP4Net{ip.MustParseIP4("10.3.5.0"), 24}, attrs, exp, 13},
  35. }
  36. config := `{ "Network": "10.3.0.0/16", "SubnetMin": "10.3.1.0", "SubnetMax": "10.3.5.0" }`
  37. return NewMockRegistry("_", config, subnets)
  38. }
  39. func TestAcquireLease(t *testing.T) {
  40. msr := newDummyRegistry()
  41. sm := NewMockManager(msr)
  42. extIaddr, _ := ip.ParseIP4("1.2.3.4")
  43. attrs := LeaseAttrs{
  44. PublicIP: extIaddr,
  45. }
  46. l, err := sm.AcquireLease(context.Background(), "_", &attrs)
  47. if err != nil {
  48. t.Fatal("AcquireLease failed: ", err)
  49. }
  50. if l.Subnet.String() != "10.3.3.0/24" {
  51. t.Fatal("Subnet mismatch: expected 10.3.3.0/24, got: ", l.Subnet)
  52. }
  53. // Acquire again, should reuse
  54. if l, err = sm.AcquireLease(context.Background(), "_", &attrs); err != nil {
  55. t.Fatal("AcquireLease failed: ", err)
  56. }
  57. if l.Subnet.String() != "10.3.3.0/24" {
  58. t.Fatal("Subnet mismatch: expected 10.3.3.0/24, got: ", l.Subnet)
  59. }
  60. }
  61. func TestConfigChanged(t *testing.T) {
  62. msr := newDummyRegistry()
  63. sm := NewMockManager(msr)
  64. extIaddr, _ := ip.ParseIP4("1.2.3.4")
  65. attrs := LeaseAttrs{
  66. PublicIP: extIaddr,
  67. }
  68. l, err := sm.AcquireLease(context.Background(), "_", &attrs)
  69. if err != nil {
  70. t.Fatal("AcquireLease failed: ", err)
  71. }
  72. if l.Subnet.String() != "10.3.3.0/24" {
  73. t.Fatal("Subnet mismatch: expected 10.3.3.0/24, got: ", l.Subnet)
  74. }
  75. // Change config
  76. config := `{ "Network": "10.4.0.0/16" }`
  77. msr.setConfig("_", config)
  78. // Acquire again, should not reuse
  79. if l, err = sm.AcquireLease(context.Background(), "_", &attrs); err != nil {
  80. t.Fatal("AcquireLease failed: ", err)
  81. }
  82. newNet := newIP4Net("10.4.0.0", 16)
  83. if !newNet.Contains(l.Subnet.IP) {
  84. t.Fatalf("Subnet mismatch: expected within %v, got: %v", newNet, l.Subnet)
  85. }
  86. }
  87. func newIP4Net(ipaddr string, prefix uint) ip.IP4Net {
  88. a, err := ip.ParseIP4(ipaddr)
  89. if err != nil {
  90. panic("failed to parse ipaddr")
  91. }
  92. return ip.IP4Net{
  93. IP: a,
  94. PrefixLen: prefix,
  95. }
  96. }
  97. func acquireLease(ctx context.Context, t *testing.T, sm Manager) *Lease {
  98. extIaddr, _ := ip.ParseIP4("1.2.3.4")
  99. attrs := LeaseAttrs{
  100. PublicIP: extIaddr,
  101. }
  102. l, err := sm.AcquireLease(ctx, "_", &attrs)
  103. if err != nil {
  104. t.Fatal("AcquireLease failed: ", err)
  105. }
  106. return l
  107. }
  108. func TestWatchLeaseAdded(t *testing.T) {
  109. msr := newDummyRegistry()
  110. sm := NewMockManager(msr)
  111. ctx, cancel := context.WithCancel(context.Background())
  112. defer cancel()
  113. l := acquireLease(ctx, t, sm)
  114. events := make(chan []Event)
  115. go WatchLeases(ctx, sm, "_", l, events)
  116. evtBatch := <-events
  117. for _, evt := range evtBatch {
  118. if evt.Lease.Key() == l.Key() {
  119. t.Errorf("WatchLeases returned our own lease")
  120. }
  121. }
  122. expected := ip.IP4Net{
  123. IP: ip.MustParseIP4("10.3.6.0"),
  124. PrefixLen: 24,
  125. }
  126. attrs := &LeaseAttrs{
  127. PublicIP: ip.MustParseIP4("1.1.1.1"),
  128. }
  129. msr.createSubnet(ctx, "_", expected, attrs, 0)
  130. evtBatch = <-events
  131. if len(evtBatch) != 1 {
  132. t.Fatalf("WatchLeases produced wrong sized event batch")
  133. }
  134. evt := evtBatch[0]
  135. if evt.Type != EventAdded {
  136. t.Fatalf("WatchLeases produced wrong event type")
  137. }
  138. actual := evt.Lease.Subnet
  139. if !actual.Equal(expected) {
  140. t.Errorf("WatchSubnet produced wrong subnet: expected %s, got %s", expected, actual)
  141. }
  142. }
  143. func TestWatchLeaseRemoved(t *testing.T) {
  144. msr := newDummyRegistry()
  145. sm := NewMockManager(msr)
  146. ctx, cancel := context.WithCancel(context.Background())
  147. defer cancel()
  148. l := acquireLease(ctx, t, sm)
  149. events := make(chan []Event)
  150. go WatchLeases(ctx, sm, "_", l, events)
  151. evtBatch := <-events
  152. for _, evt := range evtBatch {
  153. if evt.Lease.Key() == l.Key() {
  154. t.Errorf("WatchLeases returned our own lease")
  155. }
  156. }
  157. expected := ip.IP4Net{ip.MustParseIP4("10.3.4.0"), 24}
  158. msr.expireSubnet("_", expected)
  159. evtBatch = <-events
  160. if len(evtBatch) != 1 {
  161. t.Fatalf("WatchLeases produced wrong sized event batch")
  162. }
  163. evt := evtBatch[0]
  164. if evt.Type != EventRemoved {
  165. t.Fatalf("WatchLeases produced wrong event type")
  166. }
  167. actual := evt.Lease.Subnet
  168. if !actual.Equal(expected) {
  169. t.Errorf("WatchSubnet produced wrong subnet: expected %s, got %s", expected, actual)
  170. }
  171. }
  172. type leaseData struct {
  173. Dummy string
  174. }
  175. func TestRenewLease(t *testing.T) {
  176. msr := newDummyRegistry()
  177. sm := NewMockManager(msr)
  178. now := time.Now()
  179. fakeClock := clockwork.NewFakeClockAt(now)
  180. clock = fakeClock
  181. // Create LeaseAttrs
  182. extIaddr, _ := ip.ParseIP4("1.2.3.4")
  183. attrs := LeaseAttrs{
  184. PublicIP: extIaddr,
  185. BackendType: "vxlan",
  186. }
  187. ld, err := json.Marshal(&leaseData{Dummy: "test string"})
  188. if err != nil {
  189. t.Fatalf("Failed to marshal leaseData: %v", err)
  190. }
  191. attrs.BackendData = json.RawMessage(ld)
  192. // Acquire lease
  193. ctx, cancel := context.WithCancel(context.Background())
  194. defer cancel()
  195. l, err := sm.AcquireLease(ctx, "_", &attrs)
  196. if err != nil {
  197. t.Fatal("AcquireLease failed: ", err)
  198. }
  199. now = now.Add(subnetTTL)
  200. fakeClock.Advance(24 * time.Hour)
  201. if err := sm.RenewLease(ctx, "_", l); err != nil {
  202. t.Fatal("RenewLease failed: ", err)
  203. }
  204. // check that it's still good
  205. n, err := msr.getNetwork(ctx, "_")
  206. if err != nil {
  207. t.Error("Failed to renew lease: could not get networks: %v", err)
  208. }
  209. for _, sn := range n.subnets {
  210. if sn.Subnet.Equal(l.Subnet) {
  211. expected := now.Add(subnetTTL)
  212. if !sn.Expiration.Equal(expected) {
  213. t.Errorf("Failed to renew lease: bad expiration; expected %v, got %v", expected, sn.Expiration)
  214. }
  215. if !reflect.DeepEqual(sn.Attrs, attrs) {
  216. t.Errorf("LeaseAttrs changed: was %#v, now %#v", attrs, sn.Attrs)
  217. }
  218. return
  219. }
  220. }
  221. t.Fatalf("Failed to find acquired lease")
  222. }
  223. func TestLeaseRevoked(t *testing.T) {
  224. msr := newDummyRegistry()
  225. sm := NewMockManager(msr)
  226. ctx, cancel := context.WithCancel(context.Background())
  227. defer cancel()
  228. l := acquireLease(ctx, t, sm)
  229. if err := sm.RevokeLease(ctx, "_", l.Subnet); err != nil {
  230. t.Fatalf("RevokeLease failed: %v", err)
  231. }
  232. _, _, err := msr.getSubnet(ctx, "_", l.Subnet)
  233. if err == nil {
  234. t.Fatalf("Revoked lease still exists")
  235. }
  236. if etcdErr, ok := err.(etcd.Error); ok && etcdErr.Code != etcd.ErrorCodeKeyNotFound {
  237. t.Fatalf("getSubnets after revoked lease returned unexpected error: %v", err)
  238. }
  239. }
  240. func TestWatchGetNetworks(t *testing.T) {
  241. msr := newDummyRegistry()
  242. sm := NewMockManager(msr)
  243. ctx, cancel := context.WithCancel(context.Background())
  244. defer cancel()
  245. // Kill the previously added "_" network
  246. msr.DeleteNetwork(ctx, "_")
  247. expected := "foobar"
  248. msr.CreateNetwork(ctx, expected, `{"Network": "10.1.1.0/16", "Backend": {"Type": "bridge"}}`)
  249. resp, err := sm.WatchNetworks(ctx, nil)
  250. if err != nil {
  251. t.Errorf("WatchNetworks(nil) failed:", err)
  252. }
  253. if len(resp.Snapshot) != 1 {
  254. t.Errorf("WatchNetworks(nil) produced wrong number of networks: expected 1, got %d", len(resp.Snapshot))
  255. }
  256. if resp.Snapshot[0] != expected {
  257. t.Errorf("WatchNetworks(nil) produced wrong network: expected %s, got %s", expected, resp.Snapshot[0])
  258. }
  259. }
  260. func TestWatchNetworkAdded(t *testing.T) {
  261. msr := newDummyRegistry()
  262. sm := NewMockManager(msr)
  263. ctx, cancel := context.WithCancel(context.Background())
  264. defer cancel()
  265. events := make(chan []Event)
  266. go WatchNetworks(ctx, sm, events)
  267. // skip over the initial snapshot
  268. <-events
  269. expected := "foobar"
  270. msr.CreateNetwork(ctx, expected, `{"Network": "10.1.1.0/16", "Backend": {"Type": "bridge"}}`)
  271. evtBatch := <-events
  272. if len(evtBatch) != 1 {
  273. t.Fatalf("WatchNetworks produced wrong sized event batch")
  274. }
  275. evt := evtBatch[0]
  276. if evt.Type != EventAdded {
  277. t.Fatalf("WatchNetworks produced wrong event type")
  278. }
  279. actual := evt.Network
  280. if actual != expected {
  281. t.Errorf("WatchNetworks produced wrong network: expected %s, got %s", expected, actual)
  282. }
  283. }
  284. func TestWatchNetworkRemoved(t *testing.T) {
  285. msr := newDummyRegistry()
  286. sm := NewMockManager(msr)
  287. ctx, cancel := context.WithCancel(context.Background())
  288. defer cancel()
  289. events := make(chan []Event)
  290. go WatchNetworks(ctx, sm, events)
  291. // skip over the initial snapshot
  292. <-events
  293. expected := "blah"
  294. msr.CreateNetwork(ctx, expected, `{"Network": "10.1.1.0/16", "Backend": {"Type": "bridge"}}`)
  295. // skip over the create event
  296. <-events
  297. err := msr.DeleteNetwork(ctx, expected)
  298. if err != nil {
  299. t.Fatalf("WatchNetworks failed to delete the network")
  300. }
  301. evtBatch := <-events
  302. if len(evtBatch) != 1 {
  303. t.Fatalf("WatchNetworks produced wrong sized event batch")
  304. }
  305. evt := evtBatch[0]
  306. if evt.Type != EventRemoved {
  307. t.Fatalf("WatchNetworks produced wrong event type")
  308. }
  309. actual := evt.Network
  310. if actual != expected {
  311. t.Errorf("WatchNetwork produced wrong network: expected %s, got %s", expected, actual)
  312. }
  313. }