v3_stm_test.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  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. "fmt"
  17. "math/rand"
  18. "strconv"
  19. "testing"
  20. v3 "github.com/coreos/etcd/clientv3"
  21. "github.com/coreos/etcd/clientv3/concurrency"
  22. "golang.org/x/net/context"
  23. )
  24. // TestSTMConflict tests that conflicts are retried.
  25. func TestSTMConflict(t *testing.T) {
  26. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  27. defer clus.Terminate(t)
  28. etcdc := clus.RandClient()
  29. keys := make([]string, 5)
  30. for i := 0; i < len(keys); i++ {
  31. keys[i] = fmt.Sprintf("foo-%d", i)
  32. if _, err := etcdc.Put(context.TODO(), keys[i], "100"); err != nil {
  33. t.Fatalf("could not make key (%v)", err)
  34. }
  35. }
  36. errc := make(chan error)
  37. for i := range keys {
  38. curEtcdc := clus.RandClient()
  39. srcKey := keys[i]
  40. applyf := func(stm concurrency.STM) error {
  41. src := stm.Get(srcKey)
  42. // must be different key to avoid double-adding
  43. dstKey := srcKey
  44. for dstKey == srcKey {
  45. dstKey = keys[rand.Intn(len(keys))]
  46. }
  47. dst := stm.Get(dstKey)
  48. srcV, _ := strconv.ParseInt(src, 10, 64)
  49. dstV, _ := strconv.ParseInt(dst, 10, 64)
  50. if srcV == 0 {
  51. // can't rand.Intn on 0, so skip this transaction
  52. return nil
  53. }
  54. xfer := int64(rand.Intn(int(srcV)) / 2)
  55. stm.Put(srcKey, fmt.Sprintf("%d", srcV-xfer))
  56. stm.Put(dstKey, fmt.Sprintf("%d", dstV+xfer))
  57. return nil
  58. }
  59. go func() {
  60. iso := concurrency.WithIsolation(concurrency.RepeatableReads)
  61. _, err := concurrency.NewSTM(curEtcdc, applyf, iso)
  62. errc <- err
  63. }()
  64. }
  65. // wait for txns
  66. for range keys {
  67. if err := <-errc; err != nil {
  68. t.Fatalf("apply failed (%v)", err)
  69. }
  70. }
  71. // ensure sum matches initial sum
  72. sum := 0
  73. for _, oldkey := range keys {
  74. rk, err := etcdc.Get(context.TODO(), oldkey)
  75. if err != nil {
  76. t.Fatalf("couldn't fetch key %s (%v)", oldkey, err)
  77. }
  78. v, _ := strconv.ParseInt(string(rk.Kvs[0].Value), 10, 64)
  79. sum += int(v)
  80. }
  81. if sum != len(keys)*100 {
  82. t.Fatalf("bad sum. got %d, expected %d", sum, len(keys)*100)
  83. }
  84. }
  85. // TestSTMPutNewKey confirms a STM put on a new key is visible after commit.
  86. func TestSTMPutNewKey(t *testing.T) {
  87. clus := NewClusterV3(t, &ClusterConfig{Size: 1})
  88. defer clus.Terminate(t)
  89. etcdc := clus.RandClient()
  90. applyf := func(stm concurrency.STM) error {
  91. stm.Put("foo", "bar")
  92. return nil
  93. }
  94. iso := concurrency.WithIsolation(concurrency.RepeatableReads)
  95. if _, err := concurrency.NewSTM(etcdc, applyf, iso); err != nil {
  96. t.Fatalf("error on stm txn (%v)", err)
  97. }
  98. resp, err := etcdc.Get(context.TODO(), "foo")
  99. if err != nil {
  100. t.Fatalf("error fetching key (%v)", err)
  101. }
  102. if string(resp.Kvs[0].Value) != "bar" {
  103. t.Fatalf("bad value. got %+v, expected 'bar' value", resp)
  104. }
  105. }
  106. // TestSTMAbort tests that an aborted txn does not modify any keys.
  107. func TestSTMAbort(t *testing.T) {
  108. clus := NewClusterV3(t, &ClusterConfig{Size: 1})
  109. defer clus.Terminate(t)
  110. etcdc := clus.RandClient()
  111. ctx, cancel := context.WithCancel(context.TODO())
  112. applyf := func(stm concurrency.STM) error {
  113. stm.Put("foo", "baz")
  114. cancel()
  115. stm.Put("foo", "bap")
  116. return nil
  117. }
  118. iso := concurrency.WithIsolation(concurrency.RepeatableReads)
  119. sctx := concurrency.WithAbortContext(ctx)
  120. if _, err := concurrency.NewSTM(etcdc, applyf, iso, sctx); err == nil {
  121. t.Fatalf("no error on stm txn")
  122. }
  123. resp, err := etcdc.Get(context.TODO(), "foo")
  124. if err != nil {
  125. t.Fatalf("error fetching key (%v)", err)
  126. }
  127. if len(resp.Kvs) != 0 {
  128. t.Fatalf("bad value. got %+v, expected nothing", resp)
  129. }
  130. }
  131. // TestSTMSerialize tests that serialization is honored when serializable.
  132. func TestSTMSerialize(t *testing.T) {
  133. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  134. defer clus.Terminate(t)
  135. etcdc := clus.RandClient()
  136. // set up initial keys
  137. keys := make([]string, 5)
  138. for i := 0; i < len(keys); i++ {
  139. keys[i] = fmt.Sprintf("foo-%d", i)
  140. }
  141. // update keys in full batches
  142. updatec := make(chan struct{})
  143. go func() {
  144. defer close(updatec)
  145. for i := 0; i < 5; i++ {
  146. s := fmt.Sprintf("%d", i)
  147. ops := []v3.Op{}
  148. for _, k := range keys {
  149. ops = append(ops, v3.OpPut(k, s))
  150. }
  151. if _, err := etcdc.Txn(context.TODO()).Then(ops...).Commit(); err != nil {
  152. t.Fatalf("couldn't put keys (%v)", err)
  153. }
  154. updatec <- struct{}{}
  155. }
  156. }()
  157. // read all keys in txn, make sure all values match
  158. errc := make(chan error)
  159. for range updatec {
  160. curEtcdc := clus.RandClient()
  161. applyf := func(stm concurrency.STM) error {
  162. vs := []string{}
  163. for i := range keys {
  164. vs = append(vs, stm.Get(keys[i]))
  165. }
  166. for i := range vs {
  167. if vs[0] != vs[i] {
  168. return fmt.Errorf("got vs[%d] = %v, want %v", i, vs[i], vs[0])
  169. }
  170. }
  171. return nil
  172. }
  173. go func() {
  174. iso := concurrency.WithIsolation(concurrency.Serializable)
  175. _, err := concurrency.NewSTM(curEtcdc, applyf, iso)
  176. errc <- err
  177. }()
  178. }
  179. for i := 0; i < 5; i++ {
  180. if err := <-errc; err != nil {
  181. t.Error(err)
  182. }
  183. }
  184. }
  185. // TestSTMApplyOnConcurrentDeletion ensures that concurrent key deletion
  186. // fails the first GET revision comparison within STM; trigger retry.
  187. func TestSTMApplyOnConcurrentDeletion(t *testing.T) {
  188. clus := NewClusterV3(t, &ClusterConfig{Size: 1})
  189. defer clus.Terminate(t)
  190. etcdc := clus.RandClient()
  191. if _, err := etcdc.Put(context.TODO(), "foo", "bar"); err != nil {
  192. t.Fatal(err)
  193. }
  194. donec, readyc := make(chan struct{}), make(chan struct{})
  195. go func() {
  196. <-readyc
  197. if _, err := etcdc.Delete(context.TODO(), "foo"); err != nil {
  198. t.Fatal(err)
  199. }
  200. close(donec)
  201. }()
  202. try := 0
  203. applyf := func(stm concurrency.STM) error {
  204. try++
  205. stm.Get("foo")
  206. if try == 1 {
  207. // trigger delete to make GET rev comparison outdated
  208. close(readyc)
  209. <-donec
  210. }
  211. stm.Put("foo2", "bar2")
  212. return nil
  213. }
  214. iso := concurrency.WithIsolation(concurrency.RepeatableReads)
  215. if _, err := concurrency.NewSTM(etcdc, applyf, iso); err != nil {
  216. t.Fatalf("error on stm txn (%v)", err)
  217. }
  218. if try != 2 {
  219. t.Fatalf("STM apply expected to run twice, got %d", try)
  220. }
  221. resp, err := etcdc.Get(context.TODO(), "foo2")
  222. if err != nil {
  223. t.Fatalf("error fetching key (%v)", err)
  224. }
  225. if string(resp.Kvs[0].Value) != "bar2" {
  226. t.Fatalf("bad value. got %+v, expected 'bar2' value", resp)
  227. }
  228. }