exec_watch_command.go 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. // Copyright 2015 The etcd Authors
  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. "context"
  17. "errors"
  18. "fmt"
  19. "os"
  20. "os/exec"
  21. "os/signal"
  22. "go.etcd.io/etcd/client"
  23. "github.com/urfave/cli"
  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, r", Usage: "watch all values for key and child keys"},
  34. },
  35. Action: func(c *cli.Context) error {
  36. execWatchCommandFunc(c, mustNewKeyAPI(c))
  37. return nil
  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(c, 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")
  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(c, ExitServerError, err)
  84. }
  85. if resp.Node.Dir {
  86. fmt.Fprintf(os.Stderr, "Ignored dir %s change\n", resp.Node.Key)
  87. continue
  88. }
  89. cmd := exec.Command(cmdArgs[0], cmdArgs[1:]...)
  90. cmd.Env = environResponse(resp, os.Environ())
  91. cmd.Stdout = os.Stdout
  92. cmd.Stderr = os.Stderr
  93. go func() {
  94. err := cmd.Start()
  95. if err != nil {
  96. fmt.Fprintf(os.Stderr, err.Error())
  97. os.Exit(1)
  98. }
  99. cmd.Wait()
  100. }()
  101. }
  102. }
  103. func environResponse(resp *client.Response, env []string) []string {
  104. env = append(env, "ETCD_WATCH_ACTION="+resp.Action)
  105. env = append(env, "ETCD_WATCH_MODIFIED_INDEX="+fmt.Sprintf("%d", resp.Node.ModifiedIndex))
  106. env = append(env, "ETCD_WATCH_KEY="+resp.Node.Key)
  107. env = append(env, "ETCD_WATCH_VALUE="+resp.Node.Value)
  108. return env
  109. }