lock_command.go 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. // Copyright 2016 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. "syscall"
  23. "github.com/coreos/etcd/clientv3"
  24. "github.com/coreos/etcd/clientv3/concurrency"
  25. "github.com/spf13/cobra"
  26. )
  27. var lockTTL = 10
  28. // NewLockCommand returns the cobra command for "lock".
  29. func NewLockCommand() *cobra.Command {
  30. c := &cobra.Command{
  31. Use: "lock <lockname> [exec-command arg1 arg2 ...]",
  32. Short: "Acquires a named lock",
  33. Run: lockCommandFunc,
  34. }
  35. c.Flags().IntVarP(&lockTTL, "ttl", "", lockTTL, "timeout for session")
  36. return c
  37. }
  38. func lockCommandFunc(cmd *cobra.Command, args []string) {
  39. if len(args) == 0 {
  40. ExitWithError(ExitBadArgs, errors.New("lock takes a lock name argument and an optional command to execute."))
  41. }
  42. c := mustClientFromCmd(cmd)
  43. if err := lockUntilSignal(c, args[0], args[1:]); err != nil {
  44. ExitWithError(ExitError, err)
  45. }
  46. }
  47. func lockUntilSignal(c *clientv3.Client, lockname string, cmdArgs []string) error {
  48. s, err := concurrency.NewSession(c, concurrency.WithTTL(lockTTL))
  49. if err != nil {
  50. return err
  51. }
  52. m := concurrency.NewMutex(s, lockname)
  53. ctx, cancel := context.WithCancel(context.TODO())
  54. // unlock in case of ordinary shutdown
  55. donec := make(chan struct{})
  56. sigc := make(chan os.Signal, 1)
  57. signal.Notify(sigc, syscall.SIGINT, syscall.SIGTERM)
  58. go func() {
  59. <-sigc
  60. cancel()
  61. close(donec)
  62. }()
  63. if err := m.Lock(ctx); err != nil {
  64. return err
  65. }
  66. if len(cmdArgs) > 0 {
  67. cmd := exec.Command(cmdArgs[0], cmdArgs[1:]...)
  68. cmd.Env = append(environLockResponse(m), os.Environ()...)
  69. cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr
  70. err := cmd.Run()
  71. unlockErr := m.Unlock(context.TODO())
  72. if err != nil {
  73. return err
  74. }
  75. return unlockErr
  76. }
  77. k, kerr := c.Get(ctx, m.Key())
  78. if kerr != nil {
  79. return kerr
  80. }
  81. if len(k.Kvs) == 0 {
  82. return errors.New("lock lost on init")
  83. }
  84. display.Get(*k)
  85. select {
  86. case <-donec:
  87. return m.Unlock(context.TODO())
  88. case <-s.Done():
  89. }
  90. return errors.New("session expired")
  91. }
  92. func environLockResponse(m *concurrency.Mutex) []string {
  93. return []string{
  94. "ETCD_LOCK_KEY=" + m.Key(),
  95. fmt.Sprintf("ETCD_LOCK_REV=%d", m.Header().Revision),
  96. }
  97. }