exec_watch_command.go 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  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/exec"
  20. "os/signal"
  21. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/codegangsta/cli"
  22. "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/context"
  23. "github.com/coreos/etcd/client"
  24. )
  25. // NewExecWatchCommand returns the CLI command for "exec-watch".
  26. func NewExecWatchCommand() cli.Command {
  27. return cli.Command{
  28. Name: "exec-watch",
  29. Usage: "watch a key for changes and exec an executable",
  30. ArgsUsage: "<key> <command> [args...]",
  31. Flags: []cli.Flag{
  32. cli.IntFlag{Name: "after-index", Value: 0, Usage: "watch after the given index"},
  33. cli.BoolFlag{Name: "recursive", Usage: "watch all values for key and child keys"},
  34. },
  35. Action: func(c *cli.Context) {
  36. execWatchCommandFunc(c, mustNewKeyAPI(c))
  37. },
  38. }
  39. }
  40. // execWatchCommandFunc executes the "exec-watch" command.
  41. func execWatchCommandFunc(c *cli.Context, ki client.KeysAPI) {
  42. args := c.Args()
  43. argslen := len(args)
  44. if argslen < 2 {
  45. handleError(ExitBadArgs, errors.New("key and command to exec required"))
  46. }
  47. var (
  48. key string
  49. cmdArgs []string
  50. )
  51. foundSep := false
  52. for i := range args {
  53. if args[i] == "--" && i != 0 {
  54. foundSep = true
  55. break
  56. }
  57. }
  58. if foundSep {
  59. key = args[0]
  60. cmdArgs = args[2:]
  61. } else {
  62. // If no flag is parsed, the order of key and cmdArgs will be switched and
  63. // args will not contain `--`.
  64. key = args[argslen-1]
  65. cmdArgs = args[:argslen-1]
  66. }
  67. index := 0
  68. if c.Int("after-index") != 0 {
  69. index = c.Int("after-index") + 1
  70. }
  71. recursive := c.Bool("recursive")
  72. sigch := make(chan os.Signal, 1)
  73. signal.Notify(sigch, os.Interrupt)
  74. go func() {
  75. <-sigch
  76. os.Exit(0)
  77. }()
  78. w := ki.Watcher(key, &client.WatcherOptions{AfterIndex: uint64(index), Recursive: recursive})
  79. for {
  80. resp, err := w.Next(context.TODO())
  81. if err != nil {
  82. handleError(ExitServerError, err)
  83. }
  84. if resp.Node.Dir {
  85. fmt.Fprintf(os.Stderr, "Ignored dir %s change", resp.Node.Key)
  86. continue
  87. }
  88. cmd := exec.Command(cmdArgs[0], cmdArgs[1:]...)
  89. cmd.Env = environResponse(resp, os.Environ())
  90. cmd.Stdout = os.Stdout
  91. cmd.Stderr = os.Stderr
  92. go func() {
  93. err := cmd.Start()
  94. if err != nil {
  95. fmt.Fprintf(os.Stderr, err.Error())
  96. os.Exit(1)
  97. }
  98. cmd.Wait()
  99. }()
  100. }
  101. }
  102. func environResponse(resp *client.Response, env []string) []string {
  103. env = append(env, "ETCD_WATCH_ACTION="+resp.Action)
  104. env = append(env, "ETCD_WATCH_MODIFIED_INDEX="+fmt.Sprintf("%d", resp.Node.ModifiedIndex))
  105. env = append(env, "ETCD_WATCH_KEY="+resp.Node.Key)
  106. env = append(env, "ETCD_WATCH_VALUE="+resp.Node.Value)
  107. return env
  108. }