From 3e00e36f41e3df18facdefaa931b6c8f116e3d76 Mon Sep 17 00:00:00 2001 From: Frank Schroeder Date: Thu, 20 Apr 2017 18:59:42 -0700 Subject: [PATCH] golint: Untangle if blocks with return in else --- api/api.go | 10 ++++---- api/lock.go | 29 ++++++++++++------------ api/semaphore.go | 29 ++++++++++++------------ command/agent/acl.go | 3 +-- command/agent/acl_test.go | 3 +-- command/agent/agent.go | 18 +++++---------- command/agent/agent_endpoint.go | 7 +++--- command/agent/agent_endpoint_test.go | 3 +-- command/agent/check.go | 7 +++--- command/agent/config.go | 24 ++++++++++---------- command/agent/kvs_endpoint.go | 9 +++----- command/agent/operator_endpoint.go | 5 ++-- command/agent/prepared_query_endpoint.go | 6 ++--- command/agent/txn_endpoint.go | 10 ++++---- command/kv_get.go | 6 ++--- command/kv_import.go | 11 ++++----- command/kv_put.go | 11 ++++----- command/operator_autopilot_set.go | 5 ++-- consul/acl.go | 27 ++++++++++------------ consul/acl_replication.go | 3 +-- consul/filter.go | 3 +-- consul/fsm.go | 27 ++++++++-------------- consul/leader.go | 23 +++++++++---------- consul/leader_test.go | 3 +-- consul/pool.go | 26 ++++++++++----------- consul/prepared_query/template.go | 3 +-- consul/prepared_query_endpoint_test.go | 3 +-- consul/server.go | 3 +-- consul/servers/manager.go | 12 +++++----- consul/state/catalog.go | 6 ++--- consul/state/prepared_query.go | 3 +-- logger/logger.go | 22 +++++++++--------- testrpc/wait.go | 3 +-- testutil/wait.go | 3 +-- tlsutil/config.go | 14 ++++++------ 35 files changed, 170 insertions(+), 210 deletions(-) diff --git a/api/api.go b/api/api.go index d67963c1b7..2225dd3bf3 100644 --- a/api/api.go +++ b/api/api.go @@ -240,8 +240,8 @@ func DefaultNonPooledConfig() *Config { // given function to make the transport. func defaultConfig(transportFn func() *http.Transport) *Config { config := &Config{ - Address: "127.0.0.1:8500", - Scheme: "http", + Address: "127.0.0.1:8500", + Scheme: "http", Transport: transportFn(), } @@ -547,11 +547,11 @@ func (r *request) toHTTP() (*http.Request, error) { // Check if we should encode the body if r.body == nil && r.obj != nil { - if b, err := encodeBody(r.obj); err != nil { + b, err := encodeBody(r.obj) + if err != nil { return nil, err - } else { - r.body = b } + r.body = b } // Create the HTTP request diff --git a/api/lock.go b/api/lock.go index 9f9845a432..466ef5fdf1 100644 --- a/api/lock.go +++ b/api/lock.go @@ -143,22 +143,23 @@ func (l *Lock) Lock(stopCh <-chan struct{}) (<-chan struct{}, error) { // Check if we need to create a session first l.lockSession = l.opts.Session if l.lockSession == "" { - if s, err := l.createSession(); err != nil { + s, err := l.createSession() + if err != nil { return nil, fmt.Errorf("failed to create session: %v", err) - } else { - l.sessionRenew = make(chan struct{}) - l.lockSession = s - session := l.c.Session() - go session.RenewPeriodic(l.opts.SessionTTL, s, nil, l.sessionRenew) - - // If we fail to acquire the lock, cleanup the session - defer func() { - if !l.isHeld { - close(l.sessionRenew) - l.sessionRenew = nil - } - }() } + + l.sessionRenew = make(chan struct{}) + l.lockSession = s + session := l.c.Session() + go session.RenewPeriodic(l.opts.SessionTTL, s, nil, l.sessionRenew) + + // If we fail to acquire the lock, cleanup the session + defer func() { + if !l.isHeld { + close(l.sessionRenew) + l.sessionRenew = nil + } + }() } // Setup the query options diff --git a/api/semaphore.go b/api/semaphore.go index e6645ac1d3..9ddbdc49e7 100644 --- a/api/semaphore.go +++ b/api/semaphore.go @@ -155,22 +155,23 @@ func (s *Semaphore) Acquire(stopCh <-chan struct{}) (<-chan struct{}, error) { // Check if we need to create a session first s.lockSession = s.opts.Session if s.lockSession == "" { - if sess, err := s.createSession(); err != nil { + sess, err := s.createSession() + if err != nil { return nil, fmt.Errorf("failed to create session: %v", err) - } else { - s.sessionRenew = make(chan struct{}) - s.lockSession = sess - session := s.c.Session() - go session.RenewPeriodic(s.opts.SessionTTL, sess, nil, s.sessionRenew) - - // If we fail to acquire the lock, cleanup the session - defer func() { - if !s.isHeld { - close(s.sessionRenew) - s.sessionRenew = nil - } - }() } + + s.sessionRenew = make(chan struct{}) + s.lockSession = sess + session := s.c.Session() + go session.RenewPeriodic(s.opts.SessionTTL, sess, nil, s.sessionRenew) + + // If we fail to acquire the lock, cleanup the session + defer func() { + if !s.isHeld { + close(s.sessionRenew) + s.sessionRenew = nil + } + }() } // Create the contender entry diff --git a/command/agent/acl.go b/command/agent/acl.go index 55cbe0bdac..d62e49cce4 100644 --- a/command/agent/acl.go +++ b/command/agent/acl.go @@ -161,9 +161,8 @@ func (m *aclManager) lookupACL(agent *Agent, id string) (acl.ACL, error) { if cached != nil && time.Now().Before(cached.Expires) { metrics.IncrCounter([]string{"consul", "acl", "cache_hit"}, 1) return cached.ACL, nil - } else { - metrics.IncrCounter([]string{"consul", "acl", "cache_miss"}, 1) } + metrics.IncrCounter([]string{"consul", "acl", "cache_miss"}, 1) // At this point we might have a stale cached ACL, or none at all, so // try to contact the servers. diff --git a/command/agent/acl_test.go b/command/agent/acl_test.go index faa6ca932a..f67cd89f27 100644 --- a/command/agent/acl_test.go +++ b/command/agent/acl_test.go @@ -40,9 +40,8 @@ type MockServer struct { func (m *MockServer) GetPolicy(args *structs.ACLPolicyRequest, reply *structs.ACLPolicy) error { if m.getPolicyFn != nil { return m.getPolicyFn(args, reply) - } else { - return fmt.Errorf("should not have called GetPolicy") } + return fmt.Errorf("should not have called GetPolicy") } func TestACL_Version8(t *testing.T) { diff --git a/command/agent/agent.go b/command/agent/agent.go index 0cdda23133..d7a6293f79 100644 --- a/command/agent/agent.go +++ b/command/agent/agent.go @@ -795,9 +795,8 @@ func (a *Agent) SnapshotRPC(args *structs.SnapshotRequest, in io.Reader, out io. func (a *Agent) Leave() error { if a.server != nil { return a.server.Leave() - } else { - return a.client.Leave() } + return a.client.Leave() } // Shutdown is used to hard stop the agent. Should be @@ -895,27 +894,24 @@ func (a *Agent) ForceLeave(node string) (err error) { func (a *Agent) LocalMember() serf.Member { if a.server != nil { return a.server.LocalMember() - } else { - return a.client.LocalMember() } + return a.client.LocalMember() } // LANMembers is used to retrieve the LAN members func (a *Agent) LANMembers() []serf.Member { if a.server != nil { return a.server.LANMembers() - } else { - return a.client.LANMembers() } + return a.client.LANMembers() } // WANMembers is used to retrieve the WAN members func (a *Agent) WANMembers() []serf.Member { if a.server != nil { return a.server.WANMembers() - } else { - return nil } + return nil } // StartSync is called once Services and Checks are registered. @@ -940,9 +936,8 @@ func (a *Agent) ResumeSync() { func (a *Agent) GetCoordinate() (*coordinate.Coordinate, error) { if a.config.Server { return a.server.GetLANCoordinate() - } else { - return a.client.GetCoordinate() } + return a.client.GetCoordinate() } // sendCoordinate is a long-running loop that periodically sends our coordinate @@ -1839,9 +1834,8 @@ func parseMetaPair(raw string) (string, string) { pair := strings.SplitN(raw, ":", 2) if len(pair) == 2 { return pair[0], pair[1] - } else { - return pair[0], "" } + return pair[0], "" } // unloadMetadata resets the local metadata state diff --git a/command/agent/agent_endpoint.go b/command/agent/agent_endpoint.go index 63be9cc16d..9eef723081 100644 --- a/command/agent/agent_endpoint.go +++ b/command/agent/agent_endpoint.go @@ -155,12 +155,11 @@ func (s *HTTPServer) AgentJoin(resp http.ResponseWriter, req *http.Request) (int // Get the address addr := strings.TrimPrefix(req.URL.Path, "/v1/agent/join/") if wan { - _, err := s.agent.JoinWAN([]string{addr}) - return nil, err + _, err = s.agent.JoinWAN([]string{addr}) } else { - _, err := s.agent.JoinLAN([]string{addr}) - return nil, err + _, err = s.agent.JoinLAN([]string{addr}) } + return nil, err } func (s *HTTPServer) AgentLeave(resp http.ResponseWriter, req *http.Request) (interface{}, error) { diff --git a/command/agent/agent_endpoint_test.go b/command/agent/agent_endpoint_test.go index bb442d9836..9a85547dc9 100644 --- a/command/agent/agent_endpoint_test.go +++ b/command/agent/agent_endpoint_test.go @@ -1948,9 +1948,8 @@ func TestAgent_Monitor(t *testing.T) { if bytes.Contains(resp.Body.Bytes(), expected) { return true, nil - } else { - return false, fmt.Errorf("didn't see expected") } + return false, fmt.Errorf("didn't see expected") }); err != nil { t.Fatalf("err: %v", err) } diff --git a/command/agent/check.go b/command/agent/check.go index 649cb2df4c..7c6324005f 100644 --- a/command/agent/check.go +++ b/command/agent/check.go @@ -701,9 +701,8 @@ func (c *CheckDocker) check() { } func shell() string { - if otherShell := os.Getenv("SHELL"); otherShell != "" { - return otherShell - } else { - return "/bin/sh" + if sh := os.Getenv("SHELL"); sh != "" { + return sh } + return "/bin/sh" } diff --git a/command/agent/config.go b/command/agent/config.go index e2df8eb1bc..91e2299b34 100644 --- a/command/agent/config.go +++ b/command/agent/config.go @@ -1265,44 +1265,44 @@ func FixupCheckType(raw interface{}) error { if ttl, ok := rawMap[ttlKey]; ok { ttlS, ok := ttl.(string) if ok { - if dur, err := time.ParseDuration(ttlS); err != nil { + dur, err := time.ParseDuration(ttlS) + if err != nil { return err - } else { - rawMap[ttlKey] = dur } + rawMap[ttlKey] = dur } } if interval, ok := rawMap[intervalKey]; ok { intervalS, ok := interval.(string) if ok { - if dur, err := time.ParseDuration(intervalS); err != nil { + dur, err := time.ParseDuration(intervalS) + if err != nil { return err - } else { - rawMap[intervalKey] = dur } + rawMap[intervalKey] = dur } } if timeout, ok := rawMap[timeoutKey]; ok { timeoutS, ok := timeout.(string) if ok { - if dur, err := time.ParseDuration(timeoutS); err != nil { + dur, err := time.ParseDuration(timeoutS) + if err != nil { return err - } else { - rawMap[timeoutKey] = dur } + rawMap[timeoutKey] = dur } } if deregister, ok := rawMap[deregisterKey]; ok { timeoutS, ok := deregister.(string) if ok { - if dur, err := time.ParseDuration(timeoutS); err != nil { + dur, err := time.ParseDuration(timeoutS) + if err != nil { return err - } else { - rawMap[deregisterKey] = dur } + rawMap[deregisterKey] = dur } } diff --git a/command/agent/kvs_endpoint.go b/command/agent/kvs_endpoint.go index 4f19e38eef..687194d106 100644 --- a/command/agent/kvs_endpoint.go +++ b/command/agent/kvs_endpoint.go @@ -41,9 +41,8 @@ func (s *HTTPServer) KVSEndpoint(resp http.ResponseWriter, req *http.Request) (i case "GET": if keyList { return s.KVSGetKeys(resp, req, &args) - } else { - return s.KVSGet(resp, req, &args) } + return s.KVSGet(resp, req, &args) case "PUT": return s.KVSPut(resp, req, &args) case "DELETE": @@ -206,9 +205,8 @@ func (s *HTTPServer) KVSPut(resp http.ResponseWriter, req *http.Request, args *s // Only use the out value if this was a CAS if applyReq.Op == api.KVSet { return true, nil - } else { - return out, nil } + return out, nil } // KVSPut handles a DELETE request @@ -252,9 +250,8 @@ func (s *HTTPServer) KVSDelete(resp http.ResponseWriter, req *http.Request, args // Only use the out value if this was a CAS if applyReq.Op == api.KVDeleteCAS { return out, nil - } else { - return true, nil } + return true, nil } // missingKey checks if the key is missing diff --git a/command/agent/operator_endpoint.go b/command/agent/operator_endpoint.go index 3d0c899d8a..8e59938249 100644 --- a/command/agent/operator_endpoint.go +++ b/command/agent/operator_endpoint.go @@ -215,6 +215,7 @@ func (s *HTTPServer) OperatorAutopilotConfiguration(resp http.ResponseWriter, re } return out, nil + case "PUT": var args structs.AutopilotSetConfigRequest s.parseDC(req, &args.Datacenter) @@ -257,9 +258,9 @@ func (s *HTTPServer) OperatorAutopilotConfiguration(resp http.ResponseWriter, re // Only use the out value if this was a CAS if !args.CAS { return true, nil - } else { - return reply, nil } + return reply, nil + default: resp.WriteHeader(http.StatusMethodNotAllowed) return nil, nil diff --git a/command/agent/prepared_query_endpoint.go b/command/agent/prepared_query_endpoint.go index b226c3ea54..5dd7bbd6e5 100644 --- a/command/agent/prepared_query_endpoint.go +++ b/command/agent/prepared_query_endpoint.go @@ -83,11 +83,11 @@ func (s *HTTPServer) PreparedQueryGeneral(resp http.ResponseWriter, req *http.Re func parseLimit(req *http.Request, limit *int) error { *limit = 0 if arg := req.URL.Query().Get("limit"); arg != "" { - if i, err := strconv.Atoi(arg); err != nil { + i, err := strconv.Atoi(arg) + if err != nil { return err - } else { - *limit = i } + *limit = i } return nil } diff --git a/command/agent/txn_endpoint.go b/command/agent/txn_endpoint.go index 0e9f054839..f8ec051895 100644 --- a/command/agent/txn_endpoint.go +++ b/command/agent/txn_endpoint.go @@ -124,15 +124,13 @@ func (s *HTTPServer) convertOps(resp http.ResponseWriter, req *http.Request) (st var netKVSize int for _, in := range ops { if in.KV != nil { - if size := len(in.KV.Value); size > maxKVSize { + size := len(in.KV.Value) + if size > maxKVSize { resp.WriteHeader(http.StatusRequestEntityTooLarge) - fmt.Fprintf(resp, "Value for key %q is too large (%d > %d bytes)", - in.KV.Key, size, maxKVSize) - + fmt.Fprintf(resp, "Value for key %q is too large (%d > %d bytes)", in.KV.Key, size, maxKVSize) return nil, 0, false - } else { - netKVSize += size } + netKVSize += size verb := api.KVOp(in.KV.Verb) if isWrite(verb) { diff --git a/command/kv_get.go b/command/kv_get.go index 5f897829c3..de3f1ee97e 100644 --- a/command/kv_get.go +++ b/command/kv_get.go @@ -184,10 +184,10 @@ func (c *KVGetCommand) Run(args []string) int { c.UI.Info(b.String()) return 0 - } else { - c.UI.Info(string(pair.Value)) - return 0 } + + c.UI.Info(string(pair.Value)) + return 0 } } diff --git a/command/kv_import.go b/command/kv_import.go index b01c406f1d..ec7247ba86 100644 --- a/command/kv_import.go +++ b/command/kv_import.go @@ -136,13 +136,12 @@ func (c *KVImportCommand) dataFromArgs(args []string) (string, error) { case '-': if len(data) > 1 { return data, nil - } else { - var b bytes.Buffer - if _, err := io.Copy(&b, stdin); err != nil { - return "", fmt.Errorf("Failed to read stdin: %s", err) - } - return b.String(), nil } + var b bytes.Buffer + if _, err := io.Copy(&b, stdin); err != nil { + return "", fmt.Errorf("Failed to read stdin: %s", err) + } + return b.String(), nil default: return data, nil } diff --git a/command/kv_put.go b/command/kv_put.go index 1723c41ed6..efd2aa7282 100644 --- a/command/kv_put.go +++ b/command/kv_put.go @@ -225,13 +225,12 @@ func (c *KVPutCommand) dataFromArgs(args []string) (string, string, error) { case '-': if len(data) > 1 { return key, data, nil - } else { - var b bytes.Buffer - if _, err := io.Copy(&b, stdin); err != nil { - return "", "", fmt.Errorf("Failed to read stdin: %s", err) - } - return key, b.String(), nil } + var b bytes.Buffer + if _, err := io.Copy(&b, stdin); err != nil { + return "", "", fmt.Errorf("Failed to read stdin: %s", err) + } + return key, b.String(), nil default: return key, data, nil } diff --git a/command/operator_autopilot_set.go b/command/operator_autopilot_set.go index 9f363a07fd..712cc6e129 100644 --- a/command/operator_autopilot_set.go +++ b/command/operator_autopilot_set.go @@ -110,8 +110,7 @@ func (c *OperatorAutopilotSetCommand) Run(args []string) int { if result { c.UI.Output("Configuration updated!") return 0 - } else { - c.UI.Output("Configuration could not be atomically updated, please try again") - return 1 } + c.UI.Output("Configuration could not be atomically updated, please try again") + return 1 } diff --git a/consul/acl.go b/consul/acl.go index e52fe38554..6c732733f0 100644 --- a/consul/acl.go +++ b/consul/acl.go @@ -170,9 +170,8 @@ func (c *aclCache) lookupACL(id, authDC string) (acl.ACL, error) { if cached != nil && time.Now().Before(cached.Expires) { metrics.IncrCounter([]string{"consul", "acl", "cache_hit"}, 1) return cached.ACL, nil - } else { - metrics.IncrCounter([]string{"consul", "acl", "cache_miss"}, 1) } + metrics.IncrCounter([]string{"consul", "acl", "cache_miss"}, 1) // Attempt to refresh the policy from the ACL datacenter via an RPC. args := structs.ACLPolicyRequest{ @@ -192,9 +191,8 @@ func (c *aclCache) lookupACL(id, authDC string) (acl.ACL, error) { // other error we report it in the logs but can continue. if strings.Contains(err.Error(), aclNotFound) { return nil, errors.New(aclNotFound) - } else { - c.logger.Printf("[ERR] consul.acl: Failed to get policy from ACL datacenter: %v", err) } + c.logger.Printf("[ERR] consul.acl: Failed to get policy from ACL datacenter: %v", err) // TODO (slackpad) - We could do a similar thing *within* the ACL // datacenter if the leader isn't available. We have a local state @@ -729,17 +727,16 @@ func vetRegisterWithACL(acl acl.ACL, subj *structs.RegisterRequest, // Service-level check for some other service. Make sure they've // got write permissions for that service. if ns == nil { - return fmt.Errorf("Unknown service '%s' for check '%s'", - check.ServiceID, check.CheckID) - } else { - other, ok := ns.Services[check.ServiceID] - if !ok { - return fmt.Errorf("Unknown service '%s' for check '%s'", - check.ServiceID, check.CheckID) - } - if !acl.ServiceWrite(other.Service) { - return errPermissionDenied - } + return fmt.Errorf("Unknown service '%s' for check '%s'", check.ServiceID, check.CheckID) + } + + other, ok := ns.Services[check.ServiceID] + if !ok { + return fmt.Errorf("Unknown service '%s' for check '%s'", check.ServiceID, check.CheckID) + } + + if !acl.ServiceWrite(other.Service) { + return errPermissionDenied } } diff --git a/consul/acl_replication.go b/consul/acl_replication.go index 4a89cc59e0..4b9b9d017d 100644 --- a/consul/acl_replication.go +++ b/consul/acl_replication.go @@ -46,9 +46,8 @@ func (a *aclIterator) Less(i, j int) bool { func (a *aclIterator) Front() *structs.ACL { if a.index < len(a.acls) { return a.acls[a.index] - } else { - return nil } + return nil } // Next advances the iterator to the next index. diff --git a/consul/filter.go b/consul/filter.go index 322cd353ab..85682a3bb2 100644 --- a/consul/filter.go +++ b/consul/filter.go @@ -63,9 +63,8 @@ func (t *txnResultsFilter) Filter(i int) bool { result := t.results[i] if result.KV != nil { return !t.acl.KeyRead(result.KV.Key) - } else { - return false } + return false } func (t *txnResultsFilter) Move(dst, src, span int) { diff --git a/consul/fsm.go b/consul/fsm.go index 96cea58ca6..dccee91702 100644 --- a/consul/fsm.go +++ b/consul/fsm.go @@ -111,9 +111,8 @@ func (c *consulFSM) Apply(log *raft.Log) interface{} { if ignoreUnknown { c.logger.Printf("[WARN] consul.fsm: ignoring unknown message type (%d), upgrade to newer version", msgType) return nil - } else { - panic(fmt.Errorf("failed to apply request: %#v", buf)) } + panic(fmt.Errorf("failed to apply request: %#v", buf)) } } @@ -176,32 +175,28 @@ func (c *consulFSM) applyKVSOperation(buf []byte, index uint64) interface{} { act, err := c.state.KVSDeleteCAS(index, req.DirEnt.ModifyIndex, req.DirEnt.Key) if err != nil { return err - } else { - return act } + return act case api.KVDeleteTree: return c.state.KVSDeleteTree(index, req.DirEnt.Key) case api.KVCAS: act, err := c.state.KVSSetCAS(index, &req.DirEnt) if err != nil { return err - } else { - return act } + return act case api.KVLock: act, err := c.state.KVSLock(index, &req.DirEnt) if err != nil { return err - } else { - return act } + return act case api.KVUnlock: act, err := c.state.KVSUnlock(index, &req.DirEnt) if err != nil { return err - } else { - return act } + return act default: err := fmt.Errorf("Invalid KVS operation '%s'", req.Op) c.logger.Printf("[WARN] consul.fsm: %v", err) @@ -219,9 +214,8 @@ func (c *consulFSM) applySessionOperation(buf []byte, index uint64) interface{} case structs.SessionCreate: if err := c.state.SessionCreate(index, &req.Session); err != nil { return err - } else { - return req.Session.ID } + return req.Session.ID case structs.SessionDestroy: return c.state.SessionDestroy(index, req.Session.ID) default: @@ -240,9 +234,8 @@ func (c *consulFSM) applyACLOperation(buf []byte, index uint64) interface{} { case structs.ACLForceSet, structs.ACLSet: if err := c.state.ACLSet(index, &req.ACL); err != nil { return err - } else { - return req.ACL.ID } + return req.ACL.ID case structs.ACLDelete: return c.state.ACLDelete(index, req.ACL.ID) default: @@ -326,12 +319,10 @@ func (c *consulFSM) applyAutopilotUpdate(buf []byte, index uint64) interface{} { act, err := c.state.AutopilotCASConfig(index, req.Config.ModifyIndex, &req.Config) if err != nil { return err - } else { - return act } - } else { - return c.state.AutopilotSetConfig(index, &req.Config) + return act } + return c.state.AutopilotSetConfig(index, &req.Config) } func (c *consulFSM) Snapshot() (raft.FSMSnapshot, error) { diff --git a/consul/leader.go b/consul/leader.go index a42d648130..263096d0ee 100644 --- a/consul/leader.go +++ b/consul/leader.go @@ -627,19 +627,18 @@ func (s *Server) joinConsulServer(m serf.Member, parts *agent.Server) error { // Exit with no-op if this is being called on an existing server if server.Address == raft.ServerAddress(addr) && server.ID == raft.ServerID(parts.ID) { return nil - } else { - future := s.raft.RemoveServer(server.ID, 0, 0) - if server.Address == raft.ServerAddress(addr) { - if err := future.Error(); err != nil { - return fmt.Errorf("error removing server with duplicate address %q: %s", server.Address, err) - } - s.logger.Printf("[INFO] consul: removed server with duplicate address: %s", server.Address) - } else { - if err := future.Error(); err != nil { - return fmt.Errorf("error removing server with duplicate ID %q: %s", server.ID, err) - } - s.logger.Printf("[INFO] consul: removed server with duplicate ID: %s", server.ID) + } + future := s.raft.RemoveServer(server.ID, 0, 0) + if server.Address == raft.ServerAddress(addr) { + if err := future.Error(); err != nil { + return fmt.Errorf("error removing server with duplicate address %q: %s", server.Address, err) } + s.logger.Printf("[INFO] consul: removed server with duplicate address: %s", server.Address) + } else { + if err := future.Error(); err != nil { + return fmt.Errorf("error removing server with duplicate ID %q: %s", server.ID, err) + } + s.logger.Printf("[INFO] consul: removed server with duplicate ID: %s", server.ID) } } } diff --git a/consul/leader_test.go b/consul/leader_test.go index 414831302b..78dac35975 100644 --- a/consul/leader_test.go +++ b/consul/leader_test.go @@ -383,9 +383,8 @@ func TestLeader_Reconcile_Races(t *testing.T) { if node != nil { nodeAddr = node.Address return true, nil - } else { - return false, nil } + return false, nil }); err != nil { t.Fatalf("client should be registered: %v", err) } diff --git a/consul/pool.go b/consul/pool.go index 900d9a6037..13b2bca4c3 100644 --- a/consul/pool.go +++ b/consul/pool.go @@ -311,21 +311,21 @@ func (p *ConnPool) getNewConn(dc string, addr net.Addr, version int) (*Conn, err if version < 2 { conn.Close() return nil, fmt.Errorf("cannot make client connection, unsupported protocol version %d", version) - } else { - // Write the Consul multiplex byte to set the mode - if _, err := conn.Write([]byte{byte(rpcMultiplexV2)}); err != nil { - conn.Close() - return nil, err - } - - // Setup the logger - conf := yamux.DefaultConfig() - conf.LogOutput = p.logOutput - - // Create a multiplexed session - session, _ = yamux.Client(conn, conf) } + // Write the Consul multiplex byte to set the mode + if _, err := conn.Write([]byte{byte(rpcMultiplexV2)}); err != nil { + conn.Close() + return nil, err + } + + // Setup the logger + conf := yamux.DefaultConfig() + conf.LogOutput = p.logOutput + + // Create a multiplexed session + session, _ = yamux.Client(conn, conf) + // Wrap the connection c := &Conn{ refCount: 1, diff --git a/consul/prepared_query/template.go b/consul/prepared_query/template.go index e344ae8403..9473829d6b 100644 --- a/consul/prepared_query/template.go +++ b/consul/prepared_query/template.go @@ -130,9 +130,8 @@ func (ct *CompiledTemplate) Render(name string) (*structs.PreparedQuery, error) i, ok := inputs[0].(int) if ok && i >= 0 && i < len(matches) { return matches[i], nil - } else { - return "", nil } + return "", nil }, } diff --git a/consul/prepared_query_endpoint_test.go b/consul/prepared_query_endpoint_test.go index 32224f5363..8d4ae85ffc 100644 --- a/consul/prepared_query_endpoint_test.go +++ b/consul/prepared_query_endpoint_test.go @@ -2758,9 +2758,8 @@ func (m *mockQueryServer) ForwardDC(method, dc string, args interface{}, reply i } if m.QueryFn != nil { return m.QueryFn(dc, args, reply) - } else { - return nil } + return nil } func TestPreparedQuery_queryFailover(t *testing.T) { diff --git a/consul/server.go b/consul/server.go index 320e821750..92fb81c140 100644 --- a/consul/server.go +++ b/consul/server.go @@ -334,9 +334,8 @@ func NewServer(config *Config) (*Server, error) { portFn := func(s *agent.Server) (int, bool) { if s.WanJoinPort > 0 { return s.WanJoinPort, true - } else { - return 0, false } + return 0, false } go s.Flood(portFn, s.serfWAN) diff --git a/consul/servers/manager.go b/consul/servers/manager.go index 8955110ffa..7071e058d7 100644 --- a/consul/servers/manager.go +++ b/consul/servers/manager.go @@ -207,13 +207,13 @@ func (m *Manager) FindServer() *agent.Server { if numServers == 0 { m.logger.Printf("[WARN] manager: No servers available") return nil - } else { - // Return whatever is at the front of the list because it is - // assumed to be the oldest in the server list (unless - - // hypothetically - the server list was rotated right after a - // server was added). - return l.servers[0] } + + // Return whatever is at the front of the list because it is + // assumed to be the oldest in the server list (unless - + // hypothetically - the server list was rotated right after a + // server was added). + return l.servers[0] } // getServerList is a convenience method which hides the locking semantics diff --git a/consul/state/catalog.go b/consul/state/catalog.go index 25c7e4cf47..f9959721b7 100644 --- a/consul/state/catalog.go +++ b/consul/state/catalog.go @@ -712,9 +712,8 @@ func (s *Store) NodeService(nodeName string, serviceID string) (uint64, *structs if service != nil { return idx, service.(*structs.ServiceNode).ToNodeService(), nil - } else { - return idx, nil, nil } + return idx, nil, nil } // NodeServices is used to query service registrations by node name or UUID. @@ -962,9 +961,8 @@ func (s *Store) NodeCheck(nodeName string, checkID types.CheckID) (uint64, *stru if check != nil { return idx, check.(*structs.HealthCheck), nil - } else { - return idx, nil, nil } + return idx, nil, nil } // NodeChecks is used to retrieve checks associated with the diff --git a/consul/state/prepared_query.go b/consul/state/prepared_query.go index 65f7cdf8b0..9ca653e95a 100644 --- a/consul/state/prepared_query.go +++ b/consul/state/prepared_query.go @@ -298,9 +298,8 @@ func (s *Store) PreparedQueryResolve(queryIDOrName string) (uint64, *structs.Pre return idx, nil, err } return idx, render, nil - } else { - return idx, wrapper.PreparedQuery, nil } + return idx, wrapper.PreparedQuery, nil } // Next, look for an exact name match. This is the common case for static diff --git a/logger/logger.go b/logger/logger.go index 92fa611d50..fe7cd95325 100644 --- a/logger/logger.go +++ b/logger/logger.go @@ -60,20 +60,20 @@ func Setup(config *Config, ui cli.Ui) (*logutils.LevelFilter, *GatedWriter, *Log delay := 5 * time.Second for i := 0; i <= retries; i++ { l, err := gsyslog.NewLogger(gsyslog.LOG_NOTICE, config.SyslogFacility, "consul") - if err != nil { - ui.Error(fmt.Sprintf("Syslog setup error: %v", err)) - if i == retries { - timeout := time.Duration(retries) * delay - ui.Error(fmt.Sprintf("Syslog setup did not succeed within timeout (%s).", timeout.String())) - return nil, nil, nil, nil, false - } else { - ui.Error(fmt.Sprintf("Retrying syslog setup in %s...", delay.String())) - time.Sleep(delay) - } - } else { + if err == nil { syslog = &SyslogWrapper{l, logFilter} break } + + ui.Error(fmt.Sprintf("Syslog setup error: %v", err)) + if i == retries { + timeout := time.Duration(retries) * delay + ui.Error(fmt.Sprintf("Syslog setup did not succeed within timeout (%s).", timeout.String())) + return nil, nil, nil, nil, false + } + + ui.Error(fmt.Sprintf("Retrying syslog setup in %s...", delay.String())) + time.Sleep(delay) } } diff --git a/testrpc/wait.go b/testrpc/wait.go index bf4e154594..7da6591d05 100644 --- a/testrpc/wait.go +++ b/testrpc/wait.go @@ -35,9 +35,8 @@ func WaitForResult(try testFn) error { } if err != nil { return errors.Wrap(err, "timed out with error") - } else { - return fmt.Errorf("timed out") } + return fmt.Errorf("timed out") } type rpcFn func(string, interface{}, interface{}) error diff --git a/testutil/wait.go b/testutil/wait.go index b42718dbc1..9d58f3bb91 100644 --- a/testutil/wait.go +++ b/testutil/wait.go @@ -33,7 +33,6 @@ func WaitForResult(try testFn) error { } if err != nil { return errors.Wrap(err, "timed out with error") - } else { - return fmt.Errorf("timed out") } + return fmt.Errorf("timed out") } diff --git a/tlsutil/config.go b/tlsutil/config.go index ad9ee088ea..0cb785bc30 100644 --- a/tlsutil/config.go +++ b/tlsutil/config.go @@ -213,20 +213,20 @@ func (c *Config) OutgoingTLSWrapper() (DCWrapper, error) { // Strip the trailing '.' from the domain if any domain := strings.TrimSuffix(c.Domain, ".") + wrapper := func(dc string, c net.Conn) (net.Conn, error) { + return WrapTLSClient(c, tlsConfig) + } + // Generate the wrapper based on hostname verification if c.VerifyServerHostname { - wrapper := func(dc string, conn net.Conn) (net.Conn, error) { + wrapper = func(dc string, conn net.Conn) (net.Conn, error) { conf := clone(tlsConfig) conf.ServerName = "server." + dc + "." + domain return WrapTLSClient(conn, conf) } - return wrapper, nil - } else { - wrapper := func(dc string, c net.Conn) (net.Conn, error) { - return WrapTLSClient(c, tlsConfig) - } - return wrapper, nil } + + return wrapper, nil } // SpecificDC is used to invoke a static datacenter