forked from mantl/consul-cli
/
kv_unlock.go
107 lines (84 loc) · 2.28 KB
/
kv_unlock.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package commands
import (
"fmt"
"github.com/spf13/cobra"
)
type KvUnlockOptions struct {
Session string
NoDestroy bool
}
func (k *Kv) AddUnlockSub(cmd *cobra.Command) {
kuo := &KvUnlockOptions{}
unlockCmd := &cobra.Command{
Use: "unlock <path>",
Short: "Release a lock on a given path",
Long: "Release a lock on a given path",
RunE: func(cmd *cobra.Command, args []string) error {
return k.Unlock(args, kuo)
},
}
oldUnlockCmd := &cobra.Command{
Use: "kv-unlock <path>",
Short: "Release a lock on a given path",
Long: "Release a lock on a given path",
Deprecated: "Use kv unlock",
Hidden: true,
RunE: func(cmd *cobra.Command, args []string) error {
return k.Unlock(args, kuo)
},
}
unlockCmd.Flags().StringVar(&kuo.Session, "session", "", "Session ID of the lock holder. Required")
unlockCmd.Flags().BoolVar(&kuo.NoDestroy, "no-destroy", false, "Do not destroy the session when complete")
k.AddDatacenterOption(unlockCmd)
oldUnlockCmd.Flags().StringVar(&kuo.Session, "session", "", "Session ID of the lock holder. Required")
oldUnlockCmd.Flags().BoolVar(&kuo.NoDestroy, "no-destroy", false, "Do not destroy the session when complete")
k.AddDatacenterOption(oldUnlockCmd)
cmd.AddCommand(unlockCmd)
k.AddCommand(oldUnlockCmd)
}
func (k *Kv) Unlock(args []string, kuo *KvUnlockOptions) error {
if kuo.Session == "" {
return fmt.Errorf("Session ID must be provided")
}
switch {
case len(args) == 0:
return fmt.Errorf("Key path must be specified")
case len(args) > 1:
return fmt.Errorf("Only one key path allowed")
}
path := args[0]
client, err := k.KV()
if err != nil {
return err
}
sessionClient, err := k.Session()
if err != nil {
return err
}
queryOpts := k.QueryOptions()
kv, _, err := client.Get(path, queryOpts)
if err != nil {
return err
}
if kv == nil {
return fmt.Errorf("Node '%s' does not exist", path)
}
if kv.Session != kuo.Session {
return fmt.Errorf("Session not lock holder")
}
writeOpts := k.WriteOptions()
success, _, err := client.Release(kv, writeOpts)
if err != nil {
return err
}
if !kuo.NoDestroy {
_, err = sessionClient.Destroy(kuo.Session, writeOpts)
if err != nil {
return err
}
}
if !success {
return fmt.Errorf("Failed unlocking path")
}
return nil
}