server_shutdown_test.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. // Copyright 2017 The etcd 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 integration
  15. import (
  16. "bytes"
  17. "context"
  18. "strings"
  19. "testing"
  20. "time"
  21. "github.com/coreos/etcd/clientv3"
  22. "github.com/coreos/etcd/etcdserver/api/v3rpc/rpctypes"
  23. "github.com/coreos/etcd/integration"
  24. "github.com/coreos/etcd/pkg/testutil"
  25. "google.golang.org/grpc/codes"
  26. "google.golang.org/grpc/status"
  27. )
  28. // TestBalancerUnderServerShutdownWatch expects that watch client
  29. // switch its endpoints when the member of the pinned endpoint fails.
  30. func TestBalancerUnderServerShutdownWatch(t *testing.T) {
  31. defer testutil.AfterTest(t)
  32. clus := integration.NewClusterV3(t, &integration.ClusterConfig{
  33. Size: 3,
  34. SkipCreatingClient: true,
  35. })
  36. defer clus.Terminate(t)
  37. eps := []string{clus.Members[0].GRPCAddr(), clus.Members[1].GRPCAddr(), clus.Members[2].GRPCAddr()}
  38. lead := clus.WaitLeader(t)
  39. // pin eps[lead]
  40. watchCli, err := clientv3.New(clientv3.Config{Endpoints: []string{eps[lead]}})
  41. if err != nil {
  42. t.Fatal(err)
  43. }
  44. defer watchCli.Close()
  45. // wait for eps[lead] to be pinned
  46. mustWaitPinReady(t, watchCli)
  47. // add all eps to list, so that when the original pined one fails
  48. // the client can switch to other available eps
  49. watchCli.SetEndpoints(eps...)
  50. key, val := "foo", "bar"
  51. wch := watchCli.Watch(context.Background(), key, clientv3.WithCreatedNotify())
  52. select {
  53. case <-wch:
  54. case <-time.After(3 * time.Second):
  55. t.Fatal("took too long to create watch")
  56. }
  57. donec := make(chan struct{})
  58. go func() {
  59. defer close(donec)
  60. // switch to others when eps[lead] is shut down
  61. select {
  62. case ev := <-wch:
  63. if werr := ev.Err(); werr != nil {
  64. t.Fatal(werr)
  65. }
  66. if len(ev.Events) != 1 {
  67. t.Fatalf("expected one event, got %+v", ev)
  68. }
  69. if !bytes.Equal(ev.Events[0].Kv.Value, []byte(val)) {
  70. t.Fatalf("expected %q, got %+v", val, ev.Events[0].Kv)
  71. }
  72. case <-time.After(7 * time.Second):
  73. t.Fatal("took too long to receive events")
  74. }
  75. }()
  76. // shut down eps[lead]
  77. clus.Members[lead].Terminate(t)
  78. // writes to eps[lead+1]
  79. putCli, err := clientv3.New(clientv3.Config{Endpoints: []string{eps[(lead+1)%3]}})
  80. if err != nil {
  81. t.Fatal(err)
  82. }
  83. defer putCli.Close()
  84. for {
  85. ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
  86. _, err = putCli.Put(ctx, key, val)
  87. cancel()
  88. if err == nil {
  89. break
  90. }
  91. if err == context.DeadlineExceeded || isServerCtxTimeout(err) || err == rpctypes.ErrTimeout || err == rpctypes.ErrTimeoutDueToLeaderFail {
  92. continue
  93. }
  94. t.Fatal(err)
  95. }
  96. select {
  97. case <-donec:
  98. case <-time.After(5 * time.Second): // enough time for balancer switch
  99. t.Fatal("took too long to receive events")
  100. }
  101. }
  102. func TestBalancerUnderServerShutdownPut(t *testing.T) {
  103. testBalancerUnderServerShutdownMutable(t, func(cli *clientv3.Client, ctx context.Context) error {
  104. _, err := cli.Put(ctx, "foo", "bar")
  105. return err
  106. })
  107. }
  108. func TestBalancerUnderServerShutdownDelete(t *testing.T) {
  109. testBalancerUnderServerShutdownMutable(t, func(cli *clientv3.Client, ctx context.Context) error {
  110. _, err := cli.Delete(ctx, "foo")
  111. return err
  112. })
  113. }
  114. func TestBalancerUnderServerShutdownTxn(t *testing.T) {
  115. testBalancerUnderServerShutdownMutable(t, func(cli *clientv3.Client, ctx context.Context) error {
  116. _, err := cli.Txn(ctx).
  117. If(clientv3.Compare(clientv3.Version("foo"), "=", 0)).
  118. Then(clientv3.OpPut("foo", "bar")).
  119. Else(clientv3.OpPut("foo", "baz")).Commit()
  120. return err
  121. })
  122. }
  123. // testBalancerUnderServerShutdownMutable expects that when the member of
  124. // the pinned endpoint is shut down, the balancer switches its endpoints
  125. // and all subsequent put/delete/txn requests succeed with new endpoints.
  126. func testBalancerUnderServerShutdownMutable(t *testing.T, op func(*clientv3.Client, context.Context) error) {
  127. defer testutil.AfterTest(t)
  128. clus := integration.NewClusterV3(t, &integration.ClusterConfig{
  129. Size: 3,
  130. SkipCreatingClient: true,
  131. })
  132. defer clus.Terminate(t)
  133. eps := []string{clus.Members[0].GRPCAddr(), clus.Members[1].GRPCAddr(), clus.Members[2].GRPCAddr()}
  134. // pin eps[0]
  135. cli, err := clientv3.New(clientv3.Config{Endpoints: []string{eps[0]}})
  136. if err != nil {
  137. t.Fatal(err)
  138. }
  139. defer cli.Close()
  140. // wait for eps[0] to be pinned
  141. mustWaitPinReady(t, cli)
  142. // add all eps to list, so that when the original pined one fails
  143. // the client can switch to other available eps
  144. cli.SetEndpoints(eps...)
  145. // shut down eps[0]
  146. clus.Members[0].Terminate(t)
  147. // switched to others when eps[0] was explicitly shut down
  148. // and following request should succeed
  149. // TODO: remove this (expose client connection state?)
  150. time.Sleep(time.Second)
  151. cctx, ccancel := context.WithTimeout(context.Background(), time.Second)
  152. err = op(cli, cctx)
  153. ccancel()
  154. if err != nil {
  155. t.Fatal(err)
  156. }
  157. }
  158. func TestBalancerUnderServerShutdownGetLinearizable(t *testing.T) {
  159. testBalancerUnderServerShutdownImmutable(t, func(cli *clientv3.Client, ctx context.Context) error {
  160. _, err := cli.Get(ctx, "foo")
  161. return err
  162. }, 7*time.Second) // give enough time for leader election, balancer switch
  163. }
  164. func TestBalancerUnderServerShutdownGetSerializable(t *testing.T) {
  165. testBalancerUnderServerShutdownImmutable(t, func(cli *clientv3.Client, ctx context.Context) error {
  166. _, err := cli.Get(ctx, "foo", clientv3.WithSerializable())
  167. return err
  168. }, 2*time.Second)
  169. }
  170. // testBalancerUnderServerShutdownImmutable expects that when the member of
  171. // the pinned endpoint is shut down, the balancer switches its endpoints
  172. // and all subsequent range requests succeed with new endpoints.
  173. func testBalancerUnderServerShutdownImmutable(t *testing.T, op func(*clientv3.Client, context.Context) error, timeout time.Duration) {
  174. defer testutil.AfterTest(t)
  175. clus := integration.NewClusterV3(t, &integration.ClusterConfig{
  176. Size: 3,
  177. SkipCreatingClient: true,
  178. })
  179. defer clus.Terminate(t)
  180. eps := []string{clus.Members[0].GRPCAddr(), clus.Members[1].GRPCAddr(), clus.Members[2].GRPCAddr()}
  181. // pin eps[0]
  182. cli, err := clientv3.New(clientv3.Config{Endpoints: []string{eps[0]}})
  183. if err != nil {
  184. t.Errorf("failed to create client: %v", err)
  185. }
  186. defer cli.Close()
  187. // wait for eps[0] to be pinned
  188. mustWaitPinReady(t, cli)
  189. // add all eps to list, so that when the original pined one fails
  190. // the client can switch to other available eps
  191. cli.SetEndpoints(eps...)
  192. // shut down eps[0]
  193. clus.Members[0].Terminate(t)
  194. // switched to others when eps[0] was explicitly shut down
  195. // and following request should succeed
  196. cctx, ccancel := context.WithTimeout(context.Background(), timeout)
  197. err = op(cli, cctx)
  198. ccancel()
  199. if err != nil {
  200. t.Errorf("failed to finish range request in time %v (timeout %v)", err, timeout)
  201. }
  202. }
  203. // e.g. due to clock drifts in server-side,
  204. // client context times out first in server-side
  205. // while original client-side context is not timed out yet
  206. func isServerCtxTimeout(err error) bool {
  207. if err == nil {
  208. return false
  209. }
  210. ev, _ := status.FromError(err)
  211. code := ev.Code()
  212. return code == codes.DeadlineExceeded && strings.Contains(err.Error(), "context deadline exceeded")
  213. }