forked from hashicorp/consul
-
Notifications
You must be signed in to change notification settings - Fork 0
/
watch.go
206 lines (182 loc) · 4.93 KB
/
watch.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
package command
import (
"bytes"
"encoding/json"
"fmt"
"os"
"strconv"
"strings"
"github.com/hashicorp/consul/agent"
"github.com/hashicorp/consul/watch"
)
// WatchCommand is a Command implementation that is used to setup
// a "watch" which uses a sub-process
type WatchCommand struct {
BaseCommand
ShutdownCh <-chan struct{}
}
func (c *WatchCommand) Help() string {
helpText := `
Usage: consul watch [options] [child...]
Watches for changes in a given data view from Consul. If a child process
is specified, it will be invoked with the latest results on changes. Otherwise,
the latest values are dumped to stdout and the watch terminates.
Providing the watch type is required, and other parameters may be required
or supported depending on the watch type.
` + c.BaseCommand.Help()
return strings.TrimSpace(helpText)
}
func (c *WatchCommand) Run(args []string) int {
var watchType, key, prefix, service, tag, passingOnly, state, name string
f := c.BaseCommand.NewFlagSet(c)
f.StringVar(&watchType, "type", "",
"Specifies the watch type. One of key, keyprefix, services, nodes, "+
"service, checks, or event.")
f.StringVar(&key, "key", "",
"Specifies the key to watch. Only for 'key' type.")
f.StringVar(&prefix, "prefix", "",
"Specifies the key prefix to watch. Only for 'keyprefix' type.")
f.StringVar(&service, "service", "",
"Specifies the service to watch. Required for 'service' type, "+
"optional for 'checks' type.")
f.StringVar(&tag, "tag", "",
"Specifies the service tag to filter on. Optional for 'service' type.")
f.StringVar(&passingOnly, "passingonly", "",
"Specifies if only hosts passing all checks are displayed. "+
"Optional for 'service' type, must be one of `[true|false]`. Defaults false.")
f.StringVar(&state, "state", "",
"Specifies the states to watch. Optional for 'checks' type.")
f.StringVar(&name, "name", "",
"Specifies an event name to watch. Only for 'event' type.")
if err := c.BaseCommand.Parse(args); err != nil {
return 1
}
// Check for a type
if watchType == "" {
c.UI.Error("Watch type must be specified")
c.UI.Error("")
c.UI.Error(c.Help())
return 1
}
// Grab the script to execute if any
script := strings.Join(f.Args(), " ")
// Compile the watch parameters
params := make(map[string]interface{})
if watchType != "" {
params["type"] = watchType
}
if c.BaseCommand.HTTPDatacenter() != "" {
params["datacenter"] = c.BaseCommand.HTTPDatacenter()
}
if c.BaseCommand.HTTPToken() != "" {
params["token"] = c.BaseCommand.HTTPToken()
}
if key != "" {
params["key"] = key
}
if prefix != "" {
params["prefix"] = prefix
}
if service != "" {
params["service"] = service
}
if tag != "" {
params["tag"] = tag
}
if c.BaseCommand.HTTPStale() {
params["stale"] = c.BaseCommand.HTTPStale()
}
if state != "" {
params["state"] = state
}
if name != "" {
params["name"] = name
}
if passingOnly != "" {
b, err := strconv.ParseBool(passingOnly)
if err != nil {
c.UI.Error(fmt.Sprintf("Failed to parse passingonly flag: %s", err))
return 1
}
params["passingonly"] = b
}
// Create the watch
wp, err := watch.Parse(params)
if err != nil {
c.UI.Error(fmt.Sprintf("%s", err))
return 1
}
// Create and test the HTTP client
client, err := c.BaseCommand.HTTPClient()
if err != nil {
c.UI.Error(fmt.Sprintf("Error connecting to Consul agent: %s", err))
return 1
}
_, err = client.Agent().NodeName()
if err != nil {
c.UI.Error(fmt.Sprintf("Error querying Consul agent: %s", err))
return 1
}
// Setup handler
// errExit:
// 0: false
// 1: true
errExit := 0
if script == "" {
wp.Handler = func(idx uint64, data interface{}) {
defer wp.Stop()
buf, err := json.MarshalIndent(data, "", " ")
if err != nil {
c.UI.Error(fmt.Sprintf("Error encoding output: %s", err))
errExit = 1
}
c.UI.Output(string(buf))
}
} else {
wp.Handler = func(idx uint64, data interface{}) {
// Create the command
var buf bytes.Buffer
var err error
cmd, err := agent.ExecScript(script)
if err != nil {
c.UI.Error(fmt.Sprintf("Error executing handler: %s", err))
goto ERR
}
cmd.Env = append(os.Environ(),
"CONSUL_INDEX="+strconv.FormatUint(idx, 10),
)
// Encode the input
if err = json.NewEncoder(&buf).Encode(data); err != nil {
c.UI.Error(fmt.Sprintf("Error encoding output: %s", err))
goto ERR
}
cmd.Stdin = &buf
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
// Run the handler
if err := cmd.Run(); err != nil {
c.UI.Error(fmt.Sprintf("Error executing handler: %s", err))
goto ERR
}
return
ERR:
wp.Stop()
errExit = 1
}
}
// Watch for a shutdown
go func() {
<-c.ShutdownCh
wp.Stop()
os.Exit(0)
}()
// Run the watch
if err := wp.Run(c.BaseCommand.HTTPAddr()); err != nil {
c.UI.Error(fmt.Sprintf("Error querying Consul agent: %s", err))
return 1
}
return errExit
}
func (c *WatchCommand) Synopsis() string {
return "Watch for changes in Consul"
}