leasing_test.go 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022
  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. "context"
  17. "fmt"
  18. "math/rand"
  19. "reflect"
  20. "sync"
  21. "testing"
  22. "time"
  23. "github.com/coreos/etcd/clientv3"
  24. "github.com/coreos/etcd/clientv3/concurrency"
  25. "github.com/coreos/etcd/clientv3/leasing"
  26. "github.com/coreos/etcd/integration"
  27. "github.com/coreos/etcd/pkg/testutil"
  28. )
  29. func TestLeasingPutGet(t *testing.T) {
  30. defer testutil.AfterTest(t)
  31. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
  32. defer clus.Terminate(t)
  33. lKV1, closeLKV1, err := leasing.NewKV(clus.Client(0), "foo/")
  34. testutil.AssertNil(t, err)
  35. defer closeLKV1()
  36. lKV2, closeLKV2, err := leasing.NewKV(clus.Client(1), "foo/")
  37. testutil.AssertNil(t, err)
  38. defer closeLKV2()
  39. lKV3, closeLKV3, err := leasing.NewKV(clus.Client(2), "foo/")
  40. testutil.AssertNil(t, err)
  41. defer closeLKV3()
  42. resp, err := lKV1.Get(context.TODO(), "abc")
  43. if err != nil {
  44. t.Fatal(err)
  45. }
  46. if len(resp.Kvs) != 0 {
  47. t.Errorf("expected nil, got %q", resp.Kvs[0].Key)
  48. }
  49. if _, err = lKV1.Put(context.TODO(), "abc", "def"); err != nil {
  50. t.Fatal(err)
  51. }
  52. if resp, err = lKV2.Get(context.TODO(), "abc"); err != nil {
  53. t.Fatal(err)
  54. }
  55. if string(resp.Kvs[0].Key) != "abc" {
  56. t.Errorf("expected key=%q, got key=%q", "abc", resp.Kvs[0].Key)
  57. }
  58. if string(resp.Kvs[0].Value) != "def" {
  59. t.Errorf("expected value=%q, got value=%q", "bar", resp.Kvs[0].Value)
  60. }
  61. if _, err = lKV3.Get(context.TODO(), "abc"); err != nil {
  62. t.Fatal(err)
  63. }
  64. if _, err = lKV2.Put(context.TODO(), "abc", "ghi"); err != nil {
  65. t.Fatal(err)
  66. }
  67. if resp, err = lKV3.Get(context.TODO(), "abc"); err != nil {
  68. t.Fatal(err)
  69. }
  70. if string(resp.Kvs[0].Key) != "abc" {
  71. t.Errorf("expected key=%q, got key=%q", "abc", resp.Kvs[0].Key)
  72. }
  73. if string(resp.Kvs[0].Value) != "ghi" {
  74. t.Errorf("expected value=%q, got value=%q", "bar", resp.Kvs[0].Value)
  75. }
  76. }
  77. // TestLeasingInterval checks the leasing KV fetches key intervals.
  78. func TestLeasingInterval(t *testing.T) {
  79. defer testutil.AfterTest(t)
  80. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  81. defer clus.Terminate(t)
  82. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "pfx/")
  83. testutil.AssertNil(t, err)
  84. defer closeLKV()
  85. keys := []string{"abc/a", "abc/b", "abc/a/a"}
  86. for _, k := range keys {
  87. if _, err = clus.Client(0).Put(context.TODO(), k, "v"); err != nil {
  88. t.Fatal(err)
  89. }
  90. }
  91. resp, err := lkv.Get(context.TODO(), "abc/", clientv3.WithPrefix())
  92. if err != nil {
  93. t.Fatal(err)
  94. }
  95. if len(resp.Kvs) != 3 {
  96. t.Fatalf("expected keys %+v, got response keys %+v", keys, resp.Kvs)
  97. }
  98. // load into cache
  99. if resp, err = lkv.Get(context.TODO(), "abc/a"); err != nil {
  100. t.Fatal(err)
  101. }
  102. // get when prefix is also a cached key
  103. if resp, err = lkv.Get(context.TODO(), "abc/a", clientv3.WithPrefix()); err != nil {
  104. t.Fatal(err)
  105. }
  106. if len(resp.Kvs) != 2 {
  107. t.Fatalf("expected keys %+v, got response keys %+v", keys, resp.Kvs)
  108. }
  109. }
  110. // TestLeasingPutInvalidateNew checks the leasing KV updates its cache on a Put to a new key.
  111. func TestLeasingPutInvalidateNew(t *testing.T) {
  112. defer testutil.AfterTest(t)
  113. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  114. defer clus.Terminate(t)
  115. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "pfx/")
  116. testutil.AssertNil(t, err)
  117. defer closeLKV()
  118. if _, err = lkv.Get(context.TODO(), "k"); err != nil {
  119. t.Fatal(err)
  120. }
  121. if _, err = lkv.Put(context.TODO(), "k", "v"); err != nil {
  122. t.Fatal(err)
  123. }
  124. lkvResp, err := lkv.Get(context.TODO(), "k")
  125. if err != nil {
  126. t.Fatal(err)
  127. }
  128. cResp, cerr := clus.Client(0).Get(context.TODO(), "k")
  129. if cerr != nil {
  130. t.Fatal(cerr)
  131. }
  132. if !reflect.DeepEqual(lkvResp, cResp) {
  133. t.Fatalf(`expected %+v, got response %+v`, cResp, lkvResp)
  134. }
  135. }
  136. // TestLeasingPutInvalidateExisting checks the leasing KV updates its cache on a Put to an existing key.
  137. func TestLeasingPutInvalidateExisting(t *testing.T) {
  138. defer testutil.AfterTest(t)
  139. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  140. defer clus.Terminate(t)
  141. if _, err := clus.Client(0).Put(context.TODO(), "k", "abc"); err != nil {
  142. t.Fatal(err)
  143. }
  144. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "pfx/")
  145. testutil.AssertNil(t, err)
  146. defer closeLKV()
  147. if _, err = lkv.Get(context.TODO(), "k"); err != nil {
  148. t.Fatal(err)
  149. }
  150. if _, err = lkv.Put(context.TODO(), "k", "v"); err != nil {
  151. t.Fatal(err)
  152. }
  153. lkvResp, err := lkv.Get(context.TODO(), "k")
  154. if err != nil {
  155. t.Fatal(err)
  156. }
  157. cResp, cerr := clus.Client(0).Get(context.TODO(), "k")
  158. if cerr != nil {
  159. t.Fatal(cerr)
  160. }
  161. if !reflect.DeepEqual(lkvResp, cResp) {
  162. t.Fatalf(`expected %+v, got response %+v`, cResp, lkvResp)
  163. }
  164. }
  165. // TestLeasingGetNoLeaseTTL checks a key with a TTL is not leased.
  166. func TestLeasingGetNoLeaseTTL(t *testing.T) {
  167. defer testutil.AfterTest(t)
  168. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  169. defer clus.Terminate(t)
  170. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "pfx/")
  171. testutil.AssertNil(t, err)
  172. defer closeLKV()
  173. lresp, err := clus.Client(0).Grant(context.TODO(), 60)
  174. testutil.AssertNil(t, err)
  175. _, err = clus.Client(0).Put(context.TODO(), "k", "v", clientv3.WithLease(lresp.ID))
  176. testutil.AssertNil(t, err)
  177. gresp, err := lkv.Get(context.TODO(), "k")
  178. testutil.AssertNil(t, err)
  179. testutil.AssertEqual(t, len(gresp.Kvs), 1)
  180. clus.Members[0].Stop(t)
  181. ctx, cancel := context.WithTimeout(context.TODO(), time.Second)
  182. _, err = lkv.Get(ctx, "k")
  183. cancel()
  184. testutil.AssertEqual(t, err, ctx.Err())
  185. }
  186. // TestLeasingGetSerializable checks the leasing KV can make serialized requests
  187. // when the etcd cluster is partitioned.
  188. func TestLeasingGetSerializable(t *testing.T) {
  189. defer testutil.AfterTest(t)
  190. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 2})
  191. defer clus.Terminate(t)
  192. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "pfx/")
  193. testutil.AssertNil(t, err)
  194. defer closeLKV()
  195. if _, err = clus.Client(0).Put(context.TODO(), "cached", "abc"); err != nil {
  196. t.Fatal(err)
  197. }
  198. if _, err = lkv.Get(context.TODO(), "cached"); err != nil {
  199. t.Fatal(err)
  200. }
  201. clus.Members[1].Stop(t)
  202. // don't necessarily try to acquire leasing key ownership for new key
  203. resp, err := lkv.Get(context.TODO(), "uncached", clientv3.WithSerializable())
  204. if err != nil {
  205. t.Fatal(err)
  206. }
  207. if len(resp.Kvs) != 0 {
  208. t.Fatalf(`expected no keys, got response %+v`, resp)
  209. }
  210. clus.Members[0].Stop(t)
  211. // leasing key ownership should have "cached" locally served
  212. cachedResp, err := lkv.Get(context.TODO(), "cached", clientv3.WithSerializable())
  213. if err != nil {
  214. t.Fatal(err)
  215. }
  216. if len(cachedResp.Kvs) != 1 || string(cachedResp.Kvs[0].Value) != "abc" {
  217. t.Fatalf(`expected "cached"->"abc", got response %+v`, cachedResp)
  218. }
  219. }
  220. // TestLeasingPrevKey checks the cache respects WithPrevKV on puts.
  221. func TestLeasingPrevKey(t *testing.T) {
  222. defer testutil.AfterTest(t)
  223. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 2})
  224. defer clus.Terminate(t)
  225. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "pfx/")
  226. testutil.AssertNil(t, err)
  227. defer closeLKV()
  228. if _, err = clus.Client(0).Put(context.TODO(), "k", "abc"); err != nil {
  229. t.Fatal(err)
  230. }
  231. // acquire leasing key
  232. if _, err = lkv.Get(context.TODO(), "k"); err != nil {
  233. t.Fatal(err)
  234. }
  235. resp, err := lkv.Put(context.TODO(), "k", "def", clientv3.WithPrevKV())
  236. if err != nil {
  237. t.Fatal(err)
  238. }
  239. if resp.PrevKv == nil || string(resp.PrevKv.Value) != "abc" {
  240. t.Fatalf(`expected PrevKV.Value="abc", got response %+v`, resp)
  241. }
  242. }
  243. // TestLeasingRevGet checks the cache respects Get by Revision.
  244. func TestLeasingRevGet(t *testing.T) {
  245. defer testutil.AfterTest(t)
  246. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  247. defer clus.Terminate(t)
  248. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "pfx/")
  249. testutil.AssertNil(t, err)
  250. defer closeLKV()
  251. putResp, err := clus.Client(0).Put(context.TODO(), "k", "abc")
  252. if err != nil {
  253. t.Fatal(err)
  254. }
  255. if _, err = clus.Client(0).Put(context.TODO(), "k", "def"); err != nil {
  256. t.Fatal(err)
  257. }
  258. // check historic revision
  259. getResp, gerr := lkv.Get(context.TODO(), "k", clientv3.WithRev(putResp.Header.Revision))
  260. if gerr != nil {
  261. t.Fatal(gerr)
  262. }
  263. if len(getResp.Kvs) != 1 || string(getResp.Kvs[0].Value) != "abc" {
  264. t.Fatalf(`expeted "k"->"abc" at rev=%d, got response %+v`, putResp.Header.Revision, getResp)
  265. }
  266. // check current revision
  267. getResp, gerr = lkv.Get(context.TODO(), "k")
  268. if gerr != nil {
  269. t.Fatal(gerr)
  270. }
  271. if len(getResp.Kvs) != 1 || string(getResp.Kvs[0].Value) != "def" {
  272. t.Fatalf(`expeted "k"->"abc" at rev=%d, got response %+v`, putResp.Header.Revision, getResp)
  273. }
  274. }
  275. // TestLeasingGetWithOpts checks options that can be served through the cache do not depend on the server.
  276. func TestLeasingGetWithOpts(t *testing.T) {
  277. defer testutil.AfterTest(t)
  278. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  279. defer clus.Terminate(t)
  280. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "pfx/")
  281. testutil.AssertNil(t, err)
  282. defer closeLKV()
  283. if _, err = clus.Client(0).Put(context.TODO(), "k", "abc"); err != nil {
  284. t.Fatal(err)
  285. }
  286. // in cache
  287. if _, err = lkv.Get(context.TODO(), "k", clientv3.WithKeysOnly()); err != nil {
  288. t.Fatal(err)
  289. }
  290. clus.Members[0].Stop(t)
  291. opts := []clientv3.OpOption{
  292. clientv3.WithKeysOnly(),
  293. clientv3.WithLimit(1),
  294. clientv3.WithMinCreateRev(1),
  295. clientv3.WithMinModRev(1),
  296. clientv3.WithSort(clientv3.SortByKey, clientv3.SortAscend),
  297. clientv3.WithSerializable(),
  298. }
  299. for _, opt := range opts {
  300. if _, err := lkv.Get(context.TODO(), "k", opt); err != nil {
  301. t.Fatal(err)
  302. }
  303. }
  304. getOpts := []clientv3.OpOption{}
  305. for i := 0; i < len(opts); i++ {
  306. getOpts = append(getOpts, opts[rand.Intn(len(opts))])
  307. }
  308. getOpts = getOpts[:rand.Intn(len(opts))]
  309. if _, err := lkv.Get(context.TODO(), "k", getOpts...); err != nil {
  310. t.Fatal(err)
  311. }
  312. }
  313. // TestLeasingConcurrentPut ensures that a get after concurrent puts returns
  314. // the recently put data.
  315. func TestLeasingConcurrentPut(t *testing.T) {
  316. defer testutil.AfterTest(t)
  317. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  318. defer clus.Terminate(t)
  319. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "pfx/")
  320. testutil.AssertNil(t, err)
  321. defer closeLKV()
  322. // force key into leasing key cache
  323. if _, err = lkv.Get(context.TODO(), "k"); err != nil {
  324. t.Fatal(err)
  325. }
  326. // concurrently put through leasing client
  327. numPuts := 16
  328. putc := make(chan *clientv3.PutResponse, numPuts)
  329. for i := 0; i < numPuts; i++ {
  330. go func() {
  331. resp, perr := lkv.Put(context.TODO(), "k", "abc")
  332. if perr != nil {
  333. t.Fatal(perr)
  334. }
  335. putc <- resp
  336. }()
  337. }
  338. // record maximum revision from puts
  339. maxRev := int64(0)
  340. for i := 0; i < numPuts; i++ {
  341. if resp := <-putc; resp.Header.Revision > maxRev {
  342. maxRev = resp.Header.Revision
  343. }
  344. }
  345. // confirm Get gives most recently put revisions
  346. getResp, gerr := lkv.Get(context.TODO(), "k")
  347. if gerr != nil {
  348. t.Fatal(err)
  349. }
  350. if mr := getResp.Kvs[0].ModRevision; mr != maxRev {
  351. t.Errorf("expected ModRevision %d, got %d", maxRev, mr)
  352. }
  353. if ver := getResp.Kvs[0].Version; ver != int64(numPuts) {
  354. t.Errorf("expected Version %d, got %d", numPuts, ver)
  355. }
  356. }
  357. func TestLeasingDisconnectedGet(t *testing.T) {
  358. defer testutil.AfterTest(t)
  359. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  360. defer clus.Terminate(t)
  361. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "pfx/")
  362. testutil.AssertNil(t, err)
  363. defer closeLKV()
  364. if _, err = clus.Client(0).Put(context.TODO(), "cached", "abc"); err != nil {
  365. t.Fatal(err)
  366. }
  367. // get key so it's cached
  368. if _, err = lkv.Get(context.TODO(), "cached"); err != nil {
  369. t.Fatal(err)
  370. }
  371. clus.Members[0].Stop(t)
  372. // leasing key ownership should have "cached" locally served
  373. cachedResp, err := lkv.Get(context.TODO(), "cached")
  374. if err != nil {
  375. t.Fatal(err)
  376. }
  377. if len(cachedResp.Kvs) != 1 || string(cachedResp.Kvs[0].Value) != "abc" {
  378. t.Fatalf(`expected "cached"->"abc", got response %+v`, cachedResp)
  379. }
  380. }
  381. func TestLeasingDeleteOwner(t *testing.T) {
  382. defer testutil.AfterTest(t)
  383. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  384. defer clus.Terminate(t)
  385. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "pfx/")
  386. testutil.AssertNil(t, err)
  387. defer closeLKV()
  388. if _, err = clus.Client(0).Put(context.TODO(), "k", "abc"); err != nil {
  389. t.Fatal(err)
  390. }
  391. // get+own / delete / get
  392. if _, err = lkv.Get(context.TODO(), "k"); err != nil {
  393. t.Fatal(err)
  394. }
  395. if _, err = lkv.Delete(context.TODO(), "k"); err != nil {
  396. t.Fatal(err)
  397. }
  398. resp, err := lkv.Get(context.TODO(), "k")
  399. if err != nil {
  400. t.Fatal(err)
  401. }
  402. if len(resp.Kvs) != 0 {
  403. t.Fatalf(`expected "k" to be deleted, got response %+v`, resp)
  404. }
  405. // try to double delete
  406. if _, err = lkv.Delete(context.TODO(), "k"); err != nil {
  407. t.Fatal(err)
  408. }
  409. }
  410. func TestLeasingDeleteNonOwner(t *testing.T) {
  411. defer testutil.AfterTest(t)
  412. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  413. defer clus.Terminate(t)
  414. lkv1, closeLKV1, err := leasing.NewKV(clus.Client(0), "pfx/")
  415. testutil.AssertNil(t, err)
  416. defer closeLKV1()
  417. lkv2, closeLKV2, err := leasing.NewKV(clus.Client(0), "pfx/")
  418. testutil.AssertNil(t, err)
  419. defer closeLKV2()
  420. if _, err = clus.Client(0).Put(context.TODO(), "k", "abc"); err != nil {
  421. t.Fatal(err)
  422. }
  423. // acquire ownership
  424. if _, err = lkv1.Get(context.TODO(), "k"); err != nil {
  425. t.Fatal(err)
  426. }
  427. // delete via non-owner
  428. if _, err = lkv2.Delete(context.TODO(), "k"); err != nil {
  429. t.Fatal(err)
  430. }
  431. // key should be removed from lkv1
  432. resp, err := lkv1.Get(context.TODO(), "k")
  433. if err != nil {
  434. t.Fatal(err)
  435. }
  436. if len(resp.Kvs) != 0 {
  437. t.Fatalf(`expected "k" to be deleted, got response %+v`, resp)
  438. }
  439. }
  440. func TestLeasingOverwriteResponse(t *testing.T) {
  441. defer testutil.AfterTest(t)
  442. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  443. defer clus.Terminate(t)
  444. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "pfx/")
  445. testutil.AssertNil(t, err)
  446. defer closeLKV()
  447. if _, err = clus.Client(0).Put(context.TODO(), "k", "abc"); err != nil {
  448. t.Fatal(err)
  449. }
  450. resp, err := lkv.Get(context.TODO(), "k")
  451. if err != nil {
  452. t.Fatal(err)
  453. }
  454. resp.Kvs[0].Key[0] = 'z'
  455. resp.Kvs[0].Value[0] = 'z'
  456. resp, err = lkv.Get(context.TODO(), "k")
  457. if err != nil {
  458. t.Fatal(err)
  459. }
  460. if string(resp.Kvs[0].Key) != "k" {
  461. t.Errorf(`expected key "k", got %q`, string(resp.Kvs[0].Key))
  462. }
  463. if string(resp.Kvs[0].Value) != "abc" {
  464. t.Errorf(`expected value "abc", got %q`, string(resp.Kvs[0].Value))
  465. }
  466. }
  467. func TestLeasingOwnerPutResponse(t *testing.T) {
  468. defer testutil.AfterTest(t)
  469. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  470. defer clus.Terminate(t)
  471. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "pfx/")
  472. testutil.AssertNil(t, err)
  473. defer closeLKV()
  474. if _, err = clus.Client(0).Put(context.TODO(), "k", "abc"); err != nil {
  475. t.Fatal(err)
  476. }
  477. gresp, gerr := lkv.Get(context.TODO(), "k")
  478. if gerr != nil {
  479. t.Fatal(gerr)
  480. }
  481. presp, err := lkv.Put(context.TODO(), "k", "def")
  482. if err != nil {
  483. t.Fatal(err)
  484. }
  485. if presp == nil {
  486. t.Fatal("expected put response, got nil")
  487. }
  488. clus.Members[0].Stop(t)
  489. gresp, gerr = lkv.Get(context.TODO(), "k")
  490. if gerr != nil {
  491. t.Fatal(gerr)
  492. }
  493. if gresp.Kvs[0].ModRevision != presp.Header.Revision {
  494. t.Errorf("expected mod revision %d, got %d", presp.Header.Revision, gresp.Kvs[0].ModRevision)
  495. }
  496. if gresp.Kvs[0].Version != 2 {
  497. t.Errorf("expected version 2, got version %d", gresp.Kvs[0].Version)
  498. }
  499. }
  500. func TestLeasingTxnOwnerGetRange(t *testing.T) {
  501. defer testutil.AfterTest(t)
  502. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  503. defer clus.Terminate(t)
  504. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "pfx/")
  505. testutil.AssertNil(t, err)
  506. defer closeLKV()
  507. keyCount := rand.Intn(10) + 1
  508. for i := 0; i < keyCount; i++ {
  509. k := fmt.Sprintf("k-%d", i)
  510. if _, err := clus.Client(0).Put(context.TODO(), k, k+k); err != nil {
  511. t.Fatal(err)
  512. }
  513. }
  514. if _, err := lkv.Get(context.TODO(), "k-"); err != nil {
  515. t.Fatal(err)
  516. }
  517. tresp, terr := lkv.Txn(context.TODO()).Then(clientv3.OpGet("k-", clientv3.WithPrefix())).Commit()
  518. if terr != nil {
  519. t.Fatal(terr)
  520. }
  521. if resp := tresp.Responses[0].GetResponseRange(); len(resp.Kvs) != keyCount {
  522. t.Fatalf("expected %d keys, got response %+v", keyCount, resp.Kvs)
  523. }
  524. }
  525. func TestLeasingTxnOwnerGet(t *testing.T) {
  526. defer testutil.AfterTest(t)
  527. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  528. defer clus.Terminate(t)
  529. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "pfx/")
  530. testutil.AssertNil(t, err)
  531. defer closeLKV()
  532. keyCount := rand.Intn(10) + 1
  533. var ops []clientv3.Op
  534. presps := make([]*clientv3.PutResponse, keyCount)
  535. for i := range presps {
  536. k := fmt.Sprintf("k-%d", i)
  537. presp, err := clus.Client(0).Put(context.TODO(), k, k+k)
  538. if err != nil {
  539. t.Fatal(err)
  540. }
  541. presps[i] = presp
  542. if _, err = lkv.Get(context.TODO(), k); err != nil {
  543. t.Fatal(err)
  544. }
  545. ops = append(ops, clientv3.OpGet(k))
  546. }
  547. ops = ops[:rand.Intn(len(ops))]
  548. // served through cache
  549. clus.Members[0].Stop(t)
  550. var thenOps, elseOps []clientv3.Op
  551. cmps, useThen := randCmps("k-", presps)
  552. if useThen {
  553. thenOps = ops
  554. elseOps = []clientv3.Op{clientv3.OpPut("k", "1")}
  555. } else {
  556. thenOps = []clientv3.Op{clientv3.OpPut("k", "1")}
  557. elseOps = ops
  558. }
  559. tresp, terr := lkv.Txn(context.TODO()).
  560. If(cmps...).
  561. Then(thenOps...).
  562. Else(elseOps...).Commit()
  563. if terr != nil {
  564. t.Fatal(terr)
  565. }
  566. if tresp.Succeeded != useThen {
  567. t.Fatalf("expected succeeded=%v, got tresp=%+v", useThen, tresp)
  568. }
  569. if len(tresp.Responses) != len(ops) {
  570. t.Fatalf("expected %d responses, got %d", len(ops), len(tresp.Responses))
  571. }
  572. wrev := presps[len(presps)-1].Header.Revision
  573. if tresp.Header.Revision < wrev {
  574. t.Fatalf("expected header revision >= %d, got %d", wrev, tresp.Header.Revision)
  575. }
  576. for i := range ops {
  577. k := fmt.Sprintf("k-%d", i)
  578. rr := tresp.Responses[i].GetResponseRange()
  579. if rr == nil {
  580. t.Errorf("expected get response, got %+v", tresp.Responses[i])
  581. }
  582. if string(rr.Kvs[0].Key) != k || string(rr.Kvs[0].Value) != k+k {
  583. t.Errorf(`expected key for %q, got %+v`, k, rr.Kvs)
  584. }
  585. }
  586. }
  587. func TestLeasingTxnOwnerDeleteRange(t *testing.T) {
  588. defer testutil.AfterTest(t)
  589. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  590. defer clus.Terminate(t)
  591. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "pfx/")
  592. testutil.AssertNil(t, err)
  593. defer closeLKV()
  594. keyCount := rand.Intn(10) + 1
  595. for i := 0; i < keyCount; i++ {
  596. k := fmt.Sprintf("k-%d", i)
  597. if _, perr := clus.Client(0).Put(context.TODO(), k, k+k); perr != nil {
  598. t.Fatal(perr)
  599. }
  600. }
  601. // cache in lkv
  602. resp, err := lkv.Get(context.TODO(), "k-", clientv3.WithPrefix())
  603. if err != nil {
  604. t.Fatal(err)
  605. }
  606. if len(resp.Kvs) != keyCount {
  607. t.Fatalf("expected %d keys, got %d", keyCount, len(resp.Kvs))
  608. }
  609. if _, terr := lkv.Txn(context.TODO()).Then(clientv3.OpDelete("k-", clientv3.WithPrefix())).Commit(); terr != nil {
  610. t.Fatal(terr)
  611. }
  612. resp, err = lkv.Get(context.TODO(), "k-", clientv3.WithPrefix())
  613. if err != nil {
  614. t.Fatal(err)
  615. }
  616. if len(resp.Kvs) != 0 {
  617. t.Fatalf("expected no keys, got %d", len(resp.Kvs))
  618. }
  619. }
  620. func TestLeasingTxnOwnerDelete(t *testing.T) {
  621. defer testutil.AfterTest(t)
  622. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  623. defer clus.Terminate(t)
  624. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "pfx/")
  625. testutil.AssertNil(t, err)
  626. defer closeLKV()
  627. if _, err = clus.Client(0).Put(context.TODO(), "k", "abc"); err != nil {
  628. t.Fatal(err)
  629. }
  630. // cache in lkv
  631. if _, gerr := lkv.Get(context.TODO(), "k"); gerr != nil {
  632. t.Fatal(gerr)
  633. }
  634. if _, terr := lkv.Txn(context.TODO()).Then(clientv3.OpDelete("k")).Commit(); terr != nil {
  635. t.Fatal(terr)
  636. }
  637. resp, err := lkv.Get(context.TODO(), "k")
  638. if err != nil {
  639. t.Fatal(err)
  640. }
  641. if len(resp.Kvs) != 0 {
  642. t.Fatalf("expected no keys, got %d", len(resp.Kvs))
  643. }
  644. }
  645. func TestLeasingTxnOwnerIf(t *testing.T) {
  646. defer testutil.AfterTest(t)
  647. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  648. defer clus.Terminate(t)
  649. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "pfx/")
  650. testutil.AssertNil(t, err)
  651. defer closeLKV()
  652. if _, err = clus.Client(0).Put(context.TODO(), "k", "abc"); err != nil {
  653. t.Fatal(err)
  654. }
  655. if _, err = lkv.Get(context.TODO(), "k"); err != nil {
  656. t.Fatal(err)
  657. }
  658. // served through cache
  659. clus.Members[0].Stop(t)
  660. tests := []struct {
  661. cmps []clientv3.Cmp
  662. wSucceeded bool
  663. wResponses int
  664. }{
  665. // success
  666. {
  667. cmps: []clientv3.Cmp{clientv3.Compare(clientv3.Value("k"), "=", "abc")},
  668. wSucceeded: true,
  669. wResponses: 1,
  670. },
  671. {
  672. cmps: []clientv3.Cmp{clientv3.Compare(clientv3.CreateRevision("k"), "=", 2)},
  673. wSucceeded: true,
  674. wResponses: 1,
  675. },
  676. {
  677. cmps: []clientv3.Cmp{clientv3.Compare(clientv3.ModRevision("k"), "=", 2)},
  678. wSucceeded: true,
  679. wResponses: 1,
  680. },
  681. {
  682. cmps: []clientv3.Cmp{clientv3.Compare(clientv3.Version("k"), "=", 1)},
  683. wSucceeded: true,
  684. wResponses: 1,
  685. },
  686. // failure
  687. {
  688. cmps: []clientv3.Cmp{clientv3.Compare(clientv3.Value("k"), ">", "abc")},
  689. },
  690. {
  691. cmps: []clientv3.Cmp{clientv3.Compare(clientv3.CreateRevision("k"), ">", 2)},
  692. },
  693. {
  694. cmps: []clientv3.Cmp{clientv3.Compare(clientv3.ModRevision("k"), "=", 2)},
  695. wSucceeded: true,
  696. wResponses: 1,
  697. },
  698. {
  699. cmps: []clientv3.Cmp{clientv3.Compare(clientv3.Version("k"), ">", 1)},
  700. },
  701. {
  702. cmps: []clientv3.Cmp{clientv3.Compare(clientv3.Value("k"), "<", "abc")},
  703. },
  704. {
  705. cmps: []clientv3.Cmp{clientv3.Compare(clientv3.CreateRevision("k"), "<", 2)},
  706. },
  707. {
  708. cmps: []clientv3.Cmp{clientv3.Compare(clientv3.ModRevision("k"), "<", 2)},
  709. },
  710. {
  711. cmps: []clientv3.Cmp{clientv3.Compare(clientv3.Version("k"), "<", 1)},
  712. },
  713. {
  714. cmps: []clientv3.Cmp{
  715. clientv3.Compare(clientv3.Version("k"), "=", 1),
  716. clientv3.Compare(clientv3.Version("k"), "<", 1),
  717. },
  718. },
  719. }
  720. for i, tt := range tests {
  721. tresp, terr := lkv.Txn(context.TODO()).If(tt.cmps...).Then(clientv3.OpGet("k")).Commit()
  722. if terr != nil {
  723. t.Fatal(terr)
  724. }
  725. if tresp.Succeeded != tt.wSucceeded {
  726. t.Errorf("#%d: expected succeeded %v, got %v", i, tt.wSucceeded, tresp.Succeeded)
  727. }
  728. if len(tresp.Responses) != tt.wResponses {
  729. t.Errorf("#%d: expected %d responses, got %d", i, tt.wResponses, len(tresp.Responses))
  730. }
  731. }
  732. }
  733. func TestLeasingTxnCancel(t *testing.T) {
  734. defer testutil.AfterTest(t)
  735. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
  736. defer clus.Terminate(t)
  737. lkv1, closeLKV1, err := leasing.NewKV(clus.Client(0), "pfx/")
  738. testutil.AssertNil(t, err)
  739. defer closeLKV1()
  740. lkv2, closeLKV2, err := leasing.NewKV(clus.Client(1), "pfx/")
  741. testutil.AssertNil(t, err)
  742. defer closeLKV2()
  743. // acquire lease but disconnect so no revoke in time
  744. if _, err = lkv1.Get(context.TODO(), "k"); err != nil {
  745. t.Fatal(err)
  746. }
  747. clus.Members[0].Stop(t)
  748. // wait for leader election, if any
  749. if _, err = clus.Client(1).Get(context.TODO(), "abc"); err != nil {
  750. t.Fatal(err)
  751. }
  752. ctx, cancel := context.WithCancel(context.TODO())
  753. go func() {
  754. time.Sleep(100 * time.Millisecond)
  755. cancel()
  756. }()
  757. if _, err := lkv2.Txn(ctx).Then(clientv3.OpPut("k", "v")).Commit(); err != context.Canceled {
  758. t.Fatalf("expected %v, got %v", context.Canceled, err)
  759. }
  760. }
  761. func TestLeasingTxnNonOwnerPut(t *testing.T) {
  762. defer testutil.AfterTest(t)
  763. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  764. defer clus.Terminate(t)
  765. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "pfx/")
  766. testutil.AssertNil(t, err)
  767. defer closeLKV()
  768. lkv2, closeLKV2, err := leasing.NewKV(clus.Client(0), "pfx/")
  769. testutil.AssertNil(t, err)
  770. defer closeLKV2()
  771. if _, err = clus.Client(0).Put(context.TODO(), "k", "abc"); err != nil {
  772. t.Fatal(err)
  773. }
  774. if _, err = clus.Client(0).Put(context.TODO(), "k2", "123"); err != nil {
  775. t.Fatal(err)
  776. }
  777. // cache in lkv
  778. if _, err = lkv.Get(context.TODO(), "k"); err != nil {
  779. t.Fatal(err)
  780. }
  781. if _, err = lkv.Get(context.TODO(), "k2"); err != nil {
  782. t.Fatal(err)
  783. }
  784. // invalidate via lkv2 txn
  785. opArray := make([]clientv3.Op, 0)
  786. opArray = append(opArray, clientv3.OpPut("k2", "456"))
  787. tresp, terr := lkv2.Txn(context.TODO()).Then(
  788. clientv3.OpTxn(nil, opArray, nil),
  789. clientv3.OpPut("k", "def"),
  790. clientv3.OpPut("k3", "999"), // + a key not in any cache
  791. ).Commit()
  792. if terr != nil {
  793. t.Fatal(terr)
  794. }
  795. if !tresp.Succeeded || len(tresp.Responses) != 3 {
  796. t.Fatalf("expected txn success, got %+v", tresp)
  797. }
  798. // check cache was invalidated
  799. gresp, gerr := lkv.Get(context.TODO(), "k")
  800. if gerr != nil {
  801. t.Fatal(err)
  802. }
  803. if len(gresp.Kvs) != 1 || string(gresp.Kvs[0].Value) != "def" {
  804. t.Errorf(`expected value "def", got %+v`, gresp)
  805. }
  806. gresp, gerr = lkv.Get(context.TODO(), "k2")
  807. if gerr != nil {
  808. t.Fatal(gerr)
  809. }
  810. if len(gresp.Kvs) != 1 || string(gresp.Kvs[0].Value) != "456" {
  811. t.Errorf(`expected value "def", got %+v`, gresp)
  812. }
  813. // check puts were applied and are all in the same revision
  814. w := clus.Client(0).Watch(
  815. clus.Client(0).Ctx(),
  816. "k",
  817. clientv3.WithRev(tresp.Header.Revision),
  818. clientv3.WithPrefix())
  819. wresp := <-w
  820. c := 0
  821. evs := []clientv3.Event{}
  822. for _, ev := range wresp.Events {
  823. evs = append(evs, *ev)
  824. if ev.Kv.ModRevision == tresp.Header.Revision {
  825. c++
  826. }
  827. }
  828. if c != 3 {
  829. t.Fatalf("expected 3 put events, got %+v", evs)
  830. }
  831. }
  832. // TestLeasingTxnRandIfThenOrElse randomly leases keys two separate clients, then
  833. // issues a random If/{Then,Else} transaction on those keys to one client.
  834. func TestLeasingTxnRandIfThenOrElse(t *testing.T) {
  835. defer testutil.AfterTest(t)
  836. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  837. defer clus.Terminate(t)
  838. lkv1, closeLKV1, err1 := leasing.NewKV(clus.Client(0), "pfx/")
  839. testutil.AssertNil(t, err1)
  840. defer closeLKV1()
  841. lkv2, closeLKV2, err2 := leasing.NewKV(clus.Client(0), "pfx/")
  842. testutil.AssertNil(t, err2)
  843. defer closeLKV2()
  844. keyCount := 16
  845. dat := make([]*clientv3.PutResponse, keyCount)
  846. for i := 0; i < keyCount; i++ {
  847. k, v := fmt.Sprintf("k-%d", i), fmt.Sprintf("%d", i)
  848. dat[i], err1 = clus.Client(0).Put(context.TODO(), k, v)
  849. if err1 != nil {
  850. t.Fatal(err1)
  851. }
  852. }
  853. // nondeterministically populate leasing caches
  854. var wg sync.WaitGroup
  855. getc := make(chan struct{}, keyCount)
  856. getRandom := func(kv clientv3.KV) {
  857. defer wg.Done()
  858. for i := 0; i < keyCount/2; i++ {
  859. k := fmt.Sprintf("k-%d", rand.Intn(keyCount))
  860. if _, err := kv.Get(context.TODO(), k); err != nil {
  861. t.Fatal(err)
  862. }
  863. getc <- struct{}{}
  864. }
  865. }
  866. wg.Add(2)
  867. defer wg.Wait()
  868. go getRandom(lkv1)
  869. go getRandom(lkv2)
  870. // random list of comparisons, all true
  871. cmps, useThen := randCmps("k-", dat)
  872. // random list of puts/gets; unique keys
  873. ops := []clientv3.Op{}
  874. usedIdx := make(map[int]struct{})
  875. for i := 0; i < keyCount; i++ {
  876. idx := rand.Intn(keyCount)
  877. if _, ok := usedIdx[idx]; ok {
  878. continue
  879. }
  880. usedIdx[idx] = struct{}{}
  881. k := fmt.Sprintf("k-%d", idx)
  882. switch rand.Intn(2) {
  883. case 0:
  884. ops = append(ops, clientv3.OpGet(k))
  885. case 1:
  886. ops = append(ops, clientv3.OpPut(k, "a"))
  887. // TODO: add delete
  888. }
  889. }
  890. // random lengths
  891. ops = ops[:rand.Intn(len(ops))]
  892. // wait for some gets to populate the leasing caches before committing
  893. for i := 0; i < keyCount/2; i++ {
  894. <-getc
  895. }
  896. // randomly choose between then and else blocks
  897. var thenOps, elseOps []clientv3.Op
  898. if useThen {
  899. thenOps = ops
  900. } else {
  901. // force failure
  902. elseOps = ops
  903. }
  904. tresp, terr := lkv1.Txn(context.TODO()).If(cmps...).Then(thenOps...).Else(elseOps...).Commit()
  905. if terr != nil {
  906. t.Fatal(terr)
  907. }
  908. // cmps always succeed
  909. if tresp.Succeeded != useThen {
  910. t.Fatalf("expected succeeded=%v, got tresp=%+v", useThen, tresp)
  911. }
  912. // get should match what was put
  913. checkPuts := func(s string, kv clientv3.KV) {
  914. for _, op := range ops {
  915. if !op.IsPut() {
  916. continue
  917. }
  918. resp, rerr := kv.Get(context.TODO(), string(op.KeyBytes()))
  919. if rerr != nil {
  920. t.Fatal(rerr)
  921. }
  922. if len(resp.Kvs) != 1 || string(resp.Kvs[0].Value) != "a" {
  923. t.Fatalf(`%s: expected value="a", got %+v`, s, resp.Kvs)
  924. }
  925. }
  926. }
  927. checkPuts("client(0)", clus.Client(0))
  928. checkPuts("lkv1", lkv1)
  929. checkPuts("lkv2", lkv2)
  930. }
  931. func TestLeasingOwnerPutError(t *testing.T) {
  932. defer testutil.AfterTest(t)
  933. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  934. defer clus.Terminate(t)
  935. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "pfx/")
  936. testutil.AssertNil(t, err)
  937. defer closeLKV()
  938. if _, err = lkv.Get(context.TODO(), "k"); err != nil {
  939. t.Fatal(err)
  940. }
  941. clus.Members[0].Stop(t)
  942. ctx, cancel := context.WithTimeout(context.TODO(), 100*time.Millisecond)
  943. defer cancel()
  944. if resp, err := lkv.Put(ctx, "k", "v"); err == nil {
  945. t.Fatalf("expected error, got response %+v", resp)
  946. }
  947. }
  948. func TestLeasingOwnerDeleteError(t *testing.T) {
  949. defer testutil.AfterTest(t)
  950. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  951. defer clus.Terminate(t)
  952. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "pfx/")
  953. testutil.AssertNil(t, err)
  954. defer closeLKV()
  955. if _, err = lkv.Get(context.TODO(), "k"); err != nil {
  956. t.Fatal(err)
  957. }
  958. clus.Members[0].Stop(t)
  959. ctx, cancel := context.WithTimeout(context.TODO(), 100*time.Millisecond)
  960. defer cancel()
  961. if resp, err := lkv.Delete(ctx, "k"); err == nil {
  962. t.Fatalf("expected error, got response %+v", resp)
  963. }
  964. }
  965. func TestLeasingNonOwnerPutError(t *testing.T) {
  966. defer testutil.AfterTest(t)
  967. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  968. defer clus.Terminate(t)
  969. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "pfx/")
  970. testutil.AssertNil(t, err)
  971. defer closeLKV()
  972. clus.Members[0].Stop(t)
  973. ctx, cancel := context.WithTimeout(context.TODO(), 100*time.Millisecond)
  974. defer cancel()
  975. if resp, err := lkv.Put(ctx, "k", "v"); err == nil {
  976. t.Fatalf("expected error, got response %+v", resp)
  977. }
  978. }
  979. func TestLeasingOwnerDeletePrefix(t *testing.T) {
  980. testLeasingOwnerDelete(t, clientv3.OpDelete("key/", clientv3.WithPrefix()))
  981. }
  982. func TestLeasingOwnerDeleteFrom(t *testing.T) {
  983. testLeasingOwnerDelete(t, clientv3.OpDelete("kd", clientv3.WithFromKey()))
  984. }
  985. func testLeasingOwnerDelete(t *testing.T, del clientv3.Op) {
  986. defer testutil.AfterTest(t)
  987. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  988. defer clus.Terminate(t)
  989. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "0/")
  990. testutil.AssertNil(t, err)
  991. defer closeLKV()
  992. for i := 0; i < 8; i++ {
  993. if _, err = clus.Client(0).Put(context.TODO(), fmt.Sprintf("key/%d", i), "123"); err != nil {
  994. t.Fatal(err)
  995. }
  996. }
  997. if _, err = lkv.Get(context.TODO(), "key/1"); err != nil {
  998. t.Fatal(err)
  999. }
  1000. opResp, delErr := lkv.Do(context.TODO(), del)
  1001. if delErr != nil {
  1002. t.Fatal(delErr)
  1003. }
  1004. delResp := opResp.Del()
  1005. // confirm keys are invalidated from cache and deleted on etcd
  1006. for i := 0; i < 8; i++ {
  1007. resp, err := lkv.Get(context.TODO(), fmt.Sprintf("key/%d", i))
  1008. if err != nil {
  1009. t.Fatal(err)
  1010. }
  1011. if len(resp.Kvs) != 0 {
  1012. t.Fatalf("expected no keys on key/%d, got %+v", i, resp)
  1013. }
  1014. }
  1015. // confirm keys were deleted atomically
  1016. w := clus.Client(0).Watch(
  1017. clus.Client(0).Ctx(),
  1018. "key/",
  1019. clientv3.WithRev(delResp.Header.Revision),
  1020. clientv3.WithPrefix())
  1021. if wresp := <-w; len(wresp.Events) != 8 {
  1022. t.Fatalf("expected %d delete events,got %d", 8, len(wresp.Events))
  1023. }
  1024. }
  1025. func TestLeasingDeleteRangeBounds(t *testing.T) {
  1026. defer testutil.AfterTest(t)
  1027. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  1028. defer clus.Terminate(t)
  1029. delkv, closeDelKV, err := leasing.NewKV(clus.Client(0), "0/")
  1030. testutil.AssertNil(t, err)
  1031. defer closeDelKV()
  1032. getkv, closeGetKv, err := leasing.NewKV(clus.Client(0), "0/")
  1033. testutil.AssertNil(t, err)
  1034. defer closeGetKv()
  1035. for _, k := range []string{"j", "m"} {
  1036. if _, err = clus.Client(0).Put(context.TODO(), k, "123"); err != nil {
  1037. t.Fatal(err)
  1038. }
  1039. if _, err = getkv.Get(context.TODO(), k); err != nil {
  1040. t.Fatal(err)
  1041. }
  1042. }
  1043. if _, err = delkv.Delete(context.TODO(), "k", clientv3.WithPrefix()); err != nil {
  1044. t.Fatal(err)
  1045. }
  1046. // leases still on server?
  1047. for _, k := range []string{"j", "m"} {
  1048. resp, geterr := clus.Client(0).Get(context.TODO(), "0/"+k, clientv3.WithPrefix())
  1049. if geterr != nil {
  1050. t.Fatal(geterr)
  1051. }
  1052. if len(resp.Kvs) != 1 {
  1053. t.Fatalf("expected leasing key, got %+v", resp)
  1054. }
  1055. }
  1056. // j and m should still have leases registered since not under k*
  1057. clus.Members[0].Stop(t)
  1058. if _, err = getkv.Get(context.TODO(), "j"); err != nil {
  1059. t.Fatal(err)
  1060. }
  1061. if _, err = getkv.Get(context.TODO(), "m"); err != nil {
  1062. t.Fatal(err)
  1063. }
  1064. }
  1065. func TestLeasingDeleteRangeContendTxn(t *testing.T) {
  1066. then := []clientv3.Op{clientv3.OpDelete("key/", clientv3.WithPrefix())}
  1067. testLeasingDeleteRangeContend(t, clientv3.OpTxn(nil, then, nil))
  1068. }
  1069. func TestLeaseDeleteRangeContendDel(t *testing.T) {
  1070. op := clientv3.OpDelete("key/", clientv3.WithPrefix())
  1071. testLeasingDeleteRangeContend(t, op)
  1072. }
  1073. func testLeasingDeleteRangeContend(t *testing.T, op clientv3.Op) {
  1074. defer testutil.AfterTest(t)
  1075. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  1076. defer clus.Terminate(t)
  1077. delkv, closeDelKV, err := leasing.NewKV(clus.Client(0), "0/")
  1078. testutil.AssertNil(t, err)
  1079. defer closeDelKV()
  1080. putkv, closePutKV, err := leasing.NewKV(clus.Client(0), "0/")
  1081. testutil.AssertNil(t, err)
  1082. defer closePutKV()
  1083. for i := 0; i < 8; i++ {
  1084. key := fmt.Sprintf("key/%d", i)
  1085. if _, err = clus.Client(0).Put(context.TODO(), key, "123"); err != nil {
  1086. t.Fatal(err)
  1087. }
  1088. if _, err = putkv.Get(context.TODO(), key); err != nil {
  1089. t.Fatal(err)
  1090. }
  1091. }
  1092. ctx, cancel := context.WithCancel(context.TODO())
  1093. donec := make(chan struct{})
  1094. go func() {
  1095. defer close(donec)
  1096. for i := 0; ctx.Err() == nil; i++ {
  1097. key := fmt.Sprintf("key/%d", i%8)
  1098. putkv.Put(ctx, key, "123")
  1099. putkv.Get(ctx, key)
  1100. }
  1101. }()
  1102. _, delErr := delkv.Do(context.TODO(), op)
  1103. cancel()
  1104. <-donec
  1105. if delErr != nil {
  1106. t.Fatal(delErr)
  1107. }
  1108. // confirm keys on non-deleter match etcd
  1109. for i := 0; i < 8; i++ {
  1110. key := fmt.Sprintf("key/%d", i)
  1111. resp, err := putkv.Get(context.TODO(), key)
  1112. if err != nil {
  1113. t.Fatal(err)
  1114. }
  1115. servResp, err := clus.Client(0).Get(context.TODO(), key)
  1116. if err != nil {
  1117. t.Fatal(err)
  1118. }
  1119. if !reflect.DeepEqual(resp.Kvs, servResp.Kvs) {
  1120. t.Errorf("#%d: expected %+v, got %+v", i, servResp.Kvs, resp.Kvs)
  1121. }
  1122. }
  1123. }
  1124. func TestLeasingPutGetDeleteConcurrent(t *testing.T) {
  1125. defer testutil.AfterTest(t)
  1126. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  1127. defer clus.Terminate(t)
  1128. lkvs := make([]clientv3.KV, 16)
  1129. for i := range lkvs {
  1130. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "pfx/")
  1131. testutil.AssertNil(t, err)
  1132. defer closeLKV()
  1133. lkvs[i] = lkv
  1134. }
  1135. getdel := func(kv clientv3.KV) {
  1136. if _, err := kv.Put(context.TODO(), "k", "abc"); err != nil {
  1137. t.Fatal(err)
  1138. }
  1139. time.Sleep(time.Millisecond)
  1140. if _, err := kv.Get(context.TODO(), "k"); err != nil {
  1141. t.Fatal(err)
  1142. }
  1143. if _, err := kv.Delete(context.TODO(), "k"); err != nil {
  1144. t.Fatal(err)
  1145. }
  1146. time.Sleep(2 * time.Millisecond)
  1147. }
  1148. var wg sync.WaitGroup
  1149. wg.Add(16)
  1150. for i := 0; i < 16; i++ {
  1151. go func() {
  1152. defer wg.Done()
  1153. for _, kv := range lkvs {
  1154. getdel(kv)
  1155. }
  1156. }()
  1157. }
  1158. wg.Wait()
  1159. resp, err := lkvs[0].Get(context.TODO(), "k")
  1160. if err != nil {
  1161. t.Fatal(err)
  1162. }
  1163. if len(resp.Kvs) > 0 {
  1164. t.Fatalf("expected no kvs, got %+v", resp.Kvs)
  1165. }
  1166. resp, err = clus.Client(0).Get(context.TODO(), "k")
  1167. if err != nil {
  1168. t.Fatal(err)
  1169. }
  1170. if len(resp.Kvs) > 0 {
  1171. t.Fatalf("expected no kvs, got %+v", resp.Kvs)
  1172. }
  1173. }
  1174. // TestLeasingReconnectOwnerRevoke checks that revocation works if
  1175. // disconnected when trying to submit revoke txn.
  1176. func TestLeasingReconnectOwnerRevoke(t *testing.T) {
  1177. defer testutil.AfterTest(t)
  1178. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
  1179. defer clus.Terminate(t)
  1180. lkv1, closeLKV1, err1 := leasing.NewKV(clus.Client(0), "foo/")
  1181. testutil.AssertNil(t, err1)
  1182. defer closeLKV1()
  1183. lkv2, closeLKV2, err2 := leasing.NewKV(clus.Client(1), "foo/")
  1184. testutil.AssertNil(t, err2)
  1185. defer closeLKV2()
  1186. if _, err := lkv1.Get(context.TODO(), "k"); err != nil {
  1187. t.Fatal(err)
  1188. }
  1189. // force leader away from member 0
  1190. clus.Members[0].Stop(t)
  1191. clus.WaitLeader(t)
  1192. clus.Members[0].Restart(t)
  1193. cctx, cancel := context.WithCancel(context.TODO())
  1194. sdonec, pdonec := make(chan struct{}), make(chan struct{})
  1195. // make lkv1 connection choppy so Txn fails
  1196. go func() {
  1197. defer close(sdonec)
  1198. for i := 0; i < 10 && cctx.Err() == nil; i++ {
  1199. clus.Members[0].Stop(t)
  1200. time.Sleep(10 * time.Millisecond)
  1201. clus.Members[0].Restart(t)
  1202. }
  1203. }()
  1204. go func() {
  1205. defer close(pdonec)
  1206. if _, err := lkv2.Put(cctx, "k", "v"); err != nil {
  1207. t.Log(err)
  1208. }
  1209. resp, err := lkv1.Get(cctx, "k")
  1210. if err != nil {
  1211. t.Fatal(err)
  1212. }
  1213. if string(resp.Kvs[0].Value) != "v" {
  1214. t.Fatalf(`expected "v" value, got %+v`, resp)
  1215. }
  1216. }()
  1217. select {
  1218. case <-pdonec:
  1219. cancel()
  1220. <-sdonec
  1221. case <-time.After(10 * time.Second):
  1222. cancel()
  1223. <-sdonec
  1224. <-pdonec
  1225. t.Fatal("took to long to revoke and put")
  1226. }
  1227. }
  1228. // TestLeasingReconnectOwnerRevokeCompact checks that revocation works if
  1229. // disconnected and the watch is compacted.
  1230. func TestLeasingReconnectOwnerRevokeCompact(t *testing.T) {
  1231. defer testutil.AfterTest(t)
  1232. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
  1233. defer clus.Terminate(t)
  1234. lkv1, closeLKV1, err1 := leasing.NewKV(clus.Client(0), "foo/")
  1235. testutil.AssertNil(t, err1)
  1236. defer closeLKV1()
  1237. lkv2, closeLKV2, err2 := leasing.NewKV(clus.Client(1), "foo/")
  1238. testutil.AssertNil(t, err2)
  1239. defer closeLKV2()
  1240. if _, err := lkv1.Get(context.TODO(), "k"); err != nil {
  1241. t.Fatal(err)
  1242. }
  1243. clus.Members[0].Stop(t)
  1244. clus.WaitLeader(t)
  1245. // put some more revisions for compaction
  1246. presp, err := clus.Client(1).Put(context.TODO(), "a", "123")
  1247. if err != nil {
  1248. t.Fatal(err)
  1249. }
  1250. presp, err = clus.Client(1).Put(context.TODO(), "a", "123")
  1251. if err != nil {
  1252. t.Fatal(err)
  1253. }
  1254. // compact while lkv1 is disconnected
  1255. rev := presp.Header.Revision
  1256. if _, err = clus.Client(1).Compact(context.TODO(), rev); err != nil {
  1257. t.Fatal(err)
  1258. }
  1259. clus.Members[0].Restart(t)
  1260. cctx, cancel := context.WithTimeout(context.TODO(), 5*time.Second)
  1261. defer cancel()
  1262. if _, err = lkv2.Put(cctx, "k", "v"); err != nil {
  1263. t.Fatal(err)
  1264. }
  1265. resp, err := lkv1.Get(cctx, "k")
  1266. if err != nil {
  1267. t.Fatal(err)
  1268. }
  1269. if string(resp.Kvs[0].Value) != "v" {
  1270. t.Fatalf(`expected "v" value, got %+v`, resp)
  1271. }
  1272. }
  1273. // TestLeasingReconnectOwnerConsistency checks a write error on an owner will
  1274. // not cause inconsistency between the server and the client.
  1275. func TestLeasingReconnectOwnerConsistency(t *testing.T) {
  1276. defer testutil.AfterTest(t)
  1277. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  1278. defer clus.Terminate(t)
  1279. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "foo/")
  1280. defer closeLKV()
  1281. testutil.AssertNil(t, err)
  1282. if _, err = lkv.Put(context.TODO(), "k", "x"); err != nil {
  1283. t.Fatal(err)
  1284. }
  1285. if _, err = lkv.Put(context.TODO(), "kk", "y"); err != nil {
  1286. t.Fatal(err)
  1287. }
  1288. if _, err = lkv.Get(context.TODO(), "k"); err != nil {
  1289. t.Fatal(err)
  1290. }
  1291. for i := 0; i < 10; i++ {
  1292. v := fmt.Sprintf("%d", i)
  1293. donec := make(chan struct{})
  1294. clus.Members[0].DropConnections()
  1295. go func() {
  1296. defer close(donec)
  1297. for i := 0; i < 20; i++ {
  1298. clus.Members[0].DropConnections()
  1299. time.Sleep(time.Millisecond)
  1300. }
  1301. }()
  1302. switch rand.Intn(7) {
  1303. case 0:
  1304. _, err = lkv.Put(context.TODO(), "k", v)
  1305. case 1:
  1306. _, err = lkv.Delete(context.TODO(), "k")
  1307. case 2:
  1308. txn := lkv.Txn(context.TODO()).Then(
  1309. clientv3.OpGet("k"),
  1310. clientv3.OpDelete("k"),
  1311. )
  1312. _, err = txn.Commit()
  1313. case 3:
  1314. txn := lkv.Txn(context.TODO()).Then(
  1315. clientv3.OpGet("k"),
  1316. clientv3.OpPut("k", v),
  1317. )
  1318. _, err = txn.Commit()
  1319. case 4:
  1320. _, err = lkv.Do(context.TODO(), clientv3.OpPut("k", v))
  1321. case 5:
  1322. _, err = lkv.Do(context.TODO(), clientv3.OpDelete("k"))
  1323. case 6:
  1324. _, err = lkv.Delete(context.TODO(), "k", clientv3.WithPrefix())
  1325. }
  1326. <-donec
  1327. if err != nil {
  1328. // TODO wrap input client to generate errors
  1329. break
  1330. }
  1331. }
  1332. lresp, lerr := lkv.Get(context.TODO(), "k")
  1333. if lerr != nil {
  1334. t.Fatal(lerr)
  1335. }
  1336. cresp, cerr := clus.Client(0).Get(context.TODO(), "k")
  1337. if cerr != nil {
  1338. t.Fatal(cerr)
  1339. }
  1340. if !reflect.DeepEqual(lresp.Kvs, cresp.Kvs) {
  1341. t.Fatalf("expected %+v, got %+v", cresp, lresp)
  1342. }
  1343. }
  1344. func TestLeasingTxnAtomicCache(t *testing.T) {
  1345. defer testutil.AfterTest(t)
  1346. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  1347. defer clus.Terminate(t)
  1348. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "foo/")
  1349. testutil.AssertNil(t, err)
  1350. defer closeLKV()
  1351. puts, gets := make([]clientv3.Op, 16), make([]clientv3.Op, 16)
  1352. for i := range puts {
  1353. k := fmt.Sprintf("k-%d", i)
  1354. puts[i], gets[i] = clientv3.OpPut(k, k), clientv3.OpGet(k)
  1355. }
  1356. if _, err = clus.Client(0).Txn(context.TODO()).Then(puts...).Commit(); err != nil {
  1357. t.Fatal(err)
  1358. }
  1359. for i := range gets {
  1360. if _, err = lkv.Do(context.TODO(), gets[i]); err != nil {
  1361. t.Fatal(err)
  1362. }
  1363. }
  1364. numPutters, numGetters := 16, 16
  1365. var wgPutters, wgGetters sync.WaitGroup
  1366. wgPutters.Add(numPutters)
  1367. wgGetters.Add(numGetters)
  1368. f := func() {
  1369. defer wgPutters.Done()
  1370. for i := 0; i < 10; i++ {
  1371. if _, txnerr := lkv.Txn(context.TODO()).Then(puts...).Commit(); err != nil {
  1372. t.Fatal(txnerr)
  1373. }
  1374. }
  1375. }
  1376. donec := make(chan struct{}, numPutters)
  1377. g := func() {
  1378. defer wgGetters.Done()
  1379. for {
  1380. select {
  1381. case <-donec:
  1382. return
  1383. default:
  1384. }
  1385. tresp, err := lkv.Txn(context.TODO()).Then(gets...).Commit()
  1386. if err != nil {
  1387. t.Fatal(err)
  1388. }
  1389. revs := make([]int64, len(gets))
  1390. for i, resp := range tresp.Responses {
  1391. rr := resp.GetResponseRange()
  1392. revs[i] = rr.Kvs[0].ModRevision
  1393. }
  1394. for i := 1; i < len(revs); i++ {
  1395. if revs[i] != revs[i-1] {
  1396. t.Fatalf("expected matching revisions, got %+v", revs)
  1397. }
  1398. }
  1399. }
  1400. }
  1401. for i := 0; i < numGetters; i++ {
  1402. go g()
  1403. }
  1404. for i := 0; i < numPutters; i++ {
  1405. go f()
  1406. }
  1407. wgPutters.Wait()
  1408. close(donec)
  1409. wgGetters.Wait()
  1410. }
  1411. // TestLeasingReconnectTxn checks that Txn is resilient to disconnects.
  1412. func TestLeasingReconnectTxn(t *testing.T) {
  1413. defer testutil.AfterTest(t)
  1414. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  1415. defer clus.Terminate(t)
  1416. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "foo/")
  1417. testutil.AssertNil(t, err)
  1418. defer closeLKV()
  1419. if _, err = lkv.Get(context.TODO(), "k"); err != nil {
  1420. t.Fatal(err)
  1421. }
  1422. donec := make(chan struct{})
  1423. go func() {
  1424. defer close(donec)
  1425. clus.Members[0].DropConnections()
  1426. for i := 0; i < 10; i++ {
  1427. clus.Members[0].DropConnections()
  1428. time.Sleep(time.Millisecond)
  1429. }
  1430. }()
  1431. _, lerr := lkv.Txn(context.TODO()).
  1432. If(clientv3.Compare(clientv3.Version("k"), "=", 0)).
  1433. Then(clientv3.OpGet("k")).
  1434. Commit()
  1435. <-donec
  1436. if lerr != nil {
  1437. t.Fatal(lerr)
  1438. }
  1439. }
  1440. // TestLeasingReconnectNonOwnerGet checks a get error on an owner will
  1441. // not cause inconsistency between the server and the client.
  1442. func TestLeasingReconnectNonOwnerGet(t *testing.T) {
  1443. defer testutil.AfterTest(t)
  1444. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  1445. defer clus.Terminate(t)
  1446. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "foo/")
  1447. testutil.AssertNil(t, err)
  1448. defer closeLKV()
  1449. // populate a few keys so some leasing gets have keys
  1450. for i := 0; i < 4; i++ {
  1451. k := fmt.Sprintf("k-%d", i*2)
  1452. if _, err = lkv.Put(context.TODO(), k, k[2:]); err != nil {
  1453. t.Fatal(err)
  1454. }
  1455. }
  1456. n := 0
  1457. for i := 0; i < 10; i++ {
  1458. donec := make(chan struct{})
  1459. clus.Members[0].DropConnections()
  1460. go func() {
  1461. defer close(donec)
  1462. for j := 0; j < 10; j++ {
  1463. clus.Members[0].DropConnections()
  1464. time.Sleep(time.Millisecond)
  1465. }
  1466. }()
  1467. _, err = lkv.Get(context.TODO(), fmt.Sprintf("k-%d", i))
  1468. <-donec
  1469. n++
  1470. if err != nil {
  1471. break
  1472. }
  1473. }
  1474. for i := 0; i < n; i++ {
  1475. k := fmt.Sprintf("k-%d", i)
  1476. lresp, lerr := lkv.Get(context.TODO(), k)
  1477. if lerr != nil {
  1478. t.Fatal(lerr)
  1479. }
  1480. cresp, cerr := clus.Client(0).Get(context.TODO(), k)
  1481. if cerr != nil {
  1482. t.Fatal(cerr)
  1483. }
  1484. if !reflect.DeepEqual(lresp.Kvs, cresp.Kvs) {
  1485. t.Fatalf("expected %+v, got %+v", cresp, lresp)
  1486. }
  1487. }
  1488. }
  1489. func TestLeasingTxnRangeCmp(t *testing.T) {
  1490. defer testutil.AfterTest(t)
  1491. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  1492. defer clus.Terminate(t)
  1493. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "foo/")
  1494. testutil.AssertNil(t, err)
  1495. defer closeLKV()
  1496. if _, err = clus.Client(0).Put(context.TODO(), "k", "a"); err != nil {
  1497. t.Fatal(err)
  1498. }
  1499. // k2 version = 2
  1500. if _, err = clus.Client(0).Put(context.TODO(), "k2", "a"); err != nil {
  1501. t.Fatal(err)
  1502. }
  1503. if _, err = clus.Client(0).Put(context.TODO(), "k2", "a"); err != nil {
  1504. t.Fatal(err)
  1505. }
  1506. // cache k
  1507. if _, err = lkv.Get(context.TODO(), "k"); err != nil {
  1508. t.Fatal(err)
  1509. }
  1510. cmp := clientv3.Compare(clientv3.Version("k").WithPrefix(), "=", 1)
  1511. tresp, terr := lkv.Txn(context.TODO()).If(cmp).Commit()
  1512. if terr != nil {
  1513. t.Fatal(err)
  1514. }
  1515. if tresp.Succeeded {
  1516. t.Fatalf("expected Succeeded=false, got %+v", tresp)
  1517. }
  1518. }
  1519. func TestLeasingDo(t *testing.T) {
  1520. defer testutil.AfterTest(t)
  1521. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  1522. defer clus.Terminate(t)
  1523. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "foo/")
  1524. testutil.AssertNil(t, err)
  1525. defer closeLKV()
  1526. ops := []clientv3.Op{
  1527. clientv3.OpTxn(nil, nil, nil),
  1528. clientv3.OpGet("a"),
  1529. clientv3.OpPut("a/abc", "v"),
  1530. clientv3.OpDelete("a", clientv3.WithPrefix()),
  1531. clientv3.OpTxn(nil, nil, nil),
  1532. }
  1533. for i, op := range ops {
  1534. resp, resperr := lkv.Do(context.TODO(), op)
  1535. if resperr != nil {
  1536. t.Errorf("#%d: failed (%v)", i, resperr)
  1537. }
  1538. switch {
  1539. case op.IsGet() && resp.Get() == nil:
  1540. t.Errorf("#%d: get but nil get response", i)
  1541. case op.IsPut() && resp.Put() == nil:
  1542. t.Errorf("#%d: put op but nil get response", i)
  1543. case op.IsDelete() && resp.Del() == nil:
  1544. t.Errorf("#%d: delete op but nil delete response", i)
  1545. case op.IsTxn() && resp.Txn() == nil:
  1546. t.Errorf("#%d: txn op but nil txn response", i)
  1547. }
  1548. }
  1549. gresp, err := clus.Client(0).Get(context.TODO(), "a", clientv3.WithPrefix())
  1550. if err != nil {
  1551. t.Fatal(err)
  1552. }
  1553. if len(gresp.Kvs) != 0 {
  1554. t.Fatalf("expected no keys, got %+v", gresp.Kvs)
  1555. }
  1556. }
  1557. func TestLeasingTxnOwnerPutBranch(t *testing.T) {
  1558. defer testutil.AfterTest(t)
  1559. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
  1560. defer clus.Terminate(t)
  1561. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "foo/")
  1562. testutil.AssertNil(t, err)
  1563. defer closeLKV()
  1564. n := 0
  1565. treeOp := makePutTreeOp("tree", &n, 4)
  1566. for i := 0; i < n; i++ {
  1567. k := fmt.Sprintf("tree/%d", i)
  1568. if _, err = clus.Client(0).Put(context.TODO(), k, "a"); err != nil {
  1569. t.Fatal(err)
  1570. }
  1571. if _, err = lkv.Get(context.TODO(), k); err != nil {
  1572. t.Fatal(err)
  1573. }
  1574. }
  1575. if _, err = lkv.Do(context.TODO(), treeOp); err != nil {
  1576. t.Fatal(err)
  1577. }
  1578. // lkv shouldn't need to call out to server for updated leased keys
  1579. clus.Members[0].Stop(t)
  1580. for i := 0; i < n; i++ {
  1581. k := fmt.Sprintf("tree/%d", i)
  1582. lkvResp, err := lkv.Get(context.TODO(), k)
  1583. if err != nil {
  1584. t.Fatal(err)
  1585. }
  1586. clusResp, err := clus.Client(1).Get(context.TODO(), k)
  1587. if err != nil {
  1588. t.Fatal(err)
  1589. }
  1590. if !reflect.DeepEqual(clusResp.Kvs, lkvResp.Kvs) {
  1591. t.Fatalf("expected %+v, got %+v", clusResp.Kvs, lkvResp.Kvs)
  1592. }
  1593. }
  1594. }
  1595. func makePutTreeOp(pfx string, v *int, depth int) clientv3.Op {
  1596. key := fmt.Sprintf("%s/%d", pfx, *v)
  1597. *v = *v + 1
  1598. if depth == 0 {
  1599. return clientv3.OpPut(key, "leaf")
  1600. }
  1601. t, e := makePutTreeOp(pfx, v, depth-1), makePutTreeOp(pfx, v, depth-1)
  1602. tPut, ePut := clientv3.OpPut(key, "then"), clientv3.OpPut(key, "else")
  1603. cmps := make([]clientv3.Cmp, 1)
  1604. if rand.Intn(2) == 0 {
  1605. // follow then path
  1606. cmps[0] = clientv3.Compare(clientv3.Version("nokey"), "=", 0)
  1607. } else {
  1608. // follow else path
  1609. cmps[0] = clientv3.Compare(clientv3.Version("nokey"), ">", 0)
  1610. }
  1611. return clientv3.OpTxn(cmps, []clientv3.Op{t, tPut}, []clientv3.Op{e, ePut})
  1612. }
  1613. func randCmps(pfx string, dat []*clientv3.PutResponse) (cmps []clientv3.Cmp, then bool) {
  1614. for i := 0; i < len(dat); i++ {
  1615. idx := rand.Intn(len(dat))
  1616. k := fmt.Sprintf("%s%d", pfx, idx)
  1617. rev := dat[idx].Header.Revision
  1618. var cmp clientv3.Cmp
  1619. switch rand.Intn(4) {
  1620. case 0:
  1621. cmp = clientv3.Compare(clientv3.CreateRevision(k), ">", rev-1)
  1622. case 1:
  1623. cmp = clientv3.Compare(clientv3.Version(k), "=", 1)
  1624. case 2:
  1625. cmp = clientv3.Compare(clientv3.CreateRevision(k), "=", rev)
  1626. case 3:
  1627. cmp = clientv3.Compare(clientv3.CreateRevision(k), "!=", rev+1)
  1628. }
  1629. cmps = append(cmps, cmp)
  1630. }
  1631. cmps = cmps[:rand.Intn(len(dat))]
  1632. if rand.Intn(2) == 0 {
  1633. return cmps, true
  1634. }
  1635. i := rand.Intn(len(dat))
  1636. cmps = append(cmps, clientv3.Compare(clientv3.Version(fmt.Sprintf("k-%d", i)), "=", 0))
  1637. return cmps, false
  1638. }
  1639. func TestLeasingSessionExpire(t *testing.T) {
  1640. defer testutil.AfterTest(t)
  1641. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
  1642. defer clus.Terminate(t)
  1643. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "foo/", concurrency.WithTTL(1))
  1644. testutil.AssertNil(t, err)
  1645. defer closeLKV()
  1646. lkv2, closeLKV2, err := leasing.NewKV(clus.Client(0), "foo/")
  1647. testutil.AssertNil(t, err)
  1648. defer closeLKV2()
  1649. // acquire lease on abc
  1650. if _, err = lkv.Get(context.TODO(), "abc"); err != nil {
  1651. t.Fatal(err)
  1652. }
  1653. // down endpoint lkv uses for keepalives
  1654. clus.Members[0].Stop(t)
  1655. if err = waitForLeasingExpire(clus.Client(1), "foo/abc"); err != nil {
  1656. t.Fatal(err)
  1657. }
  1658. waitForExpireAck(t, lkv)
  1659. clus.Members[0].Restart(t)
  1660. if _, err = lkv2.Put(context.TODO(), "abc", "def"); err != nil {
  1661. t.Fatal(err)
  1662. }
  1663. resp, err := lkv.Get(context.TODO(), "abc")
  1664. if err != nil {
  1665. t.Fatal(err)
  1666. }
  1667. if v := string(resp.Kvs[0].Value); v != "def" {
  1668. t.Fatalf("expected %q, got %q", "v", v)
  1669. }
  1670. }
  1671. func TestLeasingSessionExpireCancel(t *testing.T) {
  1672. defer testutil.AfterTest(t)
  1673. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
  1674. defer clus.Terminate(t)
  1675. tests := []func(context.Context, clientv3.KV) error{
  1676. func(ctx context.Context, kv clientv3.KV) error {
  1677. _, err := kv.Get(ctx, "abc")
  1678. return err
  1679. },
  1680. func(ctx context.Context, kv clientv3.KV) error {
  1681. _, err := kv.Delete(ctx, "abc")
  1682. return err
  1683. },
  1684. func(ctx context.Context, kv clientv3.KV) error {
  1685. _, err := kv.Put(ctx, "abc", "v")
  1686. return err
  1687. },
  1688. func(ctx context.Context, kv clientv3.KV) error {
  1689. _, err := kv.Txn(ctx).Then(clientv3.OpGet("abc")).Commit()
  1690. return err
  1691. },
  1692. func(ctx context.Context, kv clientv3.KV) error {
  1693. _, err := kv.Do(ctx, clientv3.OpPut("abc", "v"))
  1694. return err
  1695. },
  1696. func(ctx context.Context, kv clientv3.KV) error {
  1697. _, err := kv.Do(ctx, clientv3.OpDelete("abc"))
  1698. return err
  1699. },
  1700. func(ctx context.Context, kv clientv3.KV) error {
  1701. _, err := kv.Do(ctx, clientv3.OpGet("abc"))
  1702. return err
  1703. },
  1704. func(ctx context.Context, kv clientv3.KV) error {
  1705. op := clientv3.OpTxn(nil, []clientv3.Op{clientv3.OpGet("abc")}, nil)
  1706. _, err := kv.Do(ctx, op)
  1707. return err
  1708. },
  1709. }
  1710. for i := range tests {
  1711. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "foo/", concurrency.WithTTL(1))
  1712. testutil.AssertNil(t, err)
  1713. defer closeLKV()
  1714. if _, err = lkv.Get(context.TODO(), "abc"); err != nil {
  1715. t.Fatal(err)
  1716. }
  1717. // down endpoint lkv uses for keepalives
  1718. clus.Members[0].Stop(t)
  1719. if err := waitForLeasingExpire(clus.Client(1), "foo/abc"); err != nil {
  1720. t.Fatal(err)
  1721. }
  1722. waitForExpireAck(t, lkv)
  1723. ctx, cancel := context.WithCancel(context.TODO())
  1724. errc := make(chan error, 1)
  1725. go func() { errc <- tests[i](ctx, lkv) }()
  1726. // some delay to get past for ctx.Err() != nil {} loops
  1727. time.Sleep(100 * time.Millisecond)
  1728. cancel()
  1729. select {
  1730. case err := <-errc:
  1731. if err != ctx.Err() {
  1732. t.Errorf("#%d: expected %v, got %v", i, ctx.Err(), err)
  1733. }
  1734. case <-time.After(5 * time.Second):
  1735. t.Errorf("#%d: timed out waiting for cancel", i)
  1736. }
  1737. clus.Members[0].Restart(t)
  1738. }
  1739. }
  1740. func waitForLeasingExpire(kv clientv3.KV, lkey string) error {
  1741. for {
  1742. time.Sleep(1 * time.Second)
  1743. resp, err := kv.Get(context.TODO(), lkey, clientv3.WithPrefix())
  1744. if err != nil {
  1745. return err
  1746. }
  1747. if len(resp.Kvs) == 0 {
  1748. // server expired the leasing key
  1749. return nil
  1750. }
  1751. }
  1752. }
  1753. func waitForExpireAck(t *testing.T, kv clientv3.KV) {
  1754. // wait for leasing client to acknowledge lost lease
  1755. for i := 0; i < 10; i++ {
  1756. ctx, cancel := context.WithTimeout(context.TODO(), time.Second)
  1757. _, err := kv.Get(ctx, "abc")
  1758. cancel()
  1759. if err == ctx.Err() {
  1760. return
  1761. }
  1762. time.Sleep(time.Second)
  1763. }
  1764. t.Fatalf("waited too long to acknlowedge lease expiration")
  1765. }