watch_command.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. "errors"
  17. "os"
  18. "os/signal"
  19. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/codegangsta/cli"
  20. "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/context"
  21. "github.com/coreos/etcd/client"
  22. )
  23. // NewWatchCommand returns the CLI command for "watch".
  24. func NewWatchCommand() cli.Command {
  25. return cli.Command{
  26. Name: "watch",
  27. Usage: "watch a key for changes",
  28. Flags: []cli.Flag{
  29. cli.BoolFlag{Name: "forever", Usage: "forever watch a key until CTRL+C"},
  30. cli.IntFlag{Name: "after-index", Value: 0, Usage: "watch after the given index"},
  31. cli.BoolFlag{Name: "recursive", Usage: "returns all values for key and child keys"},
  32. },
  33. Action: func(c *cli.Context) {
  34. watchCommandFunc(c, mustNewKeyAPI(c))
  35. },
  36. }
  37. }
  38. // watchCommandFunc executes the "watch" command.
  39. func watchCommandFunc(c *cli.Context, ki client.KeysAPI) {
  40. if len(c.Args()) == 0 {
  41. handleError(ExitBadArgs, errors.New("key required"))
  42. }
  43. key := c.Args()[0]
  44. recursive := c.Bool("recursive")
  45. forever := c.Bool("forever")
  46. index := 0
  47. if c.Int("after-index") != 0 {
  48. index = c.Int("after-index") + 1
  49. }
  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(ExitServerError, err)
  62. }
  63. if resp.Node.Dir {
  64. continue
  65. }
  66. printResponseKey(resp, c.GlobalString("output"))
  67. if !forever {
  68. stop = true
  69. }
  70. }
  71. }