network_partition_test.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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. // +build !cluster_proxy
  15. package integration
  16. import (
  17. "context"
  18. "errors"
  19. "testing"
  20. "time"
  21. "go.etcd.io/etcd/clientv3"
  22. "go.etcd.io/etcd/etcdserver/api/v3rpc/rpctypes"
  23. pb "go.etcd.io/etcd/etcdserver/etcdserverpb"
  24. "go.etcd.io/etcd/integration"
  25. "go.etcd.io/etcd/pkg/testutil"
  26. "google.golang.org/grpc"
  27. )
  28. var errExpected = errors.New("expected error")
  29. // TestBalancerUnderNetworkPartitionPut tests when one member becomes isolated,
  30. // first Put request fails, and following retry succeeds with client balancer
  31. // switching to others.
  32. func TestBalancerUnderNetworkPartitionPut(t *testing.T) {
  33. testBalancerUnderNetworkPartition(t, func(cli *clientv3.Client, ctx context.Context) error {
  34. _, err := cli.Put(ctx, "a", "b")
  35. if isClientTimeout(err) || isServerCtxTimeout(err) || err == rpctypes.ErrTimeout {
  36. return errExpected
  37. }
  38. return err
  39. }, time.Second)
  40. }
  41. func TestBalancerUnderNetworkPartitionDelete(t *testing.T) {
  42. testBalancerUnderNetworkPartition(t, func(cli *clientv3.Client, ctx context.Context) error {
  43. _, err := cli.Delete(ctx, "a")
  44. if isClientTimeout(err) || isServerCtxTimeout(err) || err == rpctypes.ErrTimeout {
  45. return errExpected
  46. }
  47. return err
  48. }, time.Second)
  49. }
  50. func TestBalancerUnderNetworkPartitionTxn(t *testing.T) {
  51. testBalancerUnderNetworkPartition(t, func(cli *clientv3.Client, ctx context.Context) error {
  52. _, err := cli.Txn(ctx).
  53. If(clientv3.Compare(clientv3.Version("foo"), "=", 0)).
  54. Then(clientv3.OpPut("foo", "bar")).
  55. Else(clientv3.OpPut("foo", "baz")).Commit()
  56. if isClientTimeout(err) || isServerCtxTimeout(err) || err == rpctypes.ErrTimeout {
  57. return errExpected
  58. }
  59. return err
  60. }, time.Second)
  61. }
  62. // TestBalancerUnderNetworkPartitionLinearizableGetWithLongTimeout tests
  63. // when one member becomes isolated, first quorum Get request succeeds
  64. // by switching endpoints within the timeout (long enough to cover endpoint switch).
  65. func TestBalancerUnderNetworkPartitionLinearizableGetWithLongTimeout(t *testing.T) {
  66. testBalancerUnderNetworkPartition(t, func(cli *clientv3.Client, ctx context.Context) error {
  67. _, err := cli.Get(ctx, "a")
  68. if err == rpctypes.ErrTimeout {
  69. return errExpected
  70. }
  71. return err
  72. }, 7*time.Second)
  73. }
  74. // TestBalancerUnderNetworkPartitionLinearizableGetWithShortTimeout tests
  75. // when one member becomes isolated, first quorum Get request fails,
  76. // and following retry succeeds with client balancer switching to others.
  77. func TestBalancerUnderNetworkPartitionLinearizableGetWithShortTimeout(t *testing.T) {
  78. testBalancerUnderNetworkPartition(t, func(cli *clientv3.Client, ctx context.Context) error {
  79. _, err := cli.Get(ctx, "a")
  80. if isClientTimeout(err) || isServerCtxTimeout(err) {
  81. return errExpected
  82. }
  83. return err
  84. }, time.Second)
  85. }
  86. func TestBalancerUnderNetworkPartitionSerializableGet(t *testing.T) {
  87. testBalancerUnderNetworkPartition(t, func(cli *clientv3.Client, ctx context.Context) error {
  88. _, err := cli.Get(ctx, "a", clientv3.WithSerializable())
  89. return err
  90. }, time.Second)
  91. }
  92. func testBalancerUnderNetworkPartition(t *testing.T, op func(*clientv3.Client, context.Context) error, timeout time.Duration) {
  93. defer testutil.AfterTest(t)
  94. clus := integration.NewClusterV3(t, &integration.ClusterConfig{
  95. Size: 3,
  96. SkipCreatingClient: true,
  97. })
  98. defer clus.Terminate(t)
  99. eps := []string{clus.Members[0].GRPCAddr(), clus.Members[1].GRPCAddr(), clus.Members[2].GRPCAddr()}
  100. // expect pin eps[0]
  101. ccfg := clientv3.Config{
  102. Endpoints: []string{eps[0]},
  103. DialTimeout: 3 * time.Second,
  104. DialOptions: []grpc.DialOption{grpc.WithBlock()},
  105. }
  106. cli, err := clientv3.New(ccfg)
  107. if err != nil {
  108. t.Fatal(err)
  109. }
  110. defer cli.Close()
  111. // wait for eps[0] to be pinned
  112. mustWaitPinReady(t, cli)
  113. // add other endpoints for later endpoint switch
  114. cli.SetEndpoints(eps...)
  115. time.Sleep(time.Second * 2)
  116. clus.Members[0].InjectPartition(t, clus.Members[1:]...)
  117. for i := 0; i < 5; i++ {
  118. ctx, cancel := context.WithTimeout(context.Background(), timeout)
  119. err = op(cli, ctx)
  120. cancel()
  121. if err == nil {
  122. break
  123. }
  124. if err != errExpected {
  125. t.Errorf("#%d: expected '%v', got '%v'", i, errExpected, err)
  126. }
  127. // give enough time for endpoint switch
  128. // TODO: remove random sleep by syncing directly with balancer
  129. if i == 0 {
  130. time.Sleep(5 * time.Second)
  131. }
  132. }
  133. if err != nil {
  134. t.Errorf("balancer did not switch in time (%v)", err)
  135. }
  136. }
  137. // TestBalancerUnderNetworkPartitionLinearizableGetLeaderElection ensures balancer
  138. // switches endpoint when leader fails and linearizable get requests returns
  139. // "etcdserver: request timed out".
  140. func TestBalancerUnderNetworkPartitionLinearizableGetLeaderElection(t *testing.T) {
  141. defer testutil.AfterTest(t)
  142. clus := integration.NewClusterV3(t, &integration.ClusterConfig{
  143. Size: 3,
  144. SkipCreatingClient: true,
  145. })
  146. defer clus.Terminate(t)
  147. eps := []string{clus.Members[0].GRPCAddr(), clus.Members[1].GRPCAddr(), clus.Members[2].GRPCAddr()}
  148. lead := clus.WaitLeader(t)
  149. timeout := 3 * clus.Members[(lead+1)%2].ServerConfig.ReqTimeout()
  150. cli, err := clientv3.New(clientv3.Config{
  151. Endpoints: []string{eps[(lead+1)%2]},
  152. DialTimeout: 2 * time.Second,
  153. DialOptions: []grpc.DialOption{grpc.WithBlock()},
  154. })
  155. if err != nil {
  156. t.Fatal(err)
  157. }
  158. defer cli.Close()
  159. // add all eps to list, so that when the original pined one fails
  160. // the client can switch to other available eps
  161. cli.SetEndpoints(eps[lead], eps[(lead+1)%2])
  162. // isolate leader
  163. clus.Members[lead].InjectPartition(t, clus.Members[(lead+1)%3], clus.Members[(lead+2)%3])
  164. // expects balancer to round robin to leader within two attempts
  165. for i := 0; i < 2; i++ {
  166. ctx, cancel := context.WithTimeout(context.TODO(), timeout)
  167. _, err = cli.Get(ctx, "a")
  168. cancel()
  169. if err == nil {
  170. break
  171. }
  172. }
  173. if err != nil {
  174. t.Fatal(err)
  175. }
  176. }
  177. func TestBalancerUnderNetworkPartitionWatchLeader(t *testing.T) {
  178. testBalancerUnderNetworkPartitionWatch(t, true)
  179. }
  180. func TestBalancerUnderNetworkPartitionWatchFollower(t *testing.T) {
  181. testBalancerUnderNetworkPartitionWatch(t, false)
  182. }
  183. // testBalancerUnderNetworkPartitionWatch ensures watch stream
  184. // to a partitioned node be closed when context requires leader.
  185. func testBalancerUnderNetworkPartitionWatch(t *testing.T, isolateLeader bool) {
  186. defer testutil.AfterTest(t)
  187. clus := integration.NewClusterV3(t, &integration.ClusterConfig{
  188. Size: 3,
  189. SkipCreatingClient: true,
  190. })
  191. defer clus.Terminate(t)
  192. eps := []string{clus.Members[0].GRPCAddr(), clus.Members[1].GRPCAddr(), clus.Members[2].GRPCAddr()}
  193. target := clus.WaitLeader(t)
  194. if !isolateLeader {
  195. target = (target + 1) % 3
  196. }
  197. // pin eps[target]
  198. watchCli, err := clientv3.New(clientv3.Config{Endpoints: []string{eps[target]}})
  199. if err != nil {
  200. t.Fatal(err)
  201. }
  202. defer watchCli.Close()
  203. // wait for eps[target] to be pinned
  204. mustWaitPinReady(t, watchCli)
  205. // add all eps to list, so that when the original pined one fails
  206. // the client can switch to other available eps
  207. watchCli.SetEndpoints(eps...)
  208. wch := watchCli.Watch(clientv3.WithRequireLeader(context.Background()), "foo", clientv3.WithCreatedNotify())
  209. select {
  210. case <-wch:
  211. case <-time.After(integration.RequestWaitTimeout):
  212. t.Fatal("took too long to create watch")
  213. }
  214. // isolate eps[target]
  215. clus.Members[target].InjectPartition(t,
  216. clus.Members[(target+1)%3],
  217. clus.Members[(target+2)%3],
  218. )
  219. select {
  220. case ev := <-wch:
  221. if len(ev.Events) != 0 {
  222. t.Fatal("expected no event")
  223. }
  224. if err = ev.Err(); err != rpctypes.ErrNoLeader {
  225. t.Fatalf("expected %v, got %v", rpctypes.ErrNoLeader, err)
  226. }
  227. case <-time.After(integration.RequestWaitTimeout): // enough time to detect leader lost
  228. t.Fatal("took too long to detect leader lost")
  229. }
  230. }
  231. func TestDropReadUnderNetworkPartition(t *testing.T) {
  232. defer testutil.AfterTest(t)
  233. clus := integration.NewClusterV3(t, &integration.ClusterConfig{
  234. Size: 3,
  235. SkipCreatingClient: true,
  236. })
  237. defer clus.Terminate(t)
  238. leaderIndex := clus.WaitLeader(t)
  239. // get a follower endpoint
  240. eps := []string{clus.Members[(leaderIndex+1)%3].GRPCAddr()}
  241. ccfg := clientv3.Config{
  242. Endpoints: eps,
  243. DialTimeout: 10 * time.Second,
  244. DialOptions: []grpc.DialOption{grpc.WithBlock()},
  245. }
  246. cli, err := clientv3.New(ccfg)
  247. if err != nil {
  248. t.Fatal(err)
  249. }
  250. defer cli.Close()
  251. // wait for eps[0] to be pinned
  252. mustWaitPinReady(t, cli)
  253. // add other endpoints for later endpoint switch
  254. cli.SetEndpoints(eps...)
  255. time.Sleep(time.Second * 2)
  256. conn, err := cli.Dial(clus.Members[(leaderIndex+1)%3].GRPCAddr())
  257. if err != nil {
  258. t.Fatal(err)
  259. }
  260. defer conn.Close()
  261. clus.Members[leaderIndex].InjectPartition(t, clus.Members[(leaderIndex+1)%3], clus.Members[(leaderIndex+2)%3])
  262. kvc := clientv3.NewKVFromKVClient(pb.NewKVClient(conn), nil)
  263. ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second)
  264. _, err = kvc.Get(ctx, "a")
  265. cancel()
  266. if err != rpctypes.ErrLeaderChanged {
  267. t.Fatalf("expected %v, got %v", rpctypes.ErrLeaderChanged, err)
  268. }
  269. for i := 0; i < 5; i++ {
  270. ctx, cancel = context.WithTimeout(context.TODO(), 10*time.Second)
  271. _, err = kvc.Get(ctx, "a")
  272. cancel()
  273. if err != nil {
  274. if err == rpctypes.ErrTimeout {
  275. <-time.After(time.Second)
  276. i++
  277. continue
  278. }
  279. t.Fatalf("expected nil or timeout, got %v", err)
  280. }
  281. // No error returned and no retry required
  282. break
  283. }
  284. }