watch_command.go 3.8 KB

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