op.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  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 clientv3
  15. import pb "go.etcd.io/etcd/etcdserver/etcdserverpb"
  16. type opType int
  17. const (
  18. // A default Op has opType 0, which is invalid.
  19. tRange opType = iota + 1
  20. tPut
  21. tDeleteRange
  22. tTxn
  23. )
  24. var noPrefixEnd = []byte{0}
  25. // Op represents an Operation that kv can execute.
  26. type Op struct {
  27. t opType
  28. key []byte
  29. end []byte
  30. // for range
  31. limit int64
  32. sort *SortOption
  33. serializable bool
  34. keysOnly bool
  35. countOnly bool
  36. minModRev int64
  37. maxModRev int64
  38. minCreateRev int64
  39. maxCreateRev int64
  40. // for range, watch
  41. rev int64
  42. // for watch, put, delete
  43. prevKV bool
  44. // for watch
  45. // fragmentation should be disabled by default
  46. // if true, split watch events when total exceeds
  47. // "--max-request-bytes" flag value + 512-byte
  48. fragment bool
  49. // for put
  50. ignoreValue bool
  51. ignoreLease bool
  52. // progressNotify is for progress updates.
  53. progressNotify bool
  54. // createdNotify is for created event
  55. createdNotify bool
  56. // filters for watchers
  57. filterPut bool
  58. filterDelete bool
  59. // for put
  60. val []byte
  61. leaseID LeaseID
  62. // txn
  63. cmps []Cmp
  64. thenOps []Op
  65. elseOps []Op
  66. }
  67. // accessors / mutators
  68. // IsTxn returns true if the "Op" type is transaction.
  69. func (op Op) IsTxn() bool {
  70. return op.t == tTxn
  71. }
  72. // Txn returns the comparison(if) operations, "then" operations, and "else" operations.
  73. func (op Op) Txn() ([]Cmp, []Op, []Op) {
  74. return op.cmps, op.thenOps, op.elseOps
  75. }
  76. // KeyBytes returns the byte slice holding the Op's key.
  77. func (op Op) KeyBytes() []byte { return op.key }
  78. // WithKeyBytes sets the byte slice for the Op's key.
  79. func (op *Op) WithKeyBytes(key []byte) { op.key = key }
  80. // RangeBytes returns the byte slice holding with the Op's range end, if any.
  81. func (op Op) RangeBytes() []byte { return op.end }
  82. // Rev returns the requested revision, if any.
  83. func (op Op) Rev() int64 { return op.rev }
  84. // IsPut returns true iff the operation is a Put.
  85. func (op Op) IsPut() bool { return op.t == tPut }
  86. // IsGet returns true iff the operation is a Get.
  87. func (op Op) IsGet() bool { return op.t == tRange }
  88. // IsDelete returns true iff the operation is a Delete.
  89. func (op Op) IsDelete() bool { return op.t == tDeleteRange }
  90. // IsSerializable returns true if the serializable field is true.
  91. func (op Op) IsSerializable() bool { return op.serializable }
  92. // IsKeysOnly returns whether keysOnly is set.
  93. func (op Op) IsKeysOnly() bool { return op.keysOnly }
  94. // IsCountOnly returns whether countOnly is set.
  95. func (op Op) IsCountOnly() bool { return op.countOnly }
  96. // MinModRev returns the operation's minimum modify revision.
  97. func (op Op) MinModRev() int64 { return op.minModRev }
  98. // MaxModRev returns the operation's maximum modify revision.
  99. func (op Op) MaxModRev() int64 { return op.maxModRev }
  100. // MinCreateRev returns the operation's minimum create revision.
  101. func (op Op) MinCreateRev() int64 { return op.minCreateRev }
  102. // MaxCreateRev returns the operation's maximum create revision.
  103. func (op Op) MaxCreateRev() int64 { return op.maxCreateRev }
  104. // WithRangeBytes sets the byte slice for the Op's range end.
  105. func (op *Op) WithRangeBytes(end []byte) { op.end = end }
  106. // ValueBytes returns the byte slice holding the Op's value, if any.
  107. func (op Op) ValueBytes() []byte { return op.val }
  108. // WithValueBytes sets the byte slice for the Op's value.
  109. func (op *Op) WithValueBytes(v []byte) { op.val = v }
  110. func (op Op) toRangeRequest() *pb.RangeRequest {
  111. if op.t != tRange {
  112. panic("op.t != tRange")
  113. }
  114. r := &pb.RangeRequest{
  115. Key: op.key,
  116. RangeEnd: op.end,
  117. Limit: op.limit,
  118. Revision: op.rev,
  119. Serializable: op.serializable,
  120. KeysOnly: op.keysOnly,
  121. CountOnly: op.countOnly,
  122. MinModRevision: op.minModRev,
  123. MaxModRevision: op.maxModRev,
  124. MinCreateRevision: op.minCreateRev,
  125. MaxCreateRevision: op.maxCreateRev,
  126. }
  127. if op.sort != nil {
  128. r.SortOrder = pb.RangeRequest_SortOrder(op.sort.Order)
  129. r.SortTarget = pb.RangeRequest_SortTarget(op.sort.Target)
  130. }
  131. return r
  132. }
  133. func (op Op) toTxnRequest() *pb.TxnRequest {
  134. thenOps := make([]*pb.RequestOp, len(op.thenOps))
  135. for i, tOp := range op.thenOps {
  136. thenOps[i] = tOp.toRequestOp()
  137. }
  138. elseOps := make([]*pb.RequestOp, len(op.elseOps))
  139. for i, eOp := range op.elseOps {
  140. elseOps[i] = eOp.toRequestOp()
  141. }
  142. cmps := make([]*pb.Compare, len(op.cmps))
  143. for i := range op.cmps {
  144. cmps[i] = (*pb.Compare)(&op.cmps[i])
  145. }
  146. return &pb.TxnRequest{Compare: cmps, Success: thenOps, Failure: elseOps}
  147. }
  148. func (op Op) toRequestOp() *pb.RequestOp {
  149. switch op.t {
  150. case tRange:
  151. return &pb.RequestOp{Request: &pb.RequestOp_RequestRange{RequestRange: op.toRangeRequest()}}
  152. case tPut:
  153. r := &pb.PutRequest{Key: op.key, Value: op.val, Lease: int64(op.leaseID), PrevKv: op.prevKV, IgnoreValue: op.ignoreValue, IgnoreLease: op.ignoreLease}
  154. return &pb.RequestOp{Request: &pb.RequestOp_RequestPut{RequestPut: r}}
  155. case tDeleteRange:
  156. r := &pb.DeleteRangeRequest{Key: op.key, RangeEnd: op.end, PrevKv: op.prevKV}
  157. return &pb.RequestOp{Request: &pb.RequestOp_RequestDeleteRange{RequestDeleteRange: r}}
  158. case tTxn:
  159. return &pb.RequestOp{Request: &pb.RequestOp_RequestTxn{RequestTxn: op.toTxnRequest()}}
  160. default:
  161. panic("Unknown Op")
  162. }
  163. }
  164. func (op Op) isWrite() bool {
  165. if op.t == tTxn {
  166. for _, tOp := range op.thenOps {
  167. if tOp.isWrite() {
  168. return true
  169. }
  170. }
  171. for _, tOp := range op.elseOps {
  172. if tOp.isWrite() {
  173. return true
  174. }
  175. }
  176. return false
  177. }
  178. return op.t != tRange
  179. }
  180. // OpGet returns "get" operation based on given key and operation options.
  181. func OpGet(key string, opts ...OpOption) Op {
  182. // WithPrefix and WithFromKey are not supported together
  183. if isWithPrefix(opts) && isWithFromKey(opts) {
  184. panic("`WithPrefix` and `WithFromKey` cannot be set at the same time, choose one")
  185. }
  186. ret := Op{t: tRange, key: []byte(key)}
  187. ret.applyOpts(opts)
  188. return ret
  189. }
  190. // OpDelete returns "delete" operation based on given key and operation options.
  191. func OpDelete(key string, opts ...OpOption) Op {
  192. // WithPrefix and WithFromKey are not supported together
  193. if isWithPrefix(opts) && isWithFromKey(opts) {
  194. panic("`WithPrefix` and `WithFromKey` cannot be set at the same time, choose one")
  195. }
  196. ret := Op{t: tDeleteRange, key: []byte(key)}
  197. ret.applyOpts(opts)
  198. switch {
  199. case ret.leaseID != 0:
  200. panic("unexpected lease in delete")
  201. case ret.limit != 0:
  202. panic("unexpected limit in delete")
  203. case ret.rev != 0:
  204. panic("unexpected revision in delete")
  205. case ret.sort != nil:
  206. panic("unexpected sort in delete")
  207. case ret.serializable:
  208. panic("unexpected serializable in delete")
  209. case ret.countOnly:
  210. panic("unexpected countOnly in delete")
  211. case ret.minModRev != 0, ret.maxModRev != 0:
  212. panic("unexpected mod revision filter in delete")
  213. case ret.minCreateRev != 0, ret.maxCreateRev != 0:
  214. panic("unexpected create revision filter in delete")
  215. case ret.filterDelete, ret.filterPut:
  216. panic("unexpected filter in delete")
  217. case ret.createdNotify:
  218. panic("unexpected createdNotify in delete")
  219. }
  220. return ret
  221. }
  222. // OpPut returns "put" operation based on given key-value and operation options.
  223. func OpPut(key, val string, opts ...OpOption) Op {
  224. ret := Op{t: tPut, key: []byte(key), val: []byte(val)}
  225. ret.applyOpts(opts)
  226. switch {
  227. case ret.end != nil:
  228. panic("unexpected range in put")
  229. case ret.limit != 0:
  230. panic("unexpected limit in put")
  231. case ret.rev != 0:
  232. panic("unexpected revision in put")
  233. case ret.sort != nil:
  234. panic("unexpected sort in put")
  235. case ret.serializable:
  236. panic("unexpected serializable in put")
  237. case ret.countOnly:
  238. panic("unexpected countOnly in put")
  239. case ret.minModRev != 0, ret.maxModRev != 0:
  240. panic("unexpected mod revision filter in put")
  241. case ret.minCreateRev != 0, ret.maxCreateRev != 0:
  242. panic("unexpected create revision filter in put")
  243. case ret.filterDelete, ret.filterPut:
  244. panic("unexpected filter in put")
  245. case ret.createdNotify:
  246. panic("unexpected createdNotify in put")
  247. }
  248. return ret
  249. }
  250. // OpTxn returns "txn" operation based on given transaction conditions.
  251. func OpTxn(cmps []Cmp, thenOps []Op, elseOps []Op) Op {
  252. return Op{t: tTxn, cmps: cmps, thenOps: thenOps, elseOps: elseOps}
  253. }
  254. func opWatch(key string, opts ...OpOption) Op {
  255. ret := Op{t: tRange, key: []byte(key)}
  256. ret.applyOpts(opts)
  257. switch {
  258. case ret.leaseID != 0:
  259. panic("unexpected lease in watch")
  260. case ret.limit != 0:
  261. panic("unexpected limit in watch")
  262. case ret.sort != nil:
  263. panic("unexpected sort in watch")
  264. case ret.serializable:
  265. panic("unexpected serializable in watch")
  266. case ret.countOnly:
  267. panic("unexpected countOnly in watch")
  268. case ret.minModRev != 0, ret.maxModRev != 0:
  269. panic("unexpected mod revision filter in watch")
  270. case ret.minCreateRev != 0, ret.maxCreateRev != 0:
  271. panic("unexpected create revision filter in watch")
  272. }
  273. return ret
  274. }
  275. func (op *Op) applyOpts(opts []OpOption) {
  276. for _, opt := range opts {
  277. opt(op)
  278. }
  279. }
  280. // OpOption configures Operations like Get, Put, Delete.
  281. type OpOption func(*Op)
  282. // WithLease attaches a lease ID to a key in 'Put' request.
  283. func WithLease(leaseID LeaseID) OpOption {
  284. return func(op *Op) { op.leaseID = leaseID }
  285. }
  286. // WithLimit limits the number of results to return from 'Get' request.
  287. // If WithLimit is given a 0 limit, it is treated as no limit.
  288. func WithLimit(n int64) OpOption { return func(op *Op) { op.limit = n } }
  289. // WithRev specifies the store revision for 'Get' request.
  290. // Or the start revision of 'Watch' request.
  291. func WithRev(rev int64) OpOption { return func(op *Op) { op.rev = rev } }
  292. // WithSort specifies the ordering in 'Get' request. It requires
  293. // 'WithRange' and/or 'WithPrefix' to be specified too.
  294. // 'target' specifies the target to sort by: key, version, revisions, value.
  295. // 'order' can be either 'SortNone', 'SortAscend', 'SortDescend'.
  296. func WithSort(target SortTarget, order SortOrder) OpOption {
  297. return func(op *Op) {
  298. if target == SortByKey && order == SortAscend {
  299. // If order != SortNone, server fetches the entire key-space,
  300. // and then applies the sort and limit, if provided.
  301. // Since by default the server returns results sorted by keys
  302. // in lexicographically ascending order, the client should ignore
  303. // SortOrder if the target is SortByKey.
  304. order = SortNone
  305. }
  306. op.sort = &SortOption{target, order}
  307. }
  308. }
  309. // GetPrefixRangeEnd gets the range end of the prefix.
  310. // 'Get(foo, WithPrefix())' is equal to 'Get(foo, WithRange(GetPrefixRangeEnd(foo))'.
  311. func GetPrefixRangeEnd(prefix string) string {
  312. return string(getPrefix([]byte(prefix)))
  313. }
  314. func getPrefix(key []byte) []byte {
  315. end := make([]byte, len(key))
  316. copy(end, key)
  317. for i := len(end) - 1; i >= 0; i-- {
  318. if end[i] < 0xff {
  319. end[i] = end[i] + 1
  320. end = end[:i+1]
  321. return end
  322. }
  323. }
  324. // next prefix does not exist (e.g., 0xffff);
  325. // default to WithFromKey policy
  326. return noPrefixEnd
  327. }
  328. // WithPrefix enables 'Get', 'Delete', or 'Watch' requests to operate
  329. // on the keys with matching prefix. For example, 'Get(foo, WithPrefix())'
  330. // can return 'foo1', 'foo2', and so on.
  331. func WithPrefix() OpOption {
  332. return func(op *Op) {
  333. if len(op.key) == 0 {
  334. op.key, op.end = []byte{0}, []byte{0}
  335. return
  336. }
  337. op.end = getPrefix(op.key)
  338. }
  339. }
  340. // WithRange specifies the range of 'Get', 'Delete', 'Watch' requests.
  341. // For example, 'Get' requests with 'WithRange(end)' returns
  342. // the keys in the range [key, end).
  343. // endKey must be lexicographically greater than start key.
  344. func WithRange(endKey string) OpOption {
  345. return func(op *Op) { op.end = []byte(endKey) }
  346. }
  347. // WithFromKey specifies the range of 'Get', 'Delete', 'Watch' requests
  348. // to be equal or greater than the key in the argument.
  349. func WithFromKey() OpOption {
  350. return func(op *Op) {
  351. if len(op.key) == 0 {
  352. op.key = []byte{0}
  353. }
  354. op.end = []byte("\x00")
  355. }
  356. }
  357. // WithSerializable makes 'Get' request serializable. By default,
  358. // it's linearizable. Serializable requests are better for lower latency
  359. // requirement.
  360. func WithSerializable() OpOption {
  361. return func(op *Op) { op.serializable = true }
  362. }
  363. // WithKeysOnly makes the 'Get' request return only the keys and the corresponding
  364. // values will be omitted.
  365. func WithKeysOnly() OpOption {
  366. return func(op *Op) { op.keysOnly = true }
  367. }
  368. // WithCountOnly makes the 'Get' request return only the count of keys.
  369. func WithCountOnly() OpOption {
  370. return func(op *Op) { op.countOnly = true }
  371. }
  372. // WithMinModRev filters out keys for Get with modification revisions less than the given revision.
  373. func WithMinModRev(rev int64) OpOption { return func(op *Op) { op.minModRev = rev } }
  374. // WithMaxModRev filters out keys for Get with modification revisions greater than the given revision.
  375. func WithMaxModRev(rev int64) OpOption { return func(op *Op) { op.maxModRev = rev } }
  376. // WithMinCreateRev filters out keys for Get with creation revisions less than the given revision.
  377. func WithMinCreateRev(rev int64) OpOption { return func(op *Op) { op.minCreateRev = rev } }
  378. // WithMaxCreateRev filters out keys for Get with creation revisions greater than the given revision.
  379. func WithMaxCreateRev(rev int64) OpOption { return func(op *Op) { op.maxCreateRev = rev } }
  380. // WithFirstCreate gets the key with the oldest creation revision in the request range.
  381. func WithFirstCreate() []OpOption { return withTop(SortByCreateRevision, SortAscend) }
  382. // WithLastCreate gets the key with the latest creation revision in the request range.
  383. func WithLastCreate() []OpOption { return withTop(SortByCreateRevision, SortDescend) }
  384. // WithFirstKey gets the lexically first key in the request range.
  385. func WithFirstKey() []OpOption { return withTop(SortByKey, SortAscend) }
  386. // WithLastKey gets the lexically last key in the request range.
  387. func WithLastKey() []OpOption { return withTop(SortByKey, SortDescend) }
  388. // WithFirstRev gets the key with the oldest modification revision in the request range.
  389. func WithFirstRev() []OpOption { return withTop(SortByModRevision, SortAscend) }
  390. // WithLastRev gets the key with the latest modification revision in the request range.
  391. func WithLastRev() []OpOption { return withTop(SortByModRevision, SortDescend) }
  392. // withTop gets the first key over the get's prefix given a sort order
  393. func withTop(target SortTarget, order SortOrder) []OpOption {
  394. return []OpOption{WithPrefix(), WithSort(target, order), WithLimit(1)}
  395. }
  396. // WithProgressNotify makes watch server send periodic progress updates
  397. // every 10 minutes when there is no incoming events.
  398. // Progress updates have zero events in WatchResponse.
  399. func WithProgressNotify() OpOption {
  400. return func(op *Op) {
  401. op.progressNotify = true
  402. }
  403. }
  404. // WithCreatedNotify makes watch server sends the created event.
  405. func WithCreatedNotify() OpOption {
  406. return func(op *Op) {
  407. op.createdNotify = true
  408. }
  409. }
  410. // WithFilterPut discards PUT events from the watcher.
  411. func WithFilterPut() OpOption {
  412. return func(op *Op) { op.filterPut = true }
  413. }
  414. // WithFilterDelete discards DELETE events from the watcher.
  415. func WithFilterDelete() OpOption {
  416. return func(op *Op) { op.filterDelete = true }
  417. }
  418. // WithPrevKV gets the previous key-value pair before the event happens. If the previous KV is already compacted,
  419. // nothing will be returned.
  420. func WithPrevKV() OpOption {
  421. return func(op *Op) {
  422. op.prevKV = true
  423. }
  424. }
  425. // WithFragment to receive raw watch response with fragmentation.
  426. // Fragmentation is disabled by default. If fragmentation is enabled,
  427. // etcd watch server will split watch response before sending to clients
  428. // when the total size of watch events exceed server-side request limit.
  429. // The default server-side request limit is 1.5 MiB, which can be configured
  430. // as "--max-request-bytes" flag value + gRPC-overhead 512 bytes.
  431. // See "etcdserver/api/v3rpc/watch.go" for more details.
  432. func WithFragment() OpOption {
  433. return func(op *Op) { op.fragment = true }
  434. }
  435. // WithIgnoreValue updates the key using its current value.
  436. // This option can not be combined with non-empty values.
  437. // Returns an error if the key does not exist.
  438. func WithIgnoreValue() OpOption {
  439. return func(op *Op) {
  440. op.ignoreValue = true
  441. }
  442. }
  443. // WithIgnoreLease updates the key using its current lease.
  444. // This option can not be combined with WithLease.
  445. // Returns an error if the key does not exist.
  446. func WithIgnoreLease() OpOption {
  447. return func(op *Op) {
  448. op.ignoreLease = true
  449. }
  450. }
  451. // LeaseOp represents an Operation that lease can execute.
  452. type LeaseOp struct {
  453. id LeaseID
  454. // for TimeToLive
  455. attachedKeys bool
  456. }
  457. // LeaseOption configures lease operations.
  458. type LeaseOption func(*LeaseOp)
  459. func (op *LeaseOp) applyOpts(opts []LeaseOption) {
  460. for _, opt := range opts {
  461. opt(op)
  462. }
  463. }
  464. // WithAttachedKeys makes TimeToLive list the keys attached to the given lease ID.
  465. func WithAttachedKeys() LeaseOption {
  466. return func(op *LeaseOp) { op.attachedKeys = true }
  467. }
  468. func toLeaseTimeToLiveRequest(id LeaseID, opts ...LeaseOption) *pb.LeaseTimeToLiveRequest {
  469. ret := &LeaseOp{id: id}
  470. ret.applyOpts(opts)
  471. return &pb.LeaseTimeToLiveRequest{ID: int64(id), Keys: ret.attachedKeys}
  472. }
  473. // isWithPrefix returns true if WithPrefix is being called in the op
  474. func isWithPrefix(opts []OpOption) bool { return isOpFuncCalled("WithPrefix", opts) }
  475. // isWithFromKey returns true if WithFromKey is being called in the op
  476. func isWithFromKey(opts []OpOption) bool { return isOpFuncCalled("WithFromKey", opts) }