watch_command.go 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  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. c := mustClientFromCmd(cmd)
  50. wc, err := getWatchChan(c, args)
  51. if err != nil {
  52. ExitWithError(ExitBadArgs, err)
  53. }
  54. printWatchCh(wc)
  55. if err = c.Close(); err != nil {
  56. ExitWithError(ExitBadConnection, err)
  57. }
  58. ExitWithError(ExitInterrupted, fmt.Errorf("watch is canceled by the server"))
  59. }
  60. func watchInteractiveFunc(cmd *cobra.Command, args []string) {
  61. c := mustClientFromCmd(cmd)
  62. reader := bufio.NewReader(os.Stdin)
  63. for {
  64. l, err := reader.ReadString('\n')
  65. if err != nil {
  66. ExitWithError(ExitInvalidInput, fmt.Errorf("Error reading watch request line: %v", err))
  67. }
  68. l = strings.TrimSuffix(l, "\n")
  69. args := argify(l)
  70. if len(args) < 2 {
  71. fmt.Fprintf(os.Stderr, "Invalid command %s (command type or key is not provided)\n", l)
  72. continue
  73. }
  74. if args[0] != "watch" {
  75. fmt.Fprintf(os.Stderr, "Invalid command %s (only support watch)\n", l)
  76. continue
  77. }
  78. flagset := NewWatchCommand().Flags()
  79. err = flagset.Parse(args[1:])
  80. if err != nil {
  81. fmt.Fprintf(os.Stderr, "Invalid command %s (%v)\n", l, err)
  82. continue
  83. }
  84. ch, err := getWatchChan(c, flagset.Args())
  85. if err != nil {
  86. fmt.Fprintf(os.Stderr, "Invalid command %s (%v)\n", l, err)
  87. continue
  88. }
  89. go printWatchCh(ch)
  90. }
  91. }
  92. func getWatchChan(c *clientv3.Client, args []string) (clientv3.WatchChan, error) {
  93. if len(args) < 1 || len(args) > 2 {
  94. return nil, fmt.Errorf("bad number of arguments")
  95. }
  96. key := args[0]
  97. opts := []clientv3.OpOption{clientv3.WithRev(watchRev)}
  98. if len(args) == 2 {
  99. if watchPrefix {
  100. return nil, fmt.Errorf("`range_end` and `--prefix` are mutually exclusive")
  101. }
  102. opts = append(opts, clientv3.WithRange(args[1]))
  103. }
  104. if watchPrefix {
  105. opts = append(opts, clientv3.WithPrefix())
  106. }
  107. if watchPrevKey {
  108. opts = append(opts, clientv3.WithPrevKV())
  109. }
  110. return c.Watch(context.TODO(), key, opts...), nil
  111. }
  112. func printWatchCh(ch clientv3.WatchChan) {
  113. for resp := range ch {
  114. if resp.Canceled {
  115. fmt.Fprintf(os.Stderr, "watch was canceled (%v)\n", resp.Err())
  116. }
  117. display.Watch(resp)
  118. }
  119. }