exec_watch_command.go 3.4 KB

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