watch_command.go 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  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 [key or prefix]",
  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 {
  48. ExitWithError(ExitBadArgs, fmt.Errorf("watch in non-interactive mode requires an argument as key or prefix"))
  49. }
  50. opts := []clientv3.OpOption{clientv3.WithRev(watchRev)}
  51. if watchPrefix {
  52. opts = append(opts, clientv3.WithPrefix())
  53. }
  54. c := mustClientFromCmd(cmd)
  55. wc := c.Watch(context.TODO(), args[0], opts...)
  56. printWatchCh(wc)
  57. err := c.Close()
  58. if err == nil {
  59. ExitWithError(ExitInterrupted, fmt.Errorf("watch is canceled by the server"))
  60. }
  61. ExitWithError(ExitBadConnection, err)
  62. }
  63. func watchInteractiveFunc(cmd *cobra.Command, args []string) {
  64. c := mustClientFromCmd(cmd)
  65. reader := bufio.NewReader(os.Stdin)
  66. for {
  67. l, err := reader.ReadString('\n')
  68. if err != nil {
  69. ExitWithError(ExitInvalidInput, fmt.Errorf("Error reading watch request line: %v", err))
  70. }
  71. l = strings.TrimSuffix(l, "\n")
  72. args := argify(l)
  73. if len(args) < 2 {
  74. fmt.Fprintf(os.Stderr, "Invalid command %s (command type or key is not provided)\n", l)
  75. continue
  76. }
  77. if args[0] != "watch" {
  78. fmt.Fprintf(os.Stderr, "Invalid command %s (only support watch)\n", l)
  79. continue
  80. }
  81. flagset := NewWatchCommand().Flags()
  82. err = flagset.Parse(args[1:])
  83. if err != nil {
  84. fmt.Fprintf(os.Stderr, "Invalid command %s (%v)\n", l, err)
  85. continue
  86. }
  87. moreargs := flagset.Args()
  88. if len(moreargs) != 1 {
  89. fmt.Fprintf(os.Stderr, "Invalid command %s (Too many arguments)\n", l)
  90. continue
  91. }
  92. var key string
  93. _, err = fmt.Sscanf(moreargs[0], "%q", &key)
  94. if err != nil {
  95. key = moreargs[0]
  96. }
  97. opts := []clientv3.OpOption{clientv3.WithRev(watchRev)}
  98. if watchPrefix {
  99. opts = append(opts, clientv3.WithPrefix())
  100. }
  101. ch := c.Watch(context.TODO(), key, opts...)
  102. go printWatchCh(ch)
  103. }
  104. }
  105. func printWatchCh(ch clientv3.WatchChan) {
  106. for resp := range ch {
  107. display.Watch(resp)
  108. }
  109. }