watch_command.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. // Copyright 2015 CoreOS, Inc.
  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. "io"
  19. "os"
  20. "strconv"
  21. "strings"
  22. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/spf13/cobra"
  23. "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/context"
  24. "github.com/coreos/etcd/clientv3"
  25. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  26. )
  27. var (
  28. watchRev int64
  29. watchPrefix bool
  30. watchHex bool
  31. watchInteractive bool
  32. )
  33. // NewWatchCommand returns the cobra command for "watch".
  34. func NewWatchCommand() *cobra.Command {
  35. cmd := &cobra.Command{
  36. Use: "watch [key or prefix]",
  37. Short: "Watch watches events stream on keys or prefixes.",
  38. Run: watchCommandFunc,
  39. }
  40. cmd.Flags().BoolVar(&watchHex, "hex", false, "print out key and value as hex encode string for text format")
  41. cmd.Flags().BoolVarP(&watchInteractive, "interactive", "i", false, "interactive mode")
  42. cmd.Flags().BoolVar(&watchPrefix, "prefix", false, "watch on a prefix if prefix is set")
  43. cmd.Flags().Int64Var(&watchRev, "rev", 0, "revision to start watching")
  44. return cmd
  45. }
  46. // watchCommandFunc executes the "watch" command.
  47. func watchCommandFunc(cmd *cobra.Command, args []string) {
  48. if watchInteractive {
  49. watchInteractiveFunc(cmd, args)
  50. return
  51. }
  52. if len(args) != 1 {
  53. ExitWithError(ExitBadArgs, fmt.Errorf("watch in non-interactive mode requires an argument as key or prefix"))
  54. }
  55. c := mustClientFromCmd(cmd)
  56. w := clientv3.NewWatcher(c)
  57. var wc clientv3.WatchChan
  58. if !watchPrefix {
  59. wc = w.Watch(context.TODO(), args[0], watchRev)
  60. } else {
  61. wc = w.Watch(context.TODO(), args[0], watchRev)
  62. }
  63. for resp := range wc {
  64. for _, e := range resp.Events {
  65. fmt.Printf("%s\r\n", e.Type)
  66. printKV(watchHex, e.Kv)
  67. }
  68. }
  69. err := w.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. wStream, err := mustClientFromCmd(cmd).Watch.Watch(context.TODO())
  77. if err != nil {
  78. ExitWithError(ExitBadConnection, err)
  79. }
  80. go recvLoop(wStream)
  81. reader := bufio.NewReader(os.Stdin)
  82. for {
  83. l, err := reader.ReadString('\n')
  84. if err != nil {
  85. ExitWithError(ExitInvalidInput, fmt.Errorf("Error reading watch request line: %v", err))
  86. }
  87. l = strings.TrimSuffix(l, "\n")
  88. // TODO: support start and end revision
  89. segs := strings.Split(l, " ")
  90. if len(segs) != 2 {
  91. fmt.Fprintf(os.Stderr, "Invalid watch request format: use \"watch [key]\", \"watchprefix [prefix]\" or \"cancel [watcher ID]\"\n")
  92. continue
  93. }
  94. var r *pb.WatchRequest
  95. switch segs[0] {
  96. case "watch":
  97. r = &pb.WatchRequest{
  98. RequestUnion: &pb.WatchRequest_CreateRequest{
  99. CreateRequest: &pb.WatchCreateRequest{
  100. Key: []byte(segs[1])}}}
  101. case "watchprefix":
  102. r = &pb.WatchRequest{
  103. RequestUnion: &pb.WatchRequest_CreateRequest{
  104. CreateRequest: &pb.WatchCreateRequest{
  105. Prefix: []byte(segs[1])}}}
  106. case "cancel":
  107. id, perr := strconv.ParseInt(segs[1], 10, 64)
  108. if perr != nil {
  109. fmt.Fprintf(os.Stderr, "Invalid cancel ID (%v)\n", perr)
  110. continue
  111. }
  112. r = &pb.WatchRequest{
  113. RequestUnion: &pb.WatchRequest_CancelRequest{
  114. CancelRequest: &pb.WatchCancelRequest{
  115. WatchId: id}}}
  116. default:
  117. fmt.Fprintf(os.Stderr, "Invalid watch request type: use watch, watchprefix or cancel\n")
  118. continue
  119. }
  120. err = wStream.Send(r)
  121. if err != nil {
  122. fmt.Fprintf(os.Stderr, "Error sending request to server: %v\n", err)
  123. }
  124. }
  125. }
  126. func recvLoop(wStream pb.Watch_WatchClient) {
  127. for {
  128. resp, err := wStream.Recv()
  129. if err == io.EOF {
  130. os.Exit(ExitSuccess)
  131. }
  132. if err != nil {
  133. ExitWithError(ExitError, err)
  134. }
  135. switch {
  136. // TODO: handle canceled/compacted and other control response types
  137. case resp.Created:
  138. fmt.Printf("watcher created: id %08x\n", resp.WatchId)
  139. case resp.Canceled:
  140. fmt.Printf("watcher canceled: id %08x\n", resp.WatchId)
  141. default:
  142. for _, ev := range resp.Events {
  143. fmt.Printf("%s: %s %s\n", ev.Type, string(ev.Kv.Key), string(ev.Kv.Value))
  144. }
  145. }
  146. }
  147. }