Vet/race fixes (#4421)

This addresses all found vet/race fixes in community edition.

---------

Co-authored-by: Damian Debkowski <damian.debkowski@hashicorp.com>
This commit is contained in:
Jeff MitchellandDamian Debkowski authored and GitHub committed 2024-02-21 16:32:26 -05:00
1 parent 4535af25aa
commit 014a5a7aae
46 files changed
+411 -176

No files matched your search

+2 -2
View File
@@ -87,12 +87,12 @@ func TestRegisterHandlerFn(t *testing.T, msgType pbs.MsgType, h UpstreamMessageH
return func(t *testing.T) {
t.Helper()
testCtx := context.Background()
var cpHandlerRegistry sync.Map
cpHandlerRegistry := new(sync.Map)
upstreamMessageHandler.Range(func(k, v interface{}) bool {
cpHandlerRegistry.Store(k, v)
return true
})
var cpTypeSpecifierRegister sync.Map
cpTypeSpecifierRegister := new(sync.Map)
upstreamMessageTypeSpecifier.Range(func(k, v interface{}) bool {
cpTypeSpecifierRegister.Store(k, v)
return true
@@ -19,7 +19,7 @@ import (
"google.golang.org/protobuf/proto"
)
var upstreamMessageHandler sync.Map
var upstreamMessageHandler *sync.Map = new(sync.Map)
// UpstreamMessageHandler defines a handler for an UpstreamMessageRequest(s).
//
@@ -65,7 +65,7 @@ func Test_RegisterUpstreamMessageHandler(t *testing.T) {
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
assert, require := assert.New(t), require.New(t)
var cp sync.Map
cp := new(sync.Map)
upstreamMessageHandler.Range(func(k, v interface{}) bool {
cp.Store(k, v)
return true
@@ -468,7 +468,7 @@ func Test_RegisterUpstreamMessageTypeSpecifier(t *testing.T) {
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
assert, require := assert.New(t), require.New(t)
var cp sync.Map
cp := new(sync.Map)
upstreamMessageTypeSpecifier.Range(func(k, v interface{}) bool {
cp.Store(k, v)
return true
@@ -82,7 +82,7 @@ type UpstreamMessageTypeSpecifier interface {
AllocResponse() proto.Message
}
var upstreamMessageTypeSpecifier sync.Map
var upstreamMessageTypeSpecifier *sync.Map = new(sync.Map)
// registerUpstreamMessageTypeSpecifier will register an
// UpstreamMessageTypeSpecifier for the specified msg name.
+2 -2
View File
@@ -170,8 +170,8 @@ func TestRotationTicking(t *testing.T) {
// Stop and start the client connections to ensure the new credentials
// are valid; if not, we won't establish a new connection and rotation
// will fail
require.NotNil(w.Worker().GrpcClientConn)
require.NoError(w.Worker().GrpcClientConn.Close())
require.NotNil(w.Worker().GrpcClientConn.Load())
require.NoError(w.Worker().GrpcClientConn.Load().Close())
require.NoError(w.Worker().StartControllerConnections())
rotationCount++
}
@@ -189,7 +189,7 @@ func (w *Worker) createClientConn(addr string) error {
return fmt.Errorf("error dialing controller for worker auth: %w", err)
}
w.GrpcClientConn = cc
w.GrpcClientConn.Store(cc)
w.controllerMultihopConn.Store(multihop.NewMultihopServiceClient(cc))
var producer handlers.UpstreamMessageServiceClientProducer
@@ -6,6 +6,7 @@ package worker
import (
"context"
"fmt"
"net"
"strconv"
"sync/atomic"
"testing"
@@ -119,8 +120,9 @@ func waitForConnectionStateCondition(upstreamConnectionState *atomic.Value, expe
}
type serverTestInfo struct {
srv *grpc.Server
address string
srv *grpc.Server
address string
listener net.Listener
}
func createTestServers(t *testing.T) ([]*serverTestInfo, error) {
@@ -133,10 +135,12 @@ func createTestServers(t *testing.T) ([]*serverTestInfo, error) {
return nil, err
}
srv := grpc.NewServer()
lInfo := &serverTestInfo{srv: srv, address: listener.Addr().String()}
lInfo := &serverTestInfo{srv: srv, listener: listener, address: listener.Addr().String()}
servers = append(servers, lInfo)
go func(i int) {
if err := servers[i].srv.Serve(listener); err != nil {
}
for i := range servers {
go func(num int) {
if err := servers[num].srv.Serve(servers[num].listener); err != nil {
t.Logf("error serving: %v", err)
}
}(i)
+38 -50
View File
@@ -7,6 +7,7 @@ import (
"fmt"
"net"
"sync"
"sync/atomic"
"testing"
"github.com/stretchr/testify/require"
@@ -20,54 +21,29 @@ func TestCountingConn(t *testing.T) {
underlyingConn *testNetConn
}{
{
name: "noErrors",
writeBytes: []byte("hello"),
underlyingConn: &testNetConn{
bytesToRead: 100,
readErr: false,
writeErr: false,
closeErr: false,
},
name: "noErrors",
writeBytes: []byte("hello"),
underlyingConn: newTestNetConn(100, false, false, false),
},
{
name: "readErr",
writeBytes: []byte("hello"),
underlyingConn: &testNetConn{
bytesToRead: 100,
readErr: true,
writeErr: false,
closeErr: false,
},
name: "readErr",
writeBytes: []byte("hello"),
underlyingConn: newTestNetConn(100, true, false, false),
},
{
name: "writeErr",
writeBytes: []byte("hello"),
underlyingConn: &testNetConn{
bytesToRead: 100,
readErr: false,
writeErr: true,
closeErr: false,
},
name: "writeErr",
writeBytes: []byte("hello"),
underlyingConn: newTestNetConn(100, false, true, false),
},
{
name: "closeErr",
writeBytes: []byte("hello"),
underlyingConn: &testNetConn{
bytesToRead: 100,
readErr: false,
writeErr: false,
closeErr: true,
},
name: "closeErr",
writeBytes: []byte("hello"),
underlyingConn: newTestNetConn(100, false, false, true),
},
{
name: "allErr",
writeBytes: []byte("hello"),
underlyingConn: &testNetConn{
bytesToRead: 100,
readErr: true,
writeErr: true,
closeErr: true,
},
name: "allErr",
writeBytes: []byte("hello"),
underlyingConn: newTestNetConn(100, true, true, true),
},
}
@@ -77,7 +53,7 @@ func TestCountingConn(t *testing.T) {
readBytes := make([]byte, tt.underlyingConn.bytesToRead)
read, err := conn.Read(readBytes)
require.True(t, tt.underlyingConn.readCalled)
require.True(t, tt.underlyingConn.readCalled.Load())
if tt.underlyingConn.readErr {
require.Error(t, err)
require.Equal(t, 1, read)
@@ -90,7 +66,7 @@ func TestCountingConn(t *testing.T) {
}
written, err := conn.Write(tt.writeBytes)
require.True(t, tt.underlyingConn.writeCalled)
require.True(t, tt.underlyingConn.writeCalled.Load())
if tt.underlyingConn.writeErr {
require.Error(t, err)
require.Equal(t, 1, written)
@@ -102,7 +78,7 @@ func TestCountingConn(t *testing.T) {
}
err = conn.Close()
require.True(t, tt.underlyingConn.closeCalled)
require.True(t, tt.underlyingConn.closeCalled.Load())
if tt.underlyingConn.closeErr {
require.Error(t, err)
} else {
@@ -121,7 +97,7 @@ func TestCountingConnConcurrentCalls(t *testing.T) {
concurrentReads := 1000
concurrentWrites := 1000
conn := &countingConn{Conn: &testNetConn{bytesToRead: bytesToRead}}
conn := &countingConn{Conn: newTestNetConn(bytesToRead, false, false, false)}
wg := sync.WaitGroup{}
wg.Add(concurrentReads)
@@ -164,13 +140,25 @@ type testNetConn struct {
closeErr bool
// Test results
readCalled bool
writeCalled bool
closeCalled bool
readCalled *atomic.Bool
writeCalled *atomic.Bool
closeCalled *atomic.Bool
}
func newTestNetConn(bytesToRead int, readErr, writeErr, closeErr bool) *testNetConn {
return &testNetConn{
bytesToRead: bytesToRead,
readErr: readErr,
writeErr: writeErr,
closeErr: closeErr,
readCalled: new(atomic.Bool),
writeCalled: new(atomic.Bool),
closeCalled: new(atomic.Bool),
}
}
func (t *testNetConn) Read(in []byte) (int, error) {
t.readCalled = true
t.readCalled.Store(true)
if t.readErr {
return 1, fmt.Errorf("oops, read error")
}
@@ -183,7 +171,7 @@ func (t *testNetConn) Read(in []byte) (int, error) {
}
func (t *testNetConn) Write(in []byte) (int, error) {
t.writeCalled = true
t.writeCalled.Store(true)
if t.writeErr {
return 1, fmt.Errorf("oops, write error")
}
@@ -192,7 +180,7 @@ func (t *testNetConn) Write(in []byte) (int, error) {
}
func (t *testNetConn) Close() error {
t.closeCalled = true
t.closeCalled.Store(true)
if t.closeErr {
return fmt.Errorf("oops, close error")
}
+1 -1
View File
@@ -89,7 +89,7 @@ func TestStartListeners(t *testing.T) {
}
w.controllerUpstreamMsgConn.Store(&dummyClientProducer)
manager, err := session.NewManager(pbs.NewSessionServiceClient(w.GrpcClientConn))
manager, err := session.NewManager(pbs.NewSessionServiceClient(w.GrpcClientConn.Load()))
require.NoError(t, err)
err = w.startListeners(manager)
if tt.expErr {
+1 -1
View File
@@ -17,7 +17,7 @@ var (
TcpHandlerName = "tcp"
// handlers is the map of registered handlers
handlers sync.Map
handlers *sync.Map = new(sync.Map)
// ErrUnknownProtocol specifies the provided protocol has no registered handler
ErrUnknownProtocol = errors.New("proxy: handler not found for protocol")
@@ -9,10 +9,10 @@ import (
)
// ProxyState contains the current state of proxies in this process.
var ProxyState proxyState
var ProxyState proxyState = proxyState{proxyCount: new(atomic.Int64)}
type proxyState struct {
proxyCount atomic.Int64
proxyCount *atomic.Int64
}
// CurrentProxiedConnections returns the current number of ongoing proxied
@@ -6,6 +6,7 @@ package proxy
import (
"net/http"
"net/http/httptest"
"sync/atomic"
"testing"
"github.com/stretchr/testify/assert"
@@ -14,7 +15,7 @@ import (
func TestProxyStateHelpers(t *testing.T) {
old := ProxyState
ProxyState = proxyState{}
ProxyState = proxyState{proxyCount: new(atomic.Int64)}
t.Cleanup(func() {
ProxyState = old
})
+2 -2
View File
@@ -24,7 +24,7 @@ func TestRegisterHandler(t *testing.T) {
t.Cleanup(func() {
handlers = oldHandler
})
handlers = sync.Map{}
handlers = new(sync.Map)
err := RegisterHandler("protocol", fn)
require.NoError(err)
@@ -47,7 +47,7 @@ func TestAlwaysTcpGetHandler(t *testing.T) {
t.Cleanup(func() {
handlers = oldHandler
})
handlers = sync.Map{}
handlers = new(sync.Map)
_, err := tcpOnly("wid", nil)
assert.ErrorIs(err, ErrUnknownProtocol)
+1 -1
View File
@@ -37,7 +37,7 @@ func registerWorkerStatusSessionService(ctx context.Context, w *Worker, server *
return fmt.Errorf("%s: server is nil", op)
}
statusSessionService := NewWorkerProxyServiceServer(w.GrpcClientConn)
statusSessionService := NewWorkerProxyServiceServer(w.GrpcClientConn.Load())
pbs.RegisterServerCoordinationServiceServer(server, statusSessionService)
pbs.RegisterSessionServiceServer(server, statusSessionService)
return nil
+2 -1
View File
@@ -61,7 +61,7 @@ type Manager interface {
type manager struct {
controllerSessionConn pbs.SessionServiceClient
sessionMap sync.Map
sessionMap *sync.Map
}
var _ Manager = (*manager)(nil)
@@ -74,6 +74,7 @@ func NewManager(client pbs.SessionServiceClient) (*manager, error) {
}
return &manager{
controllerSessionConn: client,
sessionMap: new(sync.Map),
}, nil
}
+12 -12
View File
@@ -273,7 +273,7 @@ func TestWorkerSetCloseTimeForResponse(t *testing.T) {
cases := []struct {
name string
sessionCloseInfo map[string][]*pbs.CloseConnectionResponseData
sessionInfoMap func() sync.Map
sessionInfoMap func() *sync.Map
expected []string
expectedClosed map[string]struct{}
expectedErr []error
@@ -288,8 +288,8 @@ func TestWorkerSetCloseTimeForResponse(t *testing.T) {
{ConnectionId: "bar", Status: pbs.CONNECTIONSTATUS_CONNECTIONSTATUS_CLOSED},
},
},
sessionInfoMap: func() sync.Map {
var m sync.Map
sessionInfoMap: func() *sync.Map {
m := new(sync.Map)
m.Store("one", &sess{
resp: &pbs.LookupSessionResponse{Authorization: &targets.SessionAuthorizationData{
SessionId: "one",
@@ -333,8 +333,8 @@ func TestWorkerSetCloseTimeForResponse(t *testing.T) {
{ConnectionId: "bar", Status: pbs.CONNECTIONSTATUS_CONNECTIONSTATUS_CONNECTED},
},
},
sessionInfoMap: func() sync.Map {
var m sync.Map
sessionInfoMap: func() *sync.Map {
m := new(sync.Map)
m.Store("one", &sess{
resp: &pbs.LookupSessionResponse{Authorization: &targets.SessionAuthorizationData{
SessionId: "one",
@@ -369,8 +369,8 @@ func TestWorkerSetCloseTimeForResponse(t *testing.T) {
{ConnectionId: "bar", Status: pbs.CONNECTIONSTATUS_CONNECTIONSTATUS_CLOSED},
},
},
sessionInfoMap: func() sync.Map {
var m sync.Map
sessionInfoMap: func() *sync.Map {
m := new(sync.Map)
m.Store("one", &sess{
resp: &pbs.LookupSessionResponse{Authorization: &targets.SessionAuthorizationData{
SessionId: "one",
@@ -400,8 +400,8 @@ func TestWorkerSetCloseTimeForResponse(t *testing.T) {
{ConnectionId: "bar", Status: pbs.CONNECTIONSTATUS_CONNECTIONSTATUS_CLOSED},
},
},
sessionInfoMap: func() sync.Map {
var m sync.Map
sessionInfoMap: func() *sync.Map {
m := new(sync.Map)
m.Store("one", &sess{
resp: &pbs.LookupSessionResponse{Authorization: &targets.SessionAuthorizationData{
SessionId: "one",
@@ -431,8 +431,8 @@ func TestWorkerSetCloseTimeForResponse(t *testing.T) {
{
name: "empty",
sessionCloseInfo: make(map[string][]*pbs.CloseConnectionResponseData),
sessionInfoMap: func() sync.Map {
var m sync.Map
sessionInfoMap: func() *sync.Map {
m := new(sync.Map)
m.Store("one", &sess{
resp: &pbs.LookupSessionResponse{Authorization: &targets.SessionAuthorizationData{
SessionId: "one",
@@ -453,7 +453,7 @@ func TestWorkerSetCloseTimeForResponse(t *testing.T) {
tc := tc
t.Run(tc.name, func(t *testing.T) {
require := require.New(t)
manager := &manager{}
manager := &manager{sessionMap: new(sync.Map)}
manager.sessionMap = tc.sessionInfoMap()
actual, actualErr := setCloseTimeForResponse(manager, tc.sessionCloseInfo)
+2 -2
View File
@@ -181,7 +181,7 @@ func (w *Worker) sendWorkerStatus(cancelCtx context.Context, sessionManager sess
})
// Send status information
client := pbs.NewServerCoordinationServiceClient(w.GrpcClientConn)
client := pbs.NewServerCoordinationServiceClient(w.GrpcClientConn.Load())
var tags []*pb.TagPair
// If we're not going to request a tag update, no reason to have these
// marshaled on every status call.
@@ -242,7 +242,7 @@ func (w *Worker) sendWorkerStatus(cancelCtx context.Context, sessionManager sess
// In the case that the control plane has gone down and come up with different IPs,
// append initial upstreams/ cluster addr to the resolver to try
if w.GrpcClientConn.GetState() == connectivity.TransientFailure {
if w.GrpcClientConn.Load().GetState() == connectivity.TransientFailure {
lastStatus := w.lastStatusSuccess.Load().(*LastStatusInformation)
if lastStatus != nil && lastStatus.LastCalculatedUpstreams != nil {
addrs := lastStatus.LastCalculatedUpstreams
+6 -5
View File
@@ -116,10 +116,11 @@ type Worker struct {
tickerWg sync.WaitGroup
// grpc.ClientConns are thread safe.
// See https://github.com/grpc/grpc-go/blob/master/Documentation/concurrency.md#clients
// This is exported for tests.
GrpcClientConn *grpc.ClientConn
// grpc.ClientConns are thread safe. See
// https://github.com/grpc/grpc-go/blob/master/Documentation/concurrency.md#clients
// However this is an atomic because we sometimes swap this pointer out
// (mostly in tests) - which isn't thread safe. This is exported for tests.
GrpcClientConn atomic.Pointer[grpc.ClientConn]
// receives address updates and contains the grpc resolver.
addressReceivers []addressReceiver
@@ -511,7 +512,7 @@ func (w *Worker) Start() error {
return errors.Wrap(w.baseContext, err, op, errors.WithMsg("error making controller connections"))
}
w.sessionManager, err = session.NewManager(pbs.NewSessionServiceClient(w.GrpcClientConn))
w.sessionManager, err = session.NewManager(pbs.NewSessionServiceClient(w.GrpcClientConn.Load()))
if err != nil {
return errors.Wrap(w.baseContext, err, op, errors.WithMsg("error creating session manager"))
}
@@ -82,7 +82,7 @@ func TestDeleteConnectedWorkers(t *testing.T) {
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
prevState := tc.testWorker.Worker().GrpcClientConn.GetState()
prevState := tc.testWorker.Worker().GrpcClientConn.Load().GetState()
require.NotEqual(t, connectivity.TransientFailure, prevState)
require.NotEqual(t, connectivity.Shutdown, prevState)
_, err = serverRepo.DeleteWorker(ctx, tc.workerId)
@@ -90,12 +90,12 @@ func TestDeleteConnectedWorkers(t *testing.T) {
stateChangeCtx, cancel := context.WithTimeout(ctx, 4*time.Second)
defer cancel()
for {
tc.testWorker.Worker().GrpcClientConn.ResetConnectBackoff()
if !tc.testWorker.Worker().GrpcClientConn.WaitForStateChange(stateChangeCtx, prevState) {
tc.testWorker.Worker().GrpcClientConn.Load().ResetConnectBackoff()
if !tc.testWorker.Worker().GrpcClientConn.Load().WaitForStateChange(stateChangeCtx, prevState) {
assert.Fail(t, "State didn't change before context timed out")
break
}
newState := tc.testWorker.Worker().GrpcClientConn.GetState()
newState := tc.testWorker.Worker().GrpcClientConn.Load().GetState()
t.Logf("Changed from previous state: %s to new state: %s", prevState, newState)
if newState == connectivity.Shutdown || newState == connectivity.TransientFailure {
break