watch_command.go 2.2 KB

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