Merge pull request #7894 from hashicorp/dnephin/add-linter-staticcheck-1

Fix some bugs/issues found by staticcheck
This commit is contained in:
Daniel Nephin 2020-05-19 18:44:06 -04:00 committed by hashicorp-ci
parent 573050a5a9
commit c02d4e1390
17 changed files with 87 additions and 91 deletions

View File

@ -914,7 +914,7 @@ func (s *HTTPServer) AgentRegisterService(resp http.ResponseWriter, req *http.Re
// the catalog endpoint so it helps ensure the sync will work properly. // the catalog endpoint so it helps ensure the sync will work properly.
if err := ns.Validate(); err != nil { if err := ns.Validate(); err != nil {
resp.WriteHeader(http.StatusBadRequest) resp.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(resp, err.Error()) fmt.Fprint(resp, err.Error())
return nil, nil return nil, nil
} }

View File

@ -3683,7 +3683,7 @@ func testAgent_RegisterServiceDeregisterService_Sidecar(t *testing.T, extraHCL s
require.Nil(obj) require.Nil(obj)
svcs := a.State.Services(nil) svcs := a.State.Services(nil)
svc, ok = svcs[structs.NewServiceID(tt.wantNS.ID, nil)] _, ok = svcs[structs.NewServiceID(tt.wantNS.ID, nil)]
if tt.wantSidecarIDLeftAfterDereg { if tt.wantSidecarIDLeftAfterDereg {
require.True(ok, "removed non-sidecar service at "+tt.wantNS.ID) require.True(ok, "removed non-sidecar service at "+tt.wantNS.ID)
} else { } else {

View File

@ -188,8 +188,8 @@ func (m *mockAgent) LocalState() *local.State {
return m.state return m.state
} }
func (m *mockAgent) LocalBlockingQuery(alwaysBlock bool, hash string, wait time.Duration, func (m *mockAgent) LocalBlockingQuery(_ bool, _ string, _ time.Duration,
fn func(ws memdb.WatchSet) (string, interface{}, error)) (string, interface{}, error) { _ func(ws memdb.WatchSet) (string, interface{}, error)) (string, interface{}, error) {
hash, err := hashChecks(m.checks) hash, err := hashChecks(m.checks)
if err != nil { if err != nil {

View File

@ -420,12 +420,6 @@ func (a *Autopilot) updateClusterHealth() error {
// consistent of a sample as possible. We capture the leader's index // consistent of a sample as possible. We capture the leader's index
// here as well so it roughly lines up with the same point in time. // here as well so it roughly lines up with the same point in time.
targetLastIndex := raftNode.LastIndex() targetLastIndex := raftNode.LastIndex()
var fetchList []*ServerInfo
for _, server := range servers {
if parts, ok := serverMap[string(server.ID)]; ok {
fetchList = append(fetchList, parts)
}
}
d := time.Now().Add(a.healthInterval / 2) d := time.Now().Add(a.healthInterval / 2)
ctx, cancel := context.WithDeadline(context.Background(), d) ctx, cancel := context.WithDeadline(context.Background(), d)
defer cancel() defer cancel()

View File

@ -48,7 +48,7 @@ func (m *LeaderRoutineManager) IsRunning(name string) bool {
} }
func (m *LeaderRoutineManager) Start(name string, routine LeaderRoutine) error { func (m *LeaderRoutineManager) Start(name string, routine LeaderRoutine) error {
return m.StartWithContext(nil, name, routine) return m.StartWithContext(context.TODO(), name, routine)
} }
func (m *LeaderRoutineManager) StartWithContext(parentCtx context.Context, name string, routine LeaderRoutine) error { func (m *LeaderRoutineManager) StartWithContext(parentCtx context.Context, name string, routine LeaderRoutine) error {

View File

@ -116,13 +116,9 @@ func (ct *CompiledTemplate) Render(name string, source structs.QuerySource) (*st
return nil, fmt.Errorf("Failed to copy query") return nil, fmt.Errorf("Failed to copy query")
} }
// Run the regular expression, if provided. We execute on a copy here
// to avoid internal lock contention because we expect this to be called
// from multiple goroutines.
var matches []string var matches []string
if ct.re != nil { if ct.re != nil {
re := ct.re.Copy() matches = ct.re.FindStringSubmatch(name)
matches = re.FindStringSubmatch(name)
} }
// Create a safe match function that can't fail at run time. It will // Create a safe match function that can't fail at run time. It will

View File

@ -210,61 +210,62 @@ func (s *Store) txnNode(tx *memdb.Txn, idx uint64, op *structs.TxnNodeOp) (struc
// txnService handles all Service-related operations. // txnService handles all Service-related operations.
func (s *Store) txnService(tx *memdb.Txn, idx uint64, op *structs.TxnServiceOp) (structs.TxnResults, error) { func (s *Store) txnService(tx *memdb.Txn, idx uint64, op *structs.TxnServiceOp) (structs.TxnResults, error) {
var entry *structs.NodeService
var err error
switch op.Verb { switch op.Verb {
case api.ServiceGet: case api.ServiceGet:
entry, err = s.getNodeServiceTxn(tx, op.Node, op.Service.ID, &op.Service.EnterpriseMeta) entry, err := s.getNodeServiceTxn(tx, op.Node, op.Service.ID, &op.Service.EnterpriseMeta)
if entry == nil && err == nil { switch {
err = fmt.Errorf("service %q on node %q doesn't exist", op.Service.ID, op.Node) case err != nil:
return nil, err
case entry == nil:
return nil, fmt.Errorf("service %q on node %q doesn't exist", op.Service.ID, op.Node)
default:
return structs.TxnResults{&structs.TxnResult{Service: entry}}, nil
} }
case api.ServiceSet: case api.ServiceSet:
err = s.ensureServiceTxn(tx, idx, op.Node, &op.Service) if err := s.ensureServiceTxn(tx, idx, op.Node, &op.Service); err != nil {
entry, err = s.getNodeServiceTxn(tx, op.Node, op.Service.ID, &op.Service.EnterpriseMeta) return nil, err
}
entry, err := s.getNodeServiceTxn(tx, op.Node, op.Service.ID, &op.Service.EnterpriseMeta)
return newTxnResultFromNodeServiceEntry(entry), err
case api.ServiceCAS: case api.ServiceCAS:
var ok bool ok, err := s.ensureServiceCASTxn(tx, idx, op.Node, &op.Service)
ok, err = s.ensureServiceCASTxn(tx, idx, op.Node, &op.Service) // TODO: err != nil case is ignored
if !ok && err == nil { if !ok && err == nil {
err = fmt.Errorf("failed to set service %q on node %q, index is stale", op.Service.ID, op.Node) err := fmt.Errorf("failed to set service %q on node %q, index is stale", op.Service.ID, op.Node)
break return nil, err
} }
entry, err = s.getNodeServiceTxn(tx, op.Node, op.Service.ID, &op.Service.EnterpriseMeta)
entry, err := s.getNodeServiceTxn(tx, op.Node, op.Service.ID, &op.Service.EnterpriseMeta)
return newTxnResultFromNodeServiceEntry(entry), err
case api.ServiceDelete: case api.ServiceDelete:
err = s.deleteServiceTxn(tx, idx, op.Node, op.Service.ID, &op.Service.EnterpriseMeta) err := s.deleteServiceTxn(tx, idx, op.Node, op.Service.ID, &op.Service.EnterpriseMeta)
return nil, err
case api.ServiceDeleteCAS: case api.ServiceDeleteCAS:
var ok bool ok, err := s.deleteServiceCASTxn(tx, idx, op.Service.ModifyIndex, op.Node, op.Service.ID, &op.Service.EnterpriseMeta)
ok, err = s.deleteServiceCASTxn(tx, idx, op.Service.ModifyIndex, op.Node, op.Service.ID, &op.Service.EnterpriseMeta)
if !ok && err == nil { if !ok && err == nil {
err = fmt.Errorf("failed to delete service %q on node %q, index is stale", op.Service.ID, op.Node) return nil, fmt.Errorf("failed to delete service %q on node %q, index is stale", op.Service.ID, op.Node)
} }
return nil, err
default: default:
err = fmt.Errorf("unknown Service verb %q", op.Verb) return nil, fmt.Errorf("unknown Service verb %q", op.Verb)
} }
if err != nil { }
return nil, err
// newTxnResultFromNodeServiceEntry returns a TxnResults with a single result,
// a copy of entry. The entry is copied to prevent modification of the state
// store.
func newTxnResultFromNodeServiceEntry(entry *structs.NodeService) structs.TxnResults {
if entry == nil {
return nil
} }
clone := *entry
// For a GET we keep the value, otherwise we clone and blank out the result := structs.TxnResult{Service: &clone}
// value (we have to clone so we don't modify the entry being used by return structs.TxnResults{&result}
// the state store).
if entry != nil {
if op.Verb == api.ServiceGet {
result := structs.TxnResult{Service: entry}
return structs.TxnResults{&result}, nil
}
clone := *entry
result := structs.TxnResult{Service: &clone}
return structs.TxnResults{&result}, nil
}
return nil, nil
} }
// txnCheck handles all Check-related operations. // txnCheck handles all Check-related operations.

View File

@ -236,7 +236,7 @@ func TestCoordinate_Node(t *testing.T) {
// Make sure we get a 404 with no coordinates. // Make sure we get a 404 with no coordinates.
req, _ := http.NewRequest("GET", "/v1/coordinate/node/foo?dc=dc1", nil) req, _ := http.NewRequest("GET", "/v1/coordinate/node/foo?dc=dc1", nil)
resp := httptest.NewRecorder() resp := httptest.NewRecorder()
obj, err := a.srv.CoordinateNode(resp, req) _, err := a.srv.CoordinateNode(resp, req)
if err != nil { if err != nil {
t.Fatalf("err: %v", err) t.Fatalf("err: %v", err)
} }
@ -285,7 +285,7 @@ func TestCoordinate_Node(t *testing.T) {
// Query back and check the nodes are present. // Query back and check the nodes are present.
req, _ = http.NewRequest("GET", "/v1/coordinate/node/foo?dc=dc1", nil) req, _ = http.NewRequest("GET", "/v1/coordinate/node/foo?dc=dc1", nil)
resp = httptest.NewRecorder() resp = httptest.NewRecorder()
obj, err = a.srv.CoordinateNode(resp, req) obj, err := a.srv.CoordinateNode(resp, req)
if err != nil { if err != nil {
t.Fatalf("err: %v", err) t.Fatalf("err: %v", err)
} }
@ -303,7 +303,7 @@ func TestCoordinate_Node(t *testing.T) {
// Filter on a nonexistent node segment // Filter on a nonexistent node segment
req, _ = http.NewRequest("GET", "/v1/coordinate/node/foo?segment=nope", nil) req, _ = http.NewRequest("GET", "/v1/coordinate/node/foo?segment=nope", nil)
resp = httptest.NewRecorder() resp = httptest.NewRecorder()
obj, err = a.srv.CoordinateNode(resp, req) _, err = a.srv.CoordinateNode(resp, req)
if err != nil { if err != nil {
t.Fatalf("err: %v", err) t.Fatalf("err: %v", err)
} }
@ -331,7 +331,7 @@ func TestCoordinate_Node(t *testing.T) {
// Make sure the empty filter works // Make sure the empty filter works
req, _ = http.NewRequest("GET", "/v1/coordinate/node/foo?segment=", nil) req, _ = http.NewRequest("GET", "/v1/coordinate/node/foo?segment=", nil)
resp = httptest.NewRecorder() resp = httptest.NewRecorder()
obj, err = a.srv.CoordinateNode(resp, req) _, err = a.srv.CoordinateNode(resp, req)
if err != nil { if err != nil {
t.Fatalf("err: %v", err) t.Fatalf("err: %v", err)
} }

View File

@ -116,11 +116,11 @@ func TestRecursorAddr(t *testing.T) {
if addr != "[2001:4860:4860::8888]:53" { if addr != "[2001:4860:4860::8888]:53" {
t.Fatalf("bad: %v", addr) t.Fatalf("bad: %v", addr)
} }
addr, err = recursorAddr("1.2.3.4::53") _, err = recursorAddr("1.2.3.4::53")
if err == nil || !strings.Contains(err.Error(), "too many colons in address") { if err == nil || !strings.Contains(err.Error(), "too many colons in address") {
t.Fatalf("err: %v", err) t.Fatalf("err: %v", err)
} }
addr, err = recursorAddr("2001:4860:4860::8888:::53") _, err = recursorAddr("2001:4860:4860::8888:::53")
if err == nil || !strings.Contains(err.Error(), "too many colons in address") { if err == nil || !strings.Contains(err.Error(), "too many colons in address") {
t.Fatalf("err: %v", err) t.Fatalf("err: %v", err)
} }
@ -282,7 +282,7 @@ func TestDNS_NodeLookup(t *testing.T) {
require.Equal(t, "127.0.0.1", aRec.A.String()) require.Equal(t, "127.0.0.1", aRec.A.String())
require.Equal(t, uint32(0), aRec.Hdr.Ttl) require.Equal(t, uint32(0), aRec.Hdr.Ttl)
txt, ok = in.Answer[1].(*dns.TXT) _, ok = in.Answer[1].(*dns.TXT)
require.True(t, ok, "Second answer is not a TXT record") require.True(t, ok, "Second answer is not a TXT record")
// lookup a non-existing node, we should receive a SOA // lookup a non-existing node, we should receive a SOA

View File

@ -169,20 +169,21 @@ type templatedIndexFS struct {
func (fs *templatedIndexFS) Open(name string) (http.File, error) { func (fs *templatedIndexFS) Open(name string) (http.File, error) {
file, err := fs.fs.Open(name) file, err := fs.fs.Open(name)
if err == nil && name == "/index.html" { if err != nil || name != "/index.html" {
content, _ := ioutil.ReadAll(file) return file, err
file.Seek(0, 0)
t, err := template.New("fmtedindex").Parse(string(content))
if err != nil {
return nil, err
}
var out bytes.Buffer
err = t.Execute(&out, fs.templateVars())
file = newTemplatedFile(&out, file)
} }
return file, err content, _ := ioutil.ReadAll(file)
file.Seek(0, 0)
t, err := template.New("fmtedindex").Parse(string(content))
if err != nil {
return nil, err
}
var out bytes.Buffer
if err := t.Execute(&out, fs.templateVars()); err != nil {
return nil, err
}
return newTemplatedFile(&out, file), nil
} }
// endpoint is a Consul-specific HTTP handler that takes the usual arguments in // endpoint is a Consul-specific HTTP handler that takes the usual arguments in
@ -496,7 +497,7 @@ func (s *HTTPServer) wrap(handler endpoint, methods []string) http.HandlerFunc {
fmt.Fprint(resp, err.Error()) fmt.Fprint(resp, err.Error())
case isNotFound(err): case isNotFound(err):
resp.WriteHeader(http.StatusNotFound) resp.WriteHeader(http.StatusNotFound)
fmt.Fprintf(resp, err.Error()) fmt.Fprint(resp, err.Error())
case isTooManyRequests(err): case isTooManyRequests(err):
resp.WriteHeader(http.StatusTooManyRequests) resp.WriteHeader(http.StatusTooManyRequests)
fmt.Fprint(resp, err.Error()) fmt.Fprint(resp, err.Error())

View File

@ -323,11 +323,11 @@ func TestHTTPAPI_Ban_Nonprintable_Characters(t *testing.T) {
a := NewTestAgent(t, "") a := NewTestAgent(t, "")
defer a.Shutdown() defer a.Shutdown()
req, err := http.NewRequest("GET", "/v1/kv/bad\x00ness", nil) _, err := http.NewRequest("GET", "/v1/kv/bad\x00ness", nil)
if err == nil { if err == nil {
t.Fatal("expected error") t.Fatal("expected error")
} }
req, err = http.NewRequest("GET", "/v1/kv/bad%00ness", nil) req, err := http.NewRequest("GET", "/v1/kv/bad%00ness", nil)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -342,11 +342,11 @@ func TestHTTPAPI_Allow_Nonprintable_Characters_With_Flag(t *testing.T) {
a := NewTestAgent(t, "disable_http_unprintable_char_filter = true") a := NewTestAgent(t, "disable_http_unprintable_char_filter = true")
defer a.Shutdown() defer a.Shutdown()
req, err := http.NewRequest("GET", "/v1/kv/bad\x00ness", nil) _, err := http.NewRequest("GET", "/v1/kv/bad\x00ness", nil)
if err == nil { if err == nil {
t.Fatal("expected error") t.Fatal("expected error")
} }
req, err = http.NewRequest("GET", "/v1/kv/bad%00ness", nil) req, err := http.NewRequest("GET", "/v1/kv/bad%00ness", nil)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }

View File

@ -416,7 +416,7 @@ func TestKVSEndpoint_GET_Raw(t *testing.T) {
req, _ = http.NewRequest("GET", "/v1/kv/test?raw", nil) req, _ = http.NewRequest("GET", "/v1/kv/test?raw", nil)
resp = httptest.NewRecorder() resp = httptest.NewRecorder()
obj, err = a.srv.KVSEndpoint(resp, req) _, err = a.srv.KVSEndpoint(resp, req)
if err != nil { if err != nil {
t.Fatalf("err: %v", err) t.Fatalf("err: %v", err)
} }

View File

@ -378,16 +378,17 @@ func (m *Manager) RebalanceServers() {
"number_of_servers", len(l.servers), "number_of_servers", len(l.servers),
"active_server", l.servers[0].String(), "active_server", l.servers[0].String(),
) )
} else {
// reconcileServerList failed because Serf removed the server
// that was at the front of the list that had successfully
// been Ping'ed. Between the Ping and reconcile, a Serf
// event had shown up removing the node.
//
// Instead of doing any heroics, "freeze in place" and
// continue to use the existing connection until the next
// rebalance occurs.
} }
// else {
// reconcileServerList failed because Serf removed the server
// that was at the front of the list that had successfully
// been Ping'ed. Between the Ping and reconcile, a Serf
// event had shown up removing the node.
//
// Instead of doing any heroics, "freeze in place" and
// continue to use the existing connection until the next
// rebalance occurs.
// }
} }
// reconcileServerList returns true when the first server in serverList // reconcileServerList returns true when the first server in serverList

View File

@ -14,6 +14,7 @@ import (
"github.com/hashicorp/consul/sdk/testutil/retry" "github.com/hashicorp/consul/sdk/testutil/retry"
"github.com/hashicorp/consul/testrpc" "github.com/hashicorp/consul/testrpc"
"github.com/hashicorp/consul/types" "github.com/hashicorp/consul/types"
"github.com/stretchr/testify/require"
) )
func verifySession(t *testing.T, r *retry.R, a *TestAgent, want structs.Session) { func verifySession(t *testing.T, r *retry.R, a *TestAgent, want structs.Session) {
@ -715,9 +716,11 @@ func TestSessionsForNode(t *testing.T) {
if !ok { if !ok {
t.Fatalf("should work") t.Fatalf("should work")
} }
if len(respObj) != 10 { respIDs := make([]string, 0, len(ids))
t.Fatalf("bad: %v", respObj) for _, session := range respObj {
respIDs = append(respIDs, session.ID)
} }
require.ElementsMatch(t, ids, respIDs)
}) })
} }

View File

@ -36,7 +36,7 @@ func TestUiIndex(t *testing.T) {
// Create file // Create file
path := filepath.Join(a.Config.UIDir, "my-file") path := filepath.Join(a.Config.UIDir, "my-file")
if err := ioutil.WriteFile(path, []byte("test"), 777); err != nil { if err := ioutil.WriteFile(path, []byte("test"), 0777); err != nil {
t.Fatalf("err: %v", err) t.Fatalf("err: %v", err)
} }

View File

@ -3,6 +3,7 @@ package xds
import ( import (
"errors" "errors"
"fmt" "fmt"
envoy "github.com/envoyproxy/go-control-plane/envoy/api/v2" envoy "github.com/envoyproxy/go-control-plane/envoy/api/v2"
envoycore "github.com/envoyproxy/go-control-plane/envoy/api/v2/core" envoycore "github.com/envoyproxy/go-control-plane/envoy/api/v2/core"
envoyendpoint "github.com/envoyproxy/go-control-plane/envoy/api/v2/endpoint" envoyendpoint "github.com/envoyproxy/go-control-plane/envoy/api/v2/endpoint"
@ -324,7 +325,6 @@ func (s *Server) endpointsFromDiscoveryChain(
) )
if actualTargetID != targetID { if actualTargetID != targetID {
targetID = actualTargetID targetID = actualTargetID
target = chain.Targets[actualTargetID]
} }
failover = nil failover = nil

View File

@ -552,7 +552,7 @@ func (c *cmd) grpcAddress(httpCfg *api.Config) (GRPC, error) {
} else { } else {
// Parse as host:port with option http prefix // Parse as host:port with option http prefix
grpcAddr = strings.TrimPrefix(addr, "http://") grpcAddr = strings.TrimPrefix(addr, "http://")
grpcAddr = strings.TrimPrefix(addr, "https://") grpcAddr = strings.TrimPrefix(grpcAddr, "https://")
var err error var err error
var host string var host string