registry_test.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  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 etcdv2
  15. import (
  16. "fmt"
  17. "sync"
  18. "testing"
  19. "time"
  20. etcd "github.com/coreos/etcd/client"
  21. "golang.org/x/net/context"
  22. "github.com/coreos/flannel/pkg/ip"
  23. . "github.com/coreos/flannel/subnet"
  24. )
  25. func newTestEtcdRegistry(t *testing.T) (Registry, *mockEtcd) {
  26. cfg := &EtcdConfig{
  27. Endpoints: []string{"http://127.0.0.1:4001", "http://127.0.0.1:2379"},
  28. Prefix: "/coreos.com/network",
  29. }
  30. r, err := newEtcdSubnetRegistry(cfg, func(c *EtcdConfig) (etcd.KeysAPI, error) {
  31. return newMockEtcd(), nil
  32. })
  33. if err != nil {
  34. t.Fatal("Failed to create etcd subnet registry")
  35. }
  36. return r, r.(*etcdSubnetRegistry).cli.(*mockEtcd)
  37. }
  38. func watchSubnets(t *testing.T, r Registry, ctx context.Context, sn ip.IP4Net, nextIndex uint64, result chan error) {
  39. type leaseEvent struct {
  40. etype EventType
  41. subnet ip.IP4Net
  42. found bool
  43. }
  44. expectedEvents := []leaseEvent{
  45. {EventAdded, sn, false},
  46. {EventRemoved, sn, false},
  47. }
  48. numFound := 0
  49. for {
  50. evt, index, err := r.watchSubnets(ctx, "foobar", nextIndex)
  51. switch {
  52. case err == nil:
  53. nextIndex = index
  54. for _, exp := range expectedEvents {
  55. if evt.Type != exp.etype {
  56. continue
  57. }
  58. if exp.found == true {
  59. result <- fmt.Errorf("Subnet event type already found: %v", exp)
  60. return
  61. }
  62. if !evt.Lease.Subnet.Equal(exp.subnet) {
  63. result <- fmt.Errorf("Subnet event lease %v mismatch (expected %v)", evt.Lease.Subnet, exp.subnet)
  64. }
  65. exp.found = true
  66. numFound += 1
  67. }
  68. if numFound == len(expectedEvents) {
  69. // All done; success
  70. result <- nil
  71. return
  72. }
  73. case isIndexTooSmall(err):
  74. nextIndex = err.(etcd.Error).Index
  75. default:
  76. result <- fmt.Errorf("Error watching subnet leases: %v", err)
  77. return
  78. }
  79. }
  80. }
  81. func TestEtcdRegistry(t *testing.T) {
  82. r, m := newTestEtcdRegistry(t)
  83. ctx, _ := context.WithCancel(context.Background())
  84. networks, _, err := r.getNetworks(ctx)
  85. if err != nil {
  86. t.Fatal("Failed to get networks")
  87. }
  88. if len(networks) != 0 {
  89. t.Fatal("Networks should be empty")
  90. }
  91. // Populate etcd with a network
  92. netKey := "/coreos.com/network/foobar/config"
  93. netValue := "{ \"Network\": \"10.1.0.0/16\", \"Backend\": { \"Type\": \"host-gw\" } }"
  94. m.Create(ctx, netKey, netValue)
  95. networks, _, err = r.getNetworks(ctx)
  96. if err != nil {
  97. t.Fatal("Failed to get networks the second time")
  98. }
  99. if len(networks) != 1 {
  100. t.Fatal("Failed to find expected network foobar")
  101. }
  102. config, err := r.getNetworkConfig(ctx, "foobar")
  103. if err != nil {
  104. t.Fatal("Failed to get network config")
  105. }
  106. if config != netValue {
  107. t.Fatal("Failed to match network config")
  108. }
  109. sn := ip.IP4Net{
  110. IP: ip.MustParseIP4("10.1.5.0"),
  111. PrefixLen: 24,
  112. }
  113. wg := sync.WaitGroup{}
  114. wg.Add(1)
  115. startWg := sync.WaitGroup{}
  116. startWg.Add(1)
  117. result := make(chan error, 1)
  118. go func() {
  119. startWg.Done()
  120. watchSubnets(t, r, ctx, sn, m.index, result)
  121. wg.Done()
  122. }()
  123. startWg.Wait()
  124. // Lease a subnet for the network
  125. attrs := &LeaseAttrs{
  126. PublicIP: ip.MustParseIP4("1.2.3.4"),
  127. }
  128. exp, err := r.createSubnet(ctx, "foobar", sn, attrs, 24*time.Hour)
  129. if err != nil {
  130. t.Fatal("Failed to create subnet lease")
  131. }
  132. if !exp.After(time.Now()) {
  133. t.Fatalf("Subnet lease duration %v not in the future", exp)
  134. }
  135. // Make sure the lease got created
  136. resp, err := m.Get(ctx, "/coreos.com/network/foobar/subnets/10.1.5.0-24", nil)
  137. if err != nil {
  138. t.Fatalf("Failed to verify subnet lease directly in etcd: %v", err)
  139. }
  140. if resp == nil || resp.Node == nil {
  141. t.Fatal("Failed to retrive node in subnet lease")
  142. }
  143. if resp.Node.Value != "{\"PublicIP\":\"1.2.3.4\"}" {
  144. t.Fatalf("Unexpected subnet lease node %s value %s", resp.Node.Key, resp.Node.Value)
  145. }
  146. leases, _, err := r.getSubnets(ctx, "foobar")
  147. if len(leases) != 1 {
  148. t.Fatalf("Unexpected number of leases %d (expected 1)", len(leases))
  149. }
  150. if !leases[0].Subnet.Equal(sn) {
  151. t.Fatalf("Mismatched subnet %v (expected %v)", leases[0].Subnet, sn)
  152. }
  153. lease, _, err := r.getSubnet(ctx, "foobar", sn)
  154. if lease == nil {
  155. t.Fatal("Missing subnet lease")
  156. }
  157. err = r.deleteSubnet(ctx, "foobar", sn)
  158. if err != nil {
  159. t.Fatalf("Failed to delete subnet %v: %v", sn, err)
  160. }
  161. // Make sure the lease got deleted
  162. resp, err = m.Get(ctx, "/coreos.com/network/foobar/subnets/10.1.5.0-24", nil)
  163. if err == nil {
  164. t.Fatal("Unexpected success getting deleted subnet")
  165. }
  166. wg.Wait()
  167. // Check errors from watch goroutine
  168. watchResult := <-result
  169. if watchResult != nil {
  170. t.Fatalf("Error watching keys: %v", watchResult)
  171. }
  172. // TODO: watchSubnet and watchNetworks
  173. }