txn_command.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. // Copyright 2015 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 command
  15. import (
  16. "bufio"
  17. "context"
  18. "fmt"
  19. "os"
  20. "strconv"
  21. "strings"
  22. "github.com/coreos/etcd/clientv3"
  23. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  24. "github.com/spf13/cobra"
  25. )
  26. var (
  27. txnInteractive bool
  28. )
  29. // NewTxnCommand returns the cobra command for "txn".
  30. func NewTxnCommand() *cobra.Command {
  31. cmd := &cobra.Command{
  32. Use: "txn [options]",
  33. Short: "Txn processes all the requests in one transaction",
  34. Run: txnCommandFunc,
  35. }
  36. cmd.Flags().BoolVarP(&txnInteractive, "interactive", "i", false, "Input transaction in interactive mode")
  37. return cmd
  38. }
  39. // txnCommandFunc executes the "txn" command.
  40. func txnCommandFunc(cmd *cobra.Command, args []string) {
  41. if len(args) != 0 {
  42. ExitWithError(ExitBadArgs, fmt.Errorf("txn command does not accept argument."))
  43. }
  44. reader := bufio.NewReader(os.Stdin)
  45. txn := mustClientFromCmd(cmd).Txn(context.Background())
  46. promptInteractive("compares:")
  47. txn.If(readCompares(reader)...)
  48. promptInteractive("success requests (get, put, del):")
  49. txn.Then(readOps(reader)...)
  50. promptInteractive("failure requests (get, put, del):")
  51. txn.Else(readOps(reader)...)
  52. resp, err := txn.Commit()
  53. if err != nil {
  54. ExitWithError(ExitError, err)
  55. }
  56. display.Txn(*resp)
  57. }
  58. func promptInteractive(s string) {
  59. if txnInteractive {
  60. fmt.Println(s)
  61. }
  62. }
  63. func readCompares(r *bufio.Reader) (cmps []clientv3.Cmp) {
  64. for {
  65. line, err := r.ReadString('\n')
  66. if err != nil {
  67. ExitWithError(ExitInvalidInput, err)
  68. }
  69. // remove space from the line
  70. line = strings.TrimSpace(line)
  71. if len(line) == 0 {
  72. break
  73. }
  74. cmp, err := parseCompare(line)
  75. if err != nil {
  76. ExitWithError(ExitInvalidInput, err)
  77. }
  78. cmps = append(cmps, *cmp)
  79. }
  80. return cmps
  81. }
  82. func readOps(r *bufio.Reader) (ops []clientv3.Op) {
  83. for {
  84. line, err := r.ReadString('\n')
  85. if err != nil {
  86. ExitWithError(ExitInvalidInput, err)
  87. }
  88. // remove space from the line
  89. line = strings.TrimSpace(line)
  90. if len(line) == 0 {
  91. break
  92. }
  93. op, err := parseRequestUnion(line)
  94. if err != nil {
  95. ExitWithError(ExitInvalidInput, err)
  96. }
  97. ops = append(ops, *op)
  98. }
  99. return ops
  100. }
  101. func parseRequestUnion(line string) (*clientv3.Op, error) {
  102. args := argify(line)
  103. if len(args) < 2 {
  104. return nil, fmt.Errorf("invalid txn compare request: %s", line)
  105. }
  106. opc := make(chan clientv3.Op, 1)
  107. put := NewPutCommand()
  108. put.Run = func(cmd *cobra.Command, args []string) {
  109. key, value, opts := getPutOp(cmd, args)
  110. opc <- clientv3.OpPut(key, value, opts...)
  111. }
  112. get := NewGetCommand()
  113. get.Run = func(cmd *cobra.Command, args []string) {
  114. key, opts := getGetOp(cmd, args)
  115. opc <- clientv3.OpGet(key, opts...)
  116. }
  117. del := NewDelCommand()
  118. del.Run = func(cmd *cobra.Command, args []string) {
  119. key, opts := getDelOp(cmd, args)
  120. opc <- clientv3.OpDelete(key, opts...)
  121. }
  122. cmds := &cobra.Command{SilenceErrors: true}
  123. cmds.AddCommand(put, get, del)
  124. cmds.SetArgs(args)
  125. if err := cmds.Execute(); err != nil {
  126. return nil, fmt.Errorf("invalid txn request: %s", line)
  127. }
  128. op := <-opc
  129. return &op, nil
  130. }
  131. func parseCompare(line string) (*clientv3.Cmp, error) {
  132. var (
  133. key string
  134. op string
  135. val string
  136. )
  137. lparenSplit := strings.SplitN(line, "(", 2)
  138. if len(lparenSplit) != 2 {
  139. return nil, fmt.Errorf("malformed comparison: %s", line)
  140. }
  141. target := lparenSplit[0]
  142. n, serr := fmt.Sscanf(lparenSplit[1], "%q) %s %q", &key, &op, &val)
  143. if n != 3 {
  144. return nil, fmt.Errorf("malformed comparison: %s; got %s(%q) %s %q", line, target, key, op, val)
  145. }
  146. if serr != nil {
  147. return nil, fmt.Errorf("malformed comparison: %s (%v)", line, serr)
  148. }
  149. var (
  150. v int64
  151. err error
  152. cmp clientv3.Cmp
  153. )
  154. switch target {
  155. case "ver", "version":
  156. if v, err = strconv.ParseInt(val, 10, 64); err == nil {
  157. cmp = clientv3.Compare(clientv3.Version(key), op, v)
  158. }
  159. case "c", "create":
  160. if v, err = strconv.ParseInt(val, 10, 64); err == nil {
  161. cmp = clientv3.Compare(clientv3.CreateRevision(key), op, v)
  162. }
  163. case "m", "mod":
  164. if v, err = strconv.ParseInt(val, 10, 64); err == nil {
  165. cmp = clientv3.Compare(clientv3.ModRevision(key), op, v)
  166. }
  167. case "val", "value":
  168. cmp = clientv3.Compare(clientv3.Value(key), op, val)
  169. case "lease":
  170. cmp = clientv3.Compare(clientv3.Cmp{Target: pb.Compare_LEASE}, op, val)
  171. default:
  172. return nil, fmt.Errorf("malformed comparison: %s (unknown target %s)", line, target)
  173. }
  174. if err != nil {
  175. return nil, fmt.Errorf("invalid txn compare request: %s", line)
  176. }
  177. return &cmp, nil
  178. }