watch_command.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. "fmt"
  18. "os"
  19. "os/signal"
  20. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/codegangsta/cli"
  21. "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/context"
  22. "github.com/coreos/etcd/client"
  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", 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", Usage: "returns all values for key and child keys"},
  34. },
  35. Action: func(c *cli.Context) {
  36. watchCommandFunc(c, mustNewKeyAPI(c))
  37. },
  38. }
  39. }
  40. // watchCommandFunc executes the "watch" command.
  41. func watchCommandFunc(c *cli.Context, ki client.KeysAPI) {
  42. if len(c.Args()) == 0 {
  43. handleError(ExitBadArgs, errors.New("key required"))
  44. }
  45. key := c.Args()[0]
  46. recursive := c.Bool("recursive")
  47. forever := c.Bool("forever")
  48. index := c.Int("after-index")
  49. stop := false
  50. w := ki.Watcher(key, &client.WatcherOptions{AfterIndex: uint64(index), Recursive: recursive})
  51. sigch := make(chan os.Signal, 1)
  52. signal.Notify(sigch, os.Interrupt)
  53. go func() {
  54. <-sigch
  55. os.Exit(0)
  56. }()
  57. for !stop {
  58. resp, err := w.Next(context.TODO())
  59. if err != nil {
  60. handleError(ExitServerError, err)
  61. }
  62. if resp.Node.Dir {
  63. continue
  64. }
  65. if recursive {
  66. fmt.Printf("[%s] %s\n", resp.Action, resp.Node.Key)
  67. }
  68. printResponseKey(resp, c.GlobalString("output"))
  69. if !forever {
  70. stop = true
  71. }
  72. }
  73. }