golint: Rename fields and structs

pull/2956/head
Frank Schroeder 2017-04-20 17:02:42 -07:00 committed by Frank Schröder
parent 5a3961f31f
commit cf3ec1cf5c
91 changed files with 616 additions and 619 deletions

View File

@ -43,9 +43,7 @@ const (
aclCacheSize = 10 * 1024
)
var (
permissionDeniedErr = errors.New(permissionDenied)
)
var errPermissionDenied = errors.New(permissionDenied)
// aclCacheEntry is used to cache ACL tokens.
type aclCacheEntry struct {
@ -272,14 +270,14 @@ func (a *Agent) vetServiceRegister(token string, service *structs.NodeService) e
// Vet the service itself.
if !acl.ServiceWrite(service.Service) {
return permissionDeniedErr
return errPermissionDenied
}
// Vet any service that might be getting overwritten.
services := a.state.Services()
if existing, ok := services[service.ID]; ok {
if !acl.ServiceWrite(existing.Service) {
return permissionDeniedErr
return errPermissionDenied
}
}
@ -302,7 +300,7 @@ func (a *Agent) vetServiceUpdate(token string, serviceID string) error {
services := a.state.Services()
if existing, ok := services[serviceID]; ok {
if !acl.ServiceWrite(existing.Service) {
return permissionDeniedErr
return errPermissionDenied
}
} else {
return fmt.Errorf("Unknown service %q", serviceID)
@ -326,11 +324,11 @@ func (a *Agent) vetCheckRegister(token string, check *structs.HealthCheck) error
// Vet the check itself.
if len(check.ServiceName) > 0 {
if !acl.ServiceWrite(check.ServiceName) {
return permissionDeniedErr
return errPermissionDenied
}
} else {
if !acl.NodeWrite(a.config.NodeName) {
return permissionDeniedErr
return errPermissionDenied
}
}
@ -339,11 +337,11 @@ func (a *Agent) vetCheckRegister(token string, check *structs.HealthCheck) error
if existing, ok := checks[check.CheckID]; ok {
if len(existing.ServiceName) > 0 {
if !acl.ServiceWrite(existing.ServiceName) {
return permissionDeniedErr
return errPermissionDenied
}
} else {
if !acl.NodeWrite(a.config.NodeName) {
return permissionDeniedErr
return errPermissionDenied
}
}
}
@ -367,11 +365,11 @@ func (a *Agent) vetCheckUpdate(token string, checkID types.CheckID) error {
if existing, ok := checks[checkID]; ok {
if len(existing.ServiceName) > 0 {
if !acl.ServiceWrite(existing.ServiceName) {
return permissionDeniedErr
return errPermissionDenied
}
} else {
if !acl.NodeWrite(a.config.NodeName) {
return permissionDeniedErr
return errPermissionDenied
}
}
} else {

View File

@ -41,7 +41,7 @@ func (s *HTTPServer) AgentSelf(resp http.ResponseWriter, req *http.Request) (int
return nil, err
}
if acl != nil && !acl.AgentRead(s.agent.config.NodeName) {
return nil, permissionDeniedErr
return nil, errPermissionDenied
}
return AgentSelf{
@ -67,7 +67,7 @@ func (s *HTTPServer) AgentReload(resp http.ResponseWriter, req *http.Request) (i
return nil, err
}
if acl != nil && !acl.AgentWrite(s.agent.config.NodeName) {
return nil, permissionDeniedErr
return nil, errPermissionDenied
}
// Trigger the reload
@ -143,7 +143,7 @@ func (s *HTTPServer) AgentJoin(resp http.ResponseWriter, req *http.Request) (int
return nil, err
}
if acl != nil && !acl.AgentWrite(s.agent.config.NodeName) {
return nil, permissionDeniedErr
return nil, errPermissionDenied
}
// Check if the WAN is being queried
@ -177,7 +177,7 @@ func (s *HTTPServer) AgentLeave(resp http.ResponseWriter, req *http.Request) (in
return nil, err
}
if acl != nil && !acl.AgentWrite(s.agent.config.NodeName) {
return nil, permissionDeniedErr
return nil, errPermissionDenied
}
if err := s.agent.Leave(); err != nil {
@ -195,7 +195,7 @@ func (s *HTTPServer) AgentForceLeave(resp http.ResponseWriter, req *http.Request
return nil, err
}
if acl != nil && !acl.AgentWrite(s.agent.config.NodeName) {
return nil, permissionDeniedErr
return nil, errPermissionDenied
}
addr := strings.TrimPrefix(req.URL.Path, "/v1/agent/force-leave/")
@ -574,7 +574,7 @@ func (s *HTTPServer) AgentNodeMaintenance(resp http.ResponseWriter, req *http.Re
return nil, err
}
if acl != nil && !acl.NodeWrite(s.agent.config.NodeName) {
return nil, permissionDeniedErr
return nil, errPermissionDenied
}
if enable {
@ -601,7 +601,7 @@ func (s *HTTPServer) AgentMonitor(resp http.ResponseWriter, req *http.Request) (
return nil, err
}
if acl != nil && !acl.AgentRead(s.agent.config.NodeName) {
return nil, permissionDeniedErr
return nil, errPermissionDenied
}
// Get the provided loglevel.

View File

@ -331,7 +331,7 @@ func TestAgent_Reload(t *testing.T) {
ShutdownCh: shutdownCh,
Command: base.Command{
Flags: base.FlagSetNone,
Ui: new(cli.MockUi),
UI: new(cli.MockUi),
},
}

View File

@ -34,7 +34,7 @@ const (
// Use this user agent when doing requests for
// HTTP health checks.
HttpUserAgent = "Consul Health Check"
UserAgent = "Consul Health Check"
)
// CheckType is used to create either the CheckMonitor or the CheckTTL.
@ -428,7 +428,7 @@ func (c *CheckHTTP) check() {
return
}
req.Header.Set("User-Agent", HttpUserAgent)
req.Header.Set("User-Agent", UserAgent)
req.Header.Set("Accept", "text/plain, text/*, */*")
resp, err := c.httpClient.Do(req)

View File

@ -66,7 +66,7 @@ type Command struct {
httpServers []*HTTPServer
dnsServer *DNSServer
scadaProvider *scada.Provider
scadaHttp *HTTPServer
scadaHTTP *HTTPServer
}
// readConfig is responsible for setup of our configuration using
@ -107,8 +107,8 @@ func (c *Command) readConfig() *Config {
f.StringVar(&dcDeprecated, "dc", "", "Datacenter of the agent (deprecated: use 'datacenter' instead).")
f.StringVar(&cmdConfig.Datacenter, "datacenter", "", "Datacenter of the agent.")
f.StringVar(&cmdConfig.DataDir, "data-dir", "", "Path to a data directory to store agent state.")
f.BoolVar(&cmdConfig.EnableUi, "ui", false, "Enables the built-in static web UI server.")
f.StringVar(&cmdConfig.UiDir, "ui-dir", "", "Path to directory containing the web UI resources.")
f.BoolVar(&cmdConfig.EnableUI, "ui", false, "Enables the built-in static web UI server.")
f.StringVar(&cmdConfig.UIDir, "ui-dir", "", "Path to directory containing the web UI resources.")
f.StringVar(&cmdConfig.PidFile, "pid-file", "", "Path to file to store agent PID.")
f.StringVar(&cmdConfig.EncryptKey, "encrypt", "", "Provides the gossip encryption key.")
@ -189,7 +189,7 @@ func (c *Command) readConfig() *Config {
if retryInterval != "" {
dur, err := time.ParseDuration(retryInterval)
if err != nil {
c.Ui.Error(fmt.Sprintf("Error: %s", err))
c.UI.Error(fmt.Sprintf("Error: %s", err))
return nil
}
cmdConfig.RetryInterval = dur
@ -198,7 +198,7 @@ func (c *Command) readConfig() *Config {
if retryIntervalWan != "" {
dur, err := time.ParseDuration(retryIntervalWan)
if err != nil {
c.Ui.Error(fmt.Sprintf("Error: %s", err))
c.UI.Error(fmt.Sprintf("Error: %s", err))
return nil
}
cmdConfig.RetryIntervalWan = dur
@ -222,7 +222,7 @@ func (c *Command) readConfig() *Config {
if len(configFiles) > 0 {
fileConfig, err := ReadConfigPaths(configFiles)
if err != nil {
c.Ui.Error(err.Error())
c.UI.Error(err.Error())
return nil
}
@ -236,14 +236,14 @@ func (c *Command) readConfig() *Config {
if config.NodeName == "" {
hostname, err := os.Hostname()
if err != nil {
c.Ui.Error(fmt.Sprintf("Error determining node name: %s", err))
c.UI.Error(fmt.Sprintf("Error determining node name: %s", err))
return nil
}
config.NodeName = hostname
}
config.NodeName = strings.TrimSpace(config.NodeName)
if config.NodeName == "" {
c.Ui.Error("Node name can not be empty")
c.UI.Error("Node name can not be empty")
return nil
}
@ -259,24 +259,24 @@ func (c *Command) readConfig() *Config {
// Ensure we have a data directory if we are not in dev mode.
if !dev {
if config.DataDir == "" {
c.Ui.Error("Must specify data directory using -data-dir")
c.UI.Error("Must specify data directory using -data-dir")
return nil
}
if finfo, err := os.Stat(config.DataDir); err != nil {
if !os.IsNotExist(err) {
c.Ui.Error(fmt.Sprintf("Error getting data-dir: %s", err))
c.UI.Error(fmt.Sprintf("Error getting data-dir: %s", err))
return nil
}
} else if !finfo.IsDir() {
c.Ui.Error(fmt.Sprintf("The data-dir specified at %q is not a directory", config.DataDir))
c.UI.Error(fmt.Sprintf("The data-dir specified at %q is not a directory", config.DataDir))
return nil
}
}
// Ensure all endpoints are unique
if err := config.verifyUniqueListeners(); err != nil {
c.Ui.Error(fmt.Sprintf("All listening endpoints must be unique: %s", err))
c.UI.Error(fmt.Sprintf("All listening endpoints must be unique: %s", err))
return nil
}
@ -287,43 +287,43 @@ func (c *Command) readConfig() *Config {
mdbPath := filepath.Join(config.DataDir, "mdb")
if _, err := os.Stat(mdbPath); !os.IsNotExist(err) {
if os.IsPermission(err) {
c.Ui.Error(fmt.Sprintf("CRITICAL: Permission denied for data folder at %q!", mdbPath))
c.Ui.Error("Consul will refuse to boot without access to this directory.")
c.Ui.Error("Please correct permissions and try starting again.")
c.UI.Error(fmt.Sprintf("CRITICAL: Permission denied for data folder at %q!", mdbPath))
c.UI.Error("Consul will refuse to boot without access to this directory.")
c.UI.Error("Please correct permissions and try starting again.")
return nil
}
c.Ui.Error(fmt.Sprintf("CRITICAL: Deprecated data folder found at %q!", mdbPath))
c.Ui.Error("Consul will refuse to boot with this directory present.")
c.Ui.Error("See https://www.consul.io/docs/upgrade-specific.html for more information.")
c.UI.Error(fmt.Sprintf("CRITICAL: Deprecated data folder found at %q!", mdbPath))
c.UI.Error("Consul will refuse to boot with this directory present.")
c.UI.Error("See https://www.consul.io/docs/upgrade-specific.html for more information.")
return nil
}
}
// Verify DNS settings
if config.DNSConfig.UDPAnswerLimit < 1 {
c.Ui.Error(fmt.Sprintf("dns_config.udp_answer_limit %d too low, must always be greater than zero", config.DNSConfig.UDPAnswerLimit))
c.UI.Error(fmt.Sprintf("dns_config.udp_answer_limit %d too low, must always be greater than zero", config.DNSConfig.UDPAnswerLimit))
}
if config.EncryptKey != "" {
if _, err := config.EncryptBytes(); err != nil {
c.Ui.Error(fmt.Sprintf("Invalid encryption key: %s", err))
c.UI.Error(fmt.Sprintf("Invalid encryption key: %s", err))
return nil
}
keyfileLAN := filepath.Join(config.DataDir, serfLANKeyring)
if _, err := os.Stat(keyfileLAN); err == nil {
c.Ui.Error("WARNING: LAN keyring exists but -encrypt given, using keyring")
c.UI.Error("WARNING: LAN keyring exists but -encrypt given, using keyring")
}
if config.Server {
keyfileWAN := filepath.Join(config.DataDir, serfWANKeyring)
if _, err := os.Stat(keyfileWAN); err == nil {
c.Ui.Error("WARNING: WAN keyring exists but -encrypt given, using keyring")
c.UI.Error("WARNING: WAN keyring exists but -encrypt given, using keyring")
}
}
}
// Output a warning if the 'dc' flag has been used.
if dcDeprecated != "" {
c.Ui.Error("WARNING: the 'dc' flag has been deprecated. Use 'datacenter' instead")
c.UI.Error("WARNING: the 'dc' flag has been deprecated. Use 'datacenter' instead")
// Making sure that we don't break previous versions.
config.Datacenter = dcDeprecated
@ -335,7 +335,7 @@ func (c *Command) readConfig() *Config {
// Verify datacenter is valid
if !validDatacenter.MatchString(config.Datacenter) {
c.Ui.Error("Datacenter must be alpha-numeric with underscores and hypens only")
c.UI.Error("Datacenter must be alpha-numeric with underscores and hypens only")
return nil
}
@ -345,32 +345,32 @@ func (c *Command) readConfig() *Config {
// Verify 'acl_datacenter' is valid
if !validDatacenter.MatchString(config.ACLDatacenter) {
c.Ui.Error("ACL datacenter must be alpha-numeric with underscores and hypens only")
c.UI.Error("ACL datacenter must be alpha-numeric with underscores and hypens only")
return nil
}
}
// Only allow bootstrap mode when acting as a server
if config.Bootstrap && !config.Server {
c.Ui.Error("Bootstrap mode cannot be enabled when server mode is not enabled")
c.UI.Error("Bootstrap mode cannot be enabled when server mode is not enabled")
return nil
}
// Expect can only work when acting as a server
if config.BootstrapExpect != 0 && !config.Server {
c.Ui.Error("Expect mode cannot be enabled when server mode is not enabled")
c.UI.Error("Expect mode cannot be enabled when server mode is not enabled")
return nil
}
// Expect can only work when dev mode is off
if config.BootstrapExpect > 0 && config.DevMode {
c.Ui.Error("Expect mode cannot be enabled when dev mode is enabled")
c.UI.Error("Expect mode cannot be enabled when dev mode is enabled")
return nil
}
// Expect & Bootstrap are mutually exclusive
if config.BootstrapExpect != 0 && config.Bootstrap {
c.Ui.Error("Bootstrap cannot be provided with an expected server count")
c.UI.Error("Bootstrap cannot be provided with an expected server count")
return nil
}
@ -379,13 +379,13 @@ func (c *Command) readConfig() *Config {
// Parse the watches, excluding the handler
wp, err := watch.ParseExempt(params, []string{"handler"})
if err != nil {
c.Ui.Error(fmt.Sprintf("Failed to parse watch (%#v): %v", params, err))
c.UI.Error(fmt.Sprintf("Failed to parse watch (%#v): %v", params, err))
return nil
}
// Get the handler
if err := verifyWatchHandler(wp.Exempt["handler"]); err != nil {
c.Ui.Error(fmt.Sprintf("Failed to setup watch handler (%#v): %v", params, err))
c.UI.Error(fmt.Sprintf("Failed to setup watch handler (%#v): %v", params, err))
return nil
}
@ -395,42 +395,42 @@ func (c *Command) readConfig() *Config {
// Warn if we are in expect mode
if config.BootstrapExpect == 1 {
c.Ui.Error("WARNING: BootstrapExpect Mode is specified as 1; this is the same as Bootstrap mode.")
c.UI.Error("WARNING: BootstrapExpect Mode is specified as 1; this is the same as Bootstrap mode.")
config.BootstrapExpect = 0
config.Bootstrap = true
} else if config.BootstrapExpect > 0 {
c.Ui.Error(fmt.Sprintf("WARNING: Expect Mode enabled, expecting %d servers", config.BootstrapExpect))
c.UI.Error(fmt.Sprintf("WARNING: Expect Mode enabled, expecting %d servers", config.BootstrapExpect))
}
// Warn if we are in bootstrap mode
if config.Bootstrap {
c.Ui.Error("WARNING: Bootstrap mode enabled! Do not enable unless necessary")
c.UI.Error("WARNING: Bootstrap mode enabled! Do not enable unless necessary")
}
// Need both tag key and value for EC2 discovery
if config.RetryJoinEC2.TagKey != "" || config.RetryJoinEC2.TagValue != "" {
if config.RetryJoinEC2.TagKey == "" || config.RetryJoinEC2.TagValue == "" {
c.Ui.Error("tag key and value are both required for EC2 retry-join")
c.UI.Error("tag key and value are both required for EC2 retry-join")
return nil
}
}
// EC2 and GCE discovery are mutually exclusive
if config.RetryJoinEC2.TagKey != "" && config.RetryJoinEC2.TagValue != "" && config.RetryJoinGCE.TagValue != "" {
c.Ui.Error("EC2 and GCE discovery are mutually exclusive. Please provide one or the other.")
c.UI.Error("EC2 and GCE discovery are mutually exclusive. Please provide one or the other.")
return nil
}
// Verify the node metadata entries are valid
if err := structs.ValidateMetadata(config.Meta); err != nil {
c.Ui.Error(fmt.Sprintf("Failed to parse node metadata: %v", err))
c.UI.Error(fmt.Sprintf("Failed to parse node metadata: %v", err))
}
// It doesn't make sense to include both UI options.
if config.EnableUi == true && config.UiDir != "" {
c.Ui.Error("Both the ui and ui-dir flags were specified, please provide only one")
c.Ui.Error("If trying to use your own web UI resources, use the ui-dir flag")
c.Ui.Error("If using Consul version 0.7.0 or later, the web UI is included in the binary so use ui to enable it")
if config.EnableUI == true && config.UIDir != "" {
c.UI.Error("Both the ui and ui-dir flags were specified, please provide only one")
c.UI.Error("If trying to use your own web UI resources, use the ui-dir flag")
c.UI.Error("If using Consul version 0.7.0 or later, the web UI is included in the binary so use ui to enable it")
return nil
}
@ -589,7 +589,7 @@ func (c *Config) discoverGCEHosts(logger *log.Logger) ([]string, error) {
logger.Printf("[INFO] agent: Using pre-defined GCE project name: %s", config.ProjectName)
}
zones, err := gceDiscoverZones(logger, ctx, computeService, config.ProjectName, config.ZonePattern)
zones, err := gceDiscoverZones(ctx, logger, computeService, config.ProjectName, config.ZonePattern)
if err != nil {
return nil, err
}
@ -598,7 +598,7 @@ func (c *Config) discoverGCEHosts(logger *log.Logger) ([]string, error) {
var servers []string
for _, zone := range zones {
addresses, err := gceInstancesAddressesForZone(logger, ctx, computeService, config.ProjectName, zone, config.TagValue)
addresses, err := gceInstancesAddressesForZone(ctx, logger, computeService, config.ProjectName, zone, config.TagValue)
if err != nil {
return nil, err
}
@ -642,7 +642,7 @@ func gceProjectIDFromMetadata(logger *log.Logger) (string, error) {
// gceDiscoverZones discovers a list of zones from a supplied zone pattern, or
// all of the zones available to a project.
func gceDiscoverZones(logger *log.Logger, ctx context.Context, computeService *compute.Service, project, pattern string) ([]string, error) {
func gceDiscoverZones(ctx context.Context, logger *log.Logger, computeService *compute.Service, project, pattern string) ([]string, error) {
var zones []string
if pattern != "" {
@ -672,7 +672,7 @@ func gceDiscoverZones(logger *log.Logger, ctx context.Context, computeService *c
// gceInstancesAddressesForZone locates all instances within a specific project
// and zone, matching the supplied tag. Only the private IP addresses are
// returned, but ID is also logged.
func gceInstancesAddressesForZone(logger *log.Logger, ctx context.Context, computeService *compute.Service, project, zone, tag string) ([]string, error) {
func gceInstancesAddressesForZone(ctx context.Context, logger *log.Logger, computeService *compute.Service, project, zone, tag string) ([]string, error) {
var addresses []string
call := computeService.Instances.List(project, zone)
if err := call.Pages(ctx, func(page *compute.InstanceList) error {
@ -693,10 +693,10 @@ func gceInstancesAddressesForZone(logger *log.Logger, ctx context.Context, compu
// setupAgent is used to start the agent and various interfaces
func (c *Command) setupAgent(config *Config, logOutput io.Writer, logWriter *logger.LogWriter) error {
c.Ui.Output("Starting Consul agent...")
c.UI.Output("Starting Consul agent...")
agent, err := Create(config, logOutput, logWriter, c.configReloadCh)
if err != nil {
c.Ui.Error(fmt.Sprintf("Error starting agent: %s", err))
c.UI.Error(fmt.Sprintf("Error starting agent: %s", err))
return err
}
c.agent = agent
@ -704,7 +704,7 @@ func (c *Command) setupAgent(config *Config, logOutput io.Writer, logWriter *log
// Enable the SCADA integration
if err := c.setupScadaConn(config); err != nil {
agent.Shutdown()
c.Ui.Error(fmt.Sprintf("Error starting SCADA connection: %s", err))
c.UI.Error(fmt.Sprintf("Error starting SCADA connection: %s", err))
return err
}
@ -712,7 +712,7 @@ func (c *Command) setupAgent(config *Config, logOutput io.Writer, logWriter *log
servers, err := NewHTTPServers(agent, config, logOutput)
if err != nil {
agent.Shutdown()
c.Ui.Error(fmt.Sprintf("Error starting http servers: %s", err))
c.UI.Error(fmt.Sprintf("Error starting http servers: %s", err))
return err
}
c.httpServers = servers
@ -722,7 +722,7 @@ func (c *Command) setupAgent(config *Config, logOutput io.Writer, logWriter *log
dnsAddr, err := config.ClientListener(config.Addresses.DNS, config.Ports.DNS)
if err != nil {
agent.Shutdown()
c.Ui.Error(fmt.Sprintf("Invalid DNS bind address: %s", err))
c.UI.Error(fmt.Sprintf("Invalid DNS bind address: %s", err))
return err
}
@ -730,7 +730,7 @@ func (c *Command) setupAgent(config *Config, logOutput io.Writer, logWriter *log
config.Domain, dnsAddr.String(), config.DNSRecursors)
if err != nil {
agent.Shutdown()
c.Ui.Error(fmt.Sprintf("Error starting dns server: %s", err))
c.UI.Error(fmt.Sprintf("Error starting dns server: %s", err))
return err
}
c.dnsServer = server
@ -765,18 +765,18 @@ func (c *Command) setupAgent(config *Config, logOutput io.Writer, logWriter *log
// checkpointResults is used to handler periodic results from our update checker
func (c *Command) checkpointResults(results *checkpoint.CheckResponse, err error) {
if err != nil {
c.Ui.Error(fmt.Sprintf("Failed to check for updates: %v", err))
c.UI.Error(fmt.Sprintf("Failed to check for updates: %v", err))
return
}
if results.Outdated {
c.Ui.Error(fmt.Sprintf("Newer Consul version available: %s (currently running: %s)", results.CurrentVersion, c.Version))
c.UI.Error(fmt.Sprintf("Newer Consul version available: %s (currently running: %s)", results.CurrentVersion, c.Version))
}
for _, alert := range results.Alerts {
switch alert.Level {
case "info":
c.Ui.Info(fmt.Sprintf("Bulletin [%s]: %s (%s)", alert.Level, alert.Message, alert.URL))
c.UI.Info(fmt.Sprintf("Bulletin [%s]: %s (%s)", alert.Level, alert.Message, alert.URL))
default:
c.Ui.Error(fmt.Sprintf("Bulletin [%s]: %s (%s)", alert.Level, alert.Message, alert.URL))
c.UI.Error(fmt.Sprintf("Bulletin [%s]: %s (%s)", alert.Level, alert.Message, alert.URL))
}
}
}
@ -787,13 +787,13 @@ func (c *Command) startupJoin(config *Config) error {
return nil
}
c.Ui.Output("Joining cluster...")
c.UI.Output("Joining cluster...")
n, err := c.agent.JoinLAN(config.StartJoin)
if err != nil {
return err
}
c.Ui.Info(fmt.Sprintf("Join completed. Synced with %d initial agents", n))
c.UI.Info(fmt.Sprintf("Join completed. Synced with %d initial agents", n))
return nil
}
@ -803,13 +803,13 @@ func (c *Command) startupJoinWan(config *Config) error {
return nil
}
c.Ui.Output("Joining -wan cluster...")
c.UI.Output("Joining -wan cluster...")
n, err := c.agent.JoinWAN(config.StartJoinWan)
if err != nil {
return err
}
c.Ui.Info(fmt.Sprintf("Join -wan completed. Synced with %d initial agents", n))
c.UI.Info(fmt.Sprintf("Join -wan completed. Synced with %d initial agents", n))
return nil
}
@ -916,11 +916,11 @@ func (c *Command) gossipEncrypted() bool {
}
func (c *Command) Run(args []string) int {
c.Ui = &cli.PrefixedUi{
c.UI = &cli.PrefixedUi{
OutputPrefix: "==> ",
InfoPrefix: " ",
ErrorPrefix: "==> ",
Ui: c.Ui,
Ui: c.UI,
}
// Parse our configs
@ -936,7 +936,7 @@ func (c *Command) Run(args []string) int {
EnableSyslog: config.EnableSyslog,
SyslogFacility: config.SyslogFacility,
}
logFilter, logGate, logWriter, logOutput, ok := logger.Setup(logConfig, c.Ui)
logFilter, logGate, logWriter, logOutput, ok := logger.Setup(logConfig, c.UI)
if !ok {
return 1
}
@ -960,7 +960,7 @@ func (c *Command) Run(args []string) int {
if config.Telemetry.StatsiteAddr != "" {
sink, err := metrics.NewStatsiteSink(config.Telemetry.StatsiteAddr)
if err != nil {
c.Ui.Error(fmt.Sprintf("Failed to start statsite sink. Got: %s", err))
c.UI.Error(fmt.Sprintf("Failed to start statsite sink. Got: %s", err))
return 1
}
fanout = append(fanout, sink)
@ -970,7 +970,7 @@ func (c *Command) Run(args []string) int {
if config.Telemetry.StatsdAddr != "" {
sink, err := metrics.NewStatsdSink(config.Telemetry.StatsdAddr)
if err != nil {
c.Ui.Error(fmt.Sprintf("Failed to start statsd sink. Got: %s", err))
c.UI.Error(fmt.Sprintf("Failed to start statsd sink. Got: %s", err))
return 1
}
fanout = append(fanout, sink)
@ -986,7 +986,7 @@ func (c *Command) Run(args []string) int {
sink, err := datadog.NewDogStatsdSink(config.Telemetry.DogStatsdAddr, metricsConf.HostName)
if err != nil {
c.Ui.Error(fmt.Sprintf("Failed to start DogStatsd sink. Got: %s", err))
c.UI.Error(fmt.Sprintf("Failed to start DogStatsd sink. Got: %s", err))
return 1
}
sink.SetTags(tags)
@ -1023,7 +1023,7 @@ func (c *Command) Run(args []string) int {
sink, err := circonus.NewCirconusSink(cfg)
if err != nil {
c.Ui.Error(fmt.Sprintf("Failed to start Circonus sink. Got: %s", err))
c.UI.Error(fmt.Sprintf("Failed to start Circonus sink. Got: %s", err))
return 1
}
sink.Start()
@ -1053,8 +1053,8 @@ func (c *Command) Run(args []string) int {
// Check and shut down the SCADA listeners at the end
defer func() {
if c.scadaHttp != nil {
c.scadaHttp.Shutdown()
if c.scadaHTTP != nil {
c.scadaHTTP.Shutdown()
}
if c.scadaProvider != nil {
c.scadaProvider.Shutdown()
@ -1063,13 +1063,13 @@ func (c *Command) Run(args []string) int {
// Join startup nodes if specified
if err := c.startupJoin(config); err != nil {
c.Ui.Error(err.Error())
c.UI.Error(err.Error())
return 1
}
// Join startup nodes if specified
if err := c.startupJoinWan(config); err != nil {
c.Ui.Error(err.Error())
c.UI.Error(err.Error())
return 1
}
@ -1081,11 +1081,11 @@ func (c *Command) Run(args []string) int {
} else if config.Ports.HTTPS != -1 {
httpAddr, err = config.ClientListener(config.Addresses.HTTPS, config.Ports.HTTPS)
} else if len(config.WatchPlans) > 0 {
c.Ui.Error("Error: cannot use watches if both HTTP and HTTPS are disabled")
c.UI.Error("Error: cannot use watches if both HTTP and HTTPS are disabled")
return 1
}
if err != nil {
c.Ui.Error(fmt.Sprintf("Failed to determine HTTP address: %v", err))
c.UI.Error(fmt.Sprintf("Failed to determine HTTP address: %v", err))
}
// Register the watches
@ -1099,7 +1099,7 @@ func (c *Command) Run(args []string) int {
addr = "unix://" + addr
}
if err := wp.Run(addr); err != nil {
c.Ui.Error(fmt.Sprintf("Error running watch: %v", err))
c.UI.Error(fmt.Sprintf("Error running watch: %v", err))
}
}(wp)
}
@ -1121,23 +1121,23 @@ func (c *Command) Run(args []string) int {
// Let the agent know we've finished registration
c.agent.StartSync()
c.Ui.Output("Consul agent running!")
c.Ui.Info(fmt.Sprintf(" Version: '%s'", c.HumanVersion))
c.Ui.Info(fmt.Sprintf(" Node ID: '%s'", config.NodeID))
c.Ui.Info(fmt.Sprintf(" Node name: '%s'", config.NodeName))
c.Ui.Info(fmt.Sprintf(" Datacenter: '%s'", config.Datacenter))
c.Ui.Info(fmt.Sprintf(" Server: %v (bootstrap: %v)", config.Server, config.Bootstrap))
c.Ui.Info(fmt.Sprintf(" Client Addr: %v (HTTP: %d, HTTPS: %d, DNS: %d)", config.ClientAddr,
c.UI.Output("Consul agent running!")
c.UI.Info(fmt.Sprintf(" Version: '%s'", c.HumanVersion))
c.UI.Info(fmt.Sprintf(" Node ID: '%s'", config.NodeID))
c.UI.Info(fmt.Sprintf(" Node name: '%s'", config.NodeName))
c.UI.Info(fmt.Sprintf(" Datacenter: '%s'", config.Datacenter))
c.UI.Info(fmt.Sprintf(" Server: %v (bootstrap: %v)", config.Server, config.Bootstrap))
c.UI.Info(fmt.Sprintf(" Client Addr: %v (HTTP: %d, HTTPS: %d, DNS: %d)", config.ClientAddr,
config.Ports.HTTP, config.Ports.HTTPS, config.Ports.DNS))
c.Ui.Info(fmt.Sprintf(" Cluster Addr: %v (LAN: %d, WAN: %d)", config.AdvertiseAddr,
c.UI.Info(fmt.Sprintf(" Cluster Addr: %v (LAN: %d, WAN: %d)", config.AdvertiseAddr,
config.Ports.SerfLan, config.Ports.SerfWan))
c.Ui.Info(fmt.Sprintf("Gossip encrypt: %v, RPC-TLS: %v, TLS-Incoming: %v",
c.UI.Info(fmt.Sprintf("Gossip encrypt: %v, RPC-TLS: %v, TLS-Incoming: %v",
gossipEncrypted, config.VerifyOutgoing, config.VerifyIncoming))
c.Ui.Info(fmt.Sprintf(" Atlas: %s", atlas))
c.UI.Info(fmt.Sprintf(" Atlas: %s", atlas))
// Enable log streaming
c.Ui.Info("")
c.Ui.Output("Log data will now stream in as it occurs:\n")
c.UI.Info("")
c.UI.Output("Log data will now stream in as it occurs:\n")
logGate.Flush()
// Start retry join process
@ -1184,7 +1184,7 @@ WAIT:
goto WAIT
}
c.Ui.Output(fmt.Sprintf("Caught signal: %v", sig))
c.UI.Output(fmt.Sprintf("Caught signal: %v", sig))
// Check if this is a SIGHUP
if sig == syscall.SIGHUP {
@ -1193,7 +1193,7 @@ WAIT:
config = conf
}
if err != nil {
c.Ui.Error(err.Error())
c.UI.Error(err.Error())
}
// Send result back if reload was called via HTTP
if reloadErrCh != nil {
@ -1217,10 +1217,10 @@ WAIT:
// Attempt a graceful leave
gracefulCh := make(chan struct{})
c.Ui.Output("Gracefully shutting down agent...")
c.UI.Output("Gracefully shutting down agent...")
go func() {
if err := c.agent.Leave(); err != nil {
c.Ui.Error(fmt.Sprintf("Error: %s", err))
c.UI.Error(fmt.Sprintf("Error: %s", err))
return
}
close(gracefulCh)
@ -1239,7 +1239,7 @@ WAIT:
// handleReload is invoked when we should reload our configs, e.g. SIGHUP
func (c *Command) handleReload(config *Config) (*Config, error) {
c.Ui.Output("Reloading configuration...")
c.UI.Output("Reloading configuration...")
var errs error
newConf := c.readConfig()
if newConf == nil {
@ -1336,8 +1336,8 @@ func (c *Command) setupScadaConn(config *Config) error {
if c.scadaProvider != nil {
c.scadaProvider.Shutdown()
}
if c.scadaHttp != nil {
c.scadaHttp.Shutdown()
if c.scadaHTTP != nil {
c.scadaHTTP.Shutdown()
}
// No-op if we don't have an infrastructure
@ -1345,7 +1345,7 @@ func (c *Command) setupScadaConn(config *Config) error {
return nil
}
c.Ui.Error("WARNING: The hosted version of Consul Enterprise will be deprecated " +
c.UI.Error("WARNING: The hosted version of Consul Enterprise will be deprecated " +
"on March 7th, 2017. For details, see " +
"https://atlas.hashicorp.com/help/consul/alternatives")
@ -1366,13 +1366,13 @@ func (c *Command) setupScadaConn(config *Config) error {
}
// Create the new provider and listener
c.Ui.Output("Connecting to Atlas: " + config.AtlasInfrastructure)
c.UI.Output("Connecting to Atlas: " + config.AtlasInfrastructure)
provider, list, err := scada.NewHTTPProvider(scadaConfig, c.logOutput)
if err != nil {
return err
}
c.scadaProvider = provider
c.scadaHttp = newScadaHttp(c.agent, list)
c.scadaHTTP = newScadaHTTP(c.agent, list)
return nil
}

View File

@ -19,7 +19,7 @@ import (
func baseCommand(ui *cli.MockUi) base.Command {
return base.Command{
Flags: base.FlagSetNone,
Ui: ui,
UI: ui,
}
}
@ -386,7 +386,7 @@ func TestSetupScadaConn(t *testing.T) {
if err := cmd.setupScadaConn(conf1); err != nil {
t.Fatalf("err: %s", err)
}
http1 := cmd.scadaHttp
http1 := cmd.scadaHTTP
provider1 := cmd.scadaProvider
// Performing setup again tears down original and replaces
@ -397,8 +397,8 @@ func TestSetupScadaConn(t *testing.T) {
if err := cmd.setupScadaConn(conf2); err != nil {
t.Fatalf("err: %s", err)
}
if cmd.scadaHttp == http1 || cmd.scadaProvider == provider1 {
t.Fatalf("should change: %#v %#v", cmd.scadaHttp, cmd.scadaProvider)
if cmd.scadaHTTP == http1 || cmd.scadaProvider == provider1 {
t.Fatalf("should change: %#v %#v", cmd.scadaHTTP, cmd.scadaProvider)
}
// Original provider and listener must be closed

View File

@ -536,13 +536,13 @@ type Config struct {
ReconnectTimeoutWan time.Duration `mapstructure:"-"`
ReconnectTimeoutWanRaw string `mapstructure:"reconnect_timeout_wan"`
// EnableUi enables the statically-compiled assets for the Consul web UI and
// EnableUI enables the statically-compiled assets for the Consul web UI and
// serves them at the default /ui/ endpoint automatically.
EnableUi bool `mapstructure:"ui"`
EnableUI bool `mapstructure:"ui"`
// UiDir is the directory containing the Web UI resources.
// UIDir is the directory containing the Web UI resources.
// If provided, the UI endpoints will be enabled.
UiDir string `mapstructure:"ui_dir"`
UIDir string `mapstructure:"ui_dir"`
// PidFile is the file to store our PID in
PidFile string `mapstructure:"pid_file"`
@ -849,7 +849,7 @@ func DevConfig() *Config {
conf.Server = true
conf.EnableDebug = true
conf.DisableAnonymousSignature = true
conf.EnableUi = true
conf.EnableUI = true
conf.BindAddr = "127.0.0.1"
return conf
}
@ -1568,11 +1568,11 @@ func MergeConfig(a, b *Config) *Config {
if b.Addresses.RPC != "" {
result.Addresses.RPC = b.Addresses.RPC
}
if b.EnableUi {
result.EnableUi = true
if b.EnableUI {
result.EnableUI = true
}
if b.UiDir != "" {
result.UiDir = b.UiDir
if b.UIDir != "" {
result.UIDir = b.UIDir
}
if b.PidFile != "" {
result.PidFile = b.PidFile

View File

@ -544,7 +544,7 @@ func TestDecodeConfig(t *testing.T) {
t.Fatalf("err: %s", err)
}
if !config.EnableUi {
if !config.EnableUI {
t.Fatalf("bad: %#v", config)
}
@ -555,7 +555,7 @@ func TestDecodeConfig(t *testing.T) {
t.Fatalf("err: %s", err)
}
if config.UiDir != "/opt/consul-ui" {
if config.UIDir != "/opt/consul-ui" {
t.Fatalf("bad: %#v", config)
}
@ -1699,8 +1699,8 @@ func TestMergeConfig(t *testing.T) {
Services: []*ServiceDefinition{nil},
StartJoin: []string{"1.1.1.1"},
StartJoinWan: []string{"1.1.1.1"},
EnableUi: true,
UiDir: "/opt/consul-ui",
EnableUI: true,
UIDir: "/opt/consul-ui",
EnableSyslog: true,
RejoinAfterLeave: true,
RetryJoin: []string{"1.1.1.1"},

View File

@ -87,7 +87,7 @@ func NewHTTPServers(agent *Agent, config *Config, logOutput io.Writer) ([]*HTTPS
mux: mux,
listener: list,
logger: log.New(logOutput, "", log.LstdFlags),
uiDir: config.UiDir,
uiDir: config.UIDir,
addr: httpAddr.String(),
}
srv.registerHandlers(config.EnableDebug)
@ -139,7 +139,7 @@ func NewHTTPServers(agent *Agent, config *Config, logOutput io.Writer) ([]*HTTPS
mux: mux,
listener: list,
logger: log.New(logOutput, "", log.LstdFlags),
uiDir: config.UiDir,
uiDir: config.UIDir,
addr: httpAddr.String(),
}
srv.registerHandlers(config.EnableDebug)
@ -152,9 +152,9 @@ func NewHTTPServers(agent *Agent, config *Config, logOutput io.Writer) ([]*HTTPS
return servers, nil
}
// newScadaHttp creates a new HTTP server wrapping the SCADA
// newScadaHTTP creates a new HTTP server wrapping the SCADA
// listener such that HTTP calls can be sent from the brokers.
func newScadaHttp(agent *Agent, list net.Listener) *HTTPServer {
func newScadaHTTP(agent *Agent, list net.Listener) *HTTPServer {
// Create the mux
mux := http.NewServeMux()
@ -323,7 +323,7 @@ func (s *HTTPServer) registerHandlers(enableDebug bool) {
// Use the custom UI dir if provided.
if s.uiDir != "" {
s.mux.Handle("/ui/", http.StripPrefix("/ui/", http.FileServer(http.Dir(s.uiDir))))
} else if s.agent.config.EnableUi {
} else if s.agent.config.EnableUI {
s.mux.Handle("/ui/", http.StripPrefix("/ui/", http.FileServer(assetFS())))
}
@ -419,7 +419,7 @@ func (s *HTTPServer) marshalJSON(req *http.Request, obj interface{}) ([]byte, er
// Returns true if the UI is enabled.
func (s *HTTPServer) IsUIEnabled() bool {
return s.uiDir != "" || s.agent.config.EnableUi
return s.uiDir != "" || s.agent.config.EnableUI
}
// Renders a simple index page

View File

@ -685,23 +685,23 @@ func TestScadaHTTP(t *testing.T) {
defer list.Close()
// Create the SCADA HTTP server
scadaHttp := newScadaHttp(agent, list)
scadaHTTP := newScadaHTTP(agent, list)
// Returned server uses the listener and scada addr
if scadaHttp.listener != list {
t.Fatalf("bad listener: %#v", scadaHttp)
if scadaHTTP.listener != list {
t.Fatalf("bad listener: %#v", scadaHTTP)
}
if scadaHttp.addr != scadaHTTPAddr {
t.Fatalf("expected %v, got: %v", scadaHttp.addr, scadaHTTPAddr)
if scadaHTTP.addr != scadaHTTPAddr {
t.Fatalf("expected %v, got: %v", scadaHTTP.addr, scadaHTTPAddr)
}
// Check that debug endpoints were not enabled. This will cause
// the serve mux to panic if the routes are already handled.
mockFn := func(w http.ResponseWriter, r *http.Request) {}
scadaHttp.mux.HandleFunc("/debug/pprof/", mockFn)
scadaHttp.mux.HandleFunc("/debug/pprof/cmdline", mockFn)
scadaHttp.mux.HandleFunc("/debug/pprof/profile", mockFn)
scadaHttp.mux.HandleFunc("/debug/pprof/symbol", mockFn)
scadaHTTP.mux.HandleFunc("/debug/pprof/", mockFn)
scadaHTTP.mux.HandleFunc("/debug/pprof/cmdline", mockFn)
scadaHTTP.mux.HandleFunc("/debug/pprof/profile", mockFn)
scadaHTTP.mux.HandleFunc("/debug/pprof/symbol", mockFn)
}
func TestEnableWebUI(t *testing.T) {
@ -720,7 +720,7 @@ func TestEnableWebUI(t *testing.T) {
t.Fatalf("should handle ui")
}
}, func(c *Config) {
c.EnableUi = true
c.EnableUI = true
})
}

View File

@ -28,7 +28,7 @@ func TestUiIndex(t *testing.T) {
// Make the server
dir, srv := makeHTTPServerWithConfig(t, func(c *Config) {
c.UiDir = uiDir
c.UIDir = uiDir
})
defer os.RemoveAll(dir)
defer srv.Shutdown()

View File

@ -29,7 +29,7 @@ const (
)
type Command struct {
Ui cli.Ui
UI cli.Ui
Flags FlagSetFlags
flagSet *flag.FlagSet
@ -145,7 +145,7 @@ func (c *Command) httpFlagsServer(f *flag.FlagSet) *flag.FlagSet {
// generates help output and adds the appropriate API flags.
func (c *Command) NewFlagSet(command cli.Command) *flag.FlagSet {
f := flag.NewFlagSet("", flag.ContinueOnError)
f.Usage = func() { c.Ui.Error(command.Help()) }
f.Usage = func() { c.UI.Error(command.Help()) }
if c.hasClientHTTP() {
c.httpFlagsClient(f)
@ -159,7 +159,7 @@ func (c *Command) NewFlagSet(command cli.Command) *flag.FlagSet {
errScanner := bufio.NewScanner(errR)
go func() {
for errScanner.Scan() {
c.Ui.Error(errScanner.Text())
c.UI.Error(errScanner.Text())
}
}()
f.SetOutput(errW)

View File

@ -48,13 +48,13 @@ func (c *ConfigTestCommand) Run(args []string) int {
}
if len(configFiles) <= 0 {
c.Ui.Error("Must specify config using -config-file or -config-dir")
c.UI.Error("Must specify config using -config-file or -config-dir")
return 1
}
_, err := agent.ReadConfigPaths(configFiles)
if err != nil {
c.Ui.Error(fmt.Sprintf("Config validation failed: %v", err.Error()))
c.UI.Error(fmt.Sprintf("Config validation failed: %v", err.Error()))
return 1
}
return 0

View File

@ -14,7 +14,7 @@ func testConfigTestCommand(t *testing.T) (*cli.MockUi, *ConfigTestCommand) {
ui := new(cli.MockUi)
return ui, &ConfigTestCommand{
Command: base.Command{
Ui: ui,
UI: ui,
Flags: base.FlagSetNone,
},
}

View File

@ -47,33 +47,33 @@ func (c *EventCommand) Run(args []string) int {
// Check for a name
if name == "" {
c.Ui.Error("Event name must be specified")
c.Ui.Error("")
c.Ui.Error(c.Help())
c.UI.Error("Event name must be specified")
c.UI.Error("")
c.UI.Error(c.Help())
return 1
}
// Validate the filters
if node != "" {
if _, err := regexp.Compile(node); err != nil {
c.Ui.Error(fmt.Sprintf("Failed to compile node filter regexp: %v", err))
c.UI.Error(fmt.Sprintf("Failed to compile node filter regexp: %v", err))
return 1
}
}
if service != "" {
if _, err := regexp.Compile(service); err != nil {
c.Ui.Error(fmt.Sprintf("Failed to compile service filter regexp: %v", err))
c.UI.Error(fmt.Sprintf("Failed to compile service filter regexp: %v", err))
return 1
}
}
if tag != "" {
if _, err := regexp.Compile(tag); err != nil {
c.Ui.Error(fmt.Sprintf("Failed to compile tag filter regexp: %v", err))
c.UI.Error(fmt.Sprintf("Failed to compile tag filter regexp: %v", err))
return 1
}
}
if tag != "" && service == "" {
c.Ui.Error("Cannot provide tag filter without service filter.")
c.UI.Error("Cannot provide tag filter without service filter.")
return 1
}
@ -85,21 +85,21 @@ func (c *EventCommand) Run(args []string) int {
case 1:
payload = []byte(args[0])
default:
c.Ui.Error("Too many command line arguments.")
c.Ui.Error("")
c.Ui.Error(c.Help())
c.UI.Error("Too many command line arguments.")
c.UI.Error("")
c.UI.Error(c.Help())
return 1
}
// Create and test the HTTP client
client, err := c.Command.HTTPClient()
if err != nil {
c.Ui.Error(fmt.Sprintf("Error connecting to Consul agent: %s", err))
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))
c.UI.Error(fmt.Sprintf("Error querying Consul agent: %s", err))
return 1
}
@ -116,12 +116,12 @@ func (c *EventCommand) Run(args []string) int {
// Fire the event
id, _, err := event.Fire(params, nil)
if err != nil {
c.Ui.Error(fmt.Sprintf("Error firing event: %s", err))
c.UI.Error(fmt.Sprintf("Error firing event: %s", err))
return 1
}
// Write out the ID
c.Ui.Output(fmt.Sprintf("Event ID: %s", id))
c.UI.Output(fmt.Sprintf("Event ID: %s", id))
return 0
}

View File

@ -18,7 +18,7 @@ func TestEventCommandRun(t *testing.T) {
ui := new(cli.MockUi)
c := &EventCommand{
Command: base.Command{
Ui: ui,
UI: ui,
Flags: base.FlagSetClientHTTP,
},
}

View File

@ -156,9 +156,9 @@ func (c *ExecCommand) Run(args []string) int {
var buf bytes.Buffer
_, err := io.Copy(&buf, os.Stdin)
if err != nil {
c.Ui.Error(fmt.Sprintf("Failed to read stdin: %v", err))
c.Ui.Error("")
c.Ui.Error(c.Help())
c.UI.Error(fmt.Sprintf("Failed to read stdin: %v", err))
c.UI.Error("")
c.UI.Error(c.Help())
return 1
}
c.conf.script = buf.Bytes()
@ -166,27 +166,27 @@ func (c *ExecCommand) Run(args []string) int {
// Ensure we have a command or script
if c.conf.cmd == "" && len(c.conf.script) == 0 {
c.Ui.Error("Must specify a command to execute")
c.Ui.Error("")
c.Ui.Error(c.Help())
c.UI.Error("Must specify a command to execute")
c.UI.Error("")
c.UI.Error(c.Help())
return 1
}
// Validate the configuration
if err := c.conf.validate(); err != nil {
c.Ui.Error(err.Error())
c.UI.Error(err.Error())
return 1
}
// Create and test the HTTP client
client, err := c.Command.HTTPClient()
if err != nil {
c.Ui.Error(fmt.Sprintf("Error connecting to Consul agent: %s", err))
c.UI.Error(fmt.Sprintf("Error connecting to Consul agent: %s", err))
return 1
}
info, err := client.Agent().Self()
if err != nil {
c.Ui.Error(fmt.Sprintf("Error querying Consul agent: %s", err))
c.UI.Error(fmt.Sprintf("Error querying Consul agent: %s", err))
return 1
}
c.client = client
@ -194,7 +194,7 @@ func (c *ExecCommand) Run(args []string) int {
// Check if this is a foreign datacenter
if c.Command.HTTPDatacenter() != "" && c.Command.HTTPDatacenter() != info["Config"]["Datacenter"] {
if c.conf.verbose {
c.Ui.Info("Remote exec in foreign datacenter, using Session TTL")
c.UI.Info("Remote exec in foreign datacenter, using Session TTL")
}
c.conf.foreignDC = true
c.conf.localDC = info["Config"]["Datacenter"].(string)
@ -204,29 +204,29 @@ func (c *ExecCommand) Run(args []string) int {
// Create the job spec
spec, err := c.makeRExecSpec()
if err != nil {
c.Ui.Error(fmt.Sprintf("Failed to create job spec: %s", err))
c.UI.Error(fmt.Sprintf("Failed to create job spec: %s", err))
return 1
}
// Create a session for this
c.sessionID, err = c.createSession()
if err != nil {
c.Ui.Error(fmt.Sprintf("Failed to create session: %s", err))
c.UI.Error(fmt.Sprintf("Failed to create session: %s", err))
return 1
}
defer c.destroySession()
if c.conf.verbose {
c.Ui.Info(fmt.Sprintf("Created remote execution session: %s", c.sessionID))
c.UI.Info(fmt.Sprintf("Created remote execution session: %s", c.sessionID))
}
// Upload the payload
if err := c.uploadPayload(spec); err != nil {
c.Ui.Error(fmt.Sprintf("Failed to create job file: %s", err))
c.UI.Error(fmt.Sprintf("Failed to create job file: %s", err))
return 1
}
defer c.destroyData()
if c.conf.verbose {
c.Ui.Info(fmt.Sprintf("Uploaded remote execution spec"))
c.UI.Info(fmt.Sprintf("Uploaded remote execution spec"))
}
// Wait for replication. This is done so that when the event is
@ -242,11 +242,11 @@ func (c *ExecCommand) Run(args []string) int {
// Fire the event
id, err := c.fireEvent()
if err != nil {
c.Ui.Error(fmt.Sprintf("Failed to fire event: %s", err))
c.UI.Error(fmt.Sprintf("Failed to fire event: %s", err))
return 1
}
if c.conf.verbose {
c.Ui.Info(fmt.Sprintf("Fired remote execution event: %s", id))
c.UI.Info(fmt.Sprintf("Fired remote execution event: %s", id))
}
// Wait for the job to finish now
@ -268,7 +268,7 @@ func (c *ExecCommand) waitForJob() int {
errCh := make(chan struct{}, 1)
defer close(doneCh)
go c.streamResults(doneCh, ackCh, heartCh, outputCh, exitCh, errCh)
target := &TargetedUi{Ui: c.Ui}
target := &TargetedUI{UI: c.UI}
var ackCount, exitCount, badExit int
OUTER:
@ -307,9 +307,9 @@ OUTER:
}
case <-time.After(waitIntv):
c.Ui.Info(fmt.Sprintf("%d / %d node(s) completed / acknowledged", exitCount, ackCount))
c.UI.Info(fmt.Sprintf("%d / %d node(s) completed / acknowledged", exitCount, ackCount))
if c.conf.verbose {
c.Ui.Info(fmt.Sprintf("Completed in %0.2f seconds",
c.UI.Info(fmt.Sprintf("Completed in %0.2f seconds",
float64(time.Now().Sub(start))/float64(time.Second)))
}
break OUTER
@ -348,7 +348,7 @@ func (c *ExecCommand) streamResults(doneCh chan struct{}, ackCh chan rExecAck, h
// Block on waiting for new keys
keys, qm, err := kv.Keys(dir, "", &opts)
if err != nil {
c.Ui.Error(fmt.Sprintf("Failed to read results: %s", err))
c.UI.Error(fmt.Sprintf("Failed to read results: %s", err))
goto ERR_EXIT
}
@ -380,12 +380,12 @@ func (c *ExecCommand) streamResults(doneCh chan struct{}, ackCh chan rExecAck, h
case strings.HasSuffix(key, rExecExitSuffix):
pair, _, err := kv.Get(full, nil)
if err != nil || pair == nil {
c.Ui.Error(fmt.Sprintf("Failed to read key '%s': %v", full, err))
c.UI.Error(fmt.Sprintf("Failed to read key '%s': %v", full, err))
continue
}
code, err := strconv.ParseInt(string(pair.Value), 10, 32)
if err != nil {
c.Ui.Error(fmt.Sprintf("Failed to parse exit code '%s': %v", pair.Value, err))
c.UI.Error(fmt.Sprintf("Failed to parse exit code '%s': %v", pair.Value, err))
continue
}
exitCh <- rExecExit{
@ -396,7 +396,7 @@ func (c *ExecCommand) streamResults(doneCh chan struct{}, ackCh chan rExecAck, h
case strings.LastIndex(key, rExecOutputDivider) != -1:
pair, _, err := kv.Get(full, nil)
if err != nil || pair == nil {
c.Ui.Error(fmt.Sprintf("Failed to read key '%s': %v", full, err))
c.UI.Error(fmt.Sprintf("Failed to read key '%s': %v", full, err))
continue
}
idx := strings.LastIndex(key, rExecOutputDivider)
@ -408,7 +408,7 @@ func (c *ExecCommand) streamResults(doneCh chan struct{}, ackCh chan rExecAck, h
}
default:
c.Ui.Error(fmt.Sprintf("Unknown key '%s', ignoring.", key))
c.UI.Error(fmt.Sprintf("Unknown key '%s', ignoring.", key))
}
}
}
@ -488,7 +488,7 @@ func (c *ExecCommand) createSessionForeign() (string, error) {
}
node := services[0].Node.Node
if c.conf.verbose {
c.Ui.Info(fmt.Sprintf("Binding session to remote node %s@%s",
c.UI.Info(fmt.Sprintf("Binding session to remote node %s@%s",
node, c.Command.HTTPDatacenter()))
}
@ -514,7 +514,7 @@ func (c *ExecCommand) renewSession(id string, stopCh chan struct{}) {
case <-time.After(rExecRenewInterval):
_, _, err := session.Renew(id, nil)
if err != nil {
c.Ui.Error(fmt.Sprintf("Session renew failed: %v", err))
c.UI.Error(fmt.Sprintf("Session renew failed: %v", err))
return
}
case <-stopCh:
@ -623,33 +623,33 @@ Usage: consul exec [options] [-|command...]
return strings.TrimSpace(helpText)
}
// TargetedUi is a UI that wraps another UI implementation and modifies
// TargetedUI is a UI that wraps another UI implementation and modifies
// the output to indicate a specific target. Specifically, all Say output
// is prefixed with the target name. Message output is not prefixed but
// is offset by the length of the target so that output is lined up properly
// with Say output. Machine-readable output has the proper target set.
type TargetedUi struct {
type TargetedUI struct {
Target string
Ui cli.Ui
UI cli.Ui
}
func (u *TargetedUi) Ask(query string) (string, error) {
return u.Ui.Ask(u.prefixLines(true, query))
func (u *TargetedUI) Ask(query string) (string, error) {
return u.UI.Ask(u.prefixLines(true, query))
}
func (u *TargetedUi) Info(message string) {
u.Ui.Info(u.prefixLines(true, message))
func (u *TargetedUI) Info(message string) {
u.UI.Info(u.prefixLines(true, message))
}
func (u *TargetedUi) Output(message string) {
u.Ui.Output(u.prefixLines(false, message))
func (u *TargetedUI) Output(message string) {
u.UI.Output(u.prefixLines(false, message))
}
func (u *TargetedUi) Error(message string) {
u.Ui.Error(u.prefixLines(true, message))
func (u *TargetedUI) Error(message string) {
u.UI.Error(u.prefixLines(true, message))
}
func (u *TargetedUi) prefixLines(arrow bool, message string) string {
func (u *TargetedUI) prefixLines(arrow bool, message string) string {
arrowText := "==>"
if !arrow {
arrowText = strings.Repeat(" ", len(arrowText))

View File

@ -17,7 +17,7 @@ func testExecCommand(t *testing.T) (*cli.MockUi, *ExecCommand) {
ui := new(cli.MockUi)
return ui, &ExecCommand{
Command: base.Command{
Ui: ui,
UI: ui,
Flags: base.FlagSetHTTP,
},
}

View File

@ -20,21 +20,21 @@ func (c *ForceLeaveCommand) Run(args []string) int {
nodes := f.Args()
if len(nodes) != 1 {
c.Ui.Error("A single node name must be specified to force leave.")
c.Ui.Error("")
c.Ui.Error(c.Help())
c.UI.Error("A single node name must be specified to force leave.")
c.UI.Error("")
c.UI.Error(c.Help())
return 1
}
client, err := c.Command.HTTPClient()
if err != nil {
c.Ui.Error(fmt.Sprintf("Error connecting to Consul agent: %s", err))
c.UI.Error(fmt.Sprintf("Error connecting to Consul agent: %s", err))
return 1
}
err = client.Agent().ForceLeave(nodes[0])
if err != nil {
c.Ui.Error(fmt.Sprintf("Error force leaving: %s", err))
c.UI.Error(fmt.Sprintf("Error force leaving: %s", err))
return 1
}

View File

@ -16,7 +16,7 @@ func testForceLeaveCommand(t *testing.T) (*cli.MockUi, *ForceLeaveCommand) {
ui := new(cli.MockUi)
return ui, &ForceLeaveCommand{
Command: base.Command{
Ui: ui,
UI: ui,
Flags: base.FlagSetClientHTTP,
},
}

View File

@ -33,18 +33,18 @@ func (i *InfoCommand) Run(args []string) int {
client, err := i.Command.HTTPClient()
if err != nil {
i.Ui.Error(fmt.Sprintf("Error connecting to Consul agent: %s", err))
i.UI.Error(fmt.Sprintf("Error connecting to Consul agent: %s", err))
return 1
}
self, err := client.Agent().Self()
if err != nil {
i.Ui.Error(fmt.Sprintf("Error querying agent: %s", err))
i.UI.Error(fmt.Sprintf("Error querying agent: %s", err))
return 1
}
stats, ok := self["Stats"]
if !ok {
i.Ui.Error(fmt.Sprintf("Agent response did not contain 'Stats' key: %v", self))
i.UI.Error(fmt.Sprintf("Agent response did not contain 'Stats' key: %v", self))
return 1
}
@ -57,12 +57,12 @@ func (i *InfoCommand) Run(args []string) int {
// Iterate over each top-level key
for _, key := range keys {
i.Ui.Output(key + ":")
i.UI.Output(key + ":")
// Sort the sub-keys
subvals, ok := stats[key].(map[string]interface{})
if !ok {
i.Ui.Error(fmt.Sprintf("Got invalid subkey in stats: %v", subvals))
i.UI.Error(fmt.Sprintf("Got invalid subkey in stats: %v", subvals))
return 1
}
subkeys := make([]string, 0, len(subvals))
@ -74,7 +74,7 @@ func (i *InfoCommand) Run(args []string) int {
// Iterate over the subkeys
for _, subkey := range subkeys {
val := subvals[subkey]
i.Ui.Output(fmt.Sprintf("\t%s = %s", subkey, val))
i.UI.Output(fmt.Sprintf("\t%s = %s", subkey, val))
}
}
return 0

View File

@ -18,7 +18,7 @@ func TestInfoCommandRun(t *testing.T) {
ui := new(cli.MockUi)
c := &InfoCommand{
Command: base.Command{
Ui: ui,
UI: ui,
Flags: base.FlagSetClientHTTP,
},
}

View File

@ -35,15 +35,15 @@ func (c *JoinCommand) Run(args []string) int {
addrs := f.Args()
if len(addrs) == 0 {
c.Ui.Error("At least one address to join must be specified.")
c.Ui.Error("")
c.Ui.Error(c.Help())
c.UI.Error("At least one address to join must be specified.")
c.UI.Error("")
c.UI.Error(c.Help())
return 1
}
client, err := c.Command.HTTPClient()
if err != nil {
c.Ui.Error(fmt.Sprintf("Error connecting to Consul agent: %s", err))
c.UI.Error(fmt.Sprintf("Error connecting to Consul agent: %s", err))
return 1
}
@ -51,18 +51,18 @@ func (c *JoinCommand) Run(args []string) int {
for _, addr := range addrs {
err := client.Agent().Join(addr, wan)
if err != nil {
c.Ui.Error(fmt.Sprintf("Error joining address '%s': %s", addr, err))
c.UI.Error(fmt.Sprintf("Error joining address '%s': %s", addr, err))
} else {
joins++
}
}
if joins == 0 {
c.Ui.Error("Failed to join any nodes.")
c.UI.Error("Failed to join any nodes.")
return 1
}
c.Ui.Output(fmt.Sprintf(
c.UI.Output(fmt.Sprintf(
"Successfully joined cluster by contacting %d nodes.", joins))
return 0
}

View File

@ -13,7 +13,7 @@ func testJoinCommand(t *testing.T) (*cli.MockUi, *JoinCommand) {
ui := new(cli.MockUi)
return ui, &JoinCommand{
Command: base.Command{
Ui: ui,
UI: ui,
Flags: base.FlagSetClientHTTP,
},
}

View File

@ -24,15 +24,15 @@ func (c *KeygenCommand) Run(args []string) int {
key := make([]byte, 16)
n, err := rand.Reader.Read(key)
if err != nil {
c.Ui.Error(fmt.Sprintf("Error reading random data: %s", err))
c.UI.Error(fmt.Sprintf("Error reading random data: %s", err))
return 1
}
if n != 16 {
c.Ui.Error(fmt.Sprintf("Couldn't read enough entropy. Generate more entropy!"))
c.UI.Error(fmt.Sprintf("Couldn't read enough entropy. Generate more entropy!"))
return 1
}
c.Ui.Output(base64.StdEncoding.EncodeToString(key))
c.UI.Output(base64.StdEncoding.EncodeToString(key))
return 0
}

View File

@ -15,7 +15,7 @@ func TestKeygenCommand(t *testing.T) {
ui := new(cli.MockUi)
c := &KeygenCommand{
Command: base.Command{
Ui: ui,
UI: ui,
Flags: base.FlagSetNone,
},
}

View File

@ -44,18 +44,18 @@ func (c *KeyringCommand) Run(args []string) int {
return 1
}
c.Ui = &cli.PrefixedUi{
c.UI = &cli.PrefixedUi{
OutputPrefix: "",
InfoPrefix: "==> ",
ErrorPrefix: "",
Ui: c.Ui,
Ui: c.UI,
}
// Only accept a single argument
found := listKeys
for _, arg := range []string{installKey, useKey, removeKey} {
if found && len(arg) > 0 {
c.Ui.Error("Only a single action is allowed")
c.UI.Error("Only a single action is allowed")
return 1
}
found = found || len(arg) > 0
@ -63,29 +63,29 @@ func (c *KeyringCommand) Run(args []string) int {
// Fail fast if no actionable args were passed
if !found {
c.Ui.Error(c.Help())
c.UI.Error(c.Help())
return 1
}
// Validate the relay factor
relayFactor, err := agent.ParseRelayFactor(relay)
if err != nil {
c.Ui.Error(fmt.Sprintf("Error parsing relay factor: %s", err))
c.UI.Error(fmt.Sprintf("Error parsing relay factor: %s", err))
return 1
}
// All other operations will require a client connection
client, err := c.Command.HTTPClient()
if err != nil {
c.Ui.Error(fmt.Sprintf("Error connecting to Consul agent: %s", err))
c.UI.Error(fmt.Sprintf("Error connecting to Consul agent: %s", err))
return 1
}
if listKeys {
c.Ui.Info("Gathering installed encryption keys...")
c.UI.Info("Gathering installed encryption keys...")
responses, err := client.Operator().KeyringList(&consulapi.QueryOptions{RelayFactor: relayFactor})
if err != nil {
c.Ui.Error(fmt.Sprintf("error: %s", err))
c.UI.Error(fmt.Sprintf("error: %s", err))
return 1
}
c.handleList(responses)
@ -94,30 +94,30 @@ func (c *KeyringCommand) Run(args []string) int {
opts := &consulapi.WriteOptions{RelayFactor: relayFactor}
if installKey != "" {
c.Ui.Info("Installing new gossip encryption key...")
c.UI.Info("Installing new gossip encryption key...")
err := client.Operator().KeyringInstall(installKey, opts)
if err != nil {
c.Ui.Error(fmt.Sprintf("error: %s", err))
c.UI.Error(fmt.Sprintf("error: %s", err))
return 1
}
return 0
}
if useKey != "" {
c.Ui.Info("Changing primary gossip encryption key...")
c.UI.Info("Changing primary gossip encryption key...")
err := client.Operator().KeyringUse(useKey, opts)
if err != nil {
c.Ui.Error(fmt.Sprintf("error: %s", err))
c.UI.Error(fmt.Sprintf("error: %s", err))
return 1
}
return 0
}
if removeKey != "" {
c.Ui.Info("Removing gossip encryption key...")
c.UI.Info("Removing gossip encryption key...")
err := client.Operator().KeyringRemove(removeKey, opts)
if err != nil {
c.Ui.Error(fmt.Sprintf("error: %s", err))
c.UI.Error(fmt.Sprintf("error: %s", err))
return 1
}
return 0
@ -134,10 +134,10 @@ func (c *KeyringCommand) handleList(responses []*consulapi.KeyringResponse) {
pool = "WAN"
}
c.Ui.Output("")
c.Ui.Output(pool + ":")
c.UI.Output("")
c.UI.Output(pool + ":")
for key, num := range response.Keys {
c.Ui.Output(fmt.Sprintf(" %s [%d/%d]", key, num, response.NumNodes))
c.UI.Output(fmt.Sprintf(" %s [%d/%d]", key, num, response.NumNodes))
}
}
}

View File

@ -13,7 +13,7 @@ func testKeyringCommand(t *testing.T) (*cli.MockUi, *KeyringCommand) {
ui := new(cli.MockUi)
return ui, &KeyringCommand{
Command: base.Command{
Ui: ui,
UI: ui,
Flags: base.FlagSetClientHTTP,
},
}

View File

@ -62,7 +62,7 @@ func (c *KVDeleteCommand) Run(args []string) int {
case 1:
key = args[0]
default:
c.Ui.Error(fmt.Sprintf("Too many arguments (expected 1, got %d)", len(args)))
c.UI.Error(fmt.Sprintf("Too many arguments (expected 1, got %d)", len(args)))
return 1
}
@ -76,42 +76,42 @@ func (c *KVDeleteCommand) Run(args []string) int {
// If the key is empty and we are not doing a recursive delete, this is an
// error.
if key == "" && !*recurse {
c.Ui.Error("Error! Missing KEY argument")
c.UI.Error("Error! Missing KEY argument")
return 1
}
// ModifyIndex is required for CAS
if *cas && *modifyIndex == 0 {
c.Ui.Error("Must specify -modify-index with -cas!")
c.UI.Error("Must specify -modify-index with -cas!")
return 1
}
// Specifying a ModifyIndex for a non-CAS operation is not possible.
if *modifyIndex != 0 && !*cas {
c.Ui.Error("Cannot specify -modify-index without -cas!")
c.UI.Error("Cannot specify -modify-index without -cas!")
}
// It is not valid to use a CAS and recurse in the same call
if *recurse && *cas {
c.Ui.Error("Cannot specify both -cas and -recurse!")
c.UI.Error("Cannot specify both -cas and -recurse!")
return 1
}
// Create and test the HTTP client
client, err := c.Command.HTTPClient()
if err != nil {
c.Ui.Error(fmt.Sprintf("Error connecting to Consul agent: %s", err))
c.UI.Error(fmt.Sprintf("Error connecting to Consul agent: %s", err))
return 1
}
switch {
case *recurse:
if _, err := client.KV().DeleteTree(key, nil); err != nil {
c.Ui.Error(fmt.Sprintf("Error! Did not delete prefix %s: %s", key, err))
c.UI.Error(fmt.Sprintf("Error! Did not delete prefix %s: %s", key, err))
return 1
}
c.Ui.Info(fmt.Sprintf("Success! Deleted keys with prefix: %s", key))
c.UI.Info(fmt.Sprintf("Success! Deleted keys with prefix: %s", key))
return 0
case *cas:
pair := &api.KVPair{
@ -121,23 +121,23 @@ func (c *KVDeleteCommand) Run(args []string) int {
success, _, err := client.KV().DeleteCAS(pair, nil)
if err != nil {
c.Ui.Error(fmt.Sprintf("Error! Did not delete key %s: %s", key, err))
c.UI.Error(fmt.Sprintf("Error! Did not delete key %s: %s", key, err))
return 1
}
if !success {
c.Ui.Error(fmt.Sprintf("Error! Did not delete key %s: CAS failed", key))
c.UI.Error(fmt.Sprintf("Error! Did not delete key %s: CAS failed", key))
return 1
}
c.Ui.Info(fmt.Sprintf("Success! Deleted key: %s", key))
c.UI.Info(fmt.Sprintf("Success! Deleted key: %s", key))
return 0
default:
if _, err := client.KV().Delete(key, nil); err != nil {
c.Ui.Error(fmt.Sprintf("Error deleting key %s: %s", key, err))
c.UI.Error(fmt.Sprintf("Error deleting key %s: %s", key, err))
return 1
}
c.Ui.Info(fmt.Sprintf("Success! Deleted key: %s", key))
c.UI.Info(fmt.Sprintf("Success! Deleted key: %s", key))
return 0
}
}

View File

@ -14,7 +14,7 @@ func testKVDeleteCommand(t *testing.T) (*cli.MockUi, *KVDeleteCommand) {
ui := new(cli.MockUi)
return ui, &KVDeleteCommand{
Command: base.Command{
Ui: ui,
UI: ui,
Flags: base.FlagSetHTTP,
},
}

View File

@ -52,7 +52,7 @@ func (c *KVExportCommand) Run(args []string) int {
case 1:
key = args[0]
default:
c.Ui.Error(fmt.Sprintf("Too many arguments (expected 1, got %d)", len(args)))
c.UI.Error(fmt.Sprintf("Too many arguments (expected 1, got %d)", len(args)))
return 1
}
@ -66,7 +66,7 @@ func (c *KVExportCommand) Run(args []string) int {
// Create and test the HTTP client
client, err := c.Command.HTTPClient()
if err != nil {
c.Ui.Error(fmt.Sprintf("Error connecting to Consul agent: %s", err))
c.UI.Error(fmt.Sprintf("Error connecting to Consul agent: %s", err))
return 1
}
@ -74,7 +74,7 @@ func (c *KVExportCommand) Run(args []string) int {
AllowStale: c.Command.HTTPStale(),
})
if err != nil {
c.Ui.Error(fmt.Sprintf("Error querying Consul agent: %s", err))
c.UI.Error(fmt.Sprintf("Error querying Consul agent: %s", err))
return 1
}
@ -85,11 +85,11 @@ func (c *KVExportCommand) Run(args []string) int {
marshaled, err := json.MarshalIndent(exported, "", "\t")
if err != nil {
c.Ui.Error(fmt.Sprintf("Error exporting KV data: %s", err))
c.UI.Error(fmt.Sprintf("Error exporting KV data: %s", err))
return 1
}
c.Ui.Info(string(marshaled))
c.UI.Info(string(marshaled))
return 0
}

View File

@ -18,7 +18,7 @@ func TestKVExportCommand_Run(t *testing.T) {
ui := new(cli.MockUi)
c := KVExportCommand{
Command: base.Command{
Ui: ui,
UI: ui,
Flags: base.FlagSetHTTP,
},
}

View File

@ -89,7 +89,7 @@ func (c *KVGetCommand) Run(args []string) int {
case 1:
key = args[0]
default:
c.Ui.Error(fmt.Sprintf("Too many arguments (expected 1, got %d)", len(args)))
c.UI.Error(fmt.Sprintf("Too many arguments (expected 1, got %d)", len(args)))
return 1
}
@ -103,14 +103,14 @@ func (c *KVGetCommand) Run(args []string) int {
// If the key is empty and we are not doing a recursive or key-based lookup,
// this is an error.
if key == "" && !(*recurse || *keys) {
c.Ui.Error("Error! Missing KEY argument")
c.UI.Error("Error! Missing KEY argument")
return 1
}
// Create and test the HTTP client
client, err := c.Command.HTTPClient()
if err != nil {
c.Ui.Error(fmt.Sprintf("Error connecting to Consul agent: %s", err))
c.UI.Error(fmt.Sprintf("Error connecting to Consul agent: %s", err))
return 1
}
@ -120,12 +120,12 @@ func (c *KVGetCommand) Run(args []string) int {
AllowStale: c.Command.HTTPStale(),
})
if err != nil {
c.Ui.Error(fmt.Sprintf("Error querying Consul agent: %s", err))
c.UI.Error(fmt.Sprintf("Error querying Consul agent: %s", err))
return 1
}
for _, k := range keys {
c.Ui.Info(string(k))
c.UI.Info(string(k))
}
return 0
@ -134,7 +134,7 @@ func (c *KVGetCommand) Run(args []string) int {
AllowStale: c.Command.HTTPStale(),
})
if err != nil {
c.Ui.Error(fmt.Sprintf("Error querying Consul agent: %s", err))
c.UI.Error(fmt.Sprintf("Error querying Consul agent: %s", err))
return 1
}
@ -142,20 +142,20 @@ func (c *KVGetCommand) Run(args []string) int {
if *detailed {
var b bytes.Buffer
if err := prettyKVPair(&b, pair, *base64encode); err != nil {
c.Ui.Error(fmt.Sprintf("Error rendering KV pair: %s", err))
c.UI.Error(fmt.Sprintf("Error rendering KV pair: %s", err))
return 1
}
c.Ui.Info(b.String())
c.UI.Info(b.String())
if i < len(pairs)-1 {
c.Ui.Info("")
c.UI.Info("")
}
} else {
if *base64encode {
c.Ui.Info(fmt.Sprintf("%s:%s", pair.Key, base64.StdEncoding.EncodeToString(pair.Value)))
c.UI.Info(fmt.Sprintf("%s:%s", pair.Key, base64.StdEncoding.EncodeToString(pair.Value)))
} else {
c.Ui.Info(fmt.Sprintf("%s:%s", pair.Key, pair.Value))
c.UI.Info(fmt.Sprintf("%s:%s", pair.Key, pair.Value))
}
}
}
@ -166,26 +166,26 @@ func (c *KVGetCommand) Run(args []string) int {
AllowStale: c.Command.HTTPStale(),
})
if err != nil {
c.Ui.Error(fmt.Sprintf("Error querying Consul agent: %s", err))
c.UI.Error(fmt.Sprintf("Error querying Consul agent: %s", err))
return 1
}
if pair == nil {
c.Ui.Error(fmt.Sprintf("Error! No key exists at: %s", key))
c.UI.Error(fmt.Sprintf("Error! No key exists at: %s", key))
return 1
}
if *detailed {
var b bytes.Buffer
if err := prettyKVPair(&b, pair, *base64encode); err != nil {
c.Ui.Error(fmt.Sprintf("Error rendering KV pair: %s", err))
c.UI.Error(fmt.Sprintf("Error rendering KV pair: %s", err))
return 1
}
c.Ui.Info(b.String())
c.UI.Info(b.String())
return 0
} else {
c.Ui.Info(string(pair.Value))
c.UI.Info(string(pair.Value))
return 0
}
}

View File

@ -14,7 +14,7 @@ func testKVGetCommand(t *testing.T) (*cli.MockUi, *KVGetCommand) {
ui := new(cli.MockUi)
return ui, &KVGetCommand{
Command: base.Command{
Ui: ui,
UI: ui,
Flags: base.FlagSetHTTP,
},
}

View File

@ -65,27 +65,27 @@ func (c *KVImportCommand) Run(args []string) int {
args = f.Args()
data, err := c.dataFromArgs(args)
if err != nil {
c.Ui.Error(fmt.Sprintf("Error! %s", err))
c.UI.Error(fmt.Sprintf("Error! %s", err))
return 1
}
// Create and test the HTTP client
client, err := c.Command.HTTPClient()
if err != nil {
c.Ui.Error(fmt.Sprintf("Error connecting to Consul agent: %s", err))
c.UI.Error(fmt.Sprintf("Error connecting to Consul agent: %s", err))
return 1
}
var entries []*kvExportEntry
if err := json.Unmarshal([]byte(data), &entries); err != nil {
c.Ui.Error(fmt.Sprintf("Cannot unmarshal data: %s", err))
c.UI.Error(fmt.Sprintf("Cannot unmarshal data: %s", err))
return 1
}
for _, entry := range entries {
value, err := base64.StdEncoding.DecodeString(entry.Value)
if err != nil {
c.Ui.Error(fmt.Sprintf("Error base 64 decoding value for key %s: %s", entry.Key, err))
c.UI.Error(fmt.Sprintf("Error base 64 decoding value for key %s: %s", entry.Key, err))
return 1
}
@ -96,11 +96,11 @@ func (c *KVImportCommand) Run(args []string) int {
}
if _, err := client.KV().Put(pair, nil); err != nil {
c.Ui.Error(fmt.Sprintf("Error! Failed writing data for key %s: %s", pair.Key, err))
c.UI.Error(fmt.Sprintf("Error! Failed writing data for key %s: %s", pair.Key, err))
return 1
}
c.Ui.Info(fmt.Sprintf("Imported: %s", pair.Key))
c.UI.Info(fmt.Sprintf("Imported: %s", pair.Key))
}
return 0

View File

@ -29,7 +29,7 @@ func TestKVImportCommand_Run(t *testing.T) {
ui := new(cli.MockUi)
c := &KVImportCommand{
Command: base.Command{
Ui: ui,
UI: ui,
Flags: base.FlagSetHTTP,
},
testStdin: strings.NewReader(json),

View File

@ -97,7 +97,7 @@ func (c *KVPutCommand) Run(args []string) int {
args = f.Args()
key, data, err := c.dataFromArgs(args)
if err != nil {
c.Ui.Error(fmt.Sprintf("Error! %s", err))
c.UI.Error(fmt.Sprintf("Error! %s", err))
return 1
}
@ -105,26 +105,26 @@ func (c *KVPutCommand) Run(args []string) int {
if *base64encoded {
dataBytes, err = base64.StdEncoding.DecodeString(data)
if err != nil {
c.Ui.Error(fmt.Sprintf("Error! Cannot base 64 decode data: %s", err))
c.UI.Error(fmt.Sprintf("Error! Cannot base 64 decode data: %s", err))
}
}
// Session is reauired for release or acquire
if (*release || *acquire) && *session == "" {
c.Ui.Error("Error! Missing -session (required with -acquire and -release)")
c.UI.Error("Error! Missing -session (required with -acquire and -release)")
return 1
}
// ModifyIndex is required for CAS
if *cas && *modifyIndex == 0 {
c.Ui.Error("Must specify -modify-index with -cas!")
c.UI.Error("Must specify -modify-index with -cas!")
return 1
}
// Create and test the HTTP client
client, err := c.Command.HTTPClient()
if err != nil {
c.Ui.Error(fmt.Sprintf("Error connecting to Consul agent: %s", err))
c.UI.Error(fmt.Sprintf("Error connecting to Consul agent: %s", err))
return 1
}
@ -140,49 +140,49 @@ func (c *KVPutCommand) Run(args []string) int {
case *cas:
ok, _, err := client.KV().CAS(pair, nil)
if err != nil {
c.Ui.Error(fmt.Sprintf("Error! Did not write to %s: %s", key, err))
c.UI.Error(fmt.Sprintf("Error! Did not write to %s: %s", key, err))
return 1
}
if !ok {
c.Ui.Error(fmt.Sprintf("Error! Did not write to %s: CAS failed", key))
c.UI.Error(fmt.Sprintf("Error! Did not write to %s: CAS failed", key))
return 1
}
c.Ui.Info(fmt.Sprintf("Success! Data written to: %s", key))
c.UI.Info(fmt.Sprintf("Success! Data written to: %s", key))
return 0
case *acquire:
ok, _, err := client.KV().Acquire(pair, nil)
if err != nil {
c.Ui.Error(fmt.Sprintf("Error! Failed writing data: %s", err))
c.UI.Error(fmt.Sprintf("Error! Failed writing data: %s", err))
return 1
}
if !ok {
c.Ui.Error("Error! Did not acquire lock")
c.UI.Error("Error! Did not acquire lock")
return 1
}
c.Ui.Info(fmt.Sprintf("Success! Lock acquired on: %s", key))
c.UI.Info(fmt.Sprintf("Success! Lock acquired on: %s", key))
return 0
case *release:
ok, _, err := client.KV().Release(pair, nil)
if err != nil {
c.Ui.Error(fmt.Sprintf("Error! Failed writing data: %s", key))
c.UI.Error(fmt.Sprintf("Error! Failed writing data: %s", key))
return 1
}
if !ok {
c.Ui.Error("Error! Did not release lock")
c.UI.Error("Error! Did not release lock")
return 1
}
c.Ui.Info(fmt.Sprintf("Success! Lock released on: %s", key))
c.UI.Info(fmt.Sprintf("Success! Lock released on: %s", key))
return 0
default:
if _, err := client.KV().Put(pair, nil); err != nil {
c.Ui.Error(fmt.Sprintf("Error! Failed writing data: %s", err))
c.UI.Error(fmt.Sprintf("Error! Failed writing data: %s", err))
return 1
}
c.Ui.Info(fmt.Sprintf("Success! Data written to: %s", key))
c.UI.Info(fmt.Sprintf("Success! Data written to: %s", key))
return 0
}
}

View File

@ -19,7 +19,7 @@ func testKVPutCommand(t *testing.T) (*cli.MockUi, *KVPutCommand) {
ui := new(cli.MockUi)
return ui, &KVPutCommand{
Command: base.Command{
Ui: ui,
UI: ui,
Flags: base.FlagSetHTTP,
},
}

View File

@ -30,23 +30,23 @@ func (c *LeaveCommand) Run(args []string) int {
}
nonFlagArgs := f.Args()
if len(nonFlagArgs) > 0 {
c.Ui.Error(fmt.Sprintf("Error found unexpected args: %v", nonFlagArgs))
c.Ui.Output(c.Help())
c.UI.Error(fmt.Sprintf("Error found unexpected args: %v", nonFlagArgs))
c.UI.Output(c.Help())
return 1
}
client, err := c.Command.HTTPClient()
if err != nil {
c.Ui.Error(fmt.Sprintf("Error connecting to Consul agent: %s", err))
c.UI.Error(fmt.Sprintf("Error connecting to Consul agent: %s", err))
return 1
}
if err := client.Agent().Leave(); err != nil {
c.Ui.Error(fmt.Sprintf("Error leaving: %s", err))
c.UI.Error(fmt.Sprintf("Error leaving: %s", err))
return 1
}
c.Ui.Output("Graceful leave complete")
c.UI.Output("Graceful leave complete")
return 0
}

View File

@ -11,7 +11,7 @@ func testLeaveCommand(t *testing.T) (*cli.MockUi, *LeaveCommand) {
ui := new(cli.MockUi)
return ui, &LeaveCommand{
Command: base.Command{
Ui: ui,
UI: ui,
Flags: base.FlagSetClientHTTP,
},
}

View File

@ -115,14 +115,14 @@ func (c *LockCommand) run(args []string, lu **LockUnlock) int {
// Check the limit
if limit <= 0 {
c.Ui.Error(fmt.Sprintf("Lock holder limit must be positive"))
c.UI.Error(fmt.Sprintf("Lock holder limit must be positive"))
return 1
}
// Verify the prefix and child are provided
extra := f.Args()
if len(extra) < 2 {
c.Ui.Error("Key prefix and child command must be specified")
c.UI.Error("Key prefix and child command must be specified")
return 1
}
prefix := extra[0]
@ -130,7 +130,7 @@ func (c *LockCommand) run(args []string, lu **LockUnlock) int {
script := strings.Join(extra[1:], " ")
if timeout < 0 {
c.Ui.Error("Timeout must be positive")
c.UI.Error("Timeout must be positive")
return 1
}
@ -144,19 +144,19 @@ func (c *LockCommand) run(args []string, lu **LockUnlock) int {
// Check the retry parameter
if monitorRetry < 0 {
c.Ui.Error("Number for 'monitor-retry' must be >= 0")
c.UI.Error("Number for 'monitor-retry' must be >= 0")
return 1
}
// Create and test the HTTP client
client, err := c.Command.HTTPClient()
if err != nil {
c.Ui.Error(fmt.Sprintf("Error connecting to Consul agent: %s", err))
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))
c.UI.Error(fmt.Sprintf("Error querying Consul agent: %s", err))
return 1
}
@ -167,20 +167,20 @@ func (c *LockCommand) run(args []string, lu **LockUnlock) int {
*lu, err = c.setupSemaphore(client, limit, prefix, name, oneshot, timeout, monitorRetry)
}
if err != nil {
c.Ui.Error(fmt.Sprintf("Lock setup failed: %s", err))
c.UI.Error(fmt.Sprintf("Lock setup failed: %s", err))
return 1
}
// Attempt the acquisition
if c.verbose {
c.Ui.Info("Attempting lock acquisition")
c.UI.Info("Attempting lock acquisition")
}
lockCh, err := (*lu).lockFn(c.ShutdownCh)
if lockCh == nil {
if err == nil {
c.Ui.Error("Shutdown triggered or timeout during lock acquisition")
c.UI.Error("Shutdown triggered or timeout during lock acquisition")
} else {
c.Ui.Error(fmt.Sprintf("Lock acquisition failed: %s", err))
c.UI.Error(fmt.Sprintf("Lock acquisition failed: %s", err))
}
return 1
}
@ -188,7 +188,7 @@ func (c *LockCommand) run(args []string, lu **LockUnlock) int {
// Check if we were shutdown but managed to still acquire the lock
select {
case <-c.ShutdownCh:
c.Ui.Error("Shutdown triggered during lock acquisition")
c.UI.Error("Shutdown triggered during lock acquisition")
goto RELEASE
default:
}
@ -197,7 +197,7 @@ func (c *LockCommand) run(args []string, lu **LockUnlock) int {
childDone = make(chan struct{})
go func() {
if err := c.startChild(script, childDone, passStdin); err != nil {
c.Ui.Error(fmt.Sprintf("%s", err))
c.UI.Error(fmt.Sprintf("%s", err))
}
}()
@ -205,15 +205,15 @@ func (c *LockCommand) run(args []string, lu **LockUnlock) int {
select {
case <-c.ShutdownCh:
if c.verbose {
c.Ui.Info("Shutdown triggered, killing child")
c.UI.Info("Shutdown triggered, killing child")
}
case <-lockCh:
if c.verbose {
c.Ui.Info("Lock lost, killing child")
c.UI.Info("Lock lost, killing child")
}
case <-childDone:
if c.verbose {
c.Ui.Info("Child terminated, releasing lock")
c.UI.Info("Child terminated, releasing lock")
}
goto RELEASE
}
@ -223,26 +223,26 @@ func (c *LockCommand) run(args []string, lu **LockUnlock) int {
c.childLock.Lock()
// Kill any existing child
if err := c.killChild(childDone); err != nil {
c.Ui.Error(fmt.Sprintf("%s", err))
c.UI.Error(fmt.Sprintf("%s", err))
}
RELEASE:
// Release the lock before termination
if err := (*lu).unlockFn(); err != nil {
c.Ui.Error(fmt.Sprintf("Lock release failed: %s", err))
c.UI.Error(fmt.Sprintf("Lock release failed: %s", err))
return 1
}
// Cleanup the lock if no longer in use
if err := (*lu).cleanupFn(); err != nil {
if err != (*lu).inUseErr {
c.Ui.Error(fmt.Sprintf("Lock cleanup failed: %s", err))
c.UI.Error(fmt.Sprintf("Lock cleanup failed: %s", err))
return 1
} else if c.verbose {
c.Ui.Info("Cleanup aborted, lock in use")
c.UI.Info("Cleanup aborted, lock in use")
}
} else if c.verbose {
c.Ui.Info("Cleanup succeeded")
c.UI.Info("Cleanup succeeded")
}
return 0
}
@ -259,7 +259,7 @@ func (c *LockCommand) setupLock(client *api.Client, prefix, name string,
// which we can report to the user.
key := path.Join(prefix, api.DefaultSemaphoreKey)
if c.verbose {
c.Ui.Info(fmt.Sprintf("Setting up lock at path: %s", key))
c.UI.Info(fmt.Sprintf("Setting up lock at path: %s", key))
}
opts := api.LockOptions{
Key: key,
@ -293,7 +293,7 @@ func (c *LockCommand) setupLock(client *api.Client, prefix, name string,
func (c *LockCommand) setupSemaphore(client *api.Client, limit int, prefix, name string,
oneshot bool, wait time.Duration, retry int) (*LockUnlock, error) {
if c.verbose {
c.Ui.Info(fmt.Sprintf("Setting up semaphore (limit %d) at prefix: %s", limit, prefix))
c.UI.Info(fmt.Sprintf("Setting up semaphore (limit %d) at prefix: %s", limit, prefix))
}
opts := api.SemaphoreOptions{
Prefix: prefix,
@ -325,12 +325,12 @@ func (c *LockCommand) setupSemaphore(client *api.Client, limit int, prefix, name
func (c *LockCommand) startChild(script string, doneCh chan struct{}, passStdin bool) error {
defer close(doneCh)
if c.verbose {
c.Ui.Info(fmt.Sprintf("Starting handler '%s'", script))
c.UI.Info(fmt.Sprintf("Starting handler '%s'", script))
}
// Create the command
cmd, err := agent.ExecScript(script)
if err != nil {
c.Ui.Error(fmt.Sprintf("Error executing handler: %s", err))
c.UI.Error(fmt.Sprintf("Error executing handler: %s", err))
return err
}
@ -340,7 +340,7 @@ func (c *LockCommand) startChild(script string, doneCh chan struct{}, passStdin
)
if passStdin {
if c.verbose {
c.Ui.Info("Stdin passed to handler process")
c.UI.Info("Stdin passed to handler process")
}
cmd.Stdin = os.Stdin
} else {
@ -352,7 +352,7 @@ func (c *LockCommand) startChild(script string, doneCh chan struct{}, passStdin
// Start the child process
c.childLock.Lock()
if err := cmd.Start(); err != nil {
c.Ui.Error(fmt.Sprintf("Error starting handler: %s", err))
c.UI.Error(fmt.Sprintf("Error starting handler: %s", err))
c.childLock.Unlock()
return err
}
@ -363,7 +363,7 @@ func (c *LockCommand) startChild(script string, doneCh chan struct{}, passStdin
// Wait for the child process
if err := cmd.Wait(); err != nil {
c.Ui.Error(fmt.Sprintf("Error running handler: %s", err))
c.UI.Error(fmt.Sprintf("Error running handler: %s", err))
return err
}
return nil
@ -381,14 +381,14 @@ func (c *LockCommand) killChild(childDone chan struct{}) error {
// If there is no child process (failed to start), we can quit early
if child == nil {
if c.verbose {
c.Ui.Info("No child process to kill")
c.UI.Info("No child process to kill")
}
return nil
}
// Attempt termination first
if c.verbose {
c.Ui.Info(fmt.Sprintf("Terminating child pid %d", child.Pid))
c.UI.Info(fmt.Sprintf("Terminating child pid %d", child.Pid))
}
if err := signalPid(child.Pid, syscall.SIGTERM); err != nil {
return fmt.Errorf("Failed to terminate %d: %v", child.Pid, err)
@ -398,19 +398,19 @@ func (c *LockCommand) killChild(childDone chan struct{}) error {
select {
case <-childDone:
if c.verbose {
c.Ui.Info("Child terminated")
c.UI.Info("Child terminated")
}
return nil
case <-time.After(lockKillGracePeriod):
if c.verbose {
c.Ui.Info(fmt.Sprintf("Child did not exit after grace period of %v",
c.UI.Info(fmt.Sprintf("Child did not exit after grace period of %v",
lockKillGracePeriod))
}
}
// Send a final SIGKILL
if c.verbose {
c.Ui.Info(fmt.Sprintf("Killing child pid %d", child.Pid))
c.UI.Info(fmt.Sprintf("Killing child pid %d", child.Pid))
}
if err := signalPid(child.Pid, syscall.SIGKILL); err != nil {
return fmt.Errorf("Failed to kill %d: %v", child.Pid, err)

View File

@ -17,7 +17,7 @@ func testLockCommand(t *testing.T) (*cli.MockUi, *LockCommand) {
ui := new(cli.MockUi)
return ui, &LockCommand{
Command: base.Command{
Ui: ui,
UI: ui,
Flags: base.FlagSetHTTP,
},
}

View File

@ -62,28 +62,28 @@ func (c *MaintCommand) Run(args []string) int {
// Ensure we don't have conflicting args
if enable && disable {
c.Ui.Error("Only one of -enable or -disable may be provided")
c.UI.Error("Only one of -enable or -disable may be provided")
return 1
}
if !enable && reason != "" {
c.Ui.Error("Reason may only be provided with -enable")
c.UI.Error("Reason may only be provided with -enable")
return 1
}
if !enable && !disable && serviceID != "" {
c.Ui.Error("Service requires either -enable or -disable")
c.UI.Error("Service requires either -enable or -disable")
return 1
}
// Create and test the HTTP client
client, err := c.Command.HTTPClient()
if err != nil {
c.Ui.Error(fmt.Sprintf("Error connecting to Consul agent: %s", err))
c.UI.Error(fmt.Sprintf("Error connecting to Consul agent: %s", err))
return 1
}
a := client.Agent()
nodeName, err := a.NodeName()
if err != nil {
c.Ui.Error(fmt.Sprintf("Error querying Consul agent: %s", err))
c.UI.Error(fmt.Sprintf("Error querying Consul agent: %s", err))
return 1
}
@ -91,21 +91,21 @@ func (c *MaintCommand) Run(args []string) int {
// List mode - list nodes/services in maintenance mode
checks, err := a.Checks()
if err != nil {
c.Ui.Error(fmt.Sprintf("Error getting checks: %s", err))
c.UI.Error(fmt.Sprintf("Error getting checks: %s", err))
return 1
}
for _, check := range checks {
if check.CheckID == "_node_maintenance" {
c.Ui.Output("Node:")
c.Ui.Output(" Name: " + nodeName)
c.Ui.Output(" Reason: " + check.Notes)
c.Ui.Output("")
c.UI.Output("Node:")
c.UI.Output(" Name: " + nodeName)
c.UI.Output(" Reason: " + check.Notes)
c.UI.Output("")
} else if strings.HasPrefix(string(check.CheckID), "_service_maintenance:") {
c.Ui.Output("Service:")
c.Ui.Output(" ID: " + check.ServiceID)
c.Ui.Output(" Reason: " + check.Notes)
c.Ui.Output("")
c.UI.Output("Service:")
c.UI.Output(" ID: " + check.ServiceID)
c.UI.Output(" Reason: " + check.Notes)
c.UI.Output("")
}
}
@ -116,19 +116,19 @@ func (c *MaintCommand) Run(args []string) int {
// Enable node maintenance
if serviceID == "" {
if err := a.EnableNodeMaintenance(reason); err != nil {
c.Ui.Error(fmt.Sprintf("Error enabling node maintenance: %s", err))
c.UI.Error(fmt.Sprintf("Error enabling node maintenance: %s", err))
return 1
}
c.Ui.Output("Node maintenance is now enabled")
c.UI.Output("Node maintenance is now enabled")
return 0
}
// Enable service maintenance
if err := a.EnableServiceMaintenance(serviceID, reason); err != nil {
c.Ui.Error(fmt.Sprintf("Error enabling service maintenance: %s", err))
c.UI.Error(fmt.Sprintf("Error enabling service maintenance: %s", err))
return 1
}
c.Ui.Output(fmt.Sprintf("Service maintenance is now enabled for %q", serviceID))
c.UI.Output(fmt.Sprintf("Service maintenance is now enabled for %q", serviceID))
return 0
}
@ -136,19 +136,19 @@ func (c *MaintCommand) Run(args []string) int {
// Disable node maintenance
if serviceID == "" {
if err := a.DisableNodeMaintenance(); err != nil {
c.Ui.Error(fmt.Sprintf("Error disabling node maintenance: %s", err))
c.UI.Error(fmt.Sprintf("Error disabling node maintenance: %s", err))
return 1
}
c.Ui.Output("Node maintenance is now disabled")
c.UI.Output("Node maintenance is now disabled")
return 0
}
// Disable service maintenance
if err := a.DisableServiceMaintenance(serviceID); err != nil {
c.Ui.Error(fmt.Sprintf("Error disabling service maintenance: %s", err))
c.UI.Error(fmt.Sprintf("Error disabling service maintenance: %s", err))
return 1
}
c.Ui.Output(fmt.Sprintf("Service maintenance is now disabled for %q", serviceID))
c.UI.Output(fmt.Sprintf("Service maintenance is now disabled for %q", serviceID))
return 0
}

View File

@ -13,7 +13,7 @@ func testMaintCommand(t *testing.T) (*cli.MockUi, *MaintCommand) {
ui := new(cli.MockUi)
return ui, &MaintCommand{
Command: base.Command{
Ui: ui,
UI: ui,
Flags: base.FlagSetClientHTTP,
},
}

View File

@ -52,19 +52,19 @@ func (c *MembersCommand) Run(args []string) int {
// Compile the regexp
statusRe, err := regexp.Compile(statusFilter)
if err != nil {
c.Ui.Error(fmt.Sprintf("Failed to compile status regexp: %v", err))
c.UI.Error(fmt.Sprintf("Failed to compile status regexp: %v", err))
return 1
}
client, err := c.Command.HTTPClient()
if err != nil {
c.Ui.Error(fmt.Sprintf("Error connecting to Consul agent: %s", err))
c.UI.Error(fmt.Sprintf("Error connecting to Consul agent: %s", err))
return 1
}
members, err := client.Agent().Members(wan)
if err != nil {
c.Ui.Error(fmt.Sprintf("Error retrieving members: %s", err))
c.UI.Error(fmt.Sprintf("Error retrieving members: %s", err))
return 1
}
@ -99,7 +99,7 @@ func (c *MembersCommand) Run(args []string) int {
// Generate the columnized version
output := columnize.SimpleFormat(result)
c.Ui.Output(output)
c.UI.Output(output)
return 0
}

View File

@ -12,7 +12,7 @@ func testMembersCommand(t *testing.T) (*cli.MockUi, *MembersCommand) {
ui := new(cli.MockUi)
return ui, &MembersCommand{
Command: base.Command{
Ui: ui,
UI: ui,
Flags: base.FlagSetClientHTTP,
},
}

View File

@ -46,14 +46,14 @@ func (c *MonitorCommand) Run(args []string) int {
client, err := c.Command.HTTPClient()
if err != nil {
c.Ui.Error(fmt.Sprintf("Error connecting to Consul agent: %s", err))
c.UI.Error(fmt.Sprintf("Error connecting to Consul agent: %s", err))
return 1
}
eventDoneCh := make(chan struct{})
logCh, err := client.Agent().Monitor(logLevel, eventDoneCh, nil)
if err != nil {
c.Ui.Error(fmt.Sprintf("Error starting monitor: %s", err))
c.UI.Error(fmt.Sprintf("Error starting monitor: %s", err))
return 1
}
@ -66,15 +66,15 @@ func (c *MonitorCommand) Run(args []string) int {
if log == "" {
break OUTER
}
c.Ui.Info(log)
c.UI.Info(log)
}
}
c.lock.Lock()
defer c.lock.Unlock()
if !c.quitting {
c.Ui.Info("")
c.Ui.Output("Remote side ended the monitor! This usually means that the\n" +
c.UI.Info("")
c.UI.Output("Remote side ended the monitor! This usually means that the\n" +
"remote side has exited or crashed.")
}
}()

View File

@ -35,14 +35,14 @@ func (c *OperatorAutopilotGetCommand) Run(args []string) int {
if err == flag.ErrHelp {
return 0
}
c.Ui.Error(fmt.Sprintf("Failed to parse args: %v", err))
c.UI.Error(fmt.Sprintf("Failed to parse args: %v", err))
return 1
}
// Set up a client.
client, err := c.Command.HTTPClient()
if err != nil {
c.Ui.Error(fmt.Sprintf("Error initializing client: %s", err))
c.UI.Error(fmt.Sprintf("Error initializing client: %s", err))
return 1
}
@ -52,15 +52,15 @@ func (c *OperatorAutopilotGetCommand) Run(args []string) int {
}
config, err := client.Operator().AutopilotGetConfiguration(opts)
if err != nil {
c.Ui.Error(fmt.Sprintf("Error querying Autopilot configuration: %s", err))
c.UI.Error(fmt.Sprintf("Error querying Autopilot configuration: %s", err))
return 1
}
c.Ui.Output(fmt.Sprintf("CleanupDeadServers = %v", config.CleanupDeadServers))
c.Ui.Output(fmt.Sprintf("LastContactThreshold = %v", config.LastContactThreshold.String()))
c.Ui.Output(fmt.Sprintf("MaxTrailingLogs = %v", config.MaxTrailingLogs))
c.Ui.Output(fmt.Sprintf("ServerStabilizationTime = %v", config.ServerStabilizationTime.String()))
c.Ui.Output(fmt.Sprintf("RedundancyZoneTag = %q", config.RedundancyZoneTag))
c.Ui.Output(fmt.Sprintf("DisableUpgradeMigration = %v", config.DisableUpgradeMigration))
c.UI.Output(fmt.Sprintf("CleanupDeadServers = %v", config.CleanupDeadServers))
c.UI.Output(fmt.Sprintf("LastContactThreshold = %v", config.LastContactThreshold.String()))
c.UI.Output(fmt.Sprintf("MaxTrailingLogs = %v", config.MaxTrailingLogs))
c.UI.Output(fmt.Sprintf("ServerStabilizationTime = %v", config.ServerStabilizationTime.String()))
c.UI.Output(fmt.Sprintf("RedundancyZoneTag = %q", config.RedundancyZoneTag))
c.UI.Output(fmt.Sprintf("DisableUpgradeMigration = %v", config.DisableUpgradeMigration))
return 0
}

View File

@ -20,7 +20,7 @@ func TestOperator_Autopilot_Get(t *testing.T) {
ui := new(cli.MockUi)
c := OperatorAutopilotGetCommand{
Command: base.Command{
Ui: ui,
UI: ui,
Flags: base.FlagSetHTTP,
},
}

View File

@ -65,14 +65,14 @@ func (c *OperatorAutopilotSetCommand) Run(args []string) int {
if err == flag.ErrHelp {
return 0
}
c.Ui.Error(fmt.Sprintf("Failed to parse args: %v", err))
c.UI.Error(fmt.Sprintf("Failed to parse args: %v", err))
return 1
}
// Set up a client.
client, err := c.Command.HTTPClient()
if err != nil {
c.Ui.Error(fmt.Sprintf("Error initializing client: %s", err))
c.UI.Error(fmt.Sprintf("Error initializing client: %s", err))
return 1
}
@ -80,7 +80,7 @@ func (c *OperatorAutopilotSetCommand) Run(args []string) int {
operator := client.Operator()
conf, err := operator.AutopilotGetConfiguration(nil)
if err != nil {
c.Ui.Error(fmt.Sprintf("Error querying Autopilot configuration: %s", err))
c.UI.Error(fmt.Sprintf("Error querying Autopilot configuration: %s", err))
return 1
}
@ -104,14 +104,14 @@ func (c *OperatorAutopilotSetCommand) Run(args []string) int {
// Check-and-set the new configuration.
result, err := operator.AutopilotCASConfiguration(conf, nil)
if err != nil {
c.Ui.Error(fmt.Sprintf("Error setting Autopilot configuration: %s", err))
c.UI.Error(fmt.Sprintf("Error setting Autopilot configuration: %s", err))
return 1
}
if result {
c.Ui.Output("Configuration updated!")
c.UI.Output("Configuration updated!")
return 0
} else {
c.Ui.Output("Configuration could not be atomically updated, please try again")
c.UI.Output("Configuration could not be atomically updated, please try again")
return 1
}
}

View File

@ -22,7 +22,7 @@ func TestOperator_Autopilot_Set(t *testing.T) {
ui := new(cli.MockUi)
c := OperatorAutopilotSetCommand{
Command: base.Command{
Ui: ui,
UI: ui,
Flags: base.FlagSetHTTP,
},
}

View File

@ -36,7 +36,7 @@ func (c *OperatorRaftCommand) Synopsis() string {
func (c *OperatorRaftCommand) Run(args []string) int {
if result := c.raft(args); result != nil {
c.Ui.Error(result.Error())
c.UI.Error(result.Error())
return 1
}
return 0
@ -82,16 +82,16 @@ func (c *OperatorRaftCommand) raft(args []string) error {
if listPeers {
result, err := raftListPeers(client, c.Command.HTTPStale())
if err != nil {
c.Ui.Error(fmt.Sprintf("Error getting peers: %v", err))
c.UI.Error(fmt.Sprintf("Error getting peers: %v", err))
}
c.Ui.Output(result)
c.UI.Output(result)
} else if removePeer {
if err := raftRemovePeers(address, "", client.Operator()); err != nil {
return fmt.Errorf("Error removing peer: %v", err)
}
c.Ui.Output(fmt.Sprintf("Removed peer with address %q", address))
c.UI.Output(fmt.Sprintf("Removed peer with address %q", address))
} else {
c.Ui.Output(c.Help())
c.UI.Output(c.Help())
return nil
}

View File

@ -37,23 +37,23 @@ func (c *OperatorRaftListCommand) Run(args []string) int {
if err == flag.ErrHelp {
return 0
}
c.Ui.Error(fmt.Sprintf("Failed to parse args: %v", err))
c.UI.Error(fmt.Sprintf("Failed to parse args: %v", err))
return 1
}
// Set up a client.
client, err := c.Command.HTTPClient()
if err != nil {
c.Ui.Error(fmt.Sprintf("Error initializing client: %s", err))
c.UI.Error(fmt.Sprintf("Error initializing client: %s", err))
return 1
}
// Fetch the current configuration.
result, err := raftListPeers(client, c.Command.HTTPStale())
if err != nil {
c.Ui.Error(fmt.Sprintf("Error getting peers: %v", err))
c.UI.Error(fmt.Sprintf("Error getting peers: %v", err))
}
c.Ui.Output(result)
c.UI.Output(result)
return 0
}

View File

@ -41,7 +41,7 @@ func TestOperator_Raft_ListPeers(t *testing.T) {
ui := new(cli.MockUi)
c := OperatorRaftListCommand{
Command: base.Command{
Ui: ui,
UI: ui,
Flags: base.FlagSetHTTP,
},
}

View File

@ -48,26 +48,26 @@ func (c *OperatorRaftRemoveCommand) Run(args []string) int {
if err == flag.ErrHelp {
return 0
}
c.Ui.Error(fmt.Sprintf("Failed to parse args: %v", err))
c.UI.Error(fmt.Sprintf("Failed to parse args: %v", err))
return 1
}
// Set up a client.
client, err := c.Command.HTTPClient()
if err != nil {
c.Ui.Error(fmt.Sprintf("Error initializing client: %s", err))
c.UI.Error(fmt.Sprintf("Error initializing client: %s", err))
return 1
}
// Fetch the current configuration.
if err := raftRemovePeers(address, id, client.Operator()); err != nil {
c.Ui.Error(fmt.Sprintf("Error removing peer: %v", err))
c.UI.Error(fmt.Sprintf("Error removing peer: %v", err))
return 1
}
if address != "" {
c.Ui.Output(fmt.Sprintf("Removed peer with address %q", address))
c.UI.Output(fmt.Sprintf("Removed peer with address %q", address))
} else {
c.Ui.Output(fmt.Sprintf("Removed peer with id %q", id))
c.UI.Output(fmt.Sprintf("Removed peer with id %q", id))
}
return 0

View File

@ -39,7 +39,7 @@ func TestOperator_Raft_RemovePeer(t *testing.T) {
ui := new(cli.MockUi)
c := OperatorRaftRemoveCommand{
Command: base.Command{
Ui: ui,
UI: ui,
Flags: base.FlagSetHTTP,
},
}
@ -62,7 +62,7 @@ func TestOperator_Raft_RemovePeer(t *testing.T) {
ui := new(cli.MockUi)
c := OperatorRaftRemoveCommand{
Command: base.Command{
Ui: ui,
UI: ui,
Flags: base.FlagSetHTTP,
},
}

View File

@ -11,7 +11,7 @@ func testOperatorRaftCommand(t *testing.T) (*cli.MockUi, *OperatorRaftCommand) {
ui := new(cli.MockUi)
return ui, &OperatorRaftCommand{
Command: base.Command{
Ui: ui,
UI: ui,
Flags: base.FlagSetHTTP,
},
}

View File

@ -33,16 +33,16 @@ func (c *ReloadCommand) Run(args []string) int {
client, err := c.Command.HTTPClient()
if err != nil {
c.Ui.Error(fmt.Sprintf("Error connecting to Consul agent: %s", err))
c.UI.Error(fmt.Sprintf("Error connecting to Consul agent: %s", err))
return 1
}
if err := client.Agent().Reload(); err != nil {
c.Ui.Error(fmt.Sprintf("Error reloading: %s", err))
c.UI.Error(fmt.Sprintf("Error reloading: %s", err))
return 1
}
c.Ui.Output("Configuration reload triggered")
c.UI.Output("Configuration reload triggered")
return 0
}

View File

@ -26,7 +26,7 @@ func TestReloadCommandRun(t *testing.T) {
ui := new(cli.MockUi)
c := &ReloadCommand{
Command: base.Command{
Ui: ui,
UI: ui,
Flags: base.FlagSetClientHTTP,
},
}

View File

@ -53,16 +53,16 @@ func (c *RTTCommand) Run(args []string) int {
// They must provide at least one node.
nodes := f.Args()
if len(nodes) < 1 || len(nodes) > 2 {
c.Ui.Error("One or two node names must be specified")
c.Ui.Error("")
c.Ui.Error(c.Help())
c.UI.Error("One or two node names must be specified")
c.UI.Error("")
c.UI.Error(c.Help())
return 1
}
// Create and test the HTTP client.
client, err := c.Command.HTTPClient()
if err != nil {
c.Ui.Error(fmt.Sprintf("Error connecting to Consul agent: %s", err))
c.UI.Error(fmt.Sprintf("Error connecting to Consul agent: %s", err))
return 1
}
coordClient := client.Coordinate()
@ -77,7 +77,7 @@ func (c *RTTCommand) Run(args []string) int {
agent := client.Agent()
self, err := agent.Self()
if err != nil {
c.Ui.Error(fmt.Sprintf("Unable to look up agent info: %s", err))
c.UI.Error(fmt.Sprintf("Unable to look up agent info: %s", err))
return 1
}
@ -89,7 +89,7 @@ func (c *RTTCommand) Run(args []string) int {
parts1 := strings.Split(nodes[0], ".")
parts2 := strings.Split(nodes[1], ".")
if len(parts1) != 2 || len(parts2) != 2 {
c.Ui.Error("Node names must be specified as <node name>.<datacenter> with -wan")
c.UI.Error("Node names must be specified as <node name>.<datacenter> with -wan")
return 1
}
node1, dc1 := parts1[0], parts1[1]
@ -98,7 +98,7 @@ func (c *RTTCommand) Run(args []string) int {
// Pull all the WAN coordinates.
dcs, err := coordClient.Datacenters()
if err != nil {
c.Ui.Error(fmt.Sprintf("Error getting coordinates: %s", err))
c.UI.Error(fmt.Sprintf("Error getting coordinates: %s", err))
return 1
}
@ -133,7 +133,7 @@ func (c *RTTCommand) Run(args []string) int {
agent := client.Agent()
node, err := agent.NodeName()
if err != nil {
c.Ui.Error(fmt.Sprintf("Unable to look up agent info: %s", err))
c.UI.Error(fmt.Sprintf("Unable to look up agent info: %s", err))
return 1
}
nodes = append(nodes, node)
@ -142,7 +142,7 @@ func (c *RTTCommand) Run(args []string) int {
// Pull all the LAN coordinates.
entries, _, err := coordClient.Nodes(nil)
if err != nil {
c.Ui.Error(fmt.Sprintf("Error getting coordinates: %s", err))
c.UI.Error(fmt.Sprintf("Error getting coordinates: %s", err))
return 1
}
@ -163,11 +163,11 @@ func (c *RTTCommand) Run(args []string) int {
// Make sure we found both coordinates.
if coord1 == nil {
c.Ui.Error(fmt.Sprintf("Could not find a coordinate for node %q", nodes[0]))
c.UI.Error(fmt.Sprintf("Could not find a coordinate for node %q", nodes[0]))
return 1
}
if coord2 == nil {
c.Ui.Error(fmt.Sprintf("Could not find a coordinate for node %q", nodes[1]))
c.UI.Error(fmt.Sprintf("Could not find a coordinate for node %q", nodes[1]))
return 1
}
@ -175,7 +175,7 @@ SHOW_RTT:
// Report the round trip time.
dist := fmt.Sprintf("%.3f ms", coord1.DistanceTo(coord2).Seconds()*1000.0)
c.Ui.Output(fmt.Sprintf("Estimated %s <-> %s rtt: %s (using %s coordinates)", nodes[0], nodes[1], dist, source))
c.UI.Output(fmt.Sprintf("Estimated %s <-> %s rtt: %s (using %s coordinates)", nodes[0], nodes[1], dist, source))
return 0
}

View File

@ -18,7 +18,7 @@ func testRTTCommand(t *testing.T) (*cli.MockUi, *RTTCommand) {
ui := new(cli.MockUi)
return ui, &RTTCommand{
Command: base.Command{
Ui: ui,
UI: ui,
Flags: base.FlagSetClientHTTP,
},
}

View File

@ -9,7 +9,7 @@ import (
// SnapshotCommand is a Command implementation that just shows help for
// the subcommands nested below it.
type SnapshotCommand struct {
Ui cli.Ui
UI cli.Ui
}
func (c *SnapshotCommand) Run(args []string) int {

View File

@ -45,26 +45,26 @@ func (c *SnapshotInspectCommand) Run(args []string) int {
args = flagSet.Args()
switch len(args) {
case 0:
c.Ui.Error("Missing FILE argument")
c.UI.Error("Missing FILE argument")
return 1
case 1:
file = args[0]
default:
c.Ui.Error(fmt.Sprintf("Too many arguments (expected 1, got %d)", len(args)))
c.UI.Error(fmt.Sprintf("Too many arguments (expected 1, got %d)", len(args)))
return 1
}
// Open the file.
f, err := os.Open(file)
if err != nil {
c.Ui.Error(fmt.Sprintf("Error opening snapshot file: %s", err))
c.UI.Error(fmt.Sprintf("Error opening snapshot file: %s", err))
return 1
}
defer f.Close()
meta, err := snapshot.Verify(f)
if err != nil {
c.Ui.Error(fmt.Sprintf("Error verifying snapshot: %s", err))
c.UI.Error(fmt.Sprintf("Error verifying snapshot: %s", err))
}
var b bytes.Buffer
@ -75,10 +75,10 @@ func (c *SnapshotInspectCommand) Run(args []string) int {
fmt.Fprintf(tw, "Term\t%d\n", meta.Term)
fmt.Fprintf(tw, "Version\t%d\n", meta.Version)
if err = tw.Flush(); err != nil {
c.Ui.Error(fmt.Sprintf("Error rendering snapshot info: %s", err))
c.UI.Error(fmt.Sprintf("Error rendering snapshot info: %s", err))
}
c.Ui.Info(b.String())
c.UI.Info(b.String())
return 0
}

View File

@ -16,7 +16,7 @@ func testSnapshotInspectCommand(t *testing.T) (*cli.MockUi, *SnapshotInspectComm
ui := new(cli.MockUi)
return ui, &SnapshotInspectCommand{
Command: base.Command{
Ui: ui,
UI: ui,
Flags: base.FlagSetNone,
},
}

View File

@ -53,26 +53,26 @@ func (c *SnapshotRestoreCommand) Run(args []string) int {
args = flagSet.Args()
switch len(args) {
case 0:
c.Ui.Error("Missing FILE argument")
c.UI.Error("Missing FILE argument")
return 1
case 1:
file = args[0]
default:
c.Ui.Error(fmt.Sprintf("Too many arguments (expected 1, got %d)", len(args)))
c.UI.Error(fmt.Sprintf("Too many arguments (expected 1, got %d)", len(args)))
return 1
}
// Create and test the HTTP client
client, err := c.Command.HTTPClient()
if err != nil {
c.Ui.Error(fmt.Sprintf("Error connecting to Consul agent: %s", err))
c.UI.Error(fmt.Sprintf("Error connecting to Consul agent: %s", err))
return 1
}
// Open the file.
f, err := os.Open(file)
if err != nil {
c.Ui.Error(fmt.Sprintf("Error opening snapshot file: %s", err))
c.UI.Error(fmt.Sprintf("Error opening snapshot file: %s", err))
return 1
}
defer f.Close()
@ -80,11 +80,11 @@ func (c *SnapshotRestoreCommand) Run(args []string) int {
// Restore the snapshot.
err = client.Snapshot().Restore(nil, f)
if err != nil {
c.Ui.Error(fmt.Sprintf("Error restoring snapshot: %s", err))
c.UI.Error(fmt.Sprintf("Error restoring snapshot: %s", err))
return 1
}
c.Ui.Info("Restored snapshot")
c.UI.Info("Restored snapshot")
return 0
}

View File

@ -16,7 +16,7 @@ func testSnapshotRestoreCommand(t *testing.T) (*cli.MockUi, *SnapshotRestoreComm
ui := new(cli.MockUi)
return ui, &SnapshotRestoreCommand{
Command: base.Command{
Ui: ui,
UI: ui,
Flags: base.FlagSetHTTP,
},
}

View File

@ -56,19 +56,19 @@ func (c *SnapshotSaveCommand) Run(args []string) int {
args = flagSet.Args()
switch len(args) {
case 0:
c.Ui.Error("Missing FILE argument")
c.UI.Error("Missing FILE argument")
return 1
case 1:
file = args[0]
default:
c.Ui.Error(fmt.Sprintf("Too many arguments (expected 1, got %d)", len(args)))
c.UI.Error(fmt.Sprintf("Too many arguments (expected 1, got %d)", len(args)))
return 1
}
// Create and test the HTTP client
client, err := c.Command.HTTPClient()
if err != nil {
c.Ui.Error(fmt.Sprintf("Error connecting to Consul agent: %s", err))
c.UI.Error(fmt.Sprintf("Error connecting to Consul agent: %s", err))
return 1
}
@ -77,7 +77,7 @@ func (c *SnapshotSaveCommand) Run(args []string) int {
AllowStale: c.Command.HTTPStale(),
})
if err != nil {
c.Ui.Error(fmt.Sprintf("Error saving snapshot: %s", err))
c.UI.Error(fmt.Sprintf("Error saving snapshot: %s", err))
return 1
}
defer snap.Close()
@ -85,36 +85,36 @@ func (c *SnapshotSaveCommand) Run(args []string) int {
// Save the file.
f, err := os.Create(file)
if err != nil {
c.Ui.Error(fmt.Sprintf("Error creating snapshot file: %s", err))
c.UI.Error(fmt.Sprintf("Error creating snapshot file: %s", err))
return 1
}
if _, err := io.Copy(f, snap); err != nil {
f.Close()
c.Ui.Error(fmt.Sprintf("Error writing snapshot file: %s", err))
c.UI.Error(fmt.Sprintf("Error writing snapshot file: %s", err))
return 1
}
if err := f.Close(); err != nil {
c.Ui.Error(fmt.Sprintf("Error closing snapshot file after writing: %s", err))
c.UI.Error(fmt.Sprintf("Error closing snapshot file after writing: %s", err))
return 1
}
// Read it back to verify.
f, err = os.Open(file)
if err != nil {
c.Ui.Error(fmt.Sprintf("Error opening snapshot file for verify: %s", err))
c.UI.Error(fmt.Sprintf("Error opening snapshot file for verify: %s", err))
return 1
}
if _, err := snapshot.Verify(f); err != nil {
f.Close()
c.Ui.Error(fmt.Sprintf("Error verifying snapshot file: %s", err))
c.UI.Error(fmt.Sprintf("Error verifying snapshot file: %s", err))
return 1
}
if err := f.Close(); err != nil {
c.Ui.Error(fmt.Sprintf("Error closing snapshot file after verify: %s", err))
c.UI.Error(fmt.Sprintf("Error closing snapshot file after verify: %s", err))
return 1
}
c.Ui.Info(fmt.Sprintf("Saved and verified snapshot to index %d", qm.LastIndex))
c.UI.Info(fmt.Sprintf("Saved and verified snapshot to index %d", qm.LastIndex))
return 0
}

View File

@ -15,7 +15,7 @@ func testSnapshotSaveCommand(t *testing.T) (*cli.MockUi, *SnapshotSaveCommand) {
ui := new(cli.MockUi)
return ui, &SnapshotSaveCommand{
Command: base.Command{
Ui: ui,
UI: ui,
Flags: base.FlagSetHTTP,
},
}

View File

@ -54,18 +54,18 @@ func (c *ValidateCommand) Run(args []string) int {
}
if len(configFiles) < 1 {
c.Ui.Error("Must specify at least one config file or directory")
c.UI.Error("Must specify at least one config file or directory")
return 1
}
_, err := agent.ReadConfigPaths(configFiles)
if err != nil {
c.Ui.Error(fmt.Sprintf("Config validation failed: %v", err.Error()))
c.UI.Error(fmt.Sprintf("Config validation failed: %v", err.Error()))
return 1
}
if !quiet {
c.Ui.Output("Configuration is valid!")
c.UI.Output("Configuration is valid!")
}
return 0
}

View File

@ -14,7 +14,7 @@ func testValidateCommand(t *testing.T) (*cli.MockUi, *ValidateCommand) {
ui := new(cli.MockUi)
return ui, &ValidateCommand{
Command: base.Command{
Ui: ui,
UI: ui,
Flags: base.FlagSetNone,
},
}

View File

@ -2,6 +2,7 @@ package command
import (
"fmt"
"github.com/hashicorp/consul/command/agent"
"github.com/hashicorp/consul/consul"
"github.com/mitchellh/cli"
@ -10,7 +11,7 @@ import (
// VersionCommand is a Command implementation prints the version.
type VersionCommand struct {
HumanVersion string
Ui cli.Ui
UI cli.Ui
}
func (c *VersionCommand) Help() string {
@ -18,7 +19,7 @@ func (c *VersionCommand) Help() string {
}
func (c *VersionCommand) Run(_ []string) int {
c.Ui.Output(fmt.Sprintf("Consul %s", c.HumanVersion))
c.UI.Output(fmt.Sprintf("Consul %s", c.HumanVersion))
config := agent.DefaultConfig()
var supplement string
@ -26,7 +27,7 @@ func (c *VersionCommand) Run(_ []string) int {
supplement = fmt.Sprintf(" (agent will automatically use protocol >%d when speaking to compatible agents)",
config.Protocol)
}
c.Ui.Output(fmt.Sprintf("Protocol %d spoken by default, understands %d to %d%s",
c.UI.Output(fmt.Sprintf("Protocol %d spoken by default, understands %d to %d%s",
config.Protocol, consul.ProtocolVersionMin, consul.ProtocolVersionMax, supplement))
return 0

View File

@ -66,9 +66,9 @@ func (c *WatchCommand) Run(args []string) int {
// Check for a type
if watchType == "" {
c.Ui.Error("Watch type must be specified")
c.Ui.Error("")
c.Ui.Error(c.Help())
c.UI.Error("Watch type must be specified")
c.UI.Error("")
c.UI.Error(c.Help())
return 1
}
@ -110,7 +110,7 @@ func (c *WatchCommand) Run(args []string) int {
if passingOnly != "" {
b, err := strconv.ParseBool(passingOnly)
if err != nil {
c.Ui.Error(fmt.Sprintf("Failed to parse passingonly flag: %s", err))
c.UI.Error(fmt.Sprintf("Failed to parse passingonly flag: %s", err))
return 1
}
params["passingonly"] = b
@ -119,19 +119,19 @@ func (c *WatchCommand) Run(args []string) int {
// Create the watch
wp, err := watch.Parse(params)
if err != nil {
c.Ui.Error(fmt.Sprintf("%s", err))
c.UI.Error(fmt.Sprintf("%s", err))
return 1
}
// Create and test the HTTP client
client, err := c.Command.HTTPClient()
if err != nil {
c.Ui.Error(fmt.Sprintf("Error connecting to Consul agent: %s", err))
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))
c.UI.Error(fmt.Sprintf("Error querying Consul agent: %s", err))
return 1
}
@ -146,10 +146,10 @@ func (c *WatchCommand) Run(args []string) int {
defer wp.Stop()
buf, err := json.MarshalIndent(data, "", " ")
if err != nil {
c.Ui.Error(fmt.Sprintf("Error encoding output: %s", err))
c.UI.Error(fmt.Sprintf("Error encoding output: %s", err))
errExit = 1
}
c.Ui.Output(string(buf))
c.UI.Output(string(buf))
}
} else {
wp.Handler = func(idx uint64, data interface{}) {
@ -158,7 +158,7 @@ func (c *WatchCommand) Run(args []string) int {
var err error
cmd, err := agent.ExecScript(script)
if err != nil {
c.Ui.Error(fmt.Sprintf("Error executing handler: %s", err))
c.UI.Error(fmt.Sprintf("Error executing handler: %s", err))
goto ERR
}
cmd.Env = append(os.Environ(),
@ -167,7 +167,7 @@ func (c *WatchCommand) Run(args []string) int {
// Encode the input
if err = json.NewEncoder(&buf).Encode(data); err != nil {
c.Ui.Error(fmt.Sprintf("Error encoding output: %s", err))
c.UI.Error(fmt.Sprintf("Error encoding output: %s", err))
goto ERR
}
cmd.Stdin = &buf
@ -176,7 +176,7 @@ func (c *WatchCommand) Run(args []string) int {
// Run the handler
if err := cmd.Run(); err != nil {
c.Ui.Error(fmt.Sprintf("Error executing handler: %s", err))
c.UI.Error(fmt.Sprintf("Error executing handler: %s", err))
goto ERR
}
return
@ -195,7 +195,7 @@ func (c *WatchCommand) Run(args []string) int {
// Run the watch
if err := wp.Run(c.Command.HTTPAddr()); err != nil {
c.Ui.Error(fmt.Sprintf("Error querying Consul agent: %s", err))
c.UI.Error(fmt.Sprintf("Error querying Consul agent: %s", err))
return 1
}

View File

@ -19,7 +19,7 @@ func TestWatchCommandRun(t *testing.T) {
ui := new(cli.MockUi)
c := &WatchCommand{
Command: base.Command{
Ui: ui,
UI: ui,
Flags: base.FlagSetHTTP,
},
}

View File

@ -23,7 +23,7 @@ func init() {
return &agent.Command{
Command: base.Command{
Flags: base.FlagSetNone,
Ui: ui,
UI: ui,
},
Revision: version.GitCommit,
Version: version.Version,
@ -37,7 +37,7 @@ func init() {
return &command.ConfigTestCommand{
Command: base.Command{
Flags: base.FlagSetNone,
Ui: ui,
UI: ui,
},
}, nil
},
@ -46,7 +46,7 @@ func init() {
return &command.EventCommand{
Command: base.Command{
Flags: base.FlagSetHTTP,
Ui: ui,
UI: ui,
},
}, nil
},
@ -56,7 +56,7 @@ func init() {
ShutdownCh: makeShutdownCh(),
Command: base.Command{
Flags: base.FlagSetHTTP,
Ui: ui,
UI: ui,
},
}, nil
},
@ -65,7 +65,7 @@ func init() {
return &command.ForceLeaveCommand{
Command: base.Command{
Flags: base.FlagSetClientHTTP,
Ui: ui,
UI: ui,
},
}, nil
},
@ -73,7 +73,7 @@ func init() {
"info": func() (cli.Command, error) {
return &command.InfoCommand{
Command: base.Command{
Ui: ui,
UI: ui,
Flags: base.FlagSetClientHTTP,
},
}, nil
@ -82,7 +82,7 @@ func init() {
"join": func() (cli.Command, error) {
return &command.JoinCommand{
Command: base.Command{
Ui: ui,
UI: ui,
Flags: base.FlagSetClientHTTP,
},
}, nil
@ -91,7 +91,7 @@ func init() {
"keygen": func() (cli.Command, error) {
return &command.KeygenCommand{
Command: base.Command{
Ui: ui,
UI: ui,
Flags: base.FlagSetNone,
},
}, nil
@ -100,7 +100,7 @@ func init() {
"keyring": func() (cli.Command, error) {
return &command.KeyringCommand{
Command: base.Command{
Ui: ui,
UI: ui,
Flags: base.FlagSetClientHTTP,
},
}, nil
@ -109,7 +109,7 @@ func init() {
"kv": func() (cli.Command, error) {
return &command.KVCommand{
Command: base.Command{
Ui: ui,
UI: ui,
Flags: base.FlagSetNone,
},
}, nil
@ -118,7 +118,7 @@ func init() {
"kv delete": func() (cli.Command, error) {
return &command.KVDeleteCommand{
Command: base.Command{
Ui: ui,
UI: ui,
Flags: base.FlagSetHTTP,
},
}, nil
@ -127,7 +127,7 @@ func init() {
"kv get": func() (cli.Command, error) {
return &command.KVGetCommand{
Command: base.Command{
Ui: ui,
UI: ui,
Flags: base.FlagSetHTTP,
},
}, nil
@ -136,7 +136,7 @@ func init() {
"kv put": func() (cli.Command, error) {
return &command.KVPutCommand{
Command: base.Command{
Ui: ui,
UI: ui,
Flags: base.FlagSetHTTP,
},
}, nil
@ -145,7 +145,7 @@ func init() {
"kv export": func() (cli.Command, error) {
return &command.KVExportCommand{
Command: base.Command{
Ui: ui,
UI: ui,
Flags: base.FlagSetHTTP,
},
}, nil
@ -154,7 +154,7 @@ func init() {
"kv import": func() (cli.Command, error) {
return &command.KVImportCommand{
Command: base.Command{
Ui: ui,
UI: ui,
Flags: base.FlagSetHTTP,
},
}, nil
@ -164,7 +164,7 @@ func init() {
return &command.LeaveCommand{
Command: base.Command{
Flags: base.FlagSetClientHTTP,
Ui: ui,
UI: ui,
},
}, nil
},
@ -174,7 +174,7 @@ func init() {
ShutdownCh: makeShutdownCh(),
Command: base.Command{
Flags: base.FlagSetHTTP,
Ui: ui,
UI: ui,
},
}, nil
},
@ -183,7 +183,7 @@ func init() {
return &command.MaintCommand{
Command: base.Command{
Flags: base.FlagSetClientHTTP,
Ui: ui,
UI: ui,
},
}, nil
},
@ -192,7 +192,7 @@ func init() {
return &command.MembersCommand{
Command: base.Command{
Flags: base.FlagSetClientHTTP,
Ui: ui,
UI: ui,
},
}, nil
},
@ -202,7 +202,7 @@ func init() {
ShutdownCh: makeShutdownCh(),
Command: base.Command{
Flags: base.FlagSetClientHTTP,
Ui: ui,
UI: ui,
},
}, nil
},
@ -211,7 +211,7 @@ func init() {
return &command.OperatorCommand{
Command: base.Command{
Flags: base.FlagSetNone,
Ui: ui,
UI: ui,
},
}, nil
},
@ -220,7 +220,7 @@ func init() {
return &command.OperatorAutopilotCommand{
Command: base.Command{
Flags: base.FlagSetNone,
Ui: ui,
UI: ui,
},
}, nil
},
@ -229,7 +229,7 @@ func init() {
return &command.OperatorAutopilotGetCommand{
Command: base.Command{
Flags: base.FlagSetHTTP,
Ui: ui,
UI: ui,
},
}, nil
},
@ -238,7 +238,7 @@ func init() {
return &command.OperatorAutopilotSetCommand{
Command: base.Command{
Flags: base.FlagSetHTTP,
Ui: ui,
UI: ui,
},
}, nil
},
@ -247,7 +247,7 @@ func init() {
return &command.OperatorRaftCommand{
Command: base.Command{
Flags: base.FlagSetHTTP,
Ui: ui,
UI: ui,
},
}, nil
},
@ -256,7 +256,7 @@ func init() {
return &command.OperatorRaftListCommand{
Command: base.Command{
Flags: base.FlagSetHTTP,
Ui: ui,
UI: ui,
},
}, nil
},
@ -265,7 +265,7 @@ func init() {
return &command.OperatorRaftRemoveCommand{
Command: base.Command{
Flags: base.FlagSetHTTP,
Ui: ui,
UI: ui,
},
}, nil
},
@ -274,7 +274,7 @@ func init() {
return &command.ReloadCommand{
Command: base.Command{
Flags: base.FlagSetClientHTTP,
Ui: ui,
UI: ui,
},
}, nil
},
@ -283,14 +283,14 @@ func init() {
return &command.RTTCommand{
Command: base.Command{
Flags: base.FlagSetClientHTTP,
Ui: ui,
UI: ui,
},
}, nil
},
"snapshot": func() (cli.Command, error) {
return &command.SnapshotCommand{
Ui: ui,
UI: ui,
}, nil
},
@ -298,7 +298,7 @@ func init() {
return &command.SnapshotRestoreCommand{
Command: base.Command{
Flags: base.FlagSetHTTP,
Ui: ui,
UI: ui,
},
}, nil
},
@ -307,7 +307,7 @@ func init() {
return &command.SnapshotSaveCommand{
Command: base.Command{
Flags: base.FlagSetHTTP,
Ui: ui,
UI: ui,
},
}, nil
},
@ -316,7 +316,7 @@ func init() {
return &command.SnapshotInspectCommand{
Command: base.Command{
Flags: base.FlagSetNone,
Ui: ui,
UI: ui,
},
}, nil
},
@ -325,7 +325,7 @@ func init() {
return &command.ValidateCommand{
Command: base.Command{
Flags: base.FlagSetNone,
Ui: ui,
UI: ui,
},
}, nil
},
@ -333,7 +333,7 @@ func init() {
"version": func() (cli.Command, error) {
return &command.VersionCommand{
HumanVersion: version.GetHumanVersion(),
Ui: ui,
UI: ui,
}, nil
},
@ -342,7 +342,7 @@ func init() {
ShutdownCh: makeShutdownCh(),
Command: base.Command{
Flags: base.FlagSetHTTP,
Ui: ui,
UI: ui,
},
}, nil
},

View File

@ -41,9 +41,7 @@ const (
aclCacheSize = 10 * 1024
)
var (
permissionDeniedErr = errors.New(permissionDenied)
)
var errPermissionDenied = errors.New(permissionDenied)
// aclCacheEntry is used to cache non-authoritative ACLs
// If non-authoritative, then we must respect a TTL
@ -132,10 +130,10 @@ type aclCache struct {
local acl.FaultFunc
}
// newAclCache returns a new non-authoritative cache for ACLs. This is used for
// newACLCache returns a new non-authoritative cache for ACLs. This is used for
// performance, and is used inside the ACL datacenter on non-leader servers, and
// outside the ACL datacenter everywhere.
func newAclCache(conf *Config, logger *log.Logger, rpc rpcFn, local acl.FaultFunc) (*aclCache, error) {
func newACLCache(conf *Config, logger *log.Logger, rpc rpcFn, local acl.FaultFunc) (*aclCache, error) {
var err error
cache := &aclCache{
config: conf,
@ -319,8 +317,8 @@ type aclFilter struct {
enforceVersion8 bool
}
// newAclFilter constructs a new aclFilter.
func newAclFilter(acl acl.ACL, logger *log.Logger, enforceVersion8 bool) *aclFilter {
// newACLFilter constructs a new aclFilter.
func newACLFilter(acl acl.ACL, logger *log.Logger, enforceVersion8 bool) *aclFilter {
if logger == nil {
logger = log.New(os.Stdout, "", log.LstdFlags)
}
@ -600,7 +598,7 @@ func (s *Server) filterACL(token string, subj interface{}) error {
}
// Create the filter
filt := newAclFilter(acl, s.logger, s.config.ACLEnforceVersion8)
filt := newACLFilter(acl, s.logger, s.config.ACLEnforceVersion8)
switch v := subj.(type) {
case *structs.CheckServiceNodes:
@ -672,7 +670,7 @@ func vetRegisterWithACL(acl acl.ACL, subj *structs.RegisterRequest,
// privileges.
needsNode := ns == nil || subj.ChangesNode(ns.Node)
if needsNode && !acl.NodeWrite(subj.Node) {
return permissionDeniedErr
return errPermissionDenied
}
// Vet the service change. This includes making sure they can register
@ -680,13 +678,13 @@ func vetRegisterWithACL(acl acl.ACL, subj *structs.RegisterRequest,
// is being modified by id (if any).
if subj.Service != nil {
if !acl.ServiceWrite(subj.Service.Service) {
return permissionDeniedErr
return errPermissionDenied
}
if ns != nil {
other, ok := ns.Services[subj.Service.ID]
if ok && !acl.ServiceWrite(other.Service) {
return permissionDeniedErr
return errPermissionDenied
}
}
}
@ -715,7 +713,7 @@ func vetRegisterWithACL(acl acl.ACL, subj *structs.RegisterRequest,
// Node-level check.
if check.ServiceID == "" {
if !acl.NodeWrite(subj.Node) {
return permissionDeniedErr
return errPermissionDenied
}
continue
}
@ -740,7 +738,7 @@ func vetRegisterWithACL(acl acl.ACL, subj *structs.RegisterRequest,
check.ServiceID, check.CheckID)
}
if !acl.ServiceWrite(other.Service) {
return permissionDeniedErr
return errPermissionDenied
}
}
}
@ -768,7 +766,7 @@ func vetDeregisterWithACL(acl acl.ACL, subj *structs.DeregisterRequest,
return fmt.Errorf("Unknown service '%s'", subj.ServiceID)
}
if !acl.ServiceWrite(ns.Service) {
return permissionDeniedErr
return errPermissionDenied
}
} else if subj.CheckID != "" {
if nc == nil {
@ -776,16 +774,16 @@ func vetDeregisterWithACL(acl acl.ACL, subj *structs.DeregisterRequest,
}
if nc.ServiceID != "" {
if !acl.ServiceWrite(nc.ServiceName) {
return permissionDeniedErr
return errPermissionDenied
}
} else {
if !acl.NodeWrite(subj.Node) {
return permissionDeniedErr
return errPermissionDenied
}
}
} else {
if !acl.NodeWrite(subj.Node) {
return permissionDeniedErr
return errPermissionDenied
}
}

View File

@ -93,7 +93,7 @@ func (a *ACL) Apply(args *structs.ACLRequest, reply *string) error {
if acl, err := a.srv.resolveToken(args.Token); err != nil {
return err
} else if acl == nil || !acl.ACLModify() {
return permissionDeniedErr
return errPermissionDenied
}
// If no ID is provided, generate a new ID. This must be done prior to
@ -220,7 +220,7 @@ func (a *ACL) List(args *structs.DCSpecificRequest,
if acl, err := a.srv.resolveToken(args.Token); err != nil {
return err
} else if acl == nil || !acl.ACLList() {
return permissionDeniedErr
return errPermissionDenied
}
return a.srv.blockingQuery(&args.QueryOptions,

View File

@ -821,7 +821,7 @@ func TestACL_filterHealthChecks(t *testing.T) {
// Try permissive filtering.
{
hc := fill()
filt := newAclFilter(acl.AllowAll(), nil, false)
filt := newACLFilter(acl.AllowAll(), nil, false)
filt.filterHealthChecks(&hc)
if len(hc) != 1 {
t.Fatalf("bad: %#v", hc)
@ -831,7 +831,7 @@ func TestACL_filterHealthChecks(t *testing.T) {
// Try restrictive filtering.
{
hc := fill()
filt := newAclFilter(acl.DenyAll(), nil, false)
filt := newACLFilter(acl.DenyAll(), nil, false)
filt.filterHealthChecks(&hc)
if len(hc) != 0 {
t.Fatalf("bad: %#v", hc)
@ -855,7 +855,7 @@ service "foo" {
// This will work because version 8 ACLs aren't being enforced.
{
hc := fill()
filt := newAclFilter(perms, nil, false)
filt := newACLFilter(perms, nil, false)
filt.filterHealthChecks(&hc)
if len(hc) != 1 {
t.Fatalf("bad: %#v", hc)
@ -865,7 +865,7 @@ service "foo" {
// But with version 8 the node will block it.
{
hc := fill()
filt := newAclFilter(perms, nil, true)
filt := newACLFilter(perms, nil, true)
filt.filterHealthChecks(&hc)
if len(hc) != 0 {
t.Fatalf("bad: %#v", hc)
@ -889,7 +889,7 @@ node "node1" {
// Now it should go through.
{
hc := fill()
filt := newAclFilter(perms, nil, true)
filt := newACLFilter(perms, nil, true)
filt.filterHealthChecks(&hc)
if len(hc) != 1 {
t.Fatalf("bad: %#v", hc)
@ -906,14 +906,14 @@ func TestACL_filterServices(t *testing.T) {
}
// Try permissive filtering.
filt := newAclFilter(acl.AllowAll(), nil, false)
filt := newACLFilter(acl.AllowAll(), nil, false)
filt.filterServices(services)
if len(services) != 3 {
t.Fatalf("bad: %#v", services)
}
// Try restrictive filtering.
filt = newAclFilter(acl.DenyAll(), nil, false)
filt = newACLFilter(acl.DenyAll(), nil, false)
filt.filterServices(services)
if len(services) != 1 {
t.Fatalf("bad: %#v", services)
@ -923,7 +923,7 @@ func TestACL_filterServices(t *testing.T) {
}
// Try restrictive filtering with version 8 enforcement.
filt = newAclFilter(acl.DenyAll(), nil, true)
filt = newACLFilter(acl.DenyAll(), nil, true)
filt.filterServices(services)
if len(services) != 0 {
t.Fatalf("bad: %#v", services)
@ -944,7 +944,7 @@ func TestACL_filterServiceNodes(t *testing.T) {
// Try permissive filtering.
{
nodes := fill()
filt := newAclFilter(acl.AllowAll(), nil, false)
filt := newACLFilter(acl.AllowAll(), nil, false)
filt.filterServiceNodes(&nodes)
if len(nodes) != 1 {
t.Fatalf("bad: %#v", nodes)
@ -954,7 +954,7 @@ func TestACL_filterServiceNodes(t *testing.T) {
// Try restrictive filtering.
{
nodes := fill()
filt := newAclFilter(acl.DenyAll(), nil, false)
filt := newACLFilter(acl.DenyAll(), nil, false)
filt.filterServiceNodes(&nodes)
if len(nodes) != 0 {
t.Fatalf("bad: %#v", nodes)
@ -978,7 +978,7 @@ service "foo" {
// This will work because version 8 ACLs aren't being enforced.
{
nodes := fill()
filt := newAclFilter(perms, nil, false)
filt := newACLFilter(perms, nil, false)
filt.filterServiceNodes(&nodes)
if len(nodes) != 1 {
t.Fatalf("bad: %#v", nodes)
@ -988,7 +988,7 @@ service "foo" {
// But with version 8 the node will block it.
{
nodes := fill()
filt := newAclFilter(perms, nil, true)
filt := newACLFilter(perms, nil, true)
filt.filterServiceNodes(&nodes)
if len(nodes) != 0 {
t.Fatalf("bad: %#v", nodes)
@ -1012,7 +1012,7 @@ node "node1" {
// Now it should go through.
{
nodes := fill()
filt := newAclFilter(perms, nil, true)
filt := newACLFilter(perms, nil, true)
filt.filterServiceNodes(&nodes)
if len(nodes) != 1 {
t.Fatalf("bad: %#v", nodes)
@ -1039,7 +1039,7 @@ func TestACL_filterNodeServices(t *testing.T) {
// Try nil, which is a possible input.
{
var services *structs.NodeServices
filt := newAclFilter(acl.AllowAll(), nil, false)
filt := newACLFilter(acl.AllowAll(), nil, false)
filt.filterNodeServices(&services)
if services != nil {
t.Fatalf("bad: %#v", services)
@ -1049,7 +1049,7 @@ func TestACL_filterNodeServices(t *testing.T) {
// Try permissive filtering.
{
services := fill()
filt := newAclFilter(acl.AllowAll(), nil, false)
filt := newACLFilter(acl.AllowAll(), nil, false)
filt.filterNodeServices(&services)
if len(services.Services) != 1 {
t.Fatalf("bad: %#v", services.Services)
@ -1059,7 +1059,7 @@ func TestACL_filterNodeServices(t *testing.T) {
// Try restrictive filtering.
{
services := fill()
filt := newAclFilter(acl.DenyAll(), nil, false)
filt := newACLFilter(acl.DenyAll(), nil, false)
filt.filterNodeServices(&services)
if len((*services).Services) != 0 {
t.Fatalf("bad: %#v", (*services).Services)
@ -1083,7 +1083,7 @@ service "foo" {
// This will work because version 8 ACLs aren't being enforced.
{
services := fill()
filt := newAclFilter(perms, nil, false)
filt := newACLFilter(perms, nil, false)
filt.filterNodeServices(&services)
if len((*services).Services) != 1 {
t.Fatalf("bad: %#v", (*services).Services)
@ -1093,7 +1093,7 @@ service "foo" {
// But with version 8 the node will block it.
{
services := fill()
filt := newAclFilter(perms, nil, true)
filt := newACLFilter(perms, nil, true)
filt.filterNodeServices(&services)
if services != nil {
t.Fatalf("bad: %#v", services)
@ -1117,7 +1117,7 @@ node "node1" {
// Now it should go through.
{
services := fill()
filt := newAclFilter(perms, nil, true)
filt := newACLFilter(perms, nil, true)
filt.filterNodeServices(&services)
if len((*services).Services) != 1 {
t.Fatalf("bad: %#v", (*services).Services)
@ -1151,7 +1151,7 @@ func TestACL_filterCheckServiceNodes(t *testing.T) {
// Try permissive filtering.
{
nodes := fill()
filt := newAclFilter(acl.AllowAll(), nil, false)
filt := newACLFilter(acl.AllowAll(), nil, false)
filt.filterCheckServiceNodes(&nodes)
if len(nodes) != 1 {
t.Fatalf("bad: %#v", nodes)
@ -1164,7 +1164,7 @@ func TestACL_filterCheckServiceNodes(t *testing.T) {
// Try restrictive filtering.
{
nodes := fill()
filt := newAclFilter(acl.DenyAll(), nil, false)
filt := newACLFilter(acl.DenyAll(), nil, false)
filt.filterCheckServiceNodes(&nodes)
if len(nodes) != 0 {
t.Fatalf("bad: %#v", nodes)
@ -1188,7 +1188,7 @@ service "foo" {
// This will work because version 8 ACLs aren't being enforced.
{
nodes := fill()
filt := newAclFilter(perms, nil, false)
filt := newACLFilter(perms, nil, false)
filt.filterCheckServiceNodes(&nodes)
if len(nodes) != 1 {
t.Fatalf("bad: %#v", nodes)
@ -1201,7 +1201,7 @@ service "foo" {
// But with version 8 the node will block it.
{
nodes := fill()
filt := newAclFilter(perms, nil, true)
filt := newACLFilter(perms, nil, true)
filt.filterCheckServiceNodes(&nodes)
if len(nodes) != 0 {
t.Fatalf("bad: %#v", nodes)
@ -1225,7 +1225,7 @@ node "node1" {
// Now it should go through.
{
nodes := fill()
filt := newAclFilter(perms, nil, true)
filt := newACLFilter(perms, nil, true)
filt.filterCheckServiceNodes(&nodes)
if len(nodes) != 1 {
t.Fatalf("bad: %#v", nodes)
@ -1250,21 +1250,21 @@ func TestACL_filterCoordinates(t *testing.T) {
}
// Try permissive filtering.
filt := newAclFilter(acl.AllowAll(), nil, false)
filt := newACLFilter(acl.AllowAll(), nil, false)
filt.filterCoordinates(&coords)
if len(coords) != 2 {
t.Fatalf("bad: %#v", coords)
}
// Try restrictive filtering without version 8 ACL enforcement.
filt = newAclFilter(acl.DenyAll(), nil, false)
filt = newACLFilter(acl.DenyAll(), nil, false)
filt.filterCoordinates(&coords)
if len(coords) != 2 {
t.Fatalf("bad: %#v", coords)
}
// Try restrictive filtering with version 8 ACL enforcement.
filt = newAclFilter(acl.DenyAll(), nil, true)
filt = newACLFilter(acl.DenyAll(), nil, true)
filt.filterCoordinates(&coords)
if len(coords) != 0 {
t.Fatalf("bad: %#v", coords)
@ -1283,21 +1283,21 @@ func TestACL_filterSessions(t *testing.T) {
}
// Try permissive filtering.
filt := newAclFilter(acl.AllowAll(), nil, true)
filt := newACLFilter(acl.AllowAll(), nil, true)
filt.filterSessions(&sessions)
if len(sessions) != 2 {
t.Fatalf("bad: %#v", sessions)
}
// Try restrictive filtering but with version 8 enforcement turned off.
filt = newAclFilter(acl.DenyAll(), nil, false)
filt = newACLFilter(acl.DenyAll(), nil, false)
filt.filterSessions(&sessions)
if len(sessions) != 2 {
t.Fatalf("bad: %#v", sessions)
}
// Try restrictive filtering with version 8 enforcement turned on.
filt = newAclFilter(acl.DenyAll(), nil, true)
filt = newACLFilter(acl.DenyAll(), nil, true)
filt.filterSessions(&sessions)
if len(sessions) != 0 {
t.Fatalf("bad: %#v", sessions)
@ -1330,7 +1330,7 @@ func TestACL_filterNodeDump(t *testing.T) {
// Try permissive filtering.
{
dump := fill()
filt := newAclFilter(acl.AllowAll(), nil, false)
filt := newACLFilter(acl.AllowAll(), nil, false)
filt.filterNodeDump(&dump)
if len(dump) != 1 {
t.Fatalf("bad: %#v", dump)
@ -1346,7 +1346,7 @@ func TestACL_filterNodeDump(t *testing.T) {
// Try restrictive filtering.
{
dump := fill()
filt := newAclFilter(acl.DenyAll(), nil, false)
filt := newACLFilter(acl.DenyAll(), nil, false)
filt.filterNodeDump(&dump)
if len(dump) != 1 {
t.Fatalf("bad: %#v", dump)
@ -1376,7 +1376,7 @@ service "foo" {
// This will work because version 8 ACLs aren't being enforced.
{
dump := fill()
filt := newAclFilter(perms, nil, false)
filt := newACLFilter(perms, nil, false)
filt.filterNodeDump(&dump)
if len(dump) != 1 {
t.Fatalf("bad: %#v", dump)
@ -1392,7 +1392,7 @@ service "foo" {
// But with version 8 the node will block it.
{
dump := fill()
filt := newAclFilter(perms, nil, true)
filt := newACLFilter(perms, nil, true)
filt.filterNodeDump(&dump)
if len(dump) != 0 {
t.Fatalf("bad: %#v", dump)
@ -1416,7 +1416,7 @@ node "node1" {
// Now it should go through.
{
dump := fill()
filt := newAclFilter(perms, nil, true)
filt := newACLFilter(perms, nil, true)
filt.filterNodeDump(&dump)
if len(dump) != 1 {
t.Fatalf("bad: %#v", dump)
@ -1442,21 +1442,21 @@ func TestACL_filterNodes(t *testing.T) {
}
// Try permissive filtering.
filt := newAclFilter(acl.AllowAll(), nil, true)
filt := newACLFilter(acl.AllowAll(), nil, true)
filt.filterNodes(&nodes)
if len(nodes) != 2 {
t.Fatalf("bad: %#v", nodes)
}
// Try restrictive filtering but with version 8 enforcement turned off.
filt = newAclFilter(acl.DenyAll(), nil, false)
filt = newACLFilter(acl.DenyAll(), nil, false)
filt.filterNodes(&nodes)
if len(nodes) != 2 {
t.Fatalf("bad: %#v", nodes)
}
// Try restrictive filtering with version 8 enforcement turned on.
filt = newAclFilter(acl.DenyAll(), nil, true)
filt = newACLFilter(acl.DenyAll(), nil, true)
filt.filterNodes(&nodes)
if len(nodes) != 0 {
t.Fatalf("bad: %#v", nodes)
@ -1476,7 +1476,7 @@ func TestACL_redactPreparedQueryTokens(t *testing.T) {
// Try permissive filtering with a management token. This will allow the
// embedded token to be seen.
filt := newAclFilter(acl.ManageAll(), nil, false)
filt := newACLFilter(acl.ManageAll(), nil, false)
filt.redactPreparedQueryTokens(&query)
if !reflect.DeepEqual(query, expected) {
t.Fatalf("bad: %#v", &query)
@ -1488,7 +1488,7 @@ func TestACL_redactPreparedQueryTokens(t *testing.T) {
// Now try permissive filtering with a client token, which should cause
// the embedded token to get redacted.
filt = newAclFilter(acl.AllowAll(), nil, false)
filt = newACLFilter(acl.AllowAll(), nil, false)
filt.redactPreparedQueryTokens(&query)
expected.Token = redactedToken
if !reflect.DeepEqual(query, expected) {
@ -1534,7 +1534,7 @@ func TestACL_filterPreparedQueries(t *testing.T) {
// Try permissive filtering with a management token. This will allow the
// embedded token to be seen.
filt := newAclFilter(acl.ManageAll(), nil, false)
filt := newACLFilter(acl.ManageAll(), nil, false)
filt.filterPreparedQueries(&queries)
if !reflect.DeepEqual(queries, expected) {
t.Fatalf("bad: %#v", queries)
@ -1547,7 +1547,7 @@ func TestACL_filterPreparedQueries(t *testing.T) {
// Now try permissive filtering with a client token, which should cause
// the embedded token to get redacted, and the query with no name to get
// filtered out.
filt = newAclFilter(acl.AllowAll(), nil, false)
filt = newACLFilter(acl.AllowAll(), nil, false)
filt.filterPreparedQueries(&queries)
expected[2].Token = redactedToken
expected = append(structs.PreparedQueries{}, expected[1], expected[2])
@ -1561,7 +1561,7 @@ func TestACL_filterPreparedQueries(t *testing.T) {
}
// Now try restrictive filtering.
filt = newAclFilter(acl.DenyAll(), nil, false)
filt = newACLFilter(acl.DenyAll(), nil, false)
filt.filterPreparedQueries(&queries)
if len(queries) != 0 {
t.Fatalf("bad: %#v", queries)

View File

@ -59,7 +59,7 @@ func (c *Catalog) Register(args *structs.RegisterRequest, reply *struct{}) error
// delete this and do all the ACL checks down there.
if args.Service.Service != ConsulServiceName {
if acl != nil && !acl.ServiceWrite(args.Service.Service) {
return permissionDeniedErr
return errPermissionDenied
}
}
}

View File

@ -127,7 +127,7 @@ func (c *Coordinate) Update(args *structs.CoordinateUpdateRequest, reply *struct
}
if acl != nil && c.srv.config.ACLEnforceVersion8 {
if !acl.NodeWrite(args.Node) {
return permissionDeniedErr
return errPermissionDenied
}
}

View File

@ -75,7 +75,7 @@ func (m *Internal) EventFire(args *structs.EventFireRequest,
if acl != nil && !acl.EventWrite(args.Name) {
m.srv.logger.Printf("[WARN] consul: user event %q blocked by ACLs", args.Name)
return permissionDeniedErr
return errPermissionDenied
}
// Set the query meta data

View File

@ -31,7 +31,7 @@ func kvsPreApply(srv *Server, acl acl.ACL, op api.KVOp, dirEnt *structs.DirEntry
switch op {
case api.KVDeleteTree:
if !acl.KeyWritePrefix(dirEnt.Key) {
return false, permissionDeniedErr
return false, errPermissionDenied
}
case api.KVGet, api.KVGetTree:
@ -42,12 +42,12 @@ func kvsPreApply(srv *Server, acl acl.ACL, op api.KVOp, dirEnt *structs.DirEntry
// of the transaction, and they operate on individual
// keys so we check them here.
if !acl.KeyRead(dirEnt.Key) {
return false, permissionDeniedErr
return false, errPermissionDenied
}
default:
if !acl.KeyWrite(dirEnt.Key) {
return false, permissionDeniedErr
return false, errPermissionDenied
}
}
}

View File

@ -657,7 +657,7 @@ func TestKVS_Apply_LockDelay(t *testing.T) {
if err := state.SessionCreate(5, session); err != nil {
t.Fatalf("err: %v", err)
}
validId := session.ID
validID := session.ID
// Make a lock request.
arg := structs.KVSRequest{
@ -665,7 +665,7 @@ func TestKVS_Apply_LockDelay(t *testing.T) {
Op: api.KVLock,
DirEnt: structs.DirEntry{
Key: "test",
Session: validId,
Session: validID,
},
}
var out bool

View File

@ -18,7 +18,7 @@ func (op *Operator) AutopilotGetConfiguration(args *structs.DCSpecificRequest, r
return err
}
if acl != nil && !acl.OperatorRead() {
return permissionDeniedErr
return errPermissionDenied
}
state := op.srv.fsm.State()
@ -47,7 +47,7 @@ func (op *Operator) AutopilotSetConfiguration(args *structs.AutopilotSetConfigRe
return err
}
if acl != nil && !acl.OperatorWrite() {
return permissionDeniedErr
return errPermissionDenied
}
// Apply the update
@ -83,7 +83,7 @@ func (op *Operator) ServerHealth(args *structs.DCSpecificRequest, reply *structs
return err
}
if acl != nil && !acl.OperatorRead() {
return permissionDeniedErr
return errPermissionDenied
}
// Exit early if the min Raft version is too low

View File

@ -22,7 +22,7 @@ func (op *Operator) RaftGetConfiguration(args *structs.DCSpecificRequest, reply
return err
}
if acl != nil && !acl.OperatorRead() {
return permissionDeniedErr
return errPermissionDenied
}
// We can't fetch the leader and the configuration atomically with
@ -81,7 +81,7 @@ func (op *Operator) RaftRemovePeerByAddress(args *structs.RaftRemovePeerRequest,
return err
}
if acl != nil && !acl.OperatorWrite() {
return permissionDeniedErr
return errPermissionDenied
}
// Since this is an operation designed for humans to use, we will return
@ -148,7 +148,7 @@ func (op *Operator) RaftRemovePeerByID(args *structs.RaftRemovePeerRequest, repl
return err
}
if acl != nil && !acl.OperatorWrite() {
return permissionDeniedErr
return errPermissionDenied
}
// Since this is an operation designed for humans to use, we will return

View File

@ -70,7 +70,7 @@ func (p *PreparedQuery) Apply(args *structs.PreparedQueryRequest, reply *string)
if prefix, ok := args.Query.GetACLPrefix(); ok {
if acl != nil && !acl.PreparedQueryWrite(prefix) {
p.srv.logger.Printf("[WARN] consul.prepared_query: Operation on prepared query '%s' denied due to ACLs", args.Query.ID)
return permissionDeniedErr
return errPermissionDenied
}
}
@ -90,7 +90,7 @@ func (p *PreparedQuery) Apply(args *structs.PreparedQueryRequest, reply *string)
if prefix, ok := query.GetACLPrefix(); ok {
if acl != nil && !acl.PreparedQueryWrite(prefix) {
p.srv.logger.Printf("[WARN] consul.prepared_query: Operation on prepared query '%s' denied due to ACLs", args.Query.ID)
return permissionDeniedErr
return errPermissionDenied
}
}
}
@ -249,7 +249,7 @@ func (p *PreparedQuery) Get(args *structs.PreparedQuerySpecificRequest,
// then alert the user with a permission denied error.
if len(reply.Queries) == 0 {
p.srv.logger.Printf("[WARN] consul.prepared_query: Request to get prepared query '%s' denied due to ACLs", args.QueryID)
return permissionDeniedErr
return errPermissionDenied
}
return nil
@ -317,7 +317,7 @@ func (p *PreparedQuery) Explain(args *structs.PreparedQueryExecuteRequest,
// If the query was filtered out, return an error.
if len(queries.Queries) == 0 {
p.srv.logger.Printf("[WARN] consul.prepared_query: Explain on prepared query '%s' denied due to ACLs", query.ID)
return permissionDeniedErr
return errPermissionDenied
}
reply.Query = *(queries.Queries[0])

View File

@ -289,7 +289,7 @@ func NewServer(config *Config) (*Server, error) {
if s.IsACLReplicationEnabled() {
local = s.aclLocalFault
}
if s.aclCache, err = newAclCache(config, logger, s.RPC, local); err != nil {
if s.aclCache, err = newACLCache(config, logger, s.RPC, local); err != nil {
s.Shutdown()
return nil, fmt.Errorf("Failed to create non-authoritative ACL cache: %v", err)
}

View File

@ -49,12 +49,12 @@ func (s *Session) Apply(args *structs.SessionRequest, reply *string) error {
return fmt.Errorf("Unknown session %q", args.Session.ID)
}
if !acl.SessionWrite(existing.Node) {
return permissionDeniedErr
return errPermissionDenied
}
case structs.SessionCreate:
if !acl.SessionWrite(args.Session.Node) {
return permissionDeniedErr
return errPermissionDenied
}
default:
@ -241,7 +241,7 @@ func (s *Session) Renew(args *structs.SessionSpecificRequest,
}
if acl != nil && s.srv.config.ACLEnforceVersion8 {
if !acl.SessionWrite(session.Node) {
return permissionDeniedErr
return errPermissionDenied
}
}

View File

@ -60,7 +60,7 @@ func (s *Server) dispatchSnapshotRequest(args *structs.SnapshotRequest, in io.Re
if acl, err := s.resolveToken(args.Token); err != nil {
return nil, err
} else if acl != nil && !acl.Snapshot() {
return nil, permissionDeniedErr
return nil, errPermissionDenied
}
// Dispatch the operation.

View File

@ -313,7 +313,7 @@ func TestTxn_Apply_ACLDeny(t *testing.T) {
default:
expected.Errors = append(expected.Errors, &structs.TxnError{
OpIndex: i,
What: permissionDeniedErr.Error(),
What: errPermissionDenied.Error(),
})
}
}
@ -360,7 +360,7 @@ func TestTxn_Apply_LockDelay(t *testing.T) {
if err := state.SessionCreate(5, session); err != nil {
t.Fatalf("err: %v", err)
}
validId := session.ID
validID := session.ID
// Make a lock request via an atomic transaction.
arg := structs.TxnRequest{
@ -371,7 +371,7 @@ func TestTxn_Apply_LockDelay(t *testing.T) {
Verb: api.KVLock,
DirEnt: structs.DirEntry{
Key: "test",
Session: validId,
Session: validID,
},
},
},
@ -574,7 +574,7 @@ func TestTxn_Read_ACLDeny(t *testing.T) {
default:
expected.Errors = append(expected.Errors, &structs.TxnError{
OpIndex: i,
What: permissionDeniedErr.Error(),
What: errPermissionDenied.Error(),
})
}
}

View File

@ -162,7 +162,7 @@ type TestServer struct {
LANAddr string
WANAddr string
HttpClient *http.Client
HTTPClient *http.Client
}
// NewTestServer is an easy helper method to create a new Consul
@ -256,7 +256,7 @@ func NewTestServerConfig(cb ServerConfigCallback) (*TestServer, error) {
LANAddr: fmt.Sprintf("127.0.0.1:%d", consulConfig.Ports.SerfLan),
WANAddr: fmt.Sprintf("127.0.0.1:%d", consulConfig.Ports.SerfWan),
HttpClient: client,
HTTPClient: client,
}
// Wait for the server to be ready
@ -300,7 +300,7 @@ func (s *TestServer) Stop() error {
// but will likely return before a leader is elected.
func (s *TestServer) waitForAPI() error {
if err := WaitForResult(func() (bool, error) {
resp, err := s.HttpClient.Get(s.url("/v1/agent/self"))
resp, err := s.HTTPClient.Get(s.url("/v1/agent/self"))
if err != nil {
return false, errors.Wrap(err, "failed http get")
}
@ -324,7 +324,7 @@ func (s *TestServer) waitForLeader() error {
if err := WaitForResult(func() (bool, error) {
// Query the API and check the status code.
url := s.url(fmt.Sprintf("/v1/catalog/nodes?index=%d&wait=2s", index))
resp, err := s.HttpClient.Get(url)
resp, err := s.HTTPClient.Get(url)
if err != nil {
return false, errors.Wrap(err, "failed http get")
}

View File

@ -180,7 +180,7 @@ func (s *TestServer) put(t *testing.T, path string, body io.Reader) *http.Respon
if err != nil {
t.Fatalf("failed to create PUT request: %s", err)
}
resp, err := s.HttpClient.Do(req)
resp, err := s.HTTPClient.Do(req)
if err != nil {
t.Fatalf("failed to make PUT request: %s", err)
}
@ -193,7 +193,7 @@ func (s *TestServer) put(t *testing.T, path string, body io.Reader) *http.Respon
// get performs a new HTTP GET request.
func (s *TestServer) get(t *testing.T, path string) *http.Response {
resp, err := s.HttpClient.Get(s.url(path))
resp, err := s.HTTPClient.Get(s.url(path))
if err != nil {
t.Fatalf("failed to create GET request: %s", err)
}