v3_barrier_test.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // Copyright 2016 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. "testing"
  17. "time"
  18. "go.etcd.io/etcd/clientv3"
  19. "go.etcd.io/etcd/contrib/recipes"
  20. "go.etcd.io/etcd/pkg/testutil"
  21. )
  22. func TestBarrierSingleNode(t *testing.T) {
  23. defer testutil.AfterTest(t)
  24. clus := NewClusterV3(t, &ClusterConfig{Size: 1})
  25. defer clus.Terminate(t)
  26. testBarrier(t, 5, func() *clientv3.Client { return clus.clients[0] })
  27. }
  28. func TestBarrierMultiNode(t *testing.T) {
  29. defer testutil.AfterTest(t)
  30. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  31. defer clus.Terminate(t)
  32. testBarrier(t, 5, func() *clientv3.Client { return clus.RandClient() })
  33. }
  34. func testBarrier(t *testing.T, waiters int, chooseClient func() *clientv3.Client) {
  35. b := recipe.NewBarrier(chooseClient(), "test-barrier")
  36. if err := b.Hold(); err != nil {
  37. t.Fatalf("could not hold barrier (%v)", err)
  38. }
  39. if err := b.Hold(); err == nil {
  40. t.Fatalf("able to double-hold barrier")
  41. }
  42. donec := make(chan struct{})
  43. for i := 0; i < waiters; i++ {
  44. go func() {
  45. br := recipe.NewBarrier(chooseClient(), "test-barrier")
  46. if err := br.Wait(); err != nil {
  47. t.Errorf("could not wait on barrier (%v)", err)
  48. }
  49. donec <- struct{}{}
  50. }()
  51. }
  52. select {
  53. case <-donec:
  54. t.Fatalf("barrier did not wait")
  55. default:
  56. }
  57. if err := b.Release(); err != nil {
  58. t.Fatalf("could not release barrier (%v)", err)
  59. }
  60. timerC := time.After(time.Duration(waiters*100) * time.Millisecond)
  61. for i := 0; i < waiters; i++ {
  62. select {
  63. case <-timerC:
  64. t.Fatalf("barrier timed out")
  65. case <-donec:
  66. }
  67. }
  68. }