watch_command.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. "context"
  17. "errors"
  18. "fmt"
  19. "os"
  20. "os/signal"
  21. "go.etcd.io/etcd/client"
  22. "github.com/urfave/cli"
  23. )
  24. // NewWatchCommand returns the CLI command for "watch".
  25. func NewWatchCommand() cli.Command {
  26. return cli.Command{
  27. Name: "watch",
  28. Usage: "watch a key for changes",
  29. ArgsUsage: "<key>",
  30. Flags: []cli.Flag{
  31. cli.BoolFlag{Name: "forever, f", Usage: "forever watch a key until CTRL+C"},
  32. cli.IntFlag{Name: "after-index", Value: 0, Usage: "watch after the given index"},
  33. cli.BoolFlag{Name: "recursive, r", Usage: "returns all values for key and child keys"},
  34. },
  35. Action: func(c *cli.Context) error {
  36. watchCommandFunc(c, mustNewKeyAPI(c))
  37. return nil
  38. },
  39. }
  40. }
  41. // watchCommandFunc executes the "watch" command.
  42. func watchCommandFunc(c *cli.Context, ki client.KeysAPI) {
  43. if len(c.Args()) == 0 {
  44. handleError(c, ExitBadArgs, errors.New("key required"))
  45. }
  46. key := c.Args()[0]
  47. recursive := c.Bool("recursive")
  48. forever := c.Bool("forever")
  49. index := c.Int("after-index")
  50. stop := false
  51. w := ki.Watcher(key, &client.WatcherOptions{AfterIndex: uint64(index), Recursive: recursive})
  52. sigch := make(chan os.Signal, 1)
  53. signal.Notify(sigch, os.Interrupt)
  54. go func() {
  55. <-sigch
  56. os.Exit(0)
  57. }()
  58. for !stop {
  59. resp, err := w.Next(context.TODO())
  60. if err != nil {
  61. handleError(c, ExitServerError, err)
  62. }
  63. if resp.Node.Dir {
  64. continue
  65. }
  66. if recursive {
  67. fmt.Printf("[%s] %s\n", resp.Action, resp.Node.Key)
  68. }
  69. printResponseKey(resp, c.GlobalString("output"))
  70. if !forever {
  71. stop = true
  72. }
  73. }
  74. }