open-consul/command/watch.go
Frank Schroeder cd837b0b18 pkg refactor
command/agent/*                  -> agent/*
    command/consul/*                 -> agent/consul/*
    command/agent/command{,_test}.go -> command/agent{,_test}.go
    command/base/command.go          -> command/base.go
    command/base/*                   -> command/*
    commands.go                      -> command/commands.go

The script which did the refactor is:

(
	cd $GOPATH/src/github.com/hashicorp/consul
	git mv command/agent/command.go command/agent.go
	git mv command/agent/command_test.go command/agent_test.go
	git mv command/agent/flag_slice_value{,_test}.go command/
	git mv command/agent .
	git mv command/base/command.go command/base.go
	git mv command/base/config_util{,_test}.go command/
	git mv commands.go command/
	git mv consul agent
	rmdir command/base/

	gsed -i -e 's|package agent|package command|' command/agent{,_test}.go
	gsed -i -e 's|package agent|package command|' command/flag_slice_value{,_test}.go
	gsed -i -e 's|package base|package command|' command/base.go command/config_util{,_test}.go
	gsed -i -e 's|package main|package command|' command/commands.go

	gsed -i -e 's|base.Command|BaseCommand|' command/commands.go
	gsed -i -e 's|agent.Command|AgentCommand|' command/commands.go
	gsed -i -e 's|\tCommand:|\tBaseCommand:|' command/commands.go
	gsed -i -e 's|base\.||' command/commands.go
	gsed -i -e 's|command\.||' command/commands.go

	gsed -i -e 's|command|c|' main.go
	gsed -i -e 's|range Commands|range command.Commands|' main.go
	gsed -i -e 's|Commands: Commands|Commands: command.Commands|' main.go

	gsed -i -e 's|base\.BoolValue|BoolValue|' command/operator_autopilot_set.go
	gsed -i -e 's|base\.DurationValue|DurationValue|' command/operator_autopilot_set.go
	gsed -i -e 's|base\.StringValue|StringValue|' command/operator_autopilot_set.go
	gsed -i -e 's|base\.UintValue|UintValue|' command/operator_autopilot_set.go

	gsed -i -e 's|\bCommand\b|BaseCommand|' command/base.go
	gsed -i -e 's|BaseCommand Options|Command Options|' command/base.go
	gsed -i -e 's|base.Command|BaseCommand|' command/*.go
	gsed -i -e 's|c\.Command|c.BaseCommand|g' command/*.go
	gsed -i -e 's|\tCommand:|\tBaseCommand:|' command/*_test.go
	gsed -i -e 's|base\.||' command/*_test.go

	gsed -i -e 's|\bCommand\b|AgentCommand|' command/agent{,_test}.go
	gsed -i -e 's|cmd.AgentCommand|cmd.BaseCommand|' command/agent.go

	gsed -i -e 's|cli.AgentCommand = new(Command)|cli.Command = new(AgentCommand)|' command/agent_test.go
	gsed -i -e 's|exec.AgentCommand|exec.Command|' command/agent_test.go
	gsed -i -e 's|exec.BaseCommand|exec.Command|' command/agent_test.go
	gsed -i -e 's|NewTestAgent|agent.NewTestAgent|' command/agent_test.go
	gsed -i -e 's|= TestConfig|= agent.TestConfig|' command/agent_test.go
	gsed -i -e 's|: RetryJoin|: agent.RetryJoin|' command/agent_test.go

	gsed -i -e 's|\.\./\.\./|../|' command/config_util_test.go

	gsed -i -e 's|\bverifyUniqueListeners|VerifyUniqueListeners|' agent/config{,_test}.go command/agent.go
	gsed -i -e 's|\bserfLANKeyring\b|SerfLANKeyring|g' agent/{agent,keyring,testagent}.go command/agent.go
	gsed -i -e 's|\bserfWANKeyring\b|SerfWANKeyring|g' agent/{agent,keyring,testagent}.go command/agent.go
	gsed -i -e 's|\bNewAgent\b|agent.New|g' command/agent{,_test}.go
	gsed -i -e 's|\bNewAgent|New|' agent/{acl_test,agent,testagent}.go

	gsed -i -e 's|\bAgent\b|agent.&|g' command/agent{,_test}.go
	gsed -i -e 's|\bBool\b|agent.&|g' command/agent{,_test}.go
	gsed -i -e 's|\bConfig\b|agent.&|g' command/agent{,_test}.go
	gsed -i -e 's|\bDefaultConfig\b|agent.&|g' command/agent{,_test}.go
	gsed -i -e 's|\bDevConfig\b|agent.&|g' command/agent{,_test}.go
	gsed -i -e 's|\bMergeConfig\b|agent.&|g' command/agent{,_test}.go
	gsed -i -e 's|\bReadConfigPaths\b|agent.&|g' command/agent{,_test}.go
	gsed -i -e 's|\bParseMetaPair\b|agent.&|g' command/agent{,_test}.go
	gsed -i -e 's|\bSerfLANKeyring\b|agent.&|g' command/agent{,_test}.go
	gsed -i -e 's|\bSerfWANKeyring\b|agent.&|g' command/agent{,_test}.go

	gsed -i -e 's|circonus\.agent|circonus|g' command/agent{,_test}.go
	gsed -i -e 's|logger\.agent|logger|g' command/agent{,_test}.go
	gsed -i -e 's|metrics\.agent|metrics|g' command/agent{,_test}.go
	gsed -i -e 's|// agent.Agent|// agent|' command/agent{,_test}.go
	gsed -i -e 's|a\.agent\.Config|a.Config|' command/agent{,_test}.go

	gsed -i -e 's|agent\.AppendSliceValue|AppendSliceValue|' command/{configtest,validate}.go

	gsed -i -e 's|consul/consul|agent/consul|' GNUmakefile

	gsed -i -e 's|\.\./test|../../test|' agent/consul/server_test.go

	# fix imports
	f=$(grep -rl 'github.com/hashicorp/consul/command/agent' * | grep '\.go')
	gsed -i -e 's|github.com/hashicorp/consul/command/agent|github.com/hashicorp/consul/agent|' $f
	goimports -w $f

	f=$(grep -rl 'github.com/hashicorp/consul/consul' * | grep '\.go')
	gsed -i -e 's|github.com/hashicorp/consul/consul|github.com/hashicorp/consul/agent/consul|' $f
	goimports -w $f

	goimports -w command/*.go main.go
)
2017-06-10 18:52:45 +02:00

207 lines
4.9 KiB
Go

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"
}