watch_command.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  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. "fmt"
  18. "os"
  19. "strings"
  20. "github.com/coreos/etcd/clientv3"
  21. "github.com/spf13/cobra"
  22. "golang.org/x/net/context"
  23. )
  24. var (
  25. watchRev int64
  26. watchPrefix bool
  27. watchInteractive bool
  28. watchPrevKey bool
  29. )
  30. // NewWatchCommand returns the cobra command for "watch".
  31. func NewWatchCommand() *cobra.Command {
  32. cmd := &cobra.Command{
  33. Use: "watch [options] [key or prefix] [range_end]",
  34. Short: "Watches events stream on keys or prefixes",
  35. Run: watchCommandFunc,
  36. }
  37. cmd.Flags().BoolVarP(&watchInteractive, "interactive", "i", false, "Interactive mode")
  38. cmd.Flags().BoolVar(&watchPrefix, "prefix", false, "Watch on a prefix if prefix is set")
  39. cmd.Flags().Int64Var(&watchRev, "rev", 0, "Revision to start watching")
  40. cmd.Flags().BoolVar(&watchPrevKey, "prev-kv", false, "get the previous key-value pair before the event happens")
  41. return cmd
  42. }
  43. // watchCommandFunc executes the "watch" command.
  44. func watchCommandFunc(cmd *cobra.Command, args []string) {
  45. if watchInteractive {
  46. watchInteractiveFunc(cmd, args)
  47. return
  48. }
  49. if len(args) < 1 || len(args) > 2 {
  50. ExitWithError(ExitBadArgs, fmt.Errorf("watch in non-interactive mode requires one or two arguments as key or prefix, with range end"))
  51. }
  52. opts := []clientv3.OpOption{clientv3.WithRev(watchRev)}
  53. key := args[0]
  54. if len(args) == 2 {
  55. if watchPrefix {
  56. ExitWithError(ExitBadArgs, fmt.Errorf("`range_end` and `--prefix` cannot be set at the same time, choose one"))
  57. }
  58. opts = append(opts, clientv3.WithRange(args[1]))
  59. }
  60. if watchPrefix {
  61. opts = append(opts, clientv3.WithPrefix())
  62. }
  63. if watchPrevKey {
  64. opts = append(opts, clientv3.WithPrevKV())
  65. }
  66. c := mustClientFromCmd(cmd)
  67. wc := c.Watch(context.TODO(), key, opts...)
  68. printWatchCh(wc)
  69. err := c.Close()
  70. if err == nil {
  71. ExitWithError(ExitInterrupted, fmt.Errorf("watch is canceled by the server"))
  72. }
  73. ExitWithError(ExitBadConnection, err)
  74. }
  75. func watchInteractiveFunc(cmd *cobra.Command, args []string) {
  76. c := mustClientFromCmd(cmd)
  77. reader := bufio.NewReader(os.Stdin)
  78. for {
  79. l, err := reader.ReadString('\n')
  80. if err != nil {
  81. ExitWithError(ExitInvalidInput, fmt.Errorf("Error reading watch request line: %v", err))
  82. }
  83. l = strings.TrimSuffix(l, "\n")
  84. args := argify(l)
  85. if len(args) < 2 {
  86. fmt.Fprintf(os.Stderr, "Invalid command %s (command type or key is not provided)\n", l)
  87. continue
  88. }
  89. if args[0] != "watch" {
  90. fmt.Fprintf(os.Stderr, "Invalid command %s (only support watch)\n", l)
  91. continue
  92. }
  93. flagset := NewWatchCommand().Flags()
  94. err = flagset.Parse(args[1:])
  95. if err != nil {
  96. fmt.Fprintf(os.Stderr, "Invalid command %s (%v)\n", l, err)
  97. continue
  98. }
  99. moreargs := flagset.Args()
  100. if len(moreargs) < 1 || len(moreargs) > 2 {
  101. fmt.Fprintf(os.Stderr, "Invalid command %s (Too few or many arguments)\n", l)
  102. continue
  103. }
  104. var key string
  105. _, err = fmt.Sscanf(moreargs[0], "%q", &key)
  106. if err != nil {
  107. key = moreargs[0]
  108. }
  109. opts := []clientv3.OpOption{clientv3.WithRev(watchRev)}
  110. if len(moreargs) == 2 {
  111. if watchPrefix {
  112. fmt.Fprintf(os.Stderr, "`range_end` and `--prefix` cannot be set at the same time, choose one\n")
  113. continue
  114. }
  115. opts = append(opts, clientv3.WithRange(moreargs[1]))
  116. }
  117. if watchPrefix {
  118. opts = append(opts, clientv3.WithPrefix())
  119. }
  120. ch := c.Watch(context.TODO(), key, opts...)
  121. go printWatchCh(ch)
  122. }
  123. }
  124. func printWatchCh(ch clientv3.WatchChan) {
  125. for resp := range ch {
  126. display.Watch(resp)
  127. }
  128. }