watch_command.go 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  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/Godeps/_workspace/src/google.golang.org/grpc"
  25. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  26. )
  27. // NewWatchCommand returns the cobra command for "watch".
  28. func NewWatchCommand() *cobra.Command {
  29. return &cobra.Command{
  30. Use: "watch",
  31. Short: "Watch watches the events happening or happened.",
  32. Run: watchCommandFunc,
  33. }
  34. }
  35. // watchCommandFunc executes the "watch" command.
  36. func watchCommandFunc(cmd *cobra.Command, args []string) {
  37. endpoint, err := cmd.Flags().GetString("endpoint")
  38. if err != nil {
  39. ExitWithError(ExitInvalidInput, err)
  40. }
  41. // TODO: enable grpc.WithTransportCredentials(creds)
  42. conn, err := grpc.Dial(endpoint, grpc.WithInsecure())
  43. if err != nil {
  44. ExitWithError(ExitBadConnection, err)
  45. }
  46. wAPI := pb.NewWatchClient(conn)
  47. wStream, err := wAPI.Watch(context.TODO())
  48. if err != nil {
  49. ExitWithError(ExitBadConnection, err)
  50. }
  51. go recvLoop(wStream)
  52. reader := bufio.NewReader(os.Stdin)
  53. for {
  54. l, err := reader.ReadString('\n')
  55. if err != nil {
  56. ExitWithError(ExitInvalidInput, fmt.Errorf("Error reading watch request line: %v", err))
  57. }
  58. l = strings.TrimSuffix(l, "\n")
  59. // TODO: support start and end revision
  60. segs := strings.Split(l, " ")
  61. if len(segs) != 2 {
  62. fmt.Fprintf(os.Stderr, "Invalid watch request format: use \"watch [key]\", \"watchprefix [prefix]\" or \"cancel [watcher ID]\"\n")
  63. continue
  64. }
  65. var r *pb.WatchRequest
  66. switch segs[0] {
  67. case "watch":
  68. r = &pb.WatchRequest{
  69. RequestUnion: &pb.WatchRequest_CreateRequest{
  70. CreateRequest: &pb.WatchCreateRequest{
  71. Key: []byte(segs[1])}}}
  72. case "watchprefix":
  73. r = &pb.WatchRequest{
  74. RequestUnion: &pb.WatchRequest_CreateRequest{
  75. CreateRequest: &pb.WatchCreateRequest{
  76. Prefix: []byte(segs[1])}}}
  77. case "cancel":
  78. id, perr := strconv.ParseInt(segs[1], 10, 64)
  79. if perr != nil {
  80. fmt.Fprintf(os.Stderr, "Invalid cancel ID (%v)\n", perr)
  81. continue
  82. }
  83. r = &pb.WatchRequest{
  84. RequestUnion: &pb.WatchRequest_CancelRequest{
  85. CancelRequest: &pb.WatchCancelRequest{
  86. WatchId: id}}}
  87. default:
  88. fmt.Fprintf(os.Stderr, "Invalid watch request type: use watch, watchprefix or cancel\n")
  89. continue
  90. }
  91. err = wStream.Send(r)
  92. if err != nil {
  93. fmt.Fprintf(os.Stderr, "Error sending request to server: %v\n", err)
  94. }
  95. }
  96. }
  97. func recvLoop(wStream pb.Watch_WatchClient) {
  98. for {
  99. resp, err := wStream.Recv()
  100. if err == io.EOF {
  101. os.Exit(ExitSuccess)
  102. }
  103. if err != nil {
  104. ExitWithError(ExitError, err)
  105. }
  106. switch {
  107. // TODO: handle canceled/compacted and other control response types
  108. case resp.Created:
  109. fmt.Printf("watcher created: id %08x\n", resp.WatchId)
  110. case resp.Canceled:
  111. fmt.Printf("watcher canceled: id %08x\n", resp.WatchId)
  112. default:
  113. for _, ev := range resp.Events {
  114. fmt.Printf("%s: %s %s\n", ev.Type, string(ev.Kv.Key), string(ev.Kv.Value))
  115. }
  116. }
  117. }
  118. }