registry_test.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  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. result <- fmt.Errorf("Should never get here")
  81. }
  82. func TestEtcdRegistry(t *testing.T) {
  83. r, m := newTestEtcdRegistry(t)
  84. ctx, _ := context.WithCancel(context.Background())
  85. networks, _, err := r.getNetworks(ctx)
  86. if err != nil {
  87. t.Fatal("Failed to get networks")
  88. }
  89. if len(networks) != 0 {
  90. t.Fatal("Networks should be empty")
  91. }
  92. // Populate etcd with a network
  93. netKey := "/coreos.com/network/foobar/config"
  94. netValue := "{ \"Network\": \"10.1.0.0/16\", \"Backend\": { \"Type\": \"host-gw\" } }"
  95. m.Create(ctx, netKey, netValue)
  96. networks, _, err = r.getNetworks(ctx)
  97. if err != nil {
  98. t.Fatal("Failed to get networks the second time")
  99. }
  100. if len(networks) != 1 {
  101. t.Fatal("Failed to find expected network foobar")
  102. }
  103. config, err := r.getNetworkConfig(ctx, "foobar")
  104. if err != nil {
  105. t.Fatal("Failed to get network config")
  106. }
  107. if config != netValue {
  108. t.Fatal("Failed to match network config")
  109. }
  110. sn := ip.IP4Net{
  111. IP: ip.MustParseIP4("10.1.5.0"),
  112. PrefixLen: 24,
  113. }
  114. wg := sync.WaitGroup{}
  115. wg.Add(1)
  116. startWg := sync.WaitGroup{}
  117. startWg.Add(1)
  118. result := make(chan error, 1)
  119. go func() {
  120. startWg.Done()
  121. watchSubnets(t, r, ctx, sn, m.index, result)
  122. wg.Done()
  123. }()
  124. startWg.Wait()
  125. // Lease a subnet for the network
  126. attrs := &LeaseAttrs{
  127. PublicIP: ip.MustParseIP4("1.2.3.4"),
  128. }
  129. exp, err := r.createSubnet(ctx, "foobar", sn, attrs, 24*time.Hour)
  130. if err != nil {
  131. t.Fatal("Failed to create subnet lease")
  132. }
  133. if !exp.After(time.Now()) {
  134. t.Fatal("Subnet lease duration %v not in the future", exp)
  135. }
  136. // Make sure the lease got created
  137. resp, err := m.Get(ctx, "/coreos.com/network/foobar/subnets/10.1.5.0-24", nil)
  138. if err != nil {
  139. t.Fatal("Failed to verify subnet lease directly in etcd: %v", err)
  140. }
  141. if resp == nil || resp.Node == nil {
  142. t.Fatal("Failed to retrive node in subnet lease")
  143. }
  144. if resp.Node.Value != "{\"PublicIP\":\"1.2.3.4\"}" {
  145. t.Fatal("Unexpected subnet lease node %s value %s", resp.Node.Key, resp.Node.Value)
  146. }
  147. leases, _, err := r.getSubnets(ctx, "foobar")
  148. if len(leases) != 1 {
  149. t.Fatalf("Unexpected number of leases %d (expected 1)", len(leases))
  150. }
  151. if !leases[0].Subnet.Equal(sn) {
  152. t.Fatalf("Mismatched subnet %v (expected %v)", leases[0].Subnet, sn)
  153. }
  154. lease, _, err := r.getSubnet(ctx, "foobar", sn)
  155. if lease == nil {
  156. t.Fatal("Missing subnet lease")
  157. }
  158. err = r.deleteSubnet(ctx, "foobar", sn)
  159. if err != nil {
  160. t.Fatalf("Failed to delete subnet %v: %v", sn, err)
  161. }
  162. // Make sure the lease got deleted
  163. resp, err = m.Get(ctx, "/coreos.com/network/foobar/subnets/10.1.5.0-24", nil)
  164. if err == nil {
  165. t.Fatal("Unexpected success getting deleted subnet")
  166. }
  167. wg.Wait()
  168. // Check errors from watch goroutine
  169. watchResult := <-result
  170. if watchResult != nil {
  171. t.Fatalf("Error watching keys: %v", watchResult)
  172. }
  173. // TODO: watchSubnet and watchNetworks
  174. }