registry_test.go 4.7 KB

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