Worker status refactor (#5417)
* oss: feat(proto): statistics rpc added to server coordination service * oss: feat(session): add update statistics status service * oss: feat(handlers): add Statistics method to worker service server * oss: feat(worker): add statistics ticking * oss: internal/proto: define the new RoutingInfo RPC * oss: internal/server: repository changes for RoutingInfo RPC * oss: internal/daemon: add RoutingInfo handler to worker service The new RoutingInfo RPC is used to get information from the worker that is used to make routing decisions on the controller. It also handles the initial request from the worker. * oss: feat(db): server_worker_session_info table * oss: feat(proto): session info rpc for server coordination service * oss: feat(server): worker session info request data type * oss: feat(worker): session info ticker * oss: feat(handler): server coordination handler for session info * oss: feat(session): utilize session info request time for session cleanup * oss: proto: fix some gotags comments Some of these fields were missing comments, while others had incorrectly formatted comments. * oss: worker: send connection status to server This is required for the correct tracking of orphaned connections * oss: internal/daemon/worker: add function to wait for Statistics RPC * oss: internal/daemon/worker: add routing info RPC The new RoutingInfo RPC replaces part of the Status RPC, namely the part which is used by the controller and worker to perform decisions around the establishment of new sessions and new worker connections. * oss: internal/daemon/worker: remove unnecessary error check * oss: internal/daemon/worker: lock access to config and upstreams The new confLock protects access to the conf value and to the addressReceivers slice. * oss: worker: replace Status RPC with RoutingInfo * oss: worker: deprecate the Status RPC and related types The Status RPC and related messages have been replaced by the RoutingInfo/SessionInfo/Statistics RPCs. The controller will continue to support the Status RPC until two new minor versions have been released. * oss: internal/event: add default deny for new worker RPCs * oss: internal/daemon/worker: allow RPC interval to be set The new SessionInfo/RoutingInfo/Statistics RPCs run at long intervals, which make some of our cluster tests take a long time to complete. This allows their interval to be configured in tests. * oss: all: use TestWorkerRPCInterval in slow tests This should speed up these tests significantly. * oss: internal/tests/cluster: reset sys eventer in test --------- Co-authored-by: Damian Debkowski <damian.debkowski@hashicorp.com>
This commit is contained in:
1 parent
554195f49f
commit
ec0a3f964b
70 files changed
+5492
-1618
No files matched your search
@@ -5,6 +5,7 @@ package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
stderrors "errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
@@ -13,6 +14,7 @@ import (
|
||||
"github.com/hashicorp/boundary/internal/daemon/controller/common"
|
||||
"github.com/hashicorp/boundary/internal/daemon/controller/downstream"
|
||||
"github.com/hashicorp/boundary/internal/daemon/controller/handlers"
|
||||
"github.com/hashicorp/boundary/internal/errors"
|
||||
"github.com/hashicorp/boundary/internal/event"
|
||||
pbs "github.com/hashicorp/boundary/internal/gen/controller/servers/services"
|
||||
intglobals "github.com/hashicorp/boundary/internal/globals"
|
||||
@@ -95,20 +97,148 @@ func NewWorkerServiceServer(
|
||||
}
|
||||
}
|
||||
|
||||
func (ws *workerServiceServer) Statistics(ctx context.Context, req *pbs.StatisticsRequest) (*pbs.StatisticsResponse, error) {
|
||||
const op = "workers.(workerServiceServer).Statistics"
|
||||
workerId := req.GetWorkerId()
|
||||
if workerId == "" {
|
||||
return &pbs.StatisticsResponse{}, status.Error(codes.InvalidArgument, "worker id is empty")
|
||||
}
|
||||
connectionRepo, err := ws.connectionRepoFn()
|
||||
if err != nil {
|
||||
event.WriteError(ctx, op, err, event.WithInfoMsg("error getting connection repo"))
|
||||
return &pbs.StatisticsResponse{}, status.Errorf(codes.Internal, "Error acquiring connection repo: %v", err)
|
||||
}
|
||||
connectionStats := []*session.Connection{}
|
||||
for _, s := range req.GetSessions() {
|
||||
sessionId := s.GetSessionId()
|
||||
if sessionId == "" {
|
||||
return &pbs.StatisticsResponse{}, status.Error(codes.InvalidArgument, "session id is empty")
|
||||
}
|
||||
for _, c := range s.Connections {
|
||||
connectionId := c.GetConnectionId()
|
||||
if connectionId == "" {
|
||||
return &pbs.StatisticsResponse{}, status.Error(codes.InvalidArgument, "connection id is empty")
|
||||
}
|
||||
switch c.Status {
|
||||
case pbs.CONNECTIONSTATUS_CONNECTIONSTATUS_AUTHORIZED, pbs.CONNECTIONSTATUS_CONNECTIONSTATUS_CONNECTED:
|
||||
connectionStats = append(connectionStats, &session.Connection{
|
||||
PublicId: c.GetConnectionId(),
|
||||
BytesUp: c.GetBytesUp(),
|
||||
BytesDown: c.GetBytesDown(),
|
||||
})
|
||||
default:
|
||||
// Other statuses are not included in the stats sent to the domain
|
||||
}
|
||||
}
|
||||
}
|
||||
updateBytesErr := session.UpdateConnectionBytesUpDown(ctx, connectionRepo, connectionStats)
|
||||
_, closeOrphanedErr := session.CloseOrphanedConnections(ctx, connectionRepo, workerId, connectionStats)
|
||||
sessionErrs := stderrors.Join(updateBytesErr, closeOrphanedErr)
|
||||
if sessionErrs != nil {
|
||||
return &pbs.StatisticsResponse{}, errors.Wrap(ctx, sessionErrs, op)
|
||||
}
|
||||
return &pbs.StatisticsResponse{}, nil
|
||||
}
|
||||
|
||||
func (ws *workerServiceServer) SessionInfo(ctx context.Context, req *pbs.SessionInfoRequest) (*pbs.SessionInfoResponse, error) {
|
||||
const op = "workers.(workerServiceServer).SessionInfo"
|
||||
workerId := req.GetWorkerId()
|
||||
if workerId == "" {
|
||||
return &pbs.SessionInfoResponse{}, status.Error(codes.InvalidArgument, "worker id is empty")
|
||||
}
|
||||
sessionTypeCache := map[string]pbs.SessionType{}
|
||||
var recordedSessionIds []string
|
||||
var ingressedSessionIds []string
|
||||
for _, s := range req.GetSessions() {
|
||||
sessionId := s.GetSessionId()
|
||||
sessionStatus := s.GetSessionStatus()
|
||||
sessionType := s.GetSessionType()
|
||||
switch sessionType {
|
||||
case pbs.SessionType_SESSION_TYPE_UNSPECIFIED:
|
||||
return &pbs.SessionInfoResponse{}, status.Errorf(codes.InvalidArgument, "unspecified session type")
|
||||
case pbs.SessionType_SESSION_TYPE_INGRESSED:
|
||||
if sessionStatus == pbs.SESSIONSTATUS_SESSIONSTATUS_CANCELING || sessionStatus == pbs.SESSIONSTATUS_SESSIONSTATUS_TERMINATED {
|
||||
// No need to see about canceling anything
|
||||
continue
|
||||
}
|
||||
sessionTypeCache[sessionId] = sessionType
|
||||
ingressedSessionIds = append(ingressedSessionIds, sessionId)
|
||||
case pbs.SessionType_SESSION_TYPE_RECORDED:
|
||||
if sessionStatus == pbs.SESSIONSTATUS_SESSIONSTATUS_CANCELING || sessionStatus == pbs.SESSIONSTATUS_SESSIONSTATUS_TERMINATED {
|
||||
// No need to see about canceling anything
|
||||
continue
|
||||
}
|
||||
sessionTypeCache[sessionId] = sessionType
|
||||
recordedSessionIds = append(recordedSessionIds, sessionId)
|
||||
default:
|
||||
return &pbs.SessionInfoResponse{}, status.Errorf(codes.InvalidArgument, "unknown session type: %q", s.GetSessionType().String())
|
||||
}
|
||||
}
|
||||
|
||||
sessRepo, err := ws.sessionRepoFn()
|
||||
if err != nil {
|
||||
return &pbs.SessionInfoResponse{}, status.Errorf(codes.Internal, "Error acquiring repo to query session status: %v", err)
|
||||
}
|
||||
|
||||
result := &pbs.SessionInfoResponse{}
|
||||
nonActiveSessions, err := sessRepo.CheckIfNotActive(ctx, append(ingressedSessionIds, recordedSessionIds...))
|
||||
if err != nil {
|
||||
return &pbs.SessionInfoResponse{}, status.Errorf(codes.Internal,
|
||||
"Error checking if sessions are no longer active: %v", err)
|
||||
}
|
||||
for _, s := range nonActiveSessions {
|
||||
switch sessionTypeCache[s.SessionId] {
|
||||
case pbs.SessionType_SESSION_TYPE_INGRESSED:
|
||||
var connChanges []*pbs.Connection
|
||||
for _, conn := range s.Connections {
|
||||
connChanges = append(connChanges, &pbs.Connection{
|
||||
ConnectionId: conn.GetPublicId(),
|
||||
Status: session.StatusClosed.ProtoVal(),
|
||||
})
|
||||
}
|
||||
result.NonActiveSessions = append(result.NonActiveSessions, &pbs.Session{
|
||||
SessionId: s.SessionId,
|
||||
SessionStatus: s.Status.ProtoVal(),
|
||||
SessionType: pbs.SessionType_SESSION_TYPE_INGRESSED,
|
||||
Connections: connChanges,
|
||||
})
|
||||
case pbs.SessionType_SESSION_TYPE_RECORDED:
|
||||
result.NonActiveSessions = append(result.NonActiveSessions, &pbs.Session{
|
||||
SessionId: s.SessionId,
|
||||
SessionStatus: s.Status.ProtoVal(),
|
||||
SessionType: pbs.SessionType_SESSION_TYPE_RECORDED,
|
||||
})
|
||||
default:
|
||||
return &pbs.SessionInfoResponse{}, status.Errorf(codes.Internal,
|
||||
"unknown session type found for non active session: %q", s.SessionId)
|
||||
}
|
||||
}
|
||||
|
||||
serverRepo, err := ws.serversRepoFn()
|
||||
if err != nil {
|
||||
return &pbs.SessionInfoResponse{}, status.Errorf(codes.Internal, "Error acquiring repo to upsert session info status time: %v", err)
|
||||
}
|
||||
err = serverRepo.UpsertSessionInfo(ctx, workerId)
|
||||
if err != nil {
|
||||
return &pbs.SessionInfoResponse{}, status.Errorf(codes.Internal, "Error updating the latest status time for the server session info: %v", err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// Status is the deprecated method for worker status updates.
|
||||
// This is safe to remove after the release of Boundary v0.20.0.
|
||||
func (ws *workerServiceServer) Status(ctx context.Context, req *pbs.StatusRequest) (*pbs.StatusResponse, error) {
|
||||
const op = "workers.(workerServiceServer).Status"
|
||||
// TODO: on the worker, if we get errors back from this repeatedly, do we
|
||||
// terminate all sessions since we can't know if they were canceled?
|
||||
|
||||
wStat := req.GetWorkerStatus()
|
||||
if wStat == nil {
|
||||
return &pbs.StatusResponse{}, status.Error(codes.InvalidArgument, "Worker sent nil status.")
|
||||
return nil, status.Error(codes.InvalidArgument, "Worker sent nil status.")
|
||||
}
|
||||
switch {
|
||||
case wStat.GetName() == "" && wStat.GetKeyId() == "":
|
||||
return &pbs.StatusResponse{}, status.Error(codes.InvalidArgument, "Name and keyId are not set in the request; one is required.")
|
||||
return nil, status.Error(codes.InvalidArgument, "Name and keyId are not set in the request; one is required.")
|
||||
case wStat.GetAddress() == "":
|
||||
return &pbs.StatusResponse{}, status.Error(codes.InvalidArgument, "Address is not set but is required.")
|
||||
return nil, status.Error(codes.InvalidArgument, "Address is not set but is required.")
|
||||
}
|
||||
// This Store call is currently only for testing purposes
|
||||
ws.updateTimes.Store(wStat.GetName(), time.Now())
|
||||
@@ -116,7 +246,7 @@ func (ws *workerServiceServer) Status(ctx context.Context, req *pbs.StatusReques
|
||||
serverRepo, err := ws.serversRepoFn()
|
||||
if err != nil {
|
||||
event.WriteError(ctx, op, err, event.WithInfoMsg("error getting server repo"))
|
||||
return &pbs.StatusResponse{}, status.Errorf(codes.Internal, "Error acquiring repo to store worker status: %v", err)
|
||||
return nil, status.Errorf(codes.Internal, "Error acquiring repo to store worker status: %v", err)
|
||||
}
|
||||
|
||||
// Convert API tags to storage tags
|
||||
@@ -163,7 +293,7 @@ func (ws *workerServiceServer) Status(ctx context.Context, req *pbs.StatusReques
|
||||
workerId, err := serverRepo.UpsertWorkerStatus(ctx, wConf, opts...)
|
||||
if err != nil {
|
||||
event.WriteError(ctx, op, err, event.WithInfoMsg("error storing worker status"))
|
||||
return &pbs.StatusResponse{}, status.Errorf(codes.Internal, "Error storing worker status: %v", err)
|
||||
return nil, status.Errorf(codes.Internal, "Error storing worker status: %v", err)
|
||||
}
|
||||
|
||||
// update storage states
|
||||
@@ -174,7 +304,7 @@ func (ws *workerServiceServer) Status(ctx context.Context, req *pbs.StatusReques
|
||||
controllers, err := serverRepo.ListControllers(ctx, server.WithLiveness(time.Duration(ws.livenessTimeToStale.Load())))
|
||||
if err != nil {
|
||||
event.WriteError(ctx, op, err, event.WithInfoMsg("error getting current controllers"))
|
||||
return &pbs.StatusResponse{}, status.Errorf(codes.Internal, "Error getting current controllers: %v", err)
|
||||
return nil, status.Errorf(codes.Internal, "Error getting current controllers: %v", err)
|
||||
}
|
||||
|
||||
responseControllers := []*pbs.UpstreamServer{}
|
||||
@@ -189,7 +319,7 @@ func (ws *workerServiceServer) Status(ctx context.Context, req *pbs.StatusReques
|
||||
workerAuthRepo, err := ws.workerAuthRepoFn()
|
||||
if err != nil {
|
||||
event.WriteError(ctx, op, err, event.WithInfoMsg("error getting worker auth repo"))
|
||||
return &pbs.StatusResponse{}, status.Errorf(codes.Internal, "Error acquiring repo to lookup worker auth info: %v", err)
|
||||
return nil, status.Errorf(codes.Internal, "Error acquiring repo to lookup worker auth info: %v", err)
|
||||
}
|
||||
|
||||
authorizedDownstreams := &pbs.AuthorizedDownstreamWorkerList{}
|
||||
@@ -197,7 +327,7 @@ func (ws *workerServiceServer) Status(ctx context.Context, req *pbs.StatusReques
|
||||
knownConnectedWorkers, err := serverRepo.VerifyKnownWorkers(ctx, req.GetConnectedWorkerPublicIds())
|
||||
if err != nil {
|
||||
event.WriteError(ctx, op, err, event.WithInfoMsg("error getting known connected worker ids"))
|
||||
return &pbs.StatusResponse{}, status.Errorf(codes.Internal, "Error getting known connected worker ids: %v", err)
|
||||
return nil, status.Errorf(codes.Internal, "Error getting known connected worker ids: %v", err)
|
||||
}
|
||||
authorizedDownstreams.WorkerPublicIds = knownConnectedWorkers
|
||||
}
|
||||
@@ -206,25 +336,14 @@ func (ws *workerServiceServer) Status(ctx context.Context, req *pbs.StatusReques
|
||||
authorizedKeyIds, err := workerAuthRepo.FilterToAuthorizedWorkerKeyIds(ctx, req.GetConnectedUnmappedWorkerKeyIdentifiers())
|
||||
if err != nil {
|
||||
event.WriteError(ctx, op, err, event.WithInfoMsg("error getting authorized unmapped worker key ids"))
|
||||
return &pbs.StatusResponse{}, status.Errorf(codes.Internal, "Error getting authorized worker key ids: %v", err)
|
||||
return nil, status.Errorf(codes.Internal, "Error getting authorized worker key ids: %v", err)
|
||||
}
|
||||
authorizedDownstreams.UnmappedWorkerKeyIdentifiers = authorizedKeyIds
|
||||
}
|
||||
|
||||
authorizedWorkerList := &pbs.AuthorizedWorkerList{}
|
||||
if len(req.GetConnectedWorkerKeyIdentifiers()) > 0 {
|
||||
authorizedKeyIds, err := workerAuthRepo.FilterToAuthorizedWorkerKeyIds(ctx, req.GetConnectedWorkerKeyIdentifiers())
|
||||
if err != nil {
|
||||
event.WriteError(ctx, op, err, event.WithInfoMsg("error getting authorized worker key ids"))
|
||||
return &pbs.StatusResponse{}, status.Errorf(codes.Internal, "Error getting authorized worker key ids: %v", err)
|
||||
}
|
||||
authorizedWorkerList.WorkerKeyIdentifiers = authorizedKeyIds
|
||||
}
|
||||
|
||||
ret := &pbs.StatusResponse{
|
||||
CalculatedUpstreams: responseControllers,
|
||||
WorkerId: workerId,
|
||||
AuthorizedWorkers: authorizedWorkerList,
|
||||
AuthorizedDownstreamWorkers: authorizedDownstreams,
|
||||
}
|
||||
|
||||
@@ -281,12 +400,12 @@ func (ws *workerServiceServer) Status(ctx context.Context, req *pbs.StatusReques
|
||||
sessRepo, err := ws.sessionRepoFn()
|
||||
if err != nil {
|
||||
event.WriteError(ctx, op, err, event.WithInfoMsg("error getting sessions repo"))
|
||||
return &pbs.StatusResponse{}, status.Errorf(codes.Internal, "Error acquiring repo to query session status: %v", err)
|
||||
return nil, status.Errorf(codes.Internal, "Error acquiring repo to query session status: %v", err)
|
||||
}
|
||||
connectionRepo, err := ws.connectionRepoFn()
|
||||
if err != nil {
|
||||
event.WriteError(ctx, op, err, event.WithInfoMsg("error getting connection repo"))
|
||||
return &pbs.StatusResponse{}, status.Errorf(codes.Internal, "Error acquiring repo to query session status: %v", err)
|
||||
return nil, status.Errorf(codes.Internal, "Error acquiring repo to query session status: %v", err)
|
||||
}
|
||||
|
||||
notActive, err := session.WorkerStatusReport(ctx, sessRepo, connectionRepo, workerId, stateReport)
|
||||
@@ -348,6 +467,11 @@ func (ws *workerServiceServer) Status(ctx context.Context, req *pbs.StatusReques
|
||||
})
|
||||
}
|
||||
|
||||
err = serverRepo.UpsertSessionInfo(ctx, workerId)
|
||||
if err != nil {
|
||||
return nil, status.Errorf(codes.Internal, "Error updating the latest status time for the server session info: %v", err)
|
||||
}
|
||||
|
||||
return ret, nil
|
||||
}
|
||||
|
||||
@@ -360,8 +484,8 @@ func (ws *workerServiceServer) ListHcpbWorkers(ctx context.Context, req *pbs.Lis
|
||||
return nil, status.Errorf(codes.Internal, "Error getting servers repo: %v", err)
|
||||
}
|
||||
|
||||
// We use the livenessTimeToStale here instead of WorkerStatusGracePeriod
|
||||
// since WorkerStatusGracePeriod is more for deciding which workers should
|
||||
// We use the livenessTimeToStale here instead of WorkerRPCGracePeriod
|
||||
// since WorkerRPCGracePeriod is more for deciding which workers should
|
||||
// be used for session proxying, but here we care about providing the BYOW
|
||||
// workers with a list of which upstreams to connect to as their upstreams.
|
||||
managed, err := serversRepo.ListHcpbManagedWorkers(ctx, time.Duration(ws.livenessTimeToStale.Load()))
|
||||
@@ -385,6 +509,102 @@ func (ws *workerServiceServer) ListHcpbWorkers(ctx context.Context, req *pbs.Lis
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func (ws *workerServiceServer) RoutingInfo(ctx context.Context, req *pbs.RoutingInfoRequest) (*pbs.RoutingInfoResponse, error) {
|
||||
const op = "workers.(workerServiceServer).RoutingInfo"
|
||||
wStat := req.GetWorkerStatus()
|
||||
if wStat == nil {
|
||||
return nil, status.Error(codes.InvalidArgument, "worker status is required")
|
||||
}
|
||||
switch {
|
||||
case wStat.GetPublicId() == "" && wStat.GetKeyId() == "" && wStat.GetName() == "":
|
||||
return nil, status.Error(codes.InvalidArgument, "public id, key id and name are not set in the request; one is required")
|
||||
case wStat.GetAddress() == "":
|
||||
return nil, status.Error(codes.InvalidArgument, "address is not set but is required")
|
||||
case wStat.GetReleaseVersion() == "":
|
||||
return nil, status.Error(codes.InvalidArgument, "release version is not set but is required")
|
||||
case wStat.GetOperationalState() == "":
|
||||
return nil, status.Error(codes.InvalidArgument, "operational state is not set but is required")
|
||||
case wStat.GetLocalStorageState() == "":
|
||||
return nil, status.Error(codes.InvalidArgument, "local storage state is not set but is required")
|
||||
}
|
||||
// This Store call is currently only for testing purposes
|
||||
ws.updateTimes.Store(wStat.GetName(), time.Now())
|
||||
|
||||
serverRepo, err := ws.serversRepoFn()
|
||||
if err != nil {
|
||||
return nil, status.Errorf(codes.Internal, "error getting server repo: %v", err)
|
||||
}
|
||||
workerAuthRepo, err := ws.workerAuthRepoFn()
|
||||
if err != nil {
|
||||
return nil, status.Errorf(codes.Internal, "error getting worker auth repo: %v", err)
|
||||
}
|
||||
|
||||
// Convert API tags to storage tags
|
||||
workerTags := make([]*server.Tag, 0, len(wStat.GetTags()))
|
||||
for _, v := range wStat.GetTags() {
|
||||
workerTags = append(workerTags, &server.Tag{
|
||||
Key: v.GetKey(),
|
||||
Value: v.GetValue(),
|
||||
})
|
||||
}
|
||||
|
||||
wConf := server.NewWorker(
|
||||
scope.Global.String(),
|
||||
server.WithName(wStat.GetName()),
|
||||
server.WithDescription(wStat.GetDescription()),
|
||||
server.WithAddress(wStat.GetAddress()),
|
||||
server.WithWorkerTags(workerTags...),
|
||||
server.WithReleaseVersion(wStat.ReleaseVersion),
|
||||
server.WithOperationalState(wStat.OperationalState),
|
||||
server.WithLocalStorageState(wStat.LocalStorageState),
|
||||
)
|
||||
opts := []server.Option{server.WithUpdateTags(req.GetUpdateTags())}
|
||||
if wStat.GetPublicId() != "" {
|
||||
opts = append(opts, server.WithPublicId(wStat.GetPublicId()))
|
||||
}
|
||||
if wStat.GetKeyId() != "" {
|
||||
opts = append(opts, server.WithKeyId(wStat.GetKeyId()))
|
||||
}
|
||||
workerId, err := serverRepo.UpsertWorkerStatus(ctx, wConf, opts...)
|
||||
if err != nil {
|
||||
return nil, status.Errorf(codes.Internal, "Error storing worker status: %v", err)
|
||||
}
|
||||
|
||||
if sbcStates := wStat.GetStorageBucketCredentialStates(); sbcStates != nil {
|
||||
updateWorkerStorageBucketCredentialStatesFn(ctx, serverRepo, workerId, sbcStates)
|
||||
}
|
||||
|
||||
controllers, err := serverRepo.ListControllers(ctx, server.WithLiveness(time.Duration(ws.livenessTimeToStale.Load())))
|
||||
if err != nil {
|
||||
return nil, status.Errorf(codes.Internal, "Error getting current controllers: %v", err)
|
||||
}
|
||||
var upstreamAddresses []string
|
||||
for _, c := range controllers {
|
||||
upstreamAddresses = append(upstreamAddresses, c.Address)
|
||||
}
|
||||
|
||||
authorizedDownstreams, err := server.VerifyKnownAndUnmappedWorkers(
|
||||
ctx,
|
||||
serverRepo,
|
||||
workerAuthRepo,
|
||||
req.GetConnectedWorkerPublicIds(),
|
||||
req.GetConnectedUnmappedWorkerKeyIdentifiers(),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, status.Errorf(codes.Internal, "Error getting known and authorized workers: %v", err)
|
||||
}
|
||||
|
||||
ret := &pbs.RoutingInfoResponse{
|
||||
WorkerId: workerId,
|
||||
CalculatedUpstreamAddresses: upstreamAddresses,
|
||||
AuthorizedDownstreamWorkers: &pbs.AuthorizedDownstreamWorkerList{
|
||||
WorkerPublicIds: authorizedDownstreams.WorkerPublicIds,
|
||||
UnmappedWorkerKeyIdentifiers: authorizedDownstreams.UnmappedWorkerKeyIds,
|
||||
},
|
||||
}
|
||||
return ret, nil
|
||||
}
|
||||
|
||||
// Single-hop filter lookup. We have either an egress filter or worker filter to use, if any
|
||||
// Used to verify that the worker serving this session to a client matches this filter
|
||||
func egressFilterSelector(sessionInfo *session.Session) string {
|
||||
|
||||
@@ -148,7 +148,6 @@ func TestStatus(t *testing.T) {
|
||||
},
|
||||
},
|
||||
WorkerId: worker1.PublicId,
|
||||
AuthorizedWorkers: &pbs.AuthorizedWorkerList{},
|
||||
AuthorizedDownstreamWorkers: &pbs.AuthorizedDownstreamWorkerList{},
|
||||
},
|
||||
},
|
||||
@@ -228,7 +227,6 @@ func TestStatus(t *testing.T) {
|
||||
},
|
||||
},
|
||||
WorkerId: worker1.PublicId,
|
||||
AuthorizedWorkers: &pbs.AuthorizedWorkerList{},
|
||||
AuthorizedDownstreamWorkers: &pbs.AuthorizedDownstreamWorkerList{},
|
||||
JobsRequests: []*pbs.JobChangeRequest{
|
||||
{
|
||||
@@ -336,7 +334,6 @@ func TestStatus(t *testing.T) {
|
||||
},
|
||||
},
|
||||
WorkerId: worker1.PublicId,
|
||||
AuthorizedWorkers: &pbs.AuthorizedWorkerList{},
|
||||
AuthorizedDownstreamWorkers: &pbs.AuthorizedDownstreamWorkerList{},
|
||||
JobsRequests: []*pbs.JobChangeRequest{
|
||||
{
|
||||
@@ -414,7 +411,6 @@ func TestStatus(t *testing.T) {
|
||||
},
|
||||
},
|
||||
WorkerId: worker1.PublicId,
|
||||
AuthorizedWorkers: &pbs.AuthorizedWorkerList{},
|
||||
AuthorizedDownstreamWorkers: &pbs.AuthorizedDownstreamWorkerList{},
|
||||
},
|
||||
},
|
||||
@@ -449,7 +445,7 @@ func TestStatus(t *testing.T) {
|
||||
got, err := s.Status(ctx, tc.req)
|
||||
if tc.wantErr {
|
||||
require.Error(err)
|
||||
assert.Equal(got, &pbs.StatusResponse{})
|
||||
assert.Empty(got)
|
||||
assert.Equal(tc.wantErrMsg, err.Error())
|
||||
return
|
||||
}
|
||||
@@ -468,7 +464,6 @@ func TestStatus(t *testing.T) {
|
||||
pbs.SessionJobInfo{},
|
||||
pbs.MonitorSessionJobInfo{},
|
||||
pbs.Connection{},
|
||||
pbs.AuthorizedWorkerList{},
|
||||
pbs.AuthorizedDownstreamWorkerList{},
|
||||
),
|
||||
cmpopts.IgnoreFields(pb.ServerWorkerStatus{}, "Tags"),
|
||||
@@ -628,7 +623,6 @@ func TestStatusSessionClosed(t *testing.T) {
|
||||
},
|
||||
},
|
||||
WorkerId: worker1.PublicId,
|
||||
AuthorizedWorkers: &pbs.AuthorizedWorkerList{},
|
||||
AuthorizedDownstreamWorkers: &pbs.AuthorizedDownstreamWorkerList{},
|
||||
},
|
||||
},
|
||||
@@ -662,7 +656,6 @@ func TestStatusSessionClosed(t *testing.T) {
|
||||
pbs.Job_SessionInfo{},
|
||||
pbs.SessionJobInfo{},
|
||||
pbs.Connection{},
|
||||
pbs.AuthorizedWorkerList{},
|
||||
pbs.AuthorizedDownstreamWorkerList{},
|
||||
),
|
||||
cmpopts.IgnoreFields(pb.ServerWorkerStatus{}, "Tags"),
|
||||
@@ -797,7 +790,6 @@ func TestStatusDeadConnection(t *testing.T) {
|
||||
},
|
||||
},
|
||||
WorkerId: worker1.PublicId,
|
||||
AuthorizedWorkers: &pbs.AuthorizedWorkerList{},
|
||||
AuthorizedDownstreamWorkers: &pbs.AuthorizedDownstreamWorkerList{},
|
||||
}
|
||||
|
||||
@@ -816,7 +808,6 @@ func TestStatusDeadConnection(t *testing.T) {
|
||||
pbs.Job_SessionInfo{},
|
||||
pbs.SessionJobInfo{},
|
||||
pbs.Connection{},
|
||||
pbs.AuthorizedWorkerList{},
|
||||
pbs.AuthorizedDownstreamWorkerList{},
|
||||
),
|
||||
cmpopts.IgnoreFields(pb.ServerWorkerStatus{}, "Tags"),
|
||||
@@ -952,7 +943,6 @@ func TestStatusWorkerWithKeyId(t *testing.T) {
|
||||
},
|
||||
},
|
||||
WorkerId: worker1.PublicId,
|
||||
AuthorizedWorkers: &pbs.AuthorizedWorkerList{},
|
||||
AuthorizedDownstreamWorkers: &pbs.AuthorizedDownstreamWorkerList{},
|
||||
},
|
||||
},
|
||||
@@ -992,7 +982,6 @@ func TestStatusWorkerWithKeyId(t *testing.T) {
|
||||
},
|
||||
},
|
||||
WorkerId: worker1.PublicId,
|
||||
AuthorizedWorkers: &pbs.AuthorizedWorkerList{},
|
||||
AuthorizedDownstreamWorkers: &pbs.AuthorizedDownstreamWorkerList{},
|
||||
},
|
||||
},
|
||||
@@ -1023,7 +1012,6 @@ func TestStatusWorkerWithKeyId(t *testing.T) {
|
||||
pbs.Job_SessionInfo{},
|
||||
pbs.SessionJobInfo{},
|
||||
pbs.Connection{},
|
||||
pbs.AuthorizedWorkerList{},
|
||||
pbs.AuthorizedDownstreamWorkerList{},
|
||||
),
|
||||
cmpopts.IgnoreFields(pb.ServerWorkerStatus{}, "Tags"),
|
||||
@@ -1094,7 +1082,6 @@ func TestStatusAuthorizedWorkers(t *testing.T) {
|
||||
Name: worker1.GetName(),
|
||||
Address: worker1.GetAddress(),
|
||||
},
|
||||
ConnectedWorkerKeyIdentifiers: []string{},
|
||||
},
|
||||
want: &pbs.StatusResponse{
|
||||
CalculatedUpstreams: []*pbs.UpstreamServer{
|
||||
@@ -1104,7 +1091,6 @@ func TestStatusAuthorizedWorkers(t *testing.T) {
|
||||
},
|
||||
},
|
||||
WorkerId: worker1.PublicId,
|
||||
AuthorizedWorkers: &pbs.AuthorizedWorkerList{},
|
||||
AuthorizedDownstreamWorkers: &pbs.AuthorizedDownstreamWorkerList{},
|
||||
},
|
||||
},
|
||||
@@ -1126,7 +1112,6 @@ func TestStatusAuthorizedWorkers(t *testing.T) {
|
||||
},
|
||||
},
|
||||
WorkerId: worker1.PublicId,
|
||||
AuthorizedWorkers: &pbs.AuthorizedWorkerList{},
|
||||
AuthorizedDownstreamWorkers: &pbs.AuthorizedDownstreamWorkerList{},
|
||||
},
|
||||
},
|
||||
@@ -1139,7 +1124,7 @@ func TestStatusAuthorizedWorkers(t *testing.T) {
|
||||
Name: worker1.GetName(),
|
||||
Address: worker1.GetAddress(),
|
||||
},
|
||||
ConnectedWorkerKeyIdentifiers: []string{w1KeyId, w2KeyId, "unknown"},
|
||||
ConnectedUnmappedWorkerKeyIdentifiers: []string{w1KeyId, w2KeyId, "unknown"},
|
||||
},
|
||||
want: &pbs.StatusResponse{
|
||||
CalculatedUpstreams: []*pbs.UpstreamServer{
|
||||
@@ -1149,10 +1134,9 @@ func TestStatusAuthorizedWorkers(t *testing.T) {
|
||||
},
|
||||
},
|
||||
WorkerId: worker1.PublicId,
|
||||
AuthorizedWorkers: &pbs.AuthorizedWorkerList{
|
||||
WorkerKeyIdentifiers: []string{w1KeyId, w2KeyId},
|
||||
AuthorizedDownstreamWorkers: &pbs.AuthorizedDownstreamWorkerList{
|
||||
UnmappedWorkerKeyIdentifiers: []string{w1KeyId, w2KeyId},
|
||||
},
|
||||
AuthorizedDownstreamWorkers: &pbs.AuthorizedDownstreamWorkerList{},
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -1164,8 +1148,7 @@ func TestStatusAuthorizedWorkers(t *testing.T) {
|
||||
Name: worker1.GetName(),
|
||||
Address: worker1.GetAddress(),
|
||||
},
|
||||
ConnectedWorkerKeyIdentifiers: []string{w1KeyId, w2KeyId, "unknown"},
|
||||
ConnectedUnmappedWorkerKeyIdentifiers: []string{w2KeyId, "unknown"},
|
||||
ConnectedUnmappedWorkerKeyIdentifiers: []string{w1KeyId, w2KeyId, "unknown"},
|
||||
ConnectedWorkerPublicIds: []string{w1.GetPublicId(), "unknown"},
|
||||
},
|
||||
want: &pbs.StatusResponse{
|
||||
@@ -1176,11 +1159,8 @@ func TestStatusAuthorizedWorkers(t *testing.T) {
|
||||
},
|
||||
},
|
||||
WorkerId: worker1.PublicId,
|
||||
AuthorizedWorkers: &pbs.AuthorizedWorkerList{
|
||||
WorkerKeyIdentifiers: []string{w1KeyId, w2KeyId},
|
||||
},
|
||||
AuthorizedDownstreamWorkers: &pbs.AuthorizedDownstreamWorkerList{
|
||||
UnmappedWorkerKeyIdentifiers: []string{w2KeyId},
|
||||
UnmappedWorkerKeyIdentifiers: []string{w1KeyId, w2KeyId},
|
||||
WorkerPublicIds: []string{w1.GetPublicId()},
|
||||
},
|
||||
},
|
||||
@@ -1194,8 +1174,7 @@ func TestStatusAuthorizedWorkers(t *testing.T) {
|
||||
Name: worker1.GetName(),
|
||||
Address: worker1.GetAddress(),
|
||||
},
|
||||
ConnectedWorkerKeyIdentifiers: []string{w1KeyId, w2KeyId, "unknown"},
|
||||
ConnectedUnmappedWorkerKeyIdentifiers: []string{"unknown"},
|
||||
ConnectedUnmappedWorkerKeyIdentifiers: []string{w1KeyId, w2KeyId, "unknown"},
|
||||
ConnectedWorkerPublicIds: []string{w1.GetPublicId(), w2.GetPublicId(), "unknown"},
|
||||
},
|
||||
want: &pbs.StatusResponse{
|
||||
@@ -1206,11 +1185,9 @@ func TestStatusAuthorizedWorkers(t *testing.T) {
|
||||
},
|
||||
},
|
||||
WorkerId: worker1.PublicId,
|
||||
AuthorizedWorkers: &pbs.AuthorizedWorkerList{
|
||||
WorkerKeyIdentifiers: []string{w1KeyId, w2KeyId},
|
||||
},
|
||||
AuthorizedDownstreamWorkers: &pbs.AuthorizedDownstreamWorkerList{
|
||||
WorkerPublicIds: []string{w1.GetPublicId(), w2.GetPublicId()},
|
||||
UnmappedWorkerKeyIdentifiers: []string{w1KeyId, w2KeyId},
|
||||
WorkerPublicIds: []string{w1.GetPublicId(), w2.GetPublicId()},
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -1227,10 +1204,6 @@ func TestStatusAuthorizedWorkers(t *testing.T) {
|
||||
assert.Equal(tc.wantErrMsg, err.Error())
|
||||
return
|
||||
}
|
||||
gotAuthorizedWorkers := got.GetAuthorizedWorkers()
|
||||
sort.Strings(gotAuthorizedWorkers.GetWorkerKeyIdentifiers())
|
||||
wantAuthorizedWorkers := tc.want.GetAuthorizedWorkers()
|
||||
sort.Strings(wantAuthorizedWorkers.GetWorkerKeyIdentifiers())
|
||||
sort.Strings(got.GetAuthorizedDownstreamWorkers().GetWorkerPublicIds())
|
||||
sort.Strings(tc.want.GetAuthorizedDownstreamWorkers().GetWorkerPublicIds())
|
||||
sort.Strings(got.GetAuthorizedDownstreamWorkers().GetUnmappedWorkerKeyIdentifiers())
|
||||
@@ -1248,7 +1221,6 @@ func TestStatusAuthorizedWorkers(t *testing.T) {
|
||||
pbs.Job_SessionInfo{},
|
||||
pbs.SessionJobInfo{},
|
||||
pbs.Connection{},
|
||||
pbs.AuthorizedWorkerList{},
|
||||
pbs.AuthorizedDownstreamWorkerList{},
|
||||
),
|
||||
cmpopts.IgnoreFields(pb.ServerWorkerStatus{}, "Tags"),
|
||||
|
||||
@@ -6,6 +6,7 @@ package handlers
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
@@ -16,12 +17,14 @@ import (
|
||||
"github.com/hashicorp/boundary/internal/authtoken"
|
||||
credstatic "github.com/hashicorp/boundary/internal/credential/static"
|
||||
"github.com/hashicorp/boundary/internal/db"
|
||||
pb "github.com/hashicorp/boundary/internal/gen/controller/servers"
|
||||
pbs "github.com/hashicorp/boundary/internal/gen/controller/servers/services"
|
||||
intglobals "github.com/hashicorp/boundary/internal/globals"
|
||||
"github.com/hashicorp/boundary/internal/host/static"
|
||||
"github.com/hashicorp/boundary/internal/iam"
|
||||
"github.com/hashicorp/boundary/internal/kms"
|
||||
"github.com/hashicorp/boundary/internal/server"
|
||||
"github.com/hashicorp/boundary/internal/server/store"
|
||||
"github.com/hashicorp/boundary/internal/session"
|
||||
"github.com/hashicorp/boundary/internal/target"
|
||||
"github.com/hashicorp/boundary/internal/target/tcp"
|
||||
@@ -31,6 +34,8 @@ import (
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"golang.org/x/crypto/ssh/testdata"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
"google.golang.org/protobuf/proto"
|
||||
"google.golang.org/protobuf/testing/protocmp"
|
||||
)
|
||||
@@ -629,3 +634,800 @@ func TestHcpbWorkers(t *testing.T) {
|
||||
}
|
||||
assert.ElementsMatch(expValues, gotValues)
|
||||
}
|
||||
|
||||
func TestStatistics(t *testing.T) {
|
||||
t.Parallel()
|
||||
ctx := context.Background()
|
||||
conn, _ := db.TestSetup(t, "postgres")
|
||||
rw := db.New(conn)
|
||||
wrapper := db.TestWrapper(t)
|
||||
kms := kms.TestKms(t, conn, wrapper)
|
||||
serversRepoFn := func() (*server.Repository, error) {
|
||||
return server.NewRepository(ctx, rw, rw, kms)
|
||||
}
|
||||
workerAuthRepoFn := func() (*server.WorkerAuthRepositoryStorage, error) {
|
||||
return server.NewRepositoryStorage(ctx, rw, rw, kms)
|
||||
}
|
||||
sessionRepoFn := func(opts ...session.Option) (*session.Repository, error) {
|
||||
return session.NewRepository(ctx, rw, rw, kms, opts...)
|
||||
}
|
||||
connectionRepoFn := func() (*session.ConnectionRepository, error) {
|
||||
return session.NewConnectionRepository(ctx, rw, rw, kms)
|
||||
}
|
||||
connectionRepoErrFn := func() (*session.ConnectionRepository, error) {
|
||||
return nil, fmt.Errorf("test error")
|
||||
}
|
||||
fce := &fakeControllerExtension{
|
||||
reader: rw,
|
||||
writer: rw,
|
||||
}
|
||||
cases := []struct {
|
||||
name string
|
||||
workerService *workerServiceServer
|
||||
wantErrMsg string
|
||||
expectedStatusCode codes.Code
|
||||
req *pbs.StatisticsRequest
|
||||
}{
|
||||
{
|
||||
name: "empty worker id",
|
||||
workerService: NewWorkerServiceServer(serversRepoFn, workerAuthRepoFn, sessionRepoFn, connectionRepoFn, nil, new(sync.Map), kms, new(atomic.Int64), fce),
|
||||
req: &pbs.StatisticsRequest{},
|
||||
wantErrMsg: "rpc error: code = InvalidArgument desc = worker id is empty",
|
||||
expectedStatusCode: codes.InvalidArgument,
|
||||
},
|
||||
{
|
||||
name: "missing session connection repo",
|
||||
workerService: NewWorkerServiceServer(serversRepoFn, workerAuthRepoFn, sessionRepoFn, connectionRepoErrFn, nil, new(sync.Map), kms, new(atomic.Int64), fce),
|
||||
req: &pbs.StatisticsRequest{
|
||||
WorkerId: "w_1234567890",
|
||||
Sessions: []*pbs.SessionStatistics{
|
||||
{},
|
||||
},
|
||||
},
|
||||
wantErrMsg: "rpc error: code = Internal desc = Error acquiring connection repo: test error",
|
||||
expectedStatusCode: codes.Internal,
|
||||
},
|
||||
{
|
||||
name: "nil sessions",
|
||||
workerService: NewWorkerServiceServer(serversRepoFn, workerAuthRepoFn, sessionRepoFn, connectionRepoFn, nil, new(sync.Map), kms, new(atomic.Int64), fce),
|
||||
req: &pbs.StatisticsRequest{
|
||||
WorkerId: "w_1234567890",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "empty sessions",
|
||||
workerService: NewWorkerServiceServer(serversRepoFn, workerAuthRepoFn, sessionRepoFn, connectionRepoFn, nil, new(sync.Map), kms, new(atomic.Int64), fce),
|
||||
req: &pbs.StatisticsRequest{
|
||||
WorkerId: "w_1234567890",
|
||||
Sessions: []*pbs.SessionStatistics{},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "empty session id",
|
||||
workerService: NewWorkerServiceServer(serversRepoFn, workerAuthRepoFn, sessionRepoFn, connectionRepoFn, nil, new(sync.Map), kms, new(atomic.Int64), fce),
|
||||
req: &pbs.StatisticsRequest{
|
||||
WorkerId: "w_1234567890",
|
||||
Sessions: []*pbs.SessionStatistics{
|
||||
{},
|
||||
},
|
||||
},
|
||||
wantErrMsg: "rpc error: code = InvalidArgument desc = session id is empty",
|
||||
expectedStatusCode: codes.InvalidArgument,
|
||||
},
|
||||
{
|
||||
name: "empty connection id",
|
||||
workerService: NewWorkerServiceServer(serversRepoFn, workerAuthRepoFn, sessionRepoFn, connectionRepoFn, nil, new(sync.Map), kms, new(atomic.Int64), fce),
|
||||
req: &pbs.StatisticsRequest{
|
||||
WorkerId: "w_1234567890",
|
||||
Sessions: []*pbs.SessionStatistics{
|
||||
{
|
||||
SessionId: "s_1234567890",
|
||||
Connections: []*pbs.Connection{
|
||||
{},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
wantErrMsg: "rpc error: code = InvalidArgument desc = connection id is empty",
|
||||
expectedStatusCode: codes.InvalidArgument,
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
assert, require := assert.New(t), require.New(t)
|
||||
got, err := tc.workerService.Statistics(context.Background(), tc.req)
|
||||
require.NotNil(got)
|
||||
if tc.wantErrMsg != "" {
|
||||
require.Error(err)
|
||||
assert.ErrorContains(err, tc.wantErrMsg)
|
||||
actualStatus, ok := status.FromError(err)
|
||||
require.True(ok)
|
||||
assert.Equal(tc.expectedStatusCode, actualStatus.Code())
|
||||
return
|
||||
}
|
||||
require.NoError(err)
|
||||
})
|
||||
}
|
||||
|
||||
// update the bytes up and bytes down for an active session and close an orphaned session connection
|
||||
t.Run("happy path", func(t *testing.T) {
|
||||
assert, require := assert.New(t), require.New(t)
|
||||
connectionRepoFn := func() (*session.ConnectionRepository, error) {
|
||||
return session.NewConnectionRepository(ctx, rw, rw, kms, session.WithWorkerStateDelay(0))
|
||||
}
|
||||
sessRepo, err := sessionRepoFn()
|
||||
require.NoError(err)
|
||||
connRepo, err := connectionRepoFn()
|
||||
require.NoError(err)
|
||||
|
||||
w := server.TestKmsWorker(t, conn, wrapper)
|
||||
org, prj := iam.TestScopes(t, iam.TestRepo(t, conn, wrapper))
|
||||
authToken := authtoken.TestAuthToken(t, conn, kms, org.GetPublicId())
|
||||
userId := authToken.GetIamUserId()
|
||||
hostCatalog := static.TestCatalogs(t, conn, prj.GetPublicId(), 1)[0]
|
||||
hostSet := static.TestSets(t, conn, hostCatalog.GetPublicId(), 1)[0]
|
||||
host := static.TestHosts(t, conn, hostCatalog.GetPublicId(), 1)[0]
|
||||
static.TestSetMembers(t, conn, hostSet.GetPublicId(), []*static.Host{host})
|
||||
tar := tcp.TestTarget(
|
||||
context.Background(),
|
||||
t, conn, prj.GetPublicId(), "test",
|
||||
target.WithHostSources([]string{hostSet.GetPublicId()}),
|
||||
target.WithSessionConnectionLimit(-1),
|
||||
)
|
||||
s1 := session.TestSession(t, conn, wrapper, session.ComposedOf{
|
||||
UserId: userId,
|
||||
HostId: host.GetPublicId(),
|
||||
TargetId: tar.GetPublicId(),
|
||||
HostSetId: hostSet.GetPublicId(),
|
||||
AuthTokenId: authToken.GetPublicId(),
|
||||
ProjectId: prj.GetPublicId(),
|
||||
Endpoint: "tcp://127.0.0.1:22",
|
||||
ConnectionLimit: 10,
|
||||
})
|
||||
s1, _, err = sessRepo.ActivateSession(context.Background(), s1.PublicId, s1.Version, session.TestTofu(t))
|
||||
require.NoError(err)
|
||||
c1, err := connRepo.AuthorizeConnection(context.Background(), s1.PublicId, w.GetPublicId())
|
||||
require.NoError(err)
|
||||
|
||||
s2 := session.TestSession(t, conn, wrapper, session.ComposedOf{
|
||||
UserId: userId,
|
||||
HostId: host.GetPublicId(),
|
||||
TargetId: tar.GetPublicId(),
|
||||
HostSetId: hostSet.GetPublicId(),
|
||||
AuthTokenId: authToken.GetPublicId(),
|
||||
ProjectId: prj.GetPublicId(),
|
||||
Endpoint: "tcp://127.0.0.1:22",
|
||||
ConnectionLimit: 10,
|
||||
})
|
||||
s2, _, err = sessRepo.ActivateSession(context.Background(), s2.PublicId, s2.Version, session.TestTofu(t))
|
||||
require.NoError(err)
|
||||
c2, err := connRepo.AuthorizeConnection(context.Background(), s2.PublicId, w.PublicId)
|
||||
require.NoError(err)
|
||||
|
||||
var expectedBytesUp int64 = 1024
|
||||
var expectedBytesDown int64 = 2048
|
||||
workerService := NewWorkerServiceServer(serversRepoFn, workerAuthRepoFn, sessionRepoFn, connectionRepoFn, nil, new(sync.Map), kms, new(atomic.Int64), fce)
|
||||
got, err := workerService.Statistics(context.Background(), &pbs.StatisticsRequest{
|
||||
WorkerId: w.GetPublicId(),
|
||||
Sessions: []*pbs.SessionStatistics{
|
||||
{
|
||||
SessionId: s1.PublicId,
|
||||
Connections: []*pbs.Connection{
|
||||
{
|
||||
ConnectionId: c1.PublicId,
|
||||
BytesUp: expectedBytesUp,
|
||||
BytesDown: expectedBytesDown,
|
||||
Status: pbs.CONNECTIONSTATUS_CONNECTIONSTATUS_AUTHORIZED,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
require.NoError(err)
|
||||
assert.NotNil(got)
|
||||
|
||||
conn, err := connRepo.LookupConnection(context.Background(), c1.PublicId)
|
||||
require.NoError(err)
|
||||
assert.Equal(expectedBytesUp, conn.BytesUp)
|
||||
assert.Equal(expectedBytesDown, conn.BytesDown)
|
||||
assert.Equal(session.StatusAuthorized, session.ConnectionStatusFromString(conn.Status))
|
||||
|
||||
conn, err = connRepo.LookupConnection(context.Background(), c2.PublicId)
|
||||
require.NoError(err)
|
||||
assert.Empty(conn.BytesUp)
|
||||
assert.Empty(conn.BytesDown)
|
||||
assert.Equal(session.StatusClosed, session.ConnectionStatusFromString(conn.Status))
|
||||
})
|
||||
}
|
||||
|
||||
func TestSessionInfo(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx := context.Background()
|
||||
conn, _ := db.TestSetup(t, "postgres")
|
||||
rw := db.New(conn)
|
||||
wrapper := db.TestWrapper(t)
|
||||
testKms := kms.TestKms(t, conn, wrapper)
|
||||
serversRepoFn := func() (*server.Repository, error) {
|
||||
return server.NewRepository(ctx, rw, rw, testKms)
|
||||
}
|
||||
workerAuthRepoFn := func() (*server.WorkerAuthRepositoryStorage, error) {
|
||||
return server.NewRepositoryStorage(ctx, rw, rw, testKms)
|
||||
}
|
||||
sessionRepoFn := func(opts ...session.Option) (*session.Repository, error) {
|
||||
return session.NewRepository(ctx, rw, rw, testKms, opts...)
|
||||
}
|
||||
connectionRepoFn := func() (*session.ConnectionRepository, error) {
|
||||
return session.NewConnectionRepository(ctx, rw, rw, testKms)
|
||||
}
|
||||
serversErrRepoFn := func() (*server.Repository, error) {
|
||||
return nil, errors.New("unknown error")
|
||||
}
|
||||
sessionErrRepoFn := func(opt ...session.Option) (*session.Repository, error) {
|
||||
return nil, errors.New("unknown error")
|
||||
}
|
||||
fce := &fakeControllerExtension{
|
||||
reader: rw,
|
||||
writer: rw,
|
||||
}
|
||||
iamRepo := iam.TestRepo(t, conn, wrapper)
|
||||
iam.TestScopes(t, iamRepo)
|
||||
workerId := server.TestPkiWorker(t, conn, wrapper).PublicId
|
||||
cases := []struct {
|
||||
name string
|
||||
workerService *workerServiceServer
|
||||
wantErrMsg string
|
||||
expectedStatusCode codes.Code
|
||||
req *pbs.SessionInfoRequest
|
||||
expectedResponse *pbs.SessionInfoResponse
|
||||
}{
|
||||
{
|
||||
name: "empty worker id",
|
||||
workerService: NewWorkerServiceServer(serversRepoFn, workerAuthRepoFn, sessionRepoFn, connectionRepoFn, nil, new(sync.Map), testKms, new(atomic.Int64), fce),
|
||||
req: &pbs.SessionInfoRequest{},
|
||||
wantErrMsg: "rpc error: code = InvalidArgument desc = worker id is empty",
|
||||
expectedStatusCode: codes.InvalidArgument,
|
||||
},
|
||||
{
|
||||
name: "invalid unspecified session type",
|
||||
workerService: NewWorkerServiceServer(serversRepoFn, workerAuthRepoFn, sessionRepoFn, connectionRepoFn, nil, new(sync.Map), testKms, new(atomic.Int64), fce),
|
||||
req: &pbs.SessionInfoRequest{
|
||||
WorkerId: "w_1234567890",
|
||||
Sessions: []*pbs.Session{
|
||||
{
|
||||
SessionId: "s_A",
|
||||
SessionType: pbs.SessionType_SESSION_TYPE_UNSPECIFIED,
|
||||
SessionStatus: pbs.SESSIONSTATUS_SESSIONSTATUS_ACTIVE,
|
||||
},
|
||||
},
|
||||
},
|
||||
wantErrMsg: "rpc error: code = InvalidArgument desc = unspecified session type",
|
||||
expectedStatusCode: codes.InvalidArgument,
|
||||
},
|
||||
{
|
||||
name: "invalid unknown session type",
|
||||
workerService: NewWorkerServiceServer(serversRepoFn, workerAuthRepoFn, sessionRepoFn, connectionRepoFn, nil, new(sync.Map), testKms, new(atomic.Int64), fce),
|
||||
req: &pbs.SessionInfoRequest{
|
||||
WorkerId: "w_1234567890",
|
||||
Sessions: []*pbs.Session{
|
||||
{
|
||||
SessionId: "s_A",
|
||||
SessionType: pbs.SessionType(-1),
|
||||
SessionStatus: pbs.SESSIONSTATUS_SESSIONSTATUS_ACTIVE,
|
||||
},
|
||||
},
|
||||
},
|
||||
wantErrMsg: "rpc error: code = InvalidArgument desc = unknown session type",
|
||||
expectedStatusCode: codes.InvalidArgument,
|
||||
},
|
||||
{
|
||||
name: "session repository error",
|
||||
workerService: NewWorkerServiceServer(serversRepoFn, workerAuthRepoFn, sessionErrRepoFn, connectionRepoFn, nil, new(sync.Map), testKms, new(atomic.Int64), fce),
|
||||
req: &pbs.SessionInfoRequest{
|
||||
WorkerId: "w_1234567890",
|
||||
},
|
||||
wantErrMsg: "rpc error: code = Internal desc = Error acquiring repo to query session status: unknown error",
|
||||
expectedStatusCode: codes.Internal,
|
||||
},
|
||||
{
|
||||
name: "server repository error",
|
||||
workerService: NewWorkerServiceServer(serversErrRepoFn, workerAuthRepoFn, sessionRepoFn, connectionRepoFn, nil, new(sync.Map), testKms, new(atomic.Int64), fce),
|
||||
req: &pbs.SessionInfoRequest{
|
||||
WorkerId: "w_1234567890",
|
||||
},
|
||||
wantErrMsg: "rpc error: code = Internal desc = Error acquiring repo to upsert session info status time: unknown error",
|
||||
expectedStatusCode: codes.Internal,
|
||||
},
|
||||
{
|
||||
name: "ignore canceled and terminated sessions",
|
||||
workerService: NewWorkerServiceServer(serversRepoFn, workerAuthRepoFn, sessionRepoFn, connectionRepoFn, nil, new(sync.Map), testKms, new(atomic.Int64), fce),
|
||||
req: &pbs.SessionInfoRequest{
|
||||
WorkerId: workerId,
|
||||
Sessions: []*pbs.Session{
|
||||
{
|
||||
SessionId: "s_A",
|
||||
SessionStatus: pbs.SESSIONSTATUS_SESSIONSTATUS_CANCELING,
|
||||
SessionType: pbs.SessionType_SESSION_TYPE_INGRESSED,
|
||||
},
|
||||
{
|
||||
SessionId: "s_B",
|
||||
SessionStatus: pbs.SESSIONSTATUS_SESSIONSTATUS_TERMINATED,
|
||||
SessionType: pbs.SessionType_SESSION_TYPE_INGRESSED,
|
||||
},
|
||||
{
|
||||
SessionId: "s_C",
|
||||
SessionStatus: pbs.SESSIONSTATUS_SESSIONSTATUS_CANCELING,
|
||||
SessionType: pbs.SessionType_SESSION_TYPE_RECORDED,
|
||||
},
|
||||
{
|
||||
SessionId: "s_D",
|
||||
SessionStatus: pbs.SESSIONSTATUS_SESSIONSTATUS_TERMINATED,
|
||||
SessionType: pbs.SessionType_SESSION_TYPE_RECORDED,
|
||||
},
|
||||
},
|
||||
},
|
||||
expectedResponse: &pbs.SessionInfoResponse{},
|
||||
},
|
||||
{
|
||||
name: "empty sessions",
|
||||
workerService: NewWorkerServiceServer(serversRepoFn, workerAuthRepoFn, sessionRepoFn, connectionRepoFn, nil, new(sync.Map), testKms, new(atomic.Int64), fce),
|
||||
req: &pbs.SessionInfoRequest{
|
||||
WorkerId: workerId,
|
||||
},
|
||||
expectedResponse: &pbs.SessionInfoResponse{},
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
assert, require := assert.New(t), require.New(t)
|
||||
got, err := tc.workerService.SessionInfo(context.Background(), tc.req)
|
||||
require.NotNil(got)
|
||||
if tc.wantErrMsg != "" {
|
||||
require.Error(err)
|
||||
assert.ErrorContains(err, tc.wantErrMsg)
|
||||
actualStatus, ok := status.FromError(err)
|
||||
require.True(ok)
|
||||
assert.Equal(tc.expectedStatusCode, actualStatus.Code())
|
||||
return
|
||||
}
|
||||
require.NoError(err)
|
||||
require.NotNil(got)
|
||||
assert.Len(got.NonActiveSessions, len(tc.expectedResponse.NonActiveSessions))
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("session canceled with active connections", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
assert, require := assert.New(t), require.New(t)
|
||||
sessionTypes := []pbs.SessionType{
|
||||
pbs.SessionType_SESSION_TYPE_INGRESSED,
|
||||
pbs.SessionType_SESSION_TYPE_RECORDED,
|
||||
}
|
||||
for _, sessionType := range sessionTypes {
|
||||
t.Run(sessionType.String(), func(t *testing.T) {
|
||||
t.Parallel()
|
||||
ctx := context.Background()
|
||||
conn, _ := db.TestSetup(t, "postgres")
|
||||
rw := db.New(conn)
|
||||
wrapper := db.TestWrapper(t)
|
||||
testKms := kms.TestKms(t, conn, wrapper)
|
||||
org, prj := iam.TestScopes(t, iam.TestRepo(t, conn, wrapper))
|
||||
|
||||
serverRepo, err := server.NewRepository(ctx, rw, rw, testKms)
|
||||
require.NoError(err)
|
||||
c := &store.Controller{
|
||||
PrivateId: "test_controller1",
|
||||
Address: "127.0.0.1",
|
||||
}
|
||||
_, err = serverRepo.UpsertController(ctx, c)
|
||||
require.NoError(err)
|
||||
|
||||
serversRepoFn := func() (*server.Repository, error) {
|
||||
return serverRepo, nil
|
||||
}
|
||||
workerAuthRepoFn := func() (*server.WorkerAuthRepositoryStorage, error) {
|
||||
return server.NewRepositoryStorage(ctx, rw, rw, testKms)
|
||||
}
|
||||
sessionRepoFn := func(opts ...session.Option) (*session.Repository, error) {
|
||||
return session.NewRepository(ctx, rw, rw, testKms, opts...)
|
||||
}
|
||||
connRepoFn := func() (*session.ConnectionRepository, error) {
|
||||
return session.NewConnectionRepository(ctx, rw, rw, testKms)
|
||||
}
|
||||
fce := &fakeControllerExtension{
|
||||
reader: rw,
|
||||
writer: rw,
|
||||
}
|
||||
|
||||
repo, err := sessionRepoFn()
|
||||
require.NoError(err)
|
||||
connRepo, err := connRepoFn()
|
||||
require.NoError(err)
|
||||
|
||||
at := authtoken.TestAuthToken(t, conn, testKms, org.GetPublicId())
|
||||
uId := at.GetIamUserId()
|
||||
hc := static.TestCatalogs(t, conn, prj.GetPublicId(), 1)[0]
|
||||
hs := static.TestSets(t, conn, hc.GetPublicId(), 1)[0]
|
||||
h := static.TestHosts(t, conn, hc.GetPublicId(), 1)[0]
|
||||
static.TestSetMembers(t, conn, hs.GetPublicId(), []*static.Host{h})
|
||||
tar := tcp.TestTarget(
|
||||
ctx,
|
||||
t, conn, prj.GetPublicId(), "test",
|
||||
target.WithHostSources([]string{hs.GetPublicId()}),
|
||||
target.WithSessionConnectionLimit(-1),
|
||||
)
|
||||
|
||||
worker1 := server.TestKmsWorker(t, conn, wrapper)
|
||||
sess := session.TestSession(t, conn, wrapper, session.ComposedOf{
|
||||
UserId: uId,
|
||||
HostId: h.GetPublicId(),
|
||||
TargetId: tar.GetPublicId(),
|
||||
HostSetId: hs.GetPublicId(),
|
||||
AuthTokenId: at.GetPublicId(),
|
||||
ProjectId: prj.GetPublicId(),
|
||||
Endpoint: "tcp://127.0.0.1:22",
|
||||
ConnectionLimit: 10,
|
||||
})
|
||||
tofu := session.TestTofu(t)
|
||||
sess, _, err = repo.ActivateSession(ctx, sess.PublicId, sess.Version, tofu)
|
||||
require.NoError(err)
|
||||
sess2 := session.TestSession(t, conn, wrapper, session.ComposedOf{
|
||||
UserId: uId,
|
||||
HostId: h.GetPublicId(),
|
||||
TargetId: tar.GetPublicId(),
|
||||
HostSetId: hs.GetPublicId(),
|
||||
AuthTokenId: at.GetPublicId(),
|
||||
ProjectId: prj.GetPublicId(),
|
||||
Endpoint: "tcp://127.0.0.1:22",
|
||||
ConnectionLimit: 10,
|
||||
})
|
||||
tofu2 := session.TestTofu(t)
|
||||
sess2, _, err = repo.ActivateSession(ctx, sess2.PublicId, sess2.Version, tofu2)
|
||||
require.NoError(err)
|
||||
|
||||
s := NewWorkerServiceServer(serversRepoFn, workerAuthRepoFn, sessionRepoFn, connRepoFn, nil, new(sync.Map), testKms, new(atomic.Int64), fce)
|
||||
require.NotNil(t, s)
|
||||
|
||||
_, err = connRepo.AuthorizeConnection(ctx, sess.PublicId, worker1.PublicId)
|
||||
require.NoError(err)
|
||||
|
||||
_, err = connRepo.AuthorizeConnection(ctx, sess2.PublicId, worker1.PublicId)
|
||||
require.NoError(err)
|
||||
|
||||
_, err = repo.CancelSession(ctx, sess2.PublicId, sess.Version)
|
||||
require.NoError(err)
|
||||
|
||||
got, err := s.SessionInfo(ctx, &pbs.SessionInfoRequest{
|
||||
WorkerId: worker1.GetPublicId(),
|
||||
Sessions: []*pbs.Session{
|
||||
{
|
||||
SessionId: sess2.PublicId,
|
||||
SessionStatus: pbs.SESSIONSTATUS_SESSIONSTATUS_ACTIVE,
|
||||
SessionType: sessionType,
|
||||
},
|
||||
},
|
||||
})
|
||||
require.NoError(err)
|
||||
require.NotNil(got)
|
||||
require.Len(got.NonActiveSessions, 1)
|
||||
actualNonActiveSession := got.NonActiveSessions[0]
|
||||
require.NotNil(actualNonActiveSession)
|
||||
assert.Equal(sess2.PublicId, actualNonActiveSession.SessionId)
|
||||
assert.Equal(pbs.SESSIONSTATUS_SESSIONSTATUS_CANCELING, actualNonActiveSession.SessionStatus)
|
||||
assert.Equal(sessionType, actualNonActiveSession.SessionType)
|
||||
assert.Empty(actualNonActiveSession.Connections)
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestRoutingInfo(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx := context.Background()
|
||||
conn, _ := db.TestSetup(t, "postgres")
|
||||
rw := db.New(conn)
|
||||
wrapper := db.TestWrapper(t)
|
||||
kmsCache := kms.TestKms(t, conn, wrapper)
|
||||
require.NoError(t, kmsCache.CreateKeys(context.Background(), scope.Global.String(), kms.WithRandomReader(rand.Reader)))
|
||||
|
||||
serversRepoFn := func() (*server.Repository, error) {
|
||||
return server.NewRepository(ctx, rw, rw, kmsCache)
|
||||
}
|
||||
workerAuthRepoFn := func() (*server.WorkerAuthRepositoryStorage, error) {
|
||||
return server.NewRepositoryStorage(ctx, rw, rw, kmsCache)
|
||||
}
|
||||
sessionRepoFn := func(opts ...session.Option) (*session.Repository, error) {
|
||||
return session.NewRepository(ctx, rw, rw, kmsCache, opts...)
|
||||
}
|
||||
connectionRepoFn := func() (*session.ConnectionRepository, error) {
|
||||
return session.NewConnectionRepository(ctx, rw, rw, kmsCache)
|
||||
}
|
||||
var liveDur atomic.Int64
|
||||
liveDur.Store(int64(1 * time.Second))
|
||||
fce := &fakeControllerExtension{
|
||||
reader: rw,
|
||||
writer: rw,
|
||||
}
|
||||
serverRepo, err := serversRepoFn()
|
||||
require.NoError(t, err)
|
||||
|
||||
// Set up resources
|
||||
var w1KeyId, w2KeyId string
|
||||
w1 := server.TestPkiWorker(t, conn, wrapper, server.WithTestPkiWorkerAuthorizedKeyId(&w1KeyId))
|
||||
_ = server.TestPkiWorker(t, conn, wrapper, server.WithTestPkiWorkerAuthorizedKeyId(&w2KeyId))
|
||||
w3 := server.TestKmsWorker(t, conn, wrapper, server.WithName("testworker3"))
|
||||
|
||||
c := &store.Controller{
|
||||
PrivateId: "test_controller1",
|
||||
Address: "1.2.3.4",
|
||||
}
|
||||
_, err = serverRepo.UpsertController(ctx, c)
|
||||
require.NoError(t, err)
|
||||
|
||||
s := NewWorkerServiceServer(serversRepoFn, workerAuthRepoFn, sessionRepoFn, connectionRepoFn, nil, new(sync.Map), kmsCache, &liveDur, fce)
|
||||
require.NotNil(t, s)
|
||||
require.NoError(t, err)
|
||||
|
||||
t.Run("Missing worker status", func(t *testing.T) {
|
||||
req := &pbs.RoutingInfoRequest{}
|
||||
_, err := s.RoutingInfo(ctx, req)
|
||||
require.ErrorContains(t, err, "worker status is required")
|
||||
})
|
||||
|
||||
t.Run("Missing key ID and public Id", func(t *testing.T) {
|
||||
req := &pbs.RoutingInfoRequest{
|
||||
WorkerStatus: &pb.ServerWorkerStatus{
|
||||
PublicId: "",
|
||||
KeyId: "",
|
||||
Address: "2.3.4.5:8080",
|
||||
Tags: []*pb.TagPair{
|
||||
{Key: "tag1", Value: "value1"},
|
||||
{Key: "tag2", Value: "value2"},
|
||||
},
|
||||
ReleaseVersion: "Boundary v0.18.0",
|
||||
OperationalState: server.ActiveOperationalState.String(),
|
||||
LocalStorageState: server.AvailableLocalStorageState.String(),
|
||||
},
|
||||
UpdateTags: true,
|
||||
ConnectedUnmappedWorkerKeyIdentifiers: []string{w2KeyId, "worker-key-2"},
|
||||
ConnectedWorkerPublicIds: []string{w3.PublicId, "worker-3"},
|
||||
}
|
||||
_, err := s.RoutingInfo(ctx, req)
|
||||
require.ErrorContains(t, err, "public id, key id and name are not set in the request; one is required")
|
||||
})
|
||||
|
||||
t.Run("Missing address", func(t *testing.T) {
|
||||
req := &pbs.RoutingInfoRequest{
|
||||
WorkerStatus: &pb.ServerWorkerStatus{
|
||||
PublicId: "",
|
||||
KeyId: w1KeyId,
|
||||
Address: "",
|
||||
Tags: []*pb.TagPair{
|
||||
{Key: "tag1", Value: "value1"},
|
||||
{Key: "tag2", Value: "value2"},
|
||||
},
|
||||
ReleaseVersion: "Boundary v0.18.0",
|
||||
OperationalState: server.ActiveOperationalState.String(),
|
||||
LocalStorageState: server.AvailableLocalStorageState.String(),
|
||||
},
|
||||
UpdateTags: true,
|
||||
ConnectedUnmappedWorkerKeyIdentifiers: []string{w2KeyId, "worker-key-2"},
|
||||
ConnectedWorkerPublicIds: []string{w3.PublicId, "worker-3"},
|
||||
}
|
||||
_, err := s.RoutingInfo(ctx, req)
|
||||
require.ErrorContains(t, err, "address is not set but is required")
|
||||
})
|
||||
|
||||
t.Run("Missing release version", func(t *testing.T) {
|
||||
req := &pbs.RoutingInfoRequest{
|
||||
WorkerStatus: &pb.ServerWorkerStatus{
|
||||
PublicId: "",
|
||||
KeyId: w1KeyId,
|
||||
Address: "2.3.4.5:8080",
|
||||
Tags: []*pb.TagPair{
|
||||
{Key: "tag1", Value: "value1"},
|
||||
{Key: "tag2", Value: "value2"},
|
||||
},
|
||||
ReleaseVersion: "",
|
||||
OperationalState: server.ActiveOperationalState.String(),
|
||||
LocalStorageState: server.AvailableLocalStorageState.String(),
|
||||
},
|
||||
UpdateTags: true,
|
||||
ConnectedUnmappedWorkerKeyIdentifiers: []string{w2KeyId, "worker-key-2"},
|
||||
ConnectedWorkerPublicIds: []string{w3.PublicId, "worker-3"},
|
||||
}
|
||||
_, err := s.RoutingInfo(ctx, req)
|
||||
require.ErrorContains(t, err, "release version is not set but is required")
|
||||
})
|
||||
|
||||
t.Run("Missing operational state", func(t *testing.T) {
|
||||
req := &pbs.RoutingInfoRequest{
|
||||
WorkerStatus: &pb.ServerWorkerStatus{
|
||||
PublicId: "",
|
||||
KeyId: w1KeyId,
|
||||
Address: "2.3.4.5:8080",
|
||||
Tags: []*pb.TagPair{
|
||||
{Key: "tag1", Value: "value1"},
|
||||
{Key: "tag2", Value: "value2"},
|
||||
},
|
||||
ReleaseVersion: "Boundary v0.18.0",
|
||||
OperationalState: "",
|
||||
LocalStorageState: server.AvailableLocalStorageState.String(),
|
||||
},
|
||||
UpdateTags: true,
|
||||
ConnectedUnmappedWorkerKeyIdentifiers: []string{w2KeyId, "worker-key-2"},
|
||||
ConnectedWorkerPublicIds: []string{w3.PublicId, "worker-3"},
|
||||
}
|
||||
_, err := s.RoutingInfo(ctx, req)
|
||||
require.ErrorContains(t, err, "operational state is not set but is required")
|
||||
})
|
||||
|
||||
t.Run("Missing local storage state", func(t *testing.T) {
|
||||
req := &pbs.RoutingInfoRequest{
|
||||
WorkerStatus: &pb.ServerWorkerStatus{
|
||||
PublicId: "",
|
||||
KeyId: w1KeyId,
|
||||
Address: "2.3.4.5:8080",
|
||||
Tags: []*pb.TagPair{
|
||||
{Key: "tag1", Value: "value1"},
|
||||
{Key: "tag2", Value: "value2"},
|
||||
},
|
||||
ReleaseVersion: "Boundary v0.18.0",
|
||||
OperationalState: server.ActiveOperationalState.String(),
|
||||
LocalStorageState: "",
|
||||
},
|
||||
UpdateTags: true,
|
||||
ConnectedUnmappedWorkerKeyIdentifiers: []string{w2KeyId, "worker-key-2"},
|
||||
ConnectedWorkerPublicIds: []string{w3.PublicId, "worker-3"},
|
||||
}
|
||||
_, err := s.RoutingInfo(ctx, req)
|
||||
require.ErrorContains(t, err, "local storage state is not set but is required")
|
||||
})
|
||||
|
||||
t.Run("Successful first and second request (PKI worker)", func(t *testing.T) {
|
||||
req := &pbs.RoutingInfoRequest{
|
||||
WorkerStatus: &pb.ServerWorkerStatus{
|
||||
PublicId: "", // Not set on the first request
|
||||
KeyId: w1KeyId,
|
||||
Address: "2.3.4.5:8080",
|
||||
Tags: []*pb.TagPair{
|
||||
{Key: "tag1", Value: "value1"},
|
||||
{Key: "tag2", Value: "value2"},
|
||||
},
|
||||
ReleaseVersion: "Boundary v0.18.0",
|
||||
OperationalState: server.ActiveOperationalState.String(),
|
||||
LocalStorageState: server.AvailableLocalStorageState.String(),
|
||||
},
|
||||
UpdateTags: true,
|
||||
ConnectedUnmappedWorkerKeyIdentifiers: []string{w2KeyId, "worker-key-2"},
|
||||
ConnectedWorkerPublicIds: []string{w3.PublicId, "worker-3"},
|
||||
}
|
||||
resp, err := s.RoutingInfo(ctx, req)
|
||||
require.NoError(t, err)
|
||||
assert.NotNil(t, resp)
|
||||
|
||||
assert.Equal(t, resp.WorkerId, w1.PublicId)
|
||||
assert.Equal(t, resp.CalculatedUpstreamAddresses, []string{c.Address})
|
||||
assert.Equal(t, resp.AuthorizedDownstreamWorkers.UnmappedWorkerKeyIdentifiers, []string{w2KeyId})
|
||||
assert.Equal(t, resp.AuthorizedDownstreamWorkers.WorkerPublicIds, []string{w3.PublicId})
|
||||
|
||||
w1, err := serverRepo.LookupWorker(ctx, resp.WorkerId)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, w1.Address, "2.3.4.5:8080")
|
||||
expTags := []*server.Tag{
|
||||
{Key: "tag1", Value: "value1"},
|
||||
{Key: "tag2", Value: "value2"},
|
||||
}
|
||||
assert.Empty(
|
||||
t,
|
||||
cmp.Diff(
|
||||
w1.ConfigTags,
|
||||
server.Tags(expTags),
|
||||
),
|
||||
)
|
||||
assert.Equal(t, w1.ReleaseVersion, "Boundary v0.18.0")
|
||||
assert.EqualValues(t, w1.OperationalState, server.ActiveOperationalState)
|
||||
assert.EqualValues(t, w1.LocalStorageState, server.AvailableLocalStorageState)
|
||||
|
||||
// Now send the subsequent routing info request
|
||||
req.WorkerStatus.PublicId = w1.PublicId // Only set on subsequent requests
|
||||
resp, err = s.RoutingInfo(ctx, req)
|
||||
require.NoError(t, err)
|
||||
assert.NotNil(t, resp)
|
||||
|
||||
assert.Equal(t, resp.WorkerId, w1.PublicId)
|
||||
assert.Equal(t, resp.CalculatedUpstreamAddresses, []string{c.Address})
|
||||
assert.Equal(t, resp.AuthorizedDownstreamWorkers.UnmappedWorkerKeyIdentifiers, []string{w2KeyId})
|
||||
assert.Equal(t, resp.AuthorizedDownstreamWorkers.WorkerPublicIds, []string{w3.PublicId})
|
||||
|
||||
w1, err = serverRepo.LookupWorker(ctx, resp.WorkerId)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, w1.Address, "2.3.4.5:8080")
|
||||
assert.Empty(
|
||||
t,
|
||||
cmp.Diff(
|
||||
w1.ConfigTags,
|
||||
server.Tags(expTags),
|
||||
),
|
||||
)
|
||||
assert.Equal(t, w1.ReleaseVersion, "Boundary v0.18.0")
|
||||
assert.EqualValues(t, w1.OperationalState, server.ActiveOperationalState)
|
||||
assert.EqualValues(t, w1.LocalStorageState, server.AvailableLocalStorageState)
|
||||
})
|
||||
|
||||
t.Run("Successful first and second request (KMS worker)", func(t *testing.T) {
|
||||
req := &pbs.RoutingInfoRequest{
|
||||
WorkerStatus: &pb.ServerWorkerStatus{
|
||||
PublicId: "", // Not set on the first request
|
||||
Name: "testworker3",
|
||||
Address: "2.3.4.5:8080",
|
||||
Tags: []*pb.TagPair{
|
||||
{Key: "tag1", Value: "value1"},
|
||||
{Key: "tag2", Value: "value2"},
|
||||
},
|
||||
ReleaseVersion: "Boundary v0.18.0",
|
||||
OperationalState: server.ActiveOperationalState.String(),
|
||||
LocalStorageState: server.AvailableLocalStorageState.String(),
|
||||
},
|
||||
UpdateTags: true,
|
||||
ConnectedUnmappedWorkerKeyIdentifiers: []string{w2KeyId, "worker-key-2"},
|
||||
ConnectedWorkerPublicIds: []string{w1.PublicId, "worker-4"},
|
||||
}
|
||||
resp, err := s.RoutingInfo(ctx, req)
|
||||
require.NoError(t, err)
|
||||
assert.NotNil(t, resp)
|
||||
|
||||
assert.Equal(t, resp.WorkerId, w3.PublicId)
|
||||
assert.Equal(t, resp.CalculatedUpstreamAddresses, []string{c.Address})
|
||||
assert.Equal(t, resp.AuthorizedDownstreamWorkers.UnmappedWorkerKeyIdentifiers, []string{w2KeyId})
|
||||
assert.Equal(t, resp.AuthorizedDownstreamWorkers.WorkerPublicIds, []string{w1.PublicId})
|
||||
|
||||
w3, err := serverRepo.LookupWorker(ctx, resp.WorkerId)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, w3.Address, "2.3.4.5:8080")
|
||||
expTags := []*server.Tag{
|
||||
{Key: "tag1", Value: "value1"},
|
||||
{Key: "tag2", Value: "value2"},
|
||||
}
|
||||
assert.Empty(
|
||||
t,
|
||||
cmp.Diff(
|
||||
w3.ConfigTags,
|
||||
server.Tags(expTags),
|
||||
),
|
||||
)
|
||||
assert.Equal(t, w3.ReleaseVersion, "Boundary v0.18.0")
|
||||
assert.EqualValues(t, w3.OperationalState, server.ActiveOperationalState)
|
||||
assert.EqualValues(t, w3.LocalStorageState, server.AvailableLocalStorageState)
|
||||
|
||||
// Now send the subsequent routing info request
|
||||
req.WorkerStatus.PublicId = w3.PublicId // Only set on subsequent requests
|
||||
resp, err = s.RoutingInfo(ctx, req)
|
||||
require.NoError(t, err)
|
||||
assert.NotNil(t, resp)
|
||||
|
||||
assert.Equal(t, resp.WorkerId, w3.PublicId)
|
||||
assert.Equal(t, resp.CalculatedUpstreamAddresses, []string{c.Address})
|
||||
assert.Equal(t, resp.AuthorizedDownstreamWorkers.UnmappedWorkerKeyIdentifiers, []string{w2KeyId})
|
||||
assert.Equal(t, resp.AuthorizedDownstreamWorkers.WorkerPublicIds, []string{w1.PublicId})
|
||||
|
||||
w1, err = serverRepo.LookupWorker(ctx, resp.WorkerId)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, w3.Address, "2.3.4.5:8080")
|
||||
assert.Empty(
|
||||
t,
|
||||
cmp.Diff(
|
||||
w3.ConfigTags,
|
||||
server.Tags(expTags),
|
||||
),
|
||||
)
|
||||
assert.Equal(t, w3.ReleaseVersion, "Boundary v0.18.0")
|
||||
assert.EqualValues(t, w3.OperationalState, server.ActiveOperationalState)
|
||||
assert.EqualValues(t, w3.LocalStorageState, server.AvailableLocalStorageState)
|
||||
})
|
||||
}
|
||||
@@ -117,11 +117,11 @@ type Controller struct {
|
||||
clusterListener *base.ServerListener
|
||||
|
||||
// Used for testing and tracking worker health
|
||||
workerStatusUpdateTimes *sync.Map
|
||||
workerRoutingInfoUpdateTimes *sync.Map
|
||||
|
||||
// Timing variables. These are atomics for SIGHUP support, and are int64
|
||||
// because they are casted to time.Duration.
|
||||
workerStatusGracePeriod *atomic.Int64
|
||||
workerRPCGracePeriod *atomic.Int64
|
||||
livenessTimeToStale *atomic.Int64
|
||||
getDownstreamWorkersTimeout *atomic.Int64
|
||||
|
||||
@@ -177,19 +177,19 @@ func New(ctx context.Context, conf *Config) (*Controller, error) {
|
||||
metric.InitializeApiCollectors(conf.PrometheusRegisterer)
|
||||
ratelimit.InitializeMetrics(conf.PrometheusRegisterer)
|
||||
c := &Controller{
|
||||
conf: conf,
|
||||
logger: conf.Logger.Named("controller"),
|
||||
started: ua.NewBool(false),
|
||||
tickerWg: new(sync.WaitGroup),
|
||||
schedulerWg: new(sync.WaitGroup),
|
||||
workerAuthCache: new(sync.Map),
|
||||
workerStatusUpdateTimes: new(sync.Map),
|
||||
enabledPlugins: conf.Server.EnabledPlugins,
|
||||
apiListeners: make([]*base.ServerListener, 0),
|
||||
downstreamConnManager: cluster.NewDownstreamManager(),
|
||||
workerStatusGracePeriod: new(atomic.Int64),
|
||||
livenessTimeToStale: new(atomic.Int64),
|
||||
getDownstreamWorkersTimeout: new(atomic.Int64),
|
||||
conf: conf,
|
||||
logger: conf.Logger.Named("controller"),
|
||||
started: ua.NewBool(false),
|
||||
tickerWg: new(sync.WaitGroup),
|
||||
schedulerWg: new(sync.WaitGroup),
|
||||
workerAuthCache: new(sync.Map),
|
||||
workerRoutingInfoUpdateTimes: new(sync.Map),
|
||||
enabledPlugins: conf.Server.EnabledPlugins,
|
||||
apiListeners: make([]*base.ServerListener, 0),
|
||||
downstreamConnManager: cluster.NewDownstreamManager(),
|
||||
workerRPCGracePeriod: new(atomic.Int64),
|
||||
livenessTimeToStale: new(atomic.Int64),
|
||||
getDownstreamWorkersTimeout: new(atomic.Int64),
|
||||
}
|
||||
|
||||
c.started.Store(false)
|
||||
@@ -223,11 +223,11 @@ func New(ctx context.Context, conf *Config) (*Controller, error) {
|
||||
}
|
||||
}
|
||||
|
||||
switch conf.RawConfig.Controller.WorkerStatusGracePeriodDuration {
|
||||
switch conf.RawConfig.Controller.WorkerRPCGracePeriodDuration {
|
||||
case 0:
|
||||
c.workerStatusGracePeriod.Store(int64(server.DefaultLiveness))
|
||||
c.workerRPCGracePeriod.Store(int64(server.DefaultLiveness))
|
||||
default:
|
||||
c.workerStatusGracePeriod.Store(int64(conf.RawConfig.Controller.WorkerStatusGracePeriodDuration))
|
||||
c.workerRPCGracePeriod.Store(int64(conf.RawConfig.Controller.WorkerRPCGracePeriodDuration))
|
||||
}
|
||||
switch conf.RawConfig.Controller.LivenessTimeToStaleDuration {
|
||||
case 0:
|
||||
@@ -623,7 +623,7 @@ func (c *Controller) registerJobs() error {
|
||||
if err := pluginhost.RegisterJobs(c.baseContext, c.scheduler, rw, rw, c.kms, c.conf.HostPlugins); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := session.RegisterJobs(c.baseContext, c.scheduler, rw, rw, c.kms, c.workerStatusGracePeriod); err != nil {
|
||||
if err := session.RegisterJobs(c.baseContext, c.scheduler, rw, rw, c.kms, c.workerRPCGracePeriod); err != nil {
|
||||
return err
|
||||
}
|
||||
var serverJobOpts []serversjob.Option
|
||||
@@ -633,7 +633,7 @@ func (c *Controller) registerJobs() error {
|
||||
serversjob.WithRotationFrequency(c.conf.TestOverrideWorkerAuthCaCertificateLifetime/2),
|
||||
)
|
||||
}
|
||||
if err := serversjob.RegisterJobs(c.baseContext, c.scheduler, rw, rw, c.kms, c.ControllerExtension, c.workerStatusGracePeriod, serverJobOpts...); err != nil {
|
||||
if err := serversjob.RegisterJobs(c.baseContext, c.scheduler, rw, rw, c.kms, c.ControllerExtension, c.workerRPCGracePeriod, serverJobOpts...); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := kmsjob.RegisterJobs(c.baseContext, c.scheduler, c.kms); err != nil {
|
||||
@@ -675,12 +675,12 @@ func (c *Controller) Shutdown() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// WorkerStatusUpdateTimes returns the map, which specifically is held in _this_
|
||||
// WorkerRoutingInfoUpdateTimes returns the map, which specifically is held in _this_
|
||||
// controller, not the DB. It's used in tests to verify that a given controller
|
||||
// is receiving updates from an expected set of workers, to test out balancing
|
||||
// and auto reconnection.
|
||||
func (c *Controller) WorkerStatusUpdateTimes() *sync.Map {
|
||||
return c.workerStatusUpdateTimes
|
||||
func (c *Controller) WorkerRoutingInfoUpdateTimes() *sync.Map {
|
||||
return c.workerRoutingInfoUpdateTimes
|
||||
}
|
||||
|
||||
// ReloadTimings reloads timing related parameters
|
||||
@@ -694,11 +694,11 @@ func (c *Controller) ReloadTimings(newConfig *config.Config) error {
|
||||
return errors.New(c.baseContext, errors.InvalidParameter, op, "nil config.Controller")
|
||||
}
|
||||
|
||||
switch newConfig.Controller.WorkerStatusGracePeriodDuration {
|
||||
switch newConfig.Controller.WorkerRPCGracePeriodDuration {
|
||||
case 0:
|
||||
c.workerStatusGracePeriod.Store(int64(server.DefaultLiveness))
|
||||
c.workerRPCGracePeriod.Store(int64(server.DefaultLiveness))
|
||||
default:
|
||||
c.workerStatusGracePeriod.Store(int64(newConfig.Controller.WorkerStatusGracePeriodDuration))
|
||||
c.workerRPCGracePeriod.Store(int64(newConfig.Controller.WorkerRPCGracePeriodDuration))
|
||||
}
|
||||
switch newConfig.Controller.LivenessTimeToStaleDuration {
|
||||
case 0:
|
||||
|
||||
@@ -243,7 +243,7 @@ func (c *Controller) registerGrpcServices(s *grpc.Server) error {
|
||||
c.baseContext,
|
||||
c.IamRepoFn,
|
||||
c.ServersRepoFn,
|
||||
c.workerStatusGracePeriod,
|
||||
c.workerRPCGracePeriod,
|
||||
c.kms,
|
||||
c.conf.RawConfig.Controller.MaxPageSize,
|
||||
c.ControllerExtension)
|
||||
@@ -266,7 +266,7 @@ func (c *Controller) registerGrpcServices(s *grpc.Server) error {
|
||||
c.StaticCredentialRepoFn,
|
||||
c.TargetAliasRepoFn,
|
||||
c.downstreamWorkers,
|
||||
c.workerStatusGracePeriod,
|
||||
c.workerRPCGracePeriod,
|
||||
c.conf.RawConfig.Controller.MaxPageSize,
|
||||
c.ControllerExtension,
|
||||
)
|
||||
|
||||
@@ -44,7 +44,7 @@ func init() {
|
||||
var NewServiceFn = func(ctx context.Context,
|
||||
iamRepoFn common.IamRepoFactory,
|
||||
serverRepoFn common.ServersRepoFactory,
|
||||
workerStatusGracePeriod *atomic.Int64,
|
||||
workerRPCGracePeriod *atomic.Int64,
|
||||
kms *kms.Kms,
|
||||
maxPageSize uint,
|
||||
controllerExt intglobals.ControllerExtension,
|
||||
|
||||
@@ -121,20 +121,20 @@ func IngressWorkerFilterUnsupported(string) error {
|
||||
type Service struct {
|
||||
pbs.UnsafeTargetServiceServer
|
||||
|
||||
repoFn target.RepositoryFactory
|
||||
aliasRepoFn common.TargetAliasRepoFactory
|
||||
iamRepoFn common.IamRepoFactory
|
||||
serversRepoFn common.ServersRepoFactory
|
||||
sessionRepoFn session.RepositoryFactory
|
||||
pluginHostRepoFn common.PluginHostRepoFactory
|
||||
staticHostRepoFn common.StaticRepoFactory
|
||||
vaultCredRepoFn common.VaultCredentialRepoFactory
|
||||
staticCredRepoFn common.StaticCredentialRepoFactory
|
||||
downstreams downstream.Graph
|
||||
kmsCache *kms.Kms
|
||||
workerStatusGracePeriod *atomic.Int64
|
||||
maxPageSize uint
|
||||
controllerExt intglobals.ControllerExtension
|
||||
repoFn target.RepositoryFactory
|
||||
aliasRepoFn common.TargetAliasRepoFactory
|
||||
iamRepoFn common.IamRepoFactory
|
||||
serversRepoFn common.ServersRepoFactory
|
||||
sessionRepoFn session.RepositoryFactory
|
||||
pluginHostRepoFn common.PluginHostRepoFactory
|
||||
staticHostRepoFn common.StaticRepoFactory
|
||||
vaultCredRepoFn common.VaultCredentialRepoFactory
|
||||
staticCredRepoFn common.StaticCredentialRepoFactory
|
||||
downstreams downstream.Graph
|
||||
kmsCache *kms.Kms
|
||||
workerRPCGracePeriod *atomic.Int64
|
||||
maxPageSize uint
|
||||
controllerExt intglobals.ControllerExtension
|
||||
}
|
||||
|
||||
var _ pbs.TargetServiceServer = (*Service)(nil)
|
||||
@@ -153,7 +153,7 @@ func NewService(
|
||||
staticCredRepoFn common.StaticCredentialRepoFactory,
|
||||
aliasRepoFn common.TargetAliasRepoFactory,
|
||||
downstreams downstream.Graph,
|
||||
workerStatusGracePeriod *atomic.Int64,
|
||||
workerRPCGracePeriod *atomic.Int64,
|
||||
maxPageSize uint,
|
||||
controllerExt intglobals.ControllerExtension,
|
||||
) (Service, error) {
|
||||
@@ -184,20 +184,20 @@ func NewService(
|
||||
maxPageSize = uint(globals.DefaultMaxPageSize)
|
||||
}
|
||||
return Service{
|
||||
repoFn: repoFn,
|
||||
iamRepoFn: iamRepoFn,
|
||||
serversRepoFn: serversRepoFn,
|
||||
sessionRepoFn: sessionRepoFn,
|
||||
pluginHostRepoFn: pluginHostRepoFn,
|
||||
staticHostRepoFn: staticHostRepoFn,
|
||||
vaultCredRepoFn: vaultCredRepoFn,
|
||||
staticCredRepoFn: staticCredRepoFn,
|
||||
aliasRepoFn: aliasRepoFn,
|
||||
downstreams: downstreams,
|
||||
kmsCache: kmsCache,
|
||||
workerStatusGracePeriod: workerStatusGracePeriod,
|
||||
maxPageSize: maxPageSize,
|
||||
controllerExt: controllerExt,
|
||||
repoFn: repoFn,
|
||||
iamRepoFn: iamRepoFn,
|
||||
serversRepoFn: serversRepoFn,
|
||||
sessionRepoFn: sessionRepoFn,
|
||||
pluginHostRepoFn: pluginHostRepoFn,
|
||||
staticHostRepoFn: staticHostRepoFn,
|
||||
vaultCredRepoFn: vaultCredRepoFn,
|
||||
staticCredRepoFn: staticCredRepoFn,
|
||||
aliasRepoFn: aliasRepoFn,
|
||||
downstreams: downstreams,
|
||||
kmsCache: kmsCache,
|
||||
workerRPCGracePeriod: workerRPCGracePeriod,
|
||||
maxPageSize: maxPageSize,
|
||||
controllerExt: controllerExt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -942,7 +942,7 @@ func (s Service) AuthorizeSession(ctx context.Context, req *pbs.AuthorizeSession
|
||||
// Get workers and filter down to ones that can service this request
|
||||
selectedWorkers, protoWorkerId, err := serversRepo.SelectSessionWorkers(
|
||||
ctx,
|
||||
time.Duration(s.workerStatusGracePeriod.Load()),
|
||||
time.Duration(s.workerRPCGracePeriod.Load()),
|
||||
t,
|
||||
h,
|
||||
s.controllerExt,
|
||||
|
||||
@@ -93,8 +93,8 @@ var expectedDeprecatedWorkerFilterError = "Use egress_worker_filter instead"
|
||||
func testService(t *testing.T, ctx context.Context, conn *db.DB, kms *kms.Kms, wrapper wrapping.Wrapper) (targets.Service, error) {
|
||||
rw := db.New(conn)
|
||||
sche := scheduler.TestScheduler(t, conn, wrapper)
|
||||
statusGracePeriod := new(atomic.Int64)
|
||||
statusGracePeriod.Store(int64(server.DefaultLiveness))
|
||||
workerRPCGracePeriod := new(atomic.Int64)
|
||||
workerRPCGracePeriod.Store(int64(server.DefaultLiveness))
|
||||
repoFn := func(o ...target.Option) (*target.Repository, error) {
|
||||
return target.NewRepository(ctx, rw, rw, kms, o...)
|
||||
}
|
||||
@@ -122,7 +122,7 @@ func testService(t *testing.T, ctx context.Context, conn *db.DB, kms *kms.Kms, w
|
||||
targetAliasRepoFn := func() (*talias.Repository, error) {
|
||||
return talias.NewRepository(ctx, rw, rw, kms)
|
||||
}
|
||||
return targets.NewService(ctx, kms, repoFn, iamRepoFn, serversRepoFn, sessionRepoFn, pluginHostRepoFn, staticHostRepoFn, vaultCredRepoFn, staticCredRepoFn, targetAliasRepoFn, nil, statusGracePeriod, 1000, nil)
|
||||
return targets.NewService(ctx, kms, repoFn, iamRepoFn, serversRepoFn, sessionRepoFn, pluginHostRepoFn, staticHostRepoFn, vaultCredRepoFn, staticCredRepoFn, targetAliasRepoFn, nil, workerRPCGracePeriod, 1000, nil)
|
||||
}
|
||||
|
||||
func TestGet(t *testing.T) {
|
||||
@@ -3571,9 +3571,9 @@ func TestAuthorizeSession(t *testing.T) {
|
||||
},
|
||||
}
|
||||
|
||||
statusGracePeriod := new(atomic.Int64)
|
||||
statusGracePeriod.Store(int64(server.DefaultLiveness))
|
||||
s, err := targets.NewService(ctx, kms, repoFn, iamRepoFn, serversRepoFn, sessionRepoFn, pluginHostRepoFn, staticHostRepoFn, vaultCredRepoFn, staticCredRepoFn, targetAliasRepoFn, nil, statusGracePeriod, 1000, nil)
|
||||
workerRPCGracePeriod := new(atomic.Int64)
|
||||
workerRPCGracePeriod.Store(int64(server.DefaultLiveness))
|
||||
s, err := targets.NewService(ctx, kms, repoFn, iamRepoFn, serversRepoFn, sessionRepoFn, pluginHostRepoFn, staticHostRepoFn, vaultCredRepoFn, staticCredRepoFn, targetAliasRepoFn, nil, workerRPCGracePeriod, 1000, nil)
|
||||
require.NoError(t, err)
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
@@ -3776,9 +3776,9 @@ func TestAuthorizeSessionTypedCredentials(t *testing.T) {
|
||||
_ = iam.TestUserRole(t, conn, r.GetPublicId(), at.GetIamUserId())
|
||||
_ = iam.TestRoleGrant(t, conn, r.GetPublicId(), "ids=*;type=*;actions=*")
|
||||
|
||||
statusGracePeriod := new(atomic.Int64)
|
||||
statusGracePeriod.Store(int64(server.DefaultLiveness))
|
||||
s, err := targets.NewService(ctx, kms, repoFn, iamRepoFn, serversRepoFn, sessionRepoFn, pluginHostRepoFn, staticHostRepoFn, vaultCredRepoFn, staticCredRepoFn, targetAliasRepoFn, nil, statusGracePeriod, 1000, nil)
|
||||
workerRPCGracePeriod := new(atomic.Int64)
|
||||
workerRPCGracePeriod.Store(int64(server.DefaultLiveness))
|
||||
s, err := targets.NewService(ctx, kms, repoFn, iamRepoFn, serversRepoFn, sessionRepoFn, pluginHostRepoFn, staticHostRepoFn, vaultCredRepoFn, staticCredRepoFn, targetAliasRepoFn, nil, workerRPCGracePeriod, 1000, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
hc := static.TestCatalogs(t, conn, proj.GetPublicId(), 1)[0]
|
||||
@@ -4380,9 +4380,9 @@ func TestAuthorizeSession_Errors(t *testing.T) {
|
||||
}
|
||||
org, proj := iam.TestScopes(t, iamRepo)
|
||||
|
||||
statusGracePeriod := new(atomic.Int64)
|
||||
statusGracePeriod.Store(int64(server.DefaultLiveness))
|
||||
s, err := targets.NewService(ctx, kms, repoFn, iamRepoFn, serversRepoFn, sessionRepoFn, pluginHostRepoFn, staticHostRepoFn, vaultCredRepoFn, staticCredRepoFn, targetAliasRepoFn, nil, statusGracePeriod, 1000, nil)
|
||||
workerRPCGracePeriod := new(atomic.Int64)
|
||||
workerRPCGracePeriod.Store(int64(server.DefaultLiveness))
|
||||
s, err := targets.NewService(ctx, kms, repoFn, iamRepoFn, serversRepoFn, sessionRepoFn, pluginHostRepoFn, staticHostRepoFn, vaultCredRepoFn, staticCredRepoFn, targetAliasRepoFn, nil, workerRPCGracePeriod, 1000, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Authorized user gets full permissions
|
||||
|
||||
@@ -47,7 +47,7 @@ func registerControllerServerCoordinationService(ctx context.Context, c *Control
|
||||
c.SessionRepoFn,
|
||||
c.ConnectionRepoFn,
|
||||
c.downstreamWorkers,
|
||||
c.workerStatusUpdateTimes,
|
||||
c.workerRoutingInfoUpdateTimes,
|
||||
c.kms,
|
||||
c.livenessTimeToStale,
|
||||
c.ControllerExtension,
|
||||
@@ -74,7 +74,7 @@ func registerControllerSessionService(ctx context.Context, c *Controller, server
|
||||
c.SessionRepoFn,
|
||||
c.ConnectionRepoFn,
|
||||
c.downstreamWorkers,
|
||||
c.workerStatusUpdateTimes,
|
||||
c.workerRoutingInfoUpdateTimes,
|
||||
c.kms,
|
||||
c.livenessTimeToStale,
|
||||
c.ControllerExtension,
|
||||
|
||||
@@ -473,8 +473,9 @@ type TestControllerOpts struct {
|
||||
PublicClusterAddr string
|
||||
|
||||
// The amount of time to wait before marking connections as canceling when a
|
||||
// worker has not reported in
|
||||
WorkerStatusGracePeriodDuration time.Duration
|
||||
// worker has not reported in, and whether a worker is considered to be
|
||||
// routable based on the last time it received a routing info report.
|
||||
WorkerRPCGracePeriod time.Duration
|
||||
|
||||
// The period of time after which it will consider other controllers to be
|
||||
// no longer accessible, based on time since their last status update in the
|
||||
@@ -691,8 +692,8 @@ func TestControllerConfig(t testing.TB, ctx context.Context, tc *TestController,
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if opts.WorkerStatusGracePeriodDuration != 0 {
|
||||
opts.Config.Controller.WorkerStatusGracePeriodDuration = opts.WorkerStatusGracePeriodDuration
|
||||
if opts.WorkerRPCGracePeriod != 0 {
|
||||
opts.Config.Controller.WorkerRPCGracePeriodDuration = opts.WorkerRPCGracePeriod
|
||||
}
|
||||
if opts.LivenessTimeToStaleDuration != 0 {
|
||||
opts.Config.Controller.LivenessTimeToStaleDuration = opts.LivenessTimeToStaleDuration
|
||||
@@ -862,7 +863,7 @@ func (tc *TestController) AddClusterControllerMember(t testing.TB, opts *TestCon
|
||||
DisableAuthMethodCreation: true,
|
||||
DisableAutoStart: opts.DisableAutoStart,
|
||||
PublicClusterAddr: opts.PublicClusterAddr,
|
||||
WorkerStatusGracePeriodDuration: opts.WorkerStatusGracePeriodDuration,
|
||||
WorkerRPCGracePeriod: opts.WorkerRPCGracePeriod,
|
||||
LivenessTimeToStaleDuration: opts.LivenessTimeToStaleDuration,
|
||||
WorkerAuthCaCertificateLifetime: tc.c.conf.TestOverrideWorkerAuthCaCertificateLifetime,
|
||||
WorkerAuthDebuggingEnabled: tc.c.conf.WorkerAuthDebuggingEnabled,
|
||||
@@ -881,53 +882,45 @@ func (tc *TestController) AddClusterControllerMember(t testing.TB, opts *TestCon
|
||||
return NewTestController(t, nextOpts)
|
||||
}
|
||||
|
||||
// WaitForNextWorkerStatusUpdate waits for the next status check from a worker to
|
||||
// come in. If it does not come in within the default status grace
|
||||
// WaitForNextWorkerRoutingInfoUpdate waits for the next routing info RPC from a worker to
|
||||
// come in. If it does not come in within the default worker RPC grace
|
||||
// period, this function returns an error.
|
||||
func (tc *TestController) WaitForNextWorkerStatusUpdate(workerStatusName string) error {
|
||||
const op = "controller.(TestController).WaitForNextWorkerStatusUpdate"
|
||||
ctx := context.TODO()
|
||||
event.WriteSysEvent(ctx, op, "waiting for next status report from worker", "worker", workerStatusName)
|
||||
waitStatusStart := time.Now()
|
||||
ctx, cancel := context.WithTimeout(tc.ctx, time.Duration(tc.c.workerStatusGracePeriod.Load()))
|
||||
func (tc *TestController) WaitForNextWorkerRoutingInfoUpdate(workerName string) error {
|
||||
const op = "controller.(TestController).WaitForNextWorkerRoutingInfoUpdate"
|
||||
waitStart := time.Now()
|
||||
ctx, cancel := context.WithTimeout(tc.ctx, time.Duration(tc.c.workerRPCGracePeriod.Load()))
|
||||
defer cancel()
|
||||
event.WriteSysEvent(ctx, op, "waiting for next routing info from worker", "worker", workerName)
|
||||
var err error
|
||||
for {
|
||||
if err = func() error {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
|
||||
case <-time.After(time.Second):
|
||||
// pass
|
||||
}
|
||||
|
||||
return nil
|
||||
}(); err != nil {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
break
|
||||
case <-time.After(time.Second):
|
||||
// pass
|
||||
}
|
||||
|
||||
var waitStatusCurrent time.Time
|
||||
tc.Controller().WorkerStatusUpdateTimes().Range(func(k, v any) bool {
|
||||
var waitCurrent time.Time
|
||||
tc.Controller().WorkerRoutingInfoUpdateTimes().Range(func(k, v any) bool {
|
||||
if k == nil || v == nil {
|
||||
err = fmt.Errorf("nil key or value on entry: key=%#v value=%#v", k, v)
|
||||
return false
|
||||
}
|
||||
|
||||
workerStatusUpdateId, ok := k.(string)
|
||||
workerUpdateId, ok := k.(string)
|
||||
if !ok {
|
||||
err = fmt.Errorf("unexpected type %T for key: key=%#v value=%#v", k, k, v)
|
||||
return false
|
||||
}
|
||||
|
||||
workerStatusUpdateTime, ok := v.(time.Time)
|
||||
workerUpdateTime, ok := v.(time.Time)
|
||||
if !ok {
|
||||
err = fmt.Errorf("unexpected type %T for value: key=%#v value=%#v", k, k, v)
|
||||
return false
|
||||
}
|
||||
|
||||
if workerStatusUpdateId == workerStatusName {
|
||||
waitStatusCurrent = workerStatusUpdateTime
|
||||
if workerUpdateId == workerName {
|
||||
waitCurrent = workerUpdateTime
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -938,16 +931,16 @@ func (tc *TestController) WaitForNextWorkerStatusUpdate(workerStatusName string)
|
||||
break
|
||||
}
|
||||
|
||||
if waitStatusCurrent.After(waitStatusStart) {
|
||||
if waitCurrent.After(waitStart) {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
event.WriteError(ctx, op, err, event.WithInfoMsg("error waiting for next status report from worker", "worker", workerStatusName))
|
||||
event.WriteError(ctx, op, err, event.WithInfoMsg("error waiting for next routing info RPC from worker", "worker", workerName))
|
||||
return err
|
||||
}
|
||||
event.WriteSysEvent(ctx, op, "waiting for next status report from worker received successfully", "worker", workerStatusName)
|
||||
event.WriteSysEvent(ctx, op, "next routing info RPC from worker received successfully", "worker", workerName)
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -11,11 +11,27 @@ import (
|
||||
|
||||
// In the future we could make this configurable
|
||||
const (
|
||||
// StatusInterval is the base duration used in the calculation of the random backoff
|
||||
// during the worker status report
|
||||
StatusInterval = 2 * time.Second
|
||||
// SessionInfoInterval is the base duration used in the calculation of the random backoff
|
||||
// during the worker session information report
|
||||
SessionInfoInterval = 2 * time.Second
|
||||
|
||||
// DefaultStatusTimeout is the timeout duration on status calls to the controller from
|
||||
// RoutingInfoInterval is the interval at which the worker will send routing information
|
||||
// to the controller
|
||||
RoutingInfoInterval = 10 * time.Second
|
||||
|
||||
// StatisticsInterval is the base duration used in the calculation of the random backoff
|
||||
// during the worker statistics report
|
||||
StatisticsInterval = 15 * time.Second
|
||||
|
||||
// DefaultSessionInfoTimeout is the timeout duration on SessionInfo calls to the controller from
|
||||
// the worker
|
||||
DefaultStatusTimeout = server.DefaultLiveness / 3
|
||||
DefaultSessionInfoTimeout = server.DefaultLiveness / 3
|
||||
|
||||
// DefaultRoutingInfoTimeout is the timeout duration on routing info calls to the controller from
|
||||
// the worker
|
||||
DefaultRoutingInfoTimeout = server.DefaultLiveness / 2
|
||||
|
||||
// DefaultStatisticsTimeout is the timeout duration on Statistics calls to the controller from
|
||||
// the worker
|
||||
DefaultStatisticsTimeout = server.DefaultLiveness
|
||||
)
|
||||
@@ -42,6 +42,8 @@ var HandleHcpbClusterId func(s string) string
|
||||
// StartControllerConnections starts up the resolver and initiates controller
|
||||
// connection client creation
|
||||
func (w *Worker) StartControllerConnections() error {
|
||||
w.confAddressReceiversLock.Lock()
|
||||
defer w.confAddressReceiversLock.Unlock()
|
||||
const op = "worker.(Worker).StartControllerConnections"
|
||||
initialAddrs := make([]string, 0, len(w.conf.RawConfig.Worker.InitialUpstreams))
|
||||
for _, addr := range w.conf.RawConfig.Worker.InitialUpstreams {
|
||||
@@ -261,10 +263,10 @@ func (w *Worker) workerConnectionInfo(addr string) (*structpb.Struct, error) {
|
||||
PublicAddr: w.conf.RawConfig.Worker.PublicAddr,
|
||||
OperationalState: w.operationalState.Load().(server.OperationalState).String(),
|
||||
}
|
||||
if w.LastStatusSuccess() != nil && len(w.LastStatusSuccess().GetWorkerId()) > 0 {
|
||||
if w.LastRoutingInfoSuccess() != nil && len(w.LastRoutingInfoSuccess().GetWorkerId()) > 0 {
|
||||
// even though we wont have the worker the first time we dial, any
|
||||
// redial attempts should result in the worker id being populated
|
||||
wci.WorkerId = w.LastStatusSuccess().GetWorkerId()
|
||||
wci.WorkerId = w.LastRoutingInfoSuccess().GetWorkerId()
|
||||
}
|
||||
st, err := wci.AsConnectionStateStruct()
|
||||
if err != nil {
|
||||
|
||||
@@ -198,14 +198,14 @@ func (w *Worker) handleProxy(listenerCfg *listenerutil.ListenerConfig, sessionMa
|
||||
}
|
||||
}
|
||||
|
||||
if w.LastStatusSuccess() == nil || w.LastStatusSuccess().WorkerId == "" {
|
||||
if w.LastRoutingInfoSuccess() == nil || w.LastRoutingInfoSuccess().WorkerId == "" {
|
||||
event.WriteError(ctx, op, stderrors.New("worker id is empty"))
|
||||
if err = conn.Close(websocket.StatusInternalError, "worker id is empty"); err != nil {
|
||||
event.WriteError(ctx, op, err, event.WithInfoMsg("error closing client connection"))
|
||||
}
|
||||
return
|
||||
}
|
||||
workerId := w.LastStatusSuccess().WorkerId
|
||||
workerId := w.LastRoutingInfoSuccess().WorkerId
|
||||
|
||||
var acResp *pbs.AuthorizeConnectionResponse
|
||||
var connsLeft int32
|
||||
|
||||
@@ -0,0 +1,328 @@
|
||||
// Copyright (c) HashiCorp, Inc.
|
||||
// SPDX-License-Identifier: BUSL-1.1
|
||||
|
||||
package worker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/hashicorp/boundary/internal/event"
|
||||
pb "github.com/hashicorp/boundary/internal/gen/controller/servers"
|
||||
pbs "github.com/hashicorp/boundary/internal/gen/controller/servers/services"
|
||||
"github.com/hashicorp/boundary/internal/server"
|
||||
"github.com/hashicorp/boundary/sdk/pbs/plugin"
|
||||
"github.com/hashicorp/boundary/version"
|
||||
"github.com/hashicorp/go-secure-stdlib/parseutil"
|
||||
"github.com/hashicorp/go-secure-stdlib/strutil"
|
||||
"google.golang.org/grpc/connectivity"
|
||||
)
|
||||
|
||||
var firstRoutingInfoCheckPostHooks = []func(context.Context, *Worker) error{
|
||||
// Start session route info and statistics ticking after first routing info success
|
||||
func(ctx context.Context, w *Worker) error {
|
||||
w.tickerWg.Add(2)
|
||||
go func() {
|
||||
defer w.tickerWg.Done()
|
||||
w.startSessionInfoTicking(w.baseContext)
|
||||
}()
|
||||
go func() {
|
||||
defer w.tickerWg.Done()
|
||||
w.startStatisticsTicking(w.baseContext)
|
||||
}()
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
var downstreamWorkersFactory func(ctx context.Context, workerId string, ver string) (graph, error)
|
||||
|
||||
var checkHCPBUpstreams func(w *Worker) bool
|
||||
|
||||
// LastRoutingInfo represents the last successful routing info sent to the controller.
|
||||
type LastRoutingInfo struct {
|
||||
*pbs.RoutingInfoResponse
|
||||
RoutingInfoTime time.Time
|
||||
LastCalculatedUpstreams []string
|
||||
}
|
||||
|
||||
// WaitForNextSuccessfulRoutingInfoUpdate waits for the next successful routing info. It's
|
||||
// used by testing in place of a more opaque and
|
||||
// possibly unnecessarily long sleep for things like initial controller
|
||||
// check-in, etc.
|
||||
//
|
||||
// The timeout is aligned with the worker's routing info grace period. A nil error
|
||||
// means the routing info was sent successfully.
|
||||
func (w *Worker) WaitForNextSuccessfulRoutingInfoUpdate() error {
|
||||
const op = "worker.(Worker).WaitForNextSuccessfulRoutingInfoUpdate"
|
||||
waitStart := time.Now()
|
||||
ctx, cancel := context.WithTimeout(w.baseContext, time.Duration(w.successfulRoutingInfoGracePeriod.Load()))
|
||||
defer cancel()
|
||||
event.WriteSysEvent(ctx, op, "waiting for next routing info report to controller")
|
||||
for {
|
||||
select {
|
||||
case <-time.After(time.Second):
|
||||
// pass
|
||||
|
||||
case <-ctx.Done():
|
||||
event.WriteError(ctx, op, ctx.Err(), event.WithInfoMsg("error waiting for next routing info report to controller"))
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
if w.lastSuccessfulRoutingInfoTime().After(waitStart) {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
event.WriteSysEvent(ctx, op, "next worker routing info update sent successfully")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *Worker) startRoutingInfoTicking(cancelCtx context.Context) {
|
||||
const op = "worker.(Worker).startRoutingInfoTicking"
|
||||
r := rand.New(rand.NewSource(time.Now().UnixNano()))
|
||||
|
||||
timer := time.NewTimer(0)
|
||||
for {
|
||||
select {
|
||||
case <-cancelCtx.Done():
|
||||
event.WriteSysEvent(w.baseContext, op, "RoutingInfo ticking shutting down")
|
||||
return
|
||||
|
||||
case <-timer.C:
|
||||
// If we've never managed to successfully authenticate then we won't have
|
||||
// any session information anyways and this will produce a ton of noise in
|
||||
// observability, so skip calling the function and retry in a short duration
|
||||
if w.everAuthenticated.Load() == authenticationStatusNeverAuthenticated {
|
||||
timer.Reset(10 * time.Millisecond)
|
||||
continue
|
||||
}
|
||||
|
||||
w.sendWorkerRoutingInfo(cancelCtx)
|
||||
// Desynchronize calls to controllers from workers, so we aren't always
|
||||
// getting RoutingInfo updates at the exact same intervals, to ease the load on the DB.
|
||||
timer.Reset(w.routingInfoInterval + getRandomInterval(r))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// LastRoutingInfoSuccess reports the last time we sent a successful
|
||||
// RoutingInfo request.
|
||||
func (w *Worker) LastRoutingInfoSuccess() *LastRoutingInfo {
|
||||
s, ok := w.lastRoutingInfoSuccess.Load().(*LastRoutingInfo)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func (w *Worker) sendWorkerRoutingInfo(cancelCtx context.Context) {
|
||||
const op = "worker.(Worker).sendWorkerRoutingInfo"
|
||||
// Lock access to w.conf and w.addressReceivers
|
||||
w.confAddressReceiversLock.Lock()
|
||||
defer w.confAddressReceiversLock.Unlock()
|
||||
|
||||
clientCon := w.GrpcClientConn.Load()
|
||||
// Send RoutingInfo information
|
||||
client := pbs.NewServerCoordinationServiceClient(clientCon)
|
||||
var tags []*pb.TagPair
|
||||
// If we're not going to request a tag update, no reason to have these
|
||||
// marshaled on every RoutingInfo call.
|
||||
if w.updateTags.Load() {
|
||||
tags = w.tags.Load().([]*pb.TagPair)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(cancelCtx, time.Duration(w.routingInfoCallTimeoutDuration.Load()))
|
||||
defer cancel()
|
||||
|
||||
keyId := w.WorkerAuthCurrentKeyId.Load()
|
||||
switch {
|
||||
case w.conf.RawConfig.Worker.Name == "" && keyId == "":
|
||||
event.WriteError(cancelCtx, op, errors.New("worker name and keyId are both empty; at least one is needed to identify a worker"),
|
||||
event.WithInfoMsg("error making RoutingInfo request to controller"))
|
||||
}
|
||||
|
||||
var storageBucketCredentialStates map[string]*plugin.StorageBucketCredentialState
|
||||
if w.RecordingStorage != nil {
|
||||
storageBucketCredentialStates = w.RecordingStorage.GetStorageBucketCredentialStates()
|
||||
// If the local storage state is unknown, and we have recording storage set, get the state from the recording storage
|
||||
// and set it on the worker. This is done once to ensure that the worker has the correct state for the first RoutingInfo
|
||||
// call.
|
||||
if w.localStorageState.Load() == server.UnknownLocalStorageState {
|
||||
w.localStorageState.Store(w.RecordingStorage.GetLocalStorageState(cancelCtx))
|
||||
}
|
||||
}
|
||||
versionInfo := version.Get()
|
||||
connectionState := w.downstreamConnManager.Connected()
|
||||
result, err := client.RoutingInfo(ctx, &pbs.RoutingInfoRequest{
|
||||
WorkerStatus: &pb.ServerWorkerStatus{
|
||||
Name: w.conf.RawConfig.Worker.Name,
|
||||
Description: w.conf.RawConfig.Worker.Description,
|
||||
Address: w.conf.RawConfig.Worker.PublicAddr,
|
||||
Tags: tags,
|
||||
KeyId: keyId,
|
||||
ReleaseVersion: versionInfo.FullVersionNumber(false),
|
||||
OperationalState: w.operationalState.Load().(server.OperationalState).String(),
|
||||
LocalStorageState: w.localStorageState.Load().(server.LocalStorageState).String(),
|
||||
StorageBucketCredentialStates: storageBucketCredentialStates,
|
||||
},
|
||||
ConnectedUnmappedWorkerKeyIdentifiers: connectionState.UnmappedKeyIds(),
|
||||
ConnectedWorkerPublicIds: connectionState.WorkerIds(),
|
||||
UpdateTags: w.updateTags.Load(),
|
||||
})
|
||||
if err != nil {
|
||||
event.WriteError(cancelCtx, op, err, event.WithInfoMsg("error making routing info request to controller", "controller_address", clientCon.Target()))
|
||||
|
||||
// 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 pastGrace, _, _ := w.isPastGrace(); pastGrace && w.GrpcClientConn.Load().GetState() == connectivity.TransientFailure {
|
||||
lastRoutingInfo := w.lastRoutingInfoSuccess.Load().(*LastRoutingInfo)
|
||||
if lastRoutingInfo != nil && lastRoutingInfo.LastCalculatedUpstreams != nil {
|
||||
addrs := lastRoutingInfo.LastCalculatedUpstreams
|
||||
|
||||
if len(w.conf.RawConfig.Worker.InitialUpstreams) > 0 {
|
||||
addrs = append(addrs, w.conf.RawConfig.Worker.InitialUpstreams...)
|
||||
} else if HandleHcpbClusterId != nil && len(w.conf.RawConfig.HcpbClusterId) > 0 {
|
||||
clusterId, err := parseutil.ParsePath(w.conf.RawConfig.HcpbClusterId)
|
||||
if err != nil && !errors.Is(err, parseutil.ErrNotAUrl) {
|
||||
event.WriteError(cancelCtx, op, err, event.WithInfoMsg("failed to parse HCP Boundary cluster ID"))
|
||||
} else {
|
||||
clusterAddress := HandleHcpbClusterId(clusterId)
|
||||
addrs = append(addrs, clusterAddress)
|
||||
}
|
||||
}
|
||||
|
||||
slices.Sort(addrs)
|
||||
addrs = slices.Compact(addrs)
|
||||
if slices.Equal(lastRoutingInfo.LastCalculatedUpstreams, addrs) {
|
||||
// Nothing to update
|
||||
return
|
||||
}
|
||||
|
||||
w.updateAddresses(cancelCtx, addrs)
|
||||
lastRoutingInfo.LastCalculatedUpstreams = addrs
|
||||
w.lastRoutingInfoSuccess.Store(lastRoutingInfo)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
w.updateTags.Store(false)
|
||||
|
||||
if authorized := result.GetAuthorizedDownstreamWorkers(); authorized != nil {
|
||||
connectionState.DisconnectMissingWorkers(authorized.GetWorkerPublicIds())
|
||||
connectionState.DisconnectMissingUnmappedKeyIds(authorized.GetUnmappedWorkerKeyIdentifiers())
|
||||
}
|
||||
var addrs []string
|
||||
// This may be empty if we are in a multiple hop scenario
|
||||
if len(result.GetCalculatedUpstreamAddresses()) > 0 {
|
||||
addrs = result.GetCalculatedUpstreamAddresses()
|
||||
} else if checkHCPBUpstreams != nil && checkHCPBUpstreams(w) {
|
||||
// This is a worker that is one hop away from managed workers, so attempt to get that list
|
||||
hcpbWorkersCtx, hcpbWorkersCancel := context.WithTimeout(cancelCtx, time.Duration(w.routingInfoCallTimeoutDuration.Load()))
|
||||
defer hcpbWorkersCancel()
|
||||
workersResp, err := client.ListHcpbWorkers(hcpbWorkersCtx, &pbs.ListHcpbWorkersRequest{})
|
||||
if err != nil {
|
||||
event.WriteError(hcpbWorkersCtx, op, err, event.WithInfoMsg("error fetching managed worker information"))
|
||||
} else {
|
||||
addrs = make([]string, 0, len(workersResp.Workers))
|
||||
for _, v := range workersResp.Workers {
|
||||
addrs = append(addrs, v.Address)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
w.updateAddresses(cancelCtx, addrs)
|
||||
|
||||
w.lastRoutingInfoSuccess.Store(&LastRoutingInfo{RoutingInfoResponse: result, RoutingInfoTime: time.Now(), LastCalculatedUpstreams: addrs})
|
||||
|
||||
// If we have post hooks for after the first RoutingInfo check, run them now
|
||||
if w.everAuthenticated.CompareAndSwap(authenticationStatusFirstAuthentication, authenticationStatusFirstRoutingInfoRpcSuccessful) {
|
||||
if downstreamWorkersFactory != nil {
|
||||
downstreamWorkers, err := downstreamWorkersFactory(cancelCtx, w.LastRoutingInfoSuccess().WorkerId, versionInfo.FullVersionNumber(false))
|
||||
if err != nil {
|
||||
event.WriteError(cancelCtx, op, err)
|
||||
w.conf.ServerSideShutdownCh <- struct{}{}
|
||||
return
|
||||
}
|
||||
w.downstreamWorkers.Store(&graphContainer{graph: downstreamWorkers})
|
||||
}
|
||||
for _, fn := range firstRoutingInfoCheckPostHooks {
|
||||
if err := fn(cancelCtx, w); err != nil {
|
||||
// If we can't verify status we can't be expected to behave
|
||||
// properly so error and trigger shutdown
|
||||
event.WriteError(cancelCtx, op, fmt.Errorf("error running first routing info check post hook: %w", err))
|
||||
// We don't use a non-blocking select here to ensure that it
|
||||
// happens; we should catch blocks in tests but we want to
|
||||
// ensure the signal is being listened to
|
||||
w.conf.ServerSideShutdownCh <- struct{}{}
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (w *Worker) lastSuccessfulRoutingInfoTime() time.Time {
|
||||
lastRoutingInfo := w.LastRoutingInfoSuccess()
|
||||
if lastRoutingInfo == nil {
|
||||
return w.workerStartTime
|
||||
}
|
||||
|
||||
return lastRoutingInfo.RoutingInfoTime
|
||||
}
|
||||
|
||||
// Update address receivers and dialing listeners with new addrs
|
||||
func (w *Worker) updateAddresses(cancelCtx context.Context, addrs []string) {
|
||||
const op = "worker.(Worker).updateAddresses"
|
||||
|
||||
if len(addrs) > 0 {
|
||||
lastRoutingInfo := w.lastRoutingInfoSuccess.Load().(*LastRoutingInfo)
|
||||
// Compare upstreams; update resolver if there is a difference, and emit an event with old and new addresses
|
||||
if lastRoutingInfo != nil && !strutil.EquivalentSlices(lastRoutingInfo.LastCalculatedUpstreams, addrs) {
|
||||
upstreamsMessage := fmt.Sprintf("Upstreams has changed; old upstreams were: %s, new upstreams are: %s", lastRoutingInfo.LastCalculatedUpstreams, addrs)
|
||||
event.WriteSysEvent(cancelCtx, op, upstreamsMessage)
|
||||
for _, as := range w.addressReceivers {
|
||||
as.SetAddresses(addrs)
|
||||
}
|
||||
} else if lastRoutingInfo == nil {
|
||||
for _, as := range w.addressReceivers {
|
||||
as.SetAddresses(addrs)
|
||||
}
|
||||
event.WriteSysEvent(cancelCtx, op, fmt.Sprintf("Upstreams after first RoutingInfo set to: %s", addrs))
|
||||
}
|
||||
}
|
||||
|
||||
// regardless of whether or not it's a new address, we need to set
|
||||
// them for secondary connections
|
||||
for _, as := range w.addressReceivers {
|
||||
switch {
|
||||
case as.Type() == secondaryConnectionReceiverType:
|
||||
tmpAddrs := make([]string, len(addrs))
|
||||
copy(tmpAddrs, addrs)
|
||||
if len(tmpAddrs) == 0 {
|
||||
tmpAddrs = append(tmpAddrs, w.conf.RawConfig.Worker.InitialUpstreams...)
|
||||
}
|
||||
as.SetAddresses(tmpAddrs)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (w *Worker) isPastGrace() (bool, time.Time, time.Duration) {
|
||||
t := w.lastSuccessfulRoutingInfoTime()
|
||||
u := time.Duration(w.successfulRoutingInfoGracePeriod.Load())
|
||||
v := time.Since(t)
|
||||
return v > u, t, u
|
||||
}
|
||||
|
||||
// getRandomInterval returns a random duration between -0.5 and 0.5 seconds (exclusive).
|
||||
func getRandomInterval(r *rand.Rand) time.Duration {
|
||||
// 0 to 0.5 adjustment to the base
|
||||
f := r.Float64() / 2
|
||||
// Half a chance to be faster, not slower
|
||||
if r.Float32() > 0.5 {
|
||||
f = -1 * f
|
||||
}
|
||||
return time.Duration(f * float64(time.Second))
|
||||
}
|
||||
+11
-10
@@ -11,18 +11,19 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/hashicorp/boundary/internal/cmd/base"
|
||||
"github.com/hashicorp/boundary/internal/daemon/worker/common"
|
||||
"github.com/hashicorp/boundary/internal/event"
|
||||
"github.com/hashicorp/go-hclog"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestWorkerWaitForNextSuccessfulStatusUpdate(t *testing.T) {
|
||||
func TestWorkerWaitForNextSuccessfulRoutingInfoUpdate(t *testing.T) {
|
||||
testConfig := event.DefaultEventerConfig()
|
||||
testLock := &sync.Mutex{}
|
||||
testLogger := hclog.New(&hclog.LoggerOptions{
|
||||
Mutex: testLock,
|
||||
})
|
||||
err := event.InitSysEventer(testLogger, testLock, "TestWorkerWaitForNextSuccessfulStatusUpdate", event.WithEventerConfig(testConfig))
|
||||
err := event.InitSysEventer(testLogger, testLock, "TestWorkerWaitForNextSuccessfulRoutingInfoUpdate", event.WithEventerConfig(testConfig))
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { event.TestResetSystEventer(t) })
|
||||
for _, name := range []string{"ok", "timeout"} {
|
||||
@@ -31,30 +32,30 @@ func TestWorkerWaitForNextSuccessfulStatusUpdate(t *testing.T) {
|
||||
|
||||
// As-needed initialization of a mock worker
|
||||
w := &Worker{
|
||||
logger: hclog.New(nil),
|
||||
lastStatusSuccess: new(atomic.Value),
|
||||
baseContext: context.Background(),
|
||||
successfulStatusGracePeriod: new(atomic.Int64),
|
||||
logger: hclog.New(nil),
|
||||
lastRoutingInfoSuccess: new(atomic.Value),
|
||||
baseContext: context.Background(),
|
||||
successfulRoutingInfoGracePeriod: new(atomic.Int64),
|
||||
conf: &Config{
|
||||
Server: &base.Server{},
|
||||
},
|
||||
}
|
||||
|
||||
// This is present in New()
|
||||
w.lastStatusSuccess.Store((*LastStatusInformation)(nil))
|
||||
w.successfulStatusGracePeriod.Store(int64(time.Second * 2))
|
||||
w.lastRoutingInfoSuccess.Store((*LastRoutingInfo)(nil))
|
||||
w.successfulRoutingInfoGracePeriod.Store(int64(common.DefaultRoutingInfoTimeout))
|
||||
|
||||
var wg sync.WaitGroup
|
||||
var err error
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
err = w.WaitForNextSuccessfulStatusUpdate()
|
||||
err = w.WaitForNextSuccessfulRoutingInfoUpdate()
|
||||
wg.Done()
|
||||
}()
|
||||
|
||||
if name == "ok" {
|
||||
time.Sleep(time.Millisecond * 100)
|
||||
w.lastStatusSuccess.Store(&LastStatusInformation{StatusTime: time.Now()})
|
||||
w.lastRoutingInfoSuccess.Store(&LastRoutingInfo{RoutingInfoTime: time.Now()})
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
@@ -50,7 +50,7 @@ type Manager interface {
|
||||
|
||||
// RequestCloseConnections sends connection close requests to the
|
||||
// controller, and sets close times within the worker. It should be called
|
||||
// during the worker status loop and on connection exit on the proxy.
|
||||
// during the worker session info loop and on connection exit on the proxy.
|
||||
//
|
||||
// The boolean indicates whether the function was successful, e.g. had any
|
||||
// errors. Individual events will be sent for the errors if there are any.
|
||||
|
||||
@@ -480,7 +480,7 @@ func closeConnection(ctx context.Context, sessClient pbs.SessionServiceClient, r
|
||||
|
||||
// closeConnections is a helper worker function that sends connection close
|
||||
// requests to the controller, and sets close times within the worker. It is
|
||||
// called during the worker status loop and on connection exit on the proxy.
|
||||
// called during the worker session info loop and on connection exit on the proxy.
|
||||
//
|
||||
// The boolean indicates whether the function was successful, e.g. had any
|
||||
// errors. Individual events will be sent for the errors if there are any.
|
||||
@@ -499,9 +499,9 @@ func closeConnections(ctx context.Context, sessClient pbs.SessionServiceClient,
|
||||
var sessionCloseInfo map[string][]*pbs.CloseConnectionResponseData
|
||||
var err error
|
||||
|
||||
// TODO: This, along with the status call to the controller, probably needs a
|
||||
// TODO: This, along with the session info call to the controller, probably needs a
|
||||
// bit of formalization in terms of how we handle timeouts. For now, this
|
||||
// just ensures consistency with the same status call in that it times out
|
||||
// just ensures consistency with the same session info call in that it times out
|
||||
// within an adequate period of time.
|
||||
closeConnCtx, closeConnCancel := context.WithTimeout(ctx, time.Duration(CloseCallTimeout.Load()))
|
||||
defer closeConnCancel()
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
// Copyright (c) HashiCorp, Inc.
|
||||
// SPDX-License-Identifier: BUSL-1.1
|
||||
|
||||
package session
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
pbs "github.com/hashicorp/boundary/internal/gen/controller/servers/services"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// TestManager wraps a session manager. This wrapper allows direct manipulation of the sessions map for testing.
|
||||
type TestManager struct {
|
||||
*manager
|
||||
}
|
||||
|
||||
// NewTestManager returns a wrapped session manager that allows direct manipulation of the sessions map for testing
|
||||
func NewTestManager(t *testing.T, client pbs.SessionServiceClient) *TestManager {
|
||||
sm, err := NewManager(client)
|
||||
require.NoError(t, err)
|
||||
return &TestManager{
|
||||
manager: sm,
|
||||
}
|
||||
}
|
||||
|
||||
// StoreSession will mock an active local session with no connections in the session manager
|
||||
func (m *TestManager) StoreSession(sessionId string) {
|
||||
m.manager.sessionMap.Store(sessionId, &sess{
|
||||
lock: sync.RWMutex{},
|
||||
sessionId: sessionId,
|
||||
connInfoMap: make(map[string]*ConnInfo),
|
||||
status: pbs.SESSIONSTATUS_SESSIONSTATUS_ACTIVE,
|
||||
})
|
||||
}
|
||||
|
||||
// StoreConnection will mock a connection for the given session. The session is expected to already exist
|
||||
// in the session manager.
|
||||
func (m *TestManager) StoreConnection(t *testing.T, sessionId, connectionId string) {
|
||||
s, ok := m.manager.sessionMap.Load(sessionId)
|
||||
require.True(t, ok)
|
||||
localSession := s.(*sess)
|
||||
info := &ConnInfo{
|
||||
Id: connectionId,
|
||||
Status: pbs.CONNECTIONSTATUS_CONNECTIONSTATUS_CONNECTED,
|
||||
BytesUp: func() int64 {
|
||||
return 0
|
||||
},
|
||||
BytesDown: func() int64 {
|
||||
return 0
|
||||
},
|
||||
}
|
||||
info.connCtxCancelFunc = func() {
|
||||
info.Status = pbs.CONNECTIONSTATUS_CONNECTIONSTATUS_CLOSED
|
||||
}
|
||||
localSession.connInfoMap[connectionId] = info
|
||||
m.manager.sessionMap.Store(sessionId, localSession)
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
// Copyright (c) HashiCorp, Inc.
|
||||
// SPDX-License-Identifier: BUSL-1.1
|
||||
|
||||
package worker
|
||||
|
||||
import (
|
||||
"context"
|
||||
stderr "errors"
|
||||
"math/rand"
|
||||
"time"
|
||||
|
||||
"github.com/hashicorp/boundary/internal/daemon/worker/session"
|
||||
"github.com/hashicorp/boundary/internal/errors"
|
||||
"github.com/hashicorp/boundary/internal/event"
|
||||
pbs "github.com/hashicorp/boundary/internal/gen/controller/servers/services"
|
||||
)
|
||||
|
||||
// lastSessionInfo holds the last successful session info RPC time.
|
||||
type lastSessionInfo struct {
|
||||
LastSuccessfulRequestTime time.Time
|
||||
}
|
||||
|
||||
func (w *Worker) startSessionInfoTicking(cancelCtx context.Context) {
|
||||
const op = "worker.(Worker).startSessionInfoTicking"
|
||||
r := rand.New(rand.NewSource(time.Now().UnixNano()))
|
||||
timer := time.NewTimer(0)
|
||||
for {
|
||||
select {
|
||||
case <-cancelCtx.Done():
|
||||
event.WriteSysEvent(w.baseContext, op, "session infor ticking shutting down")
|
||||
return
|
||||
case <-timer.C:
|
||||
err := w.sendSessionInfo(cancelCtx)
|
||||
if err != nil {
|
||||
event.WriteError(w.baseContext, op, err)
|
||||
}
|
||||
// Add a bit of jitter to the wait, so we aren't always getting,
|
||||
// session information updates at the exact same intervals, to
|
||||
// ease the load on the DB.
|
||||
timer.Reset(w.sessionInfoInterval + getRandomInterval(r))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (w *Worker) sendSessionInfo(cancelCtx context.Context) error {
|
||||
const op = "worker.(Worker).sendSessionInfo"
|
||||
// skip when the workerId is not available
|
||||
if w.LastRoutingInfoSuccess() == nil {
|
||||
return errors.New(cancelCtx, errors.Internal, op, "missing latest routing info")
|
||||
}
|
||||
workerId := w.LastRoutingInfoSuccess().GetWorkerId()
|
||||
if workerId == "" {
|
||||
return errors.New(cancelCtx, errors.Internal, op, "worker id is empty")
|
||||
}
|
||||
|
||||
var recordedSessionIds []string
|
||||
if w.recorderManager != nil {
|
||||
recSessIds, err := w.recorderManager.SessionsManaged(cancelCtx)
|
||||
if err != nil {
|
||||
event.WriteError(cancelCtx, op, err, event.WithInfoMsg("error getting session ids from recorderManager"))
|
||||
}
|
||||
if len(recSessIds) != 0 {
|
||||
recordedSessionIds = append(recordedSessionIds, recSessIds...)
|
||||
}
|
||||
}
|
||||
|
||||
var activeSessions []*pbs.Session
|
||||
for _, sessionId := range recordedSessionIds {
|
||||
activeSessions = append(activeSessions, &pbs.Session{
|
||||
SessionId: sessionId,
|
||||
SessionType: pbs.SessionType_SESSION_TYPE_RECORDED,
|
||||
SessionStatus: pbs.SESSIONSTATUS_SESSIONSTATUS_ACTIVE,
|
||||
})
|
||||
}
|
||||
w.sessionManager.ForEachLocalSession(func(s session.Session) bool {
|
||||
activeSessions = append(activeSessions, &pbs.Session{
|
||||
SessionId: s.GetId(),
|
||||
SessionType: pbs.SessionType_SESSION_TYPE_INGRESSED,
|
||||
SessionStatus: s.GetStatus(),
|
||||
})
|
||||
return true
|
||||
})
|
||||
// skip when there are no sessions to report
|
||||
if len(activeSessions) == 0 {
|
||||
return nil
|
||||
}
|
||||
clientCon := w.GrpcClientConn.Load()
|
||||
client := pbs.NewServerCoordinationServiceClient(clientCon)
|
||||
sessionInfoCtx, statusCancel := context.WithTimeout(cancelCtx, time.Duration(w.sessionInfoCallTimeoutDuration.Load()))
|
||||
defer statusCancel()
|
||||
result, err := client.SessionInfo(sessionInfoCtx, &pbs.SessionInfoRequest{
|
||||
WorkerId: workerId,
|
||||
Sessions: activeSessions,
|
||||
})
|
||||
if err != nil {
|
||||
if isPastGrace, lastSessionInfoTime, gracePeriod := w.isPastSessionInfoGrace(); isPastGrace {
|
||||
event.WriteError(cancelCtx, op,
|
||||
stderr.New("session information error grace period has expired, canceling all sessions on worker"),
|
||||
event.WithInfo("last_session_info_time", lastSessionInfoTime.String(), "grace_period", gracePeriod),
|
||||
)
|
||||
// Cancel connections if grace period has expired. These Connections will be closed in the
|
||||
// database on the next successful status report, or via the Controller’s dead Worker cleanup connections job.
|
||||
w.sessionManager.ForEachLocalSession(func(s session.Session) bool {
|
||||
for _, connId := range s.CancelAllLocalConnections() {
|
||||
event.WriteSysEvent(cancelCtx, op, "terminated connection due to session information grace period expiration", "session_id", s.GetId(), "connection_id", connId)
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
return errors.Wrap(cancelCtx, err, op, errors.WithCode(errors.Internal), errors.WithMsg("error making session information request to controller: controller_address: %s", clientCon.Target()))
|
||||
}
|
||||
|
||||
w.lastSessionInfoSuccess.Store(&lastSessionInfo{
|
||||
LastSuccessfulRequestTime: time.Now(),
|
||||
})
|
||||
|
||||
var nonActiveRecordedSessionIds []string
|
||||
for _, s := range result.GetNonActiveSessions() {
|
||||
switch s.GetSessionType() {
|
||||
case pbs.SessionType_SESSION_TYPE_RECORDED:
|
||||
if s.SessionStatus != pbs.SESSIONSTATUS_SESSIONSTATUS_ACTIVE {
|
||||
nonActiveRecordedSessionIds = append(nonActiveRecordedSessionIds, s.GetSessionId())
|
||||
}
|
||||
case pbs.SessionType_SESSION_TYPE_INGRESSED:
|
||||
sessionId := s.GetSessionId()
|
||||
managedSession := w.sessionManager.Get(sessionId)
|
||||
if managedSession == nil {
|
||||
event.WriteError(cancelCtx, op, stderr.New("session change requested but could not find local information for it"), event.WithInfo("session_id", sessionId))
|
||||
continue
|
||||
}
|
||||
managedSession.ApplyLocalStatus(s.GetSessionStatus())
|
||||
// Update connection state if there are any connections in the request.
|
||||
for _, c := range s.GetConnections() {
|
||||
if err := managedSession.ApplyLocalConnectionStatus(c.GetConnectionId(), c.GetStatus()); err != nil {
|
||||
event.WriteError(cancelCtx, op, err, event.WithInfo("connection_id", c.GetConnectionId()))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if w.recorderManager != nil {
|
||||
if err := w.recorderManager.ReauthorizeAllExcept(cancelCtx, nonActiveRecordedSessionIds); err != nil {
|
||||
event.WriteError(cancelCtx, op, err)
|
||||
}
|
||||
}
|
||||
// Standard cleanup: Run through current jobs. Cancel connections
|
||||
// for any canceling session or any session that is expired.
|
||||
w.cleanupConnections(cancelCtx, false, w.sessionManager)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *Worker) isPastSessionInfoGrace() (bool, time.Time, time.Duration) {
|
||||
t := w.workerStartTime
|
||||
info := w.lastSessionInfoSuccess.Load().(*lastSessionInfo)
|
||||
if info != nil {
|
||||
t = info.LastSuccessfulRequestTime
|
||||
}
|
||||
u := time.Duration(w.successfulSessionInfoGracePeriod.Load())
|
||||
v := time.Since(t)
|
||||
return v > u, t, u
|
||||
}
|
||||
|
||||
// cleanupConnections walks all sessions and shuts down all proxy connections.
|
||||
// After the local connections are terminated, they are requested to be marked
|
||||
// closed on the controller.
|
||||
// Additionally, sessions without connections are cleaned up from the
|
||||
// local worker's state.
|
||||
//
|
||||
// Use ignoreSessionState to ignore the state checks, this closes all
|
||||
// connections, regardless of whether or not the session is still active.
|
||||
func (w *Worker) cleanupConnections(cancelCtx context.Context, ignoreSessionState bool, sessionManager session.Manager) {
|
||||
const op = "worker.(Worker).cleanupConnections"
|
||||
closeInfo := make(map[string]*session.ConnectionCloseData)
|
||||
cleanSessionIds := make([]string, 0)
|
||||
sessionManager.ForEachLocalSession(func(s session.Session) bool {
|
||||
switch {
|
||||
case ignoreSessionState,
|
||||
s.GetStatus() == pbs.SESSIONSTATUS_SESSIONSTATUS_CANCELING,
|
||||
s.GetStatus() == pbs.SESSIONSTATUS_SESSIONSTATUS_TERMINATED,
|
||||
time.Until(s.GetExpiration()) < 0:
|
||||
// Cancel connections without regard to individual connection
|
||||
// state.
|
||||
closedIds := s.CancelAllLocalConnections()
|
||||
localConns := s.GetLocalConnections()
|
||||
for _, connId := range closedIds {
|
||||
var bytesUp, bytesDown int64
|
||||
connInfo, ok := localConns[connId]
|
||||
if ok {
|
||||
bytesUp = connInfo.BytesUp()
|
||||
bytesDown = connInfo.BytesDown()
|
||||
}
|
||||
closeInfo[connId] = &session.ConnectionCloseData{
|
||||
SessionId: s.GetId(),
|
||||
BytesUp: bytesUp,
|
||||
BytesDown: bytesDown,
|
||||
}
|
||||
event.WriteSysEvent(cancelCtx, op, "terminated connection due to cancellation or expiration", "session_id", s.GetId(), "connection_id", connId)
|
||||
}
|
||||
|
||||
// If the session is no longer valid and all connections
|
||||
// are marked closed, clean up the session.
|
||||
if len(closedIds) == 0 {
|
||||
cleanSessionIds = append(cleanSessionIds, s.GetId())
|
||||
}
|
||||
|
||||
default:
|
||||
// Cancel connections *with* regard to individual connection
|
||||
// state (ie: only ones that the controller has requested be
|
||||
// terminated).
|
||||
for _, connId := range s.CancelOpenLocalConnections() {
|
||||
closeInfo[connId] = &session.ConnectionCloseData{SessionId: s.GetId()}
|
||||
event.WriteSysEvent(cancelCtx, op, "terminated connection due to cancellation or expiration", "session_id", s.GetId(), "connection_id", connId)
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
})
|
||||
|
||||
// Note that we won't clean these from the info map until the
|
||||
// next time we run this function
|
||||
if len(closeInfo) > 0 {
|
||||
// Call out to a helper to send the connection close requests to the
|
||||
// controller, and set the close time. This functionality is shared with
|
||||
// post-close functionality in the proxy handler.
|
||||
_ = sessionManager.RequestCloseConnections(cancelCtx, closeInfo)
|
||||
}
|
||||
// Forget sessions where the session is expired/canceled and all
|
||||
// connections are canceled and marked closed
|
||||
sessionManager.DeleteLocalSession(cleanSessionIds)
|
||||
}
|
||||
@@ -0,0 +1,337 @@
|
||||
// Copyright (c) HashiCorp, Inc.
|
||||
// SPDX-License-Identifier: BUSL-1.1
|
||||
|
||||
package worker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/hashicorp/boundary/internal/daemon/worker/session"
|
||||
pbs "github.com/hashicorp/boundary/internal/gen/controller/servers/services"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
)
|
||||
|
||||
func Test_sendSessionInfo(t *testing.T) {
|
||||
t.Parallel()
|
||||
tests := []struct {
|
||||
name string
|
||||
lastRoutingInfo *LastRoutingInfo
|
||||
sessionSetup func(sm *session.TestManager)
|
||||
expectedInternalErrMsg string
|
||||
expectedServerErrMsg string
|
||||
expectedSessions bool
|
||||
}{
|
||||
{
|
||||
name: "nil last routing info",
|
||||
expectedInternalErrMsg: "missing latest routing info",
|
||||
},
|
||||
{
|
||||
name: "empty worker id",
|
||||
lastRoutingInfo: &LastRoutingInfo{
|
||||
RoutingInfoResponse: &pbs.RoutingInfoResponse{},
|
||||
},
|
||||
expectedInternalErrMsg: "worker id is empty",
|
||||
},
|
||||
{
|
||||
name: "empty sessions",
|
||||
lastRoutingInfo: &LastRoutingInfo{
|
||||
RoutingInfoResponse: &pbs.RoutingInfoResponse{
|
||||
WorkerId: "w_1234567890",
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "server error",
|
||||
lastRoutingInfo: &LastRoutingInfo{
|
||||
RoutingInfoResponse: &pbs.RoutingInfoResponse{
|
||||
WorkerId: "w_1234567890",
|
||||
},
|
||||
},
|
||||
sessionSetup: func(sm *session.TestManager) {
|
||||
require.NotNil(t, sm)
|
||||
sm.StoreSession("s_1234567890")
|
||||
sm.StoreConnection(t, "s_1234567890", "c_1234567890")
|
||||
},
|
||||
expectedServerErrMsg: "testing connection timeout",
|
||||
},
|
||||
{
|
||||
name: "success",
|
||||
lastRoutingInfo: &LastRoutingInfo{
|
||||
RoutingInfoResponse: &pbs.RoutingInfoResponse{
|
||||
WorkerId: "w_1234567890",
|
||||
},
|
||||
},
|
||||
sessionSetup: func(sm *session.TestManager) {
|
||||
require.NotNil(t, sm)
|
||||
sm.StoreSession("s_1234567890")
|
||||
sm.StoreConnection(t, "s_1234567890", "c_1234567890")
|
||||
},
|
||||
expectedSessions: true,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
assert, require := assert.New(t), require.New(t)
|
||||
|
||||
w := NewTestWorker(t, &TestWorkerOpts{
|
||||
DisableAutoStart: true,
|
||||
Name: tt.name,
|
||||
})
|
||||
// Ensure the recorder manager is not used
|
||||
w.Worker().recorderManager = nil
|
||||
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
require.NoError(err)
|
||||
cc, err := grpc.Dial(ln.Addr().String(), grpc.WithTransportCredentials(insecure.NewCredentials()))
|
||||
require.NoError(err)
|
||||
|
||||
mockSessionClient := pbs.NewMockSessionServiceClient()
|
||||
mockSessionClient.CloseConnectionFn = func(ctx context.Context, req *pbs.CloseConnectionRequest) (*pbs.CloseConnectionResponse, error) {
|
||||
return &pbs.CloseConnectionResponse{}, nil
|
||||
}
|
||||
sm := session.NewTestManager(t, mockSessionClient)
|
||||
if tt.sessionSetup != nil {
|
||||
tt.sessionSetup(sm)
|
||||
}
|
||||
w.Worker().sessionManager = sm
|
||||
|
||||
serverInvoked := false
|
||||
fakeServer := &mockServerCoordinationService{
|
||||
nextSessionInfoAssert: func(req *pbs.SessionInfoRequest) (*pbs.SessionInfoResponse, error) {
|
||||
serverInvoked = true
|
||||
if tt.expectedInternalErrMsg != "" {
|
||||
assert.Fail("server should not send session information for internal errors")
|
||||
}
|
||||
if tt.expectedServerErrMsg != "" {
|
||||
return &pbs.SessionInfoResponse{}, errors.New(tt.expectedServerErrMsg)
|
||||
}
|
||||
if !tt.expectedSessions {
|
||||
assert.Fail("server should not send session information when there are no managed sessions")
|
||||
}
|
||||
require.NotNil(req)
|
||||
|
||||
assert.Equal("w_1234567890", req.WorkerId)
|
||||
require.Len(req.Sessions, 1)
|
||||
assert.Equal("s_1234567890", req.Sessions[0].SessionId)
|
||||
|
||||
return &pbs.SessionInfoResponse{}, nil
|
||||
},
|
||||
}
|
||||
|
||||
srv := grpc.NewServer()
|
||||
pbs.RegisterServerCoordinationServiceServer(srv, fakeServer)
|
||||
w.Worker().GrpcClientConn.Store(cc)
|
||||
w.Worker().lastRoutingInfoSuccess.Store(tt.lastRoutingInfo)
|
||||
|
||||
serverStarted := make(chan struct{})
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
close(serverStarted)
|
||||
assert.NoError(srv.Serve(ln))
|
||||
}()
|
||||
|
||||
<-serverStarted
|
||||
actualErr := w.Worker().sendSessionInfo(context.Background())
|
||||
|
||||
if tt.expectedInternalErrMsg != "" {
|
||||
require.Error(actualErr)
|
||||
assert.ErrorContains(actualErr, tt.expectedInternalErrMsg)
|
||||
assert.False(serverInvoked)
|
||||
return
|
||||
}
|
||||
if tt.expectedServerErrMsg != "" {
|
||||
require.Error(actualErr)
|
||||
assert.ErrorContains(actualErr, tt.expectedServerErrMsg)
|
||||
assert.True(serverInvoked)
|
||||
return
|
||||
}
|
||||
require.NoError(actualErr)
|
||||
require.Equal(tt.expectedSessions, serverInvoked)
|
||||
|
||||
srv.GracefulStop()
|
||||
wg.Wait()
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("close non active managed sessions connections and ignore non existing sessions", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
assert, require := assert.New(t), require.New(t)
|
||||
|
||||
w := NewTestWorker(t, &TestWorkerOpts{
|
||||
DisableAutoStart: true,
|
||||
Name: "close non active sessions and connections",
|
||||
})
|
||||
// Ensure the recorder manager is not used
|
||||
w.Worker().recorderManager = nil
|
||||
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
require.NoError(err)
|
||||
cc, err := grpc.Dial(ln.Addr().String(), grpc.WithTransportCredentials(insecure.NewCredentials()))
|
||||
require.NoError(err)
|
||||
|
||||
mockSessionClient := pbs.NewMockSessionServiceClient()
|
||||
mockSessionClient.CloseConnectionFn = func(ctx context.Context, req *pbs.CloseConnectionRequest) (*pbs.CloseConnectionResponse, error) {
|
||||
return &pbs.CloseConnectionResponse{}, nil
|
||||
}
|
||||
sm := session.NewTestManager(t, mockSessionClient)
|
||||
sm.StoreSession("s_1234567890")
|
||||
sm.StoreConnection(t, "s_1234567890", "c_1234567890")
|
||||
w.Worker().sessionManager = sm
|
||||
|
||||
serverInvoked := false
|
||||
fakeServer := &mockServerCoordinationService{
|
||||
nextSessionInfoAssert: func(req *pbs.SessionInfoRequest) (*pbs.SessionInfoResponse, error) {
|
||||
serverInvoked = true
|
||||
assert.Equal("w_1234567890", req.WorkerId)
|
||||
require.Len(req.Sessions, 1)
|
||||
assert.Equal("s_1234567890", req.Sessions[0].SessionId)
|
||||
return &pbs.SessionInfoResponse{
|
||||
NonActiveSessions: []*pbs.Session{
|
||||
{
|
||||
SessionId: "s_1234567890",
|
||||
SessionStatus: pbs.SESSIONSTATUS_SESSIONSTATUS_TERMINATED,
|
||||
SessionType: pbs.SessionType_SESSION_TYPE_INGRESSED,
|
||||
Connections: []*pbs.Connection{
|
||||
{
|
||||
ConnectionId: "c_1234567890",
|
||||
Status: pbs.CONNECTIONSTATUS_CONNECTIONSTATUS_CLOSED,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
SessionId: "s_dne",
|
||||
SessionStatus: pbs.SESSIONSTATUS_SESSIONSTATUS_TERMINATED,
|
||||
SessionType: pbs.SessionType_SESSION_TYPE_INGRESSED,
|
||||
Connections: []*pbs.Connection{
|
||||
{
|
||||
ConnectionId: "c_dne",
|
||||
Status: pbs.CONNECTIONSTATUS_CONNECTIONSTATUS_CLOSED,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}, nil
|
||||
},
|
||||
}
|
||||
|
||||
srv := grpc.NewServer()
|
||||
pbs.RegisterServerCoordinationServiceServer(srv, fakeServer)
|
||||
w.Worker().GrpcClientConn.Store(cc)
|
||||
w.Worker().lastRoutingInfoSuccess.Store(&LastRoutingInfo{
|
||||
RoutingInfoResponse: &pbs.RoutingInfoResponse{
|
||||
WorkerId: "w_1234567890",
|
||||
},
|
||||
})
|
||||
|
||||
serverStarted := make(chan struct{})
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
close(serverStarted)
|
||||
assert.NoError(srv.Serve(ln))
|
||||
}()
|
||||
|
||||
<-serverStarted
|
||||
actualErr := w.Worker().sendSessionInfo(context.Background())
|
||||
|
||||
require.NoError(actualErr)
|
||||
assert.True(serverInvoked)
|
||||
closedSession := w.Worker().sessionManager.Get("s_1234567890")
|
||||
assert.Nil(closedSession)
|
||||
|
||||
srv.GracefulStop()
|
||||
wg.Wait()
|
||||
})
|
||||
|
||||
t.Run("validate closing local connections after last successful session info grace period", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
assert, require := assert.New(t), require.New(t)
|
||||
|
||||
w := NewTestWorker(t, &TestWorkerOpts{
|
||||
DisableAutoStart: true,
|
||||
Name: "close non active sessions and connections",
|
||||
})
|
||||
// Ensure the recorder manager is not used
|
||||
w.Worker().recorderManager = nil
|
||||
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
require.NoError(err)
|
||||
cc, err := grpc.Dial(ln.Addr().String(), grpc.WithTransportCredentials(insecure.NewCredentials()))
|
||||
require.NoError(err)
|
||||
|
||||
mockSessionClient := pbs.NewMockSessionServiceClient()
|
||||
mockSessionClient.CloseConnectionFn = func(ctx context.Context, req *pbs.CloseConnectionRequest) (*pbs.CloseConnectionResponse, error) {
|
||||
return &pbs.CloseConnectionResponse{}, nil
|
||||
}
|
||||
sm := session.NewTestManager(t, mockSessionClient)
|
||||
sm.StoreSession("s_1234567890")
|
||||
sm.StoreConnection(t, "s_1234567890", "c_1234567890")
|
||||
w.Worker().sessionManager = sm
|
||||
|
||||
serverInvoked := false
|
||||
fakeServer := &mockServerCoordinationService{
|
||||
nextSessionInfoAssert: func(req *pbs.SessionInfoRequest) (*pbs.SessionInfoResponse, error) {
|
||||
serverInvoked = true
|
||||
assert.Equal("w_1234567890", req.WorkerId)
|
||||
require.Len(req.Sessions, 1)
|
||||
assert.Equal("s_1234567890", req.Sessions[0].SessionId)
|
||||
return &pbs.SessionInfoResponse{}, errors.New("connection timeout")
|
||||
},
|
||||
}
|
||||
|
||||
srv := grpc.NewServer()
|
||||
pbs.RegisterServerCoordinationServiceServer(srv, fakeServer)
|
||||
w.Worker().GrpcClientConn.Store(cc)
|
||||
w.Worker().lastRoutingInfoSuccess.Store(&LastRoutingInfo{
|
||||
RoutingInfoResponse: &pbs.RoutingInfoResponse{
|
||||
WorkerId: "w_1234567890",
|
||||
},
|
||||
})
|
||||
// Set the status time of the last successful session information
|
||||
// to a value that ensures we have surpassed the grace period time.
|
||||
gracePeriod := time.Duration(w.Worker().successfulSessionInfoGracePeriod.Load()) + (5 * time.Second)
|
||||
w.Worker().lastSessionInfoSuccess.Store(&lastSessionInfo{
|
||||
LastSuccessfulRequestTime: time.Now().Add(-gracePeriod),
|
||||
})
|
||||
|
||||
serverStarted := make(chan struct{})
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
close(serverStarted)
|
||||
assert.NoError(srv.Serve(ln))
|
||||
}()
|
||||
|
||||
<-serverStarted
|
||||
actualErr := w.Worker().sendSessionInfo(context.Background())
|
||||
|
||||
require.Error(actualErr)
|
||||
assert.ErrorContains(actualErr, "connection timeout")
|
||||
assert.True(serverInvoked)
|
||||
localSession := w.Worker().sessionManager.Get("s_1234567890")
|
||||
require.NotNil(localSession)
|
||||
assert.Equal(pbs.SESSIONSTATUS_SESSIONSTATUS_ACTIVE, localSession.GetStatus())
|
||||
localConnections := localSession.GetLocalConnections()
|
||||
require.NotEmpty(localConnections)
|
||||
c, ok := localConnections["c_1234567890"]
|
||||
require.True(ok)
|
||||
require.NotNil(c)
|
||||
assert.Equal(pbs.CONNECTIONSTATUS_CONNECTIONSTATUS_CLOSED, c.Status)
|
||||
|
||||
srv.GracefulStop()
|
||||
wg.Wait()
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
// Copyright (c) HashiCorp, Inc.
|
||||
// SPDX-License-Identifier: BUSL-1.1
|
||||
|
||||
package worker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"math/rand"
|
||||
"time"
|
||||
|
||||
"github.com/hashicorp/boundary/internal/daemon/worker/session"
|
||||
"github.com/hashicorp/boundary/internal/errors"
|
||||
"github.com/hashicorp/boundary/internal/event"
|
||||
pbs "github.com/hashicorp/boundary/internal/gen/controller/servers/services"
|
||||
)
|
||||
|
||||
// lastStatistics holds the last successful statistics RPC time.
|
||||
type lastStatistics struct {
|
||||
LastSuccessfulRequestTime time.Time
|
||||
}
|
||||
|
||||
func (w *Worker) startStatisticsTicking(cancelCtx context.Context) {
|
||||
const op = "worker.(Worker).startStatisticsTicking"
|
||||
r := rand.New(rand.NewSource(time.Now().UnixNano()))
|
||||
timer := time.NewTimer(0)
|
||||
for {
|
||||
select {
|
||||
case <-cancelCtx.Done():
|
||||
event.WriteSysEvent(w.baseContext, op, "statistics ticking shutting down")
|
||||
return
|
||||
case <-timer.C:
|
||||
err := w.sendStatistic(cancelCtx)
|
||||
if err != nil {
|
||||
event.WriteError(w.baseContext, op, err)
|
||||
}
|
||||
// Add a bit of jitter to the wait, so we aren't always getting,
|
||||
// statistics updates at the exact same intervals, to ease the load on the DB.
|
||||
timer.Reset(w.statisticsInterval + getRandomInterval(r))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (w *Worker) sendStatistic(cancelCtx context.Context) error {
|
||||
const op = "worker.(Worker).sendStatistic"
|
||||
// skip when the workerId is not available
|
||||
if w.LastRoutingInfoSuccess() == nil {
|
||||
return errors.New(cancelCtx, errors.Internal, op, "missing latest status")
|
||||
}
|
||||
workerId := w.LastRoutingInfoSuccess().GetWorkerId()
|
||||
if workerId == "" {
|
||||
return errors.New(cancelCtx, errors.Internal, op, "worker id is empty")
|
||||
}
|
||||
sessions := []*pbs.SessionStatistics{}
|
||||
w.sessionManager.ForEachLocalSession(func(s session.Session) bool {
|
||||
localConnections := s.GetLocalConnections()
|
||||
connections := make([]*pbs.Connection, 0, len(localConnections))
|
||||
for connectionId, conn := range localConnections {
|
||||
connections = append(connections, &pbs.Connection{
|
||||
ConnectionId: connectionId,
|
||||
BytesUp: conn.BytesUp(),
|
||||
BytesDown: conn.BytesDown(),
|
||||
Status: conn.Status,
|
||||
})
|
||||
}
|
||||
sessions = append(sessions, &pbs.SessionStatistics{
|
||||
SessionId: s.GetId(),
|
||||
Connections: connections,
|
||||
})
|
||||
return true
|
||||
})
|
||||
// skip when there are no sessions to report
|
||||
if len(sessions) == 0 {
|
||||
return nil
|
||||
}
|
||||
clientCon := w.GrpcClientConn.Load()
|
||||
client := pbs.NewServerCoordinationServiceClient(clientCon)
|
||||
statisticsCtx, statusCancel := context.WithTimeout(cancelCtx, time.Duration(w.statisticsCallTimeoutDuration.Load()))
|
||||
defer statusCancel()
|
||||
_, err := client.Statistics(statisticsCtx, &pbs.StatisticsRequest{
|
||||
WorkerId: workerId,
|
||||
Sessions: sessions,
|
||||
})
|
||||
if err != nil {
|
||||
return errors.Wrap(cancelCtx, err, op, errors.WithCode(errors.Internal), errors.WithMsg("error making statistics request to controller: controller_address: %s", clientCon.Target()))
|
||||
}
|
||||
|
||||
w.lastStatisticsSuccess.Store(&lastStatistics{
|
||||
LastSuccessfulRequestTime: time.Now(),
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
// Copyright (c) HashiCorp, Inc.
|
||||
// SPDX-License-Identifier: BUSL-1.1
|
||||
|
||||
package worker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/hashicorp/boundary/internal/daemon/worker/session"
|
||||
pbs "github.com/hashicorp/boundary/internal/gen/controller/servers/services"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
)
|
||||
|
||||
func Test_sendStatistic(t *testing.T) {
|
||||
t.Parallel()
|
||||
tests := []struct {
|
||||
name string
|
||||
lastRoutingInfo *LastRoutingInfo
|
||||
sessionSetup func(sm *session.TestManager)
|
||||
expectedInternalErrMsg string
|
||||
expectedServerErrMsg string
|
||||
expectedSessions bool
|
||||
}{
|
||||
{
|
||||
name: "nil last status",
|
||||
expectedInternalErrMsg: "missing latest status",
|
||||
},
|
||||
{
|
||||
name: "empty worker id",
|
||||
lastRoutingInfo: &LastRoutingInfo{
|
||||
RoutingInfoResponse: &pbs.RoutingInfoResponse{},
|
||||
},
|
||||
expectedInternalErrMsg: "worker id is empty",
|
||||
},
|
||||
{
|
||||
name: "empty sessions",
|
||||
lastRoutingInfo: &LastRoutingInfo{
|
||||
RoutingInfoResponse: &pbs.RoutingInfoResponse{
|
||||
WorkerId: "w_1234567890",
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "server error",
|
||||
lastRoutingInfo: &LastRoutingInfo{
|
||||
RoutingInfoResponse: &pbs.RoutingInfoResponse{
|
||||
WorkerId: "w_1234567890",
|
||||
},
|
||||
},
|
||||
sessionSetup: func(sm *session.TestManager) {
|
||||
require.NotNil(t, sm)
|
||||
sm.StoreSession("s_1234567890")
|
||||
sm.StoreConnection(t, "s_1234567890", "c_1234567890")
|
||||
},
|
||||
expectedServerErrMsg: "testing connection timeout",
|
||||
},
|
||||
{
|
||||
name: "success",
|
||||
lastRoutingInfo: &LastRoutingInfo{
|
||||
RoutingInfoResponse: &pbs.RoutingInfoResponse{
|
||||
WorkerId: "w_1234567890",
|
||||
},
|
||||
},
|
||||
sessionSetup: func(sm *session.TestManager) {
|
||||
require.NotNil(t, sm)
|
||||
sm.StoreSession("s_1234567890")
|
||||
sm.StoreConnection(t, "s_1234567890", "c_1234567890")
|
||||
},
|
||||
expectedSessions: true,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
assert, require := assert.New(t), require.New(t)
|
||||
|
||||
w := NewTestWorker(t, &TestWorkerOpts{
|
||||
DisableAutoStart: true,
|
||||
Name: tt.name,
|
||||
})
|
||||
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
require.NoError(err)
|
||||
cc, err := grpc.Dial(ln.Addr().String(), grpc.WithTransportCredentials(insecure.NewCredentials()))
|
||||
require.NoError(err)
|
||||
|
||||
sm := session.NewTestManager(t, pbs.NewMockSessionServiceClient())
|
||||
if tt.sessionSetup != nil {
|
||||
tt.sessionSetup(sm)
|
||||
}
|
||||
w.Worker().sessionManager = sm
|
||||
|
||||
serverInvoked := false
|
||||
fakeServer := &mockServerCoordinationService{
|
||||
nextStatisticAssert: func(req *pbs.StatisticsRequest) (*pbs.StatisticsResponse, error) {
|
||||
serverInvoked = true
|
||||
if tt.expectedInternalErrMsg != "" {
|
||||
assert.Fail("server should not send statistics information for internal errors")
|
||||
}
|
||||
if tt.expectedServerErrMsg != "" {
|
||||
return &pbs.StatisticsResponse{}, errors.New(tt.expectedServerErrMsg)
|
||||
}
|
||||
if !tt.expectedSessions {
|
||||
assert.Fail("server should not send statistics information when there are no managed sessions")
|
||||
}
|
||||
require.NotNil(req)
|
||||
assert.Equal("w_1234567890", req.WorkerId)
|
||||
require.Len(req.Sessions, 1)
|
||||
assert.Equal("s_1234567890", req.Sessions[0].SessionId)
|
||||
require.Len(req.Sessions[0].Connections, 1)
|
||||
assert.Equal("c_1234567890", req.Sessions[0].Connections[0].ConnectionId)
|
||||
return &pbs.StatisticsResponse{}, nil
|
||||
},
|
||||
}
|
||||
srv := grpc.NewServer()
|
||||
pbs.RegisterServerCoordinationServiceServer(srv, fakeServer)
|
||||
w.Worker().GrpcClientConn.Store(cc)
|
||||
w.Worker().lastRoutingInfoSuccess.Store(tt.lastRoutingInfo)
|
||||
|
||||
serverStarted := make(chan struct{})
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
close(serverStarted)
|
||||
assert.NoError(srv.Serve(ln))
|
||||
}()
|
||||
|
||||
<-serverStarted
|
||||
actualErr := w.Worker().sendStatistic(context.Background())
|
||||
|
||||
if tt.expectedInternalErrMsg != "" {
|
||||
require.Error(actualErr)
|
||||
assert.ErrorContains(actualErr, tt.expectedInternalErrMsg)
|
||||
assert.False(serverInvoked)
|
||||
return
|
||||
}
|
||||
if tt.expectedServerErrMsg != "" {
|
||||
require.Error(actualErr)
|
||||
assert.ErrorContains(actualErr, tt.expectedServerErrMsg)
|
||||
assert.True(serverInvoked)
|
||||
return
|
||||
}
|
||||
require.NoError(actualErr)
|
||||
require.Equal(tt.expectedSessions, serverInvoked)
|
||||
|
||||
srv.GracefulStop()
|
||||
wg.Wait()
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,519 +0,0 @@
|
||||
// Copyright (c) HashiCorp, Inc.
|
||||
// SPDX-License-Identifier: BUSL-1.1
|
||||
|
||||
package worker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"time"
|
||||
|
||||
"github.com/hashicorp/boundary/internal/daemon/worker/common"
|
||||
"github.com/hashicorp/boundary/internal/daemon/worker/session"
|
||||
"github.com/hashicorp/boundary/internal/event"
|
||||
pb "github.com/hashicorp/boundary/internal/gen/controller/servers"
|
||||
pbs "github.com/hashicorp/boundary/internal/gen/controller/servers/services"
|
||||
"github.com/hashicorp/boundary/internal/server"
|
||||
"github.com/hashicorp/boundary/sdk/pbs/plugin"
|
||||
"github.com/hashicorp/boundary/version"
|
||||
"github.com/hashicorp/go-secure-stdlib/parseutil"
|
||||
"github.com/hashicorp/go-secure-stdlib/strutil"
|
||||
"google.golang.org/grpc/connectivity"
|
||||
)
|
||||
|
||||
var firstStatusCheckPostHooks []func(context.Context, *Worker) error
|
||||
|
||||
var downstreamWorkersFactory func(ctx context.Context, workerId string, ver string) (graph, error)
|
||||
|
||||
var checkHCPBUpstreams func(w *Worker) bool
|
||||
|
||||
type LastStatusInformation struct {
|
||||
*pbs.StatusResponse
|
||||
StatusTime time.Time
|
||||
LastCalculatedUpstreams []string
|
||||
}
|
||||
|
||||
func (w *Worker) startStatusTicking(cancelCtx context.Context, sessionManager session.Manager, addrReceivers *[]addressReceiver, recorderManager recorderManager) {
|
||||
const op = "worker.(Worker).startStatusTicking"
|
||||
r := rand.New(rand.NewSource(time.Now().UnixNano()))
|
||||
// This function exists to desynchronize calls to controllers from
|
||||
// workers, so we aren't always getting status updates at the exact same
|
||||
// intervals, to ease the load on the DB.
|
||||
getRandomInterval := func() time.Duration {
|
||||
// 0 to 0.5 adjustment to the base
|
||||
f := r.Float64() / 2
|
||||
// Half a chance to be faster, not slower
|
||||
if r.Float32() > 0.5 {
|
||||
f = -1 * f
|
||||
}
|
||||
return common.StatusInterval + time.Duration(f*float64(time.Second))
|
||||
}
|
||||
|
||||
timer := time.NewTimer(0)
|
||||
for {
|
||||
select {
|
||||
case <-cancelCtx.Done():
|
||||
event.WriteSysEvent(w.baseContext, op, "status ticking shutting down")
|
||||
return
|
||||
|
||||
case <-timer.C:
|
||||
// If we've never managed to successfully authenticate then we won't have
|
||||
// any session information anyways and this will produce a ton of noise in
|
||||
// observability, so skip calling the function and retry in a short duration
|
||||
if w.everAuthenticated.Load() == authenticationStatusNeverAuthenticated {
|
||||
timer.Reset(10 * time.Millisecond)
|
||||
continue
|
||||
}
|
||||
|
||||
w.sendWorkerStatus(cancelCtx, sessionManager, addrReceivers, recorderManager)
|
||||
timer.Reset(getRandomInterval())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// LastStatusSuccess reports the last time we sent a successful
|
||||
// status request.
|
||||
func (w *Worker) LastStatusSuccess() *LastStatusInformation {
|
||||
s, ok := w.lastStatusSuccess.Load().(*LastStatusInformation)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// WaitForNextSuccessfulStatusUpdate waits for the next successful status. It's
|
||||
// used by testing (and in the future, shutdown) in place of a more opaque and
|
||||
// possibly unnecessarily long sleep for things like initial controller
|
||||
// check-in, etc.
|
||||
//
|
||||
// The timeout is aligned with the worker's status grace period. A nil error
|
||||
// means the status was sent successfully.
|
||||
func (w *Worker) WaitForNextSuccessfulStatusUpdate() error {
|
||||
const op = "worker.(Worker).WaitForNextSuccessfulStatusUpdate"
|
||||
waitStatusStart := time.Now()
|
||||
ctx, cancel := context.WithTimeout(w.baseContext, time.Duration(w.successfulStatusGracePeriod.Load()))
|
||||
defer cancel()
|
||||
event.WriteSysEvent(ctx, op, "waiting for next status report to controller")
|
||||
for {
|
||||
select {
|
||||
case <-time.After(time.Second):
|
||||
// pass
|
||||
|
||||
case <-ctx.Done():
|
||||
event.WriteError(ctx, op, ctx.Err(), event.WithInfoMsg("error waiting for next status report to controller"))
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
if w.lastSuccessfulStatusTime().After(waitStatusStart) {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
event.WriteSysEvent(ctx, op, "next worker status update sent successfully")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *Worker) sendWorkerStatus(cancelCtx context.Context, sessionManager session.Manager, addressReceivers *[]addressReceiver, recorderManager recorderManager) {
|
||||
const op = "worker.(Worker).sendWorkerStatus"
|
||||
w.statusLock.Lock()
|
||||
defer w.statusLock.Unlock()
|
||||
|
||||
// Collect the different session ids that are being monitored by this worker
|
||||
var monitoredSessionIds []string
|
||||
|
||||
if recorderManager != nil {
|
||||
recSessIds, err := recorderManager.SessionsManaged(cancelCtx)
|
||||
if err != nil {
|
||||
event.WriteError(cancelCtx, op, err, event.WithInfoMsg("error getting session ids from recorderManager"))
|
||||
} else {
|
||||
monitoredSessionIds = append(monitoredSessionIds, recSessIds...)
|
||||
}
|
||||
}
|
||||
|
||||
// First send info as-is. We'll perform cleanup duties after we
|
||||
// get cancel/job change info back.
|
||||
var activeJobs []*pbs.JobStatus
|
||||
|
||||
for _, sid := range monitoredSessionIds {
|
||||
activeJobs = append(activeJobs, &pbs.JobStatus{
|
||||
Job: &pbs.Job{
|
||||
Type: pbs.JOBTYPE_JOBTYPE_MONITOR_SESSION,
|
||||
JobInfo: &pbs.Job_MonitorSessionInfo{
|
||||
MonitorSessionInfo: &pbs.MonitorSessionJobInfo{
|
||||
SessionId: sid,
|
||||
Status: pbs.SESSIONSTATUS_SESSIONSTATUS_ACTIVE,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// Range over known sessions and collect info
|
||||
sessionManager.ForEachLocalSession(func(s session.Session) bool {
|
||||
var jobInfo pbs.SessionJobInfo
|
||||
status := s.GetStatus()
|
||||
sessionId := s.GetId()
|
||||
localConnections := s.GetLocalConnections()
|
||||
connections := make([]*pbs.Connection, 0, len(localConnections))
|
||||
for k, v := range localConnections {
|
||||
connections = append(connections, &pbs.Connection{
|
||||
ConnectionId: k,
|
||||
Status: v.Status,
|
||||
BytesUp: v.BytesUp(),
|
||||
BytesDown: v.BytesDown(),
|
||||
})
|
||||
}
|
||||
jobInfo.SessionId = sessionId
|
||||
activeJobs = append(activeJobs, &pbs.JobStatus{
|
||||
Job: &pbs.Job{
|
||||
Type: pbs.JOBTYPE_JOBTYPE_SESSION,
|
||||
JobInfo: &pbs.Job_SessionInfo{
|
||||
SessionInfo: &pbs.SessionJobInfo{
|
||||
SessionId: sessionId,
|
||||
Status: status,
|
||||
Connections: connections,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
return true
|
||||
})
|
||||
|
||||
clientCon := w.GrpcClientConn.Load()
|
||||
// Send status information
|
||||
client := pbs.NewServerCoordinationServiceClient(clientCon)
|
||||
var tags []*pb.TagPair
|
||||
// If we're not going to request a tag update, no reason to have these
|
||||
// marshaled on every status call.
|
||||
if w.updateTags.Load() {
|
||||
tags = w.tags.Load().([]*pb.TagPair)
|
||||
}
|
||||
statusCtx, statusCancel := context.WithTimeout(cancelCtx, time.Duration(w.statusCallTimeoutDuration.Load()))
|
||||
defer statusCancel()
|
||||
|
||||
keyId := w.WorkerAuthCurrentKeyId.Load()
|
||||
switch {
|
||||
case w.conf.RawConfig.Worker.Name == "" && keyId == "":
|
||||
event.WriteError(cancelCtx, op, errors.New("worker name and keyId are both empty; at least one is needed to identify a worker"),
|
||||
event.WithInfoMsg("error making status request to controller"))
|
||||
}
|
||||
|
||||
var storageBucketCredentialStates map[string]*plugin.StorageBucketCredentialState
|
||||
if w.RecordingStorage != nil {
|
||||
storageBucketCredentialStates = w.RecordingStorage.GetStorageBucketCredentialStates()
|
||||
// If the local storage state is unknown, and we have recording storage set, get the state from the recording storage
|
||||
// and set it on the worker. This is done once to ensure that the worker has the correct state for the first status
|
||||
// call.
|
||||
if w.localStorageState.Load() == server.UnknownLocalStorageState {
|
||||
w.localStorageState.Store(w.RecordingStorage.GetLocalStorageState(cancelCtx))
|
||||
}
|
||||
}
|
||||
versionInfo := version.Get()
|
||||
connectionState := w.downstreamConnManager.Connected()
|
||||
result, err := client.Status(statusCtx, &pbs.StatusRequest{
|
||||
Jobs: activeJobs,
|
||||
WorkerStatus: &pb.ServerWorkerStatus{
|
||||
Name: w.conf.RawConfig.Worker.Name,
|
||||
Description: w.conf.RawConfig.Worker.Description,
|
||||
Address: w.conf.RawConfig.Worker.PublicAddr,
|
||||
Tags: tags,
|
||||
KeyId: keyId,
|
||||
ReleaseVersion: versionInfo.FullVersionNumber(false),
|
||||
OperationalState: w.operationalState.Load().(server.OperationalState).String(),
|
||||
LocalStorageState: w.localStorageState.Load().(server.LocalStorageState).String(),
|
||||
StorageBucketCredentialStates: storageBucketCredentialStates,
|
||||
},
|
||||
ConnectedWorkerKeyIdentifiers: connectionState.AllKeyIds(),
|
||||
ConnectedUnmappedWorkerKeyIdentifiers: connectionState.UnmappedKeyIds(),
|
||||
ConnectedWorkerPublicIds: connectionState.WorkerIds(),
|
||||
UpdateTags: w.updateTags.Load(),
|
||||
})
|
||||
if err != nil {
|
||||
event.WriteError(cancelCtx, op, err, event.WithInfoMsg("error making status request to controller", "controller_address", clientCon.Target()))
|
||||
// Check for last successful status. Ignore nil last status, this probably
|
||||
// means that we've never connected to a controller, and as such probably
|
||||
// don't have any sessions to worry about anyway.
|
||||
//
|
||||
// If a length of time has passed since we've been able to communicate, we
|
||||
// want to start terminating all connections as a "break glass" kind of
|
||||
// scenario, as there will be no way we can really tell if these
|
||||
// connections should continue to exist.
|
||||
if isPastGrace, lastStatusTime, gracePeriod := w.isPastGrace(); isPastGrace {
|
||||
event.WriteError(cancelCtx, op,
|
||||
errors.New("status error grace period has expired, canceling all sessions on worker"),
|
||||
event.WithInfo("last_status_time", lastStatusTime.String(), "grace_period", gracePeriod),
|
||||
)
|
||||
|
||||
// Cancel connections if grace period has expired. These Connections will be closed in the
|
||||
// database on the next successful status report, or via the Controller’s dead Worker cleanup connections job.
|
||||
sessionManager.ForEachLocalSession(func(s session.Session) bool {
|
||||
for _, connId := range s.CancelAllLocalConnections() {
|
||||
event.WriteSysEvent(cancelCtx, op, "terminated connection due to status grace period expiration", "session_id", s.GetId(), "connection_id", connId)
|
||||
}
|
||||
return true
|
||||
})
|
||||
|
||||
// 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.Load().GetState() == connectivity.TransientFailure {
|
||||
lastStatus := w.lastStatusSuccess.Load().(*LastStatusInformation)
|
||||
if lastStatus != nil && lastStatus.LastCalculatedUpstreams != nil {
|
||||
addrs := lastStatus.LastCalculatedUpstreams
|
||||
|
||||
if len(w.conf.RawConfig.Worker.InitialUpstreams) > 0 {
|
||||
addrs = append(addrs, w.conf.RawConfig.Worker.InitialUpstreams...)
|
||||
} else if HandleHcpbClusterId != nil && len(w.conf.RawConfig.HcpbClusterId) > 0 {
|
||||
clusterId, err := parseutil.ParsePath(w.conf.RawConfig.HcpbClusterId)
|
||||
if err != nil && !errors.Is(err, parseutil.ErrNotAUrl) {
|
||||
event.WriteError(cancelCtx, op, err, event.WithInfoMsg("failed to parse HCP Boundary cluster ID"))
|
||||
} else {
|
||||
clusterAddress := HandleHcpbClusterId(clusterId)
|
||||
addrs = append(addrs, clusterAddress)
|
||||
}
|
||||
}
|
||||
|
||||
addrs = strutil.RemoveDuplicates(addrs, false)
|
||||
if strutil.EquivalentSlices(lastStatus.LastCalculatedUpstreams, addrs) {
|
||||
// Nothing to update
|
||||
return
|
||||
}
|
||||
|
||||
w.updateAddresses(cancelCtx, addrs, addressReceivers)
|
||||
lastStatus.LastCalculatedUpstreams = addrs
|
||||
w.lastStatusSuccess.Store(lastStatus)
|
||||
}
|
||||
}
|
||||
|
||||
// Exit out of status function; our work here is done and we don't need to create closeConnection requests
|
||||
return
|
||||
}
|
||||
|
||||
// Standard cleanup: Run through current jobs. Cancel connections
|
||||
// for any canceling session or any session that is expired.
|
||||
w.cleanupConnections(cancelCtx, false, sessionManager)
|
||||
return
|
||||
}
|
||||
|
||||
w.updateTags.Store(false)
|
||||
|
||||
if authorized := result.GetAuthorizedDownstreamWorkers(); authorized != nil {
|
||||
connectionState.DisconnectMissingWorkers(authorized.GetWorkerPublicIds())
|
||||
connectionState.DisconnectMissingUnmappedKeyIds(authorized.GetUnmappedWorkerKeyIdentifiers())
|
||||
} else if authorized := result.GetAuthorizedWorkers(); authorized != nil {
|
||||
connectionState.DisconnectAllMissingKeyIds(authorized.GetWorkerKeyIdentifiers())
|
||||
}
|
||||
var addrs []string
|
||||
// This may be empty if we are in a multiple hop scenario
|
||||
if len(result.CalculatedUpstreams) > 0 {
|
||||
addrs = make([]string, 0, len(result.CalculatedUpstreams))
|
||||
for _, v := range result.CalculatedUpstreams {
|
||||
addrs = append(addrs, v.Address)
|
||||
}
|
||||
} else if checkHCPBUpstreams != nil && checkHCPBUpstreams(w) {
|
||||
// This is a worker that is one hop away from managed workers, so attempt to get that list
|
||||
hcpbWorkersCtx, hcpbWorkersCancel := context.WithTimeout(cancelCtx, time.Duration(w.statusCallTimeoutDuration.Load()))
|
||||
defer hcpbWorkersCancel()
|
||||
workersResp, err := client.ListHcpbWorkers(hcpbWorkersCtx, &pbs.ListHcpbWorkersRequest{})
|
||||
if err != nil {
|
||||
event.WriteError(hcpbWorkersCtx, op, err, event.WithInfoMsg("error fetching managed worker information"))
|
||||
} else {
|
||||
addrs = make([]string, 0, len(workersResp.Workers))
|
||||
for _, v := range workersResp.Workers {
|
||||
addrs = append(addrs, v.Address)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
w.updateAddresses(cancelCtx, addrs, addressReceivers)
|
||||
|
||||
w.lastStatusSuccess.Store(&LastStatusInformation{StatusResponse: result, StatusTime: time.Now(), LastCalculatedUpstreams: addrs})
|
||||
|
||||
var nonActiveMonitoredSessionIds []string
|
||||
|
||||
for _, request := range result.GetJobsRequests() {
|
||||
switch request.GetRequestType() {
|
||||
case pbs.CHANGETYPE_CHANGETYPE_UPDATE_STATE:
|
||||
switch request.GetJob().GetType() {
|
||||
case pbs.JOBTYPE_JOBTYPE_MONITOR_SESSION:
|
||||
si := request.GetJob().GetMonitorSessionInfo()
|
||||
if si != nil && si.Status != pbs.SESSIONSTATUS_SESSIONSTATUS_ACTIVE {
|
||||
nonActiveMonitoredSessionIds = append(nonActiveMonitoredSessionIds, si.GetSessionId())
|
||||
}
|
||||
case pbs.JOBTYPE_JOBTYPE_SESSION:
|
||||
sessInfo := request.GetJob().GetSessionInfo()
|
||||
sessionId := sessInfo.GetSessionId()
|
||||
si := sessionManager.Get(sessionId)
|
||||
if si == nil {
|
||||
event.WriteError(cancelCtx, op, errors.New("session change requested but could not find local information for it"), event.WithInfo("session_id", sessionId))
|
||||
continue
|
||||
}
|
||||
si.ApplyLocalStatus(sessInfo.GetStatus())
|
||||
|
||||
// Update connection state if there are any connections in
|
||||
// the request.
|
||||
for _, conn := range sessInfo.GetConnections() {
|
||||
if err := si.ApplyLocalConnectionStatus(conn.GetConnectionId(), conn.GetStatus()); err != nil {
|
||||
event.WriteError(cancelCtx, op, err, event.WithInfo("connection_id", conn.GetConnectionId()))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if recorderManager != nil {
|
||||
if err := recorderManager.ReauthorizeAllExcept(cancelCtx, nonActiveMonitoredSessionIds); err != nil {
|
||||
event.WriteError(cancelCtx, op, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Standard cleanup: Run through current jobs. Cancel connections
|
||||
// for any canceling session or any session that is expired.
|
||||
w.cleanupConnections(cancelCtx, false, sessionManager)
|
||||
|
||||
// If we have post hooks for after the first status check, run them now
|
||||
if w.everAuthenticated.CompareAndSwap(authenticationStatusFirstAuthentication, authenticationStatusFirstStatusRpcSuccessful) {
|
||||
if downstreamWorkersFactory != nil {
|
||||
downstreamWorkers, err := downstreamWorkersFactory(cancelCtx, w.LastStatusSuccess().WorkerId, versionInfo.FullVersionNumber(false))
|
||||
if err != nil {
|
||||
event.WriteError(cancelCtx, op, err)
|
||||
w.conf.ServerSideShutdownCh <- struct{}{}
|
||||
return
|
||||
}
|
||||
w.downstreamWorkers.Store(&graphContainer{graph: downstreamWorkers})
|
||||
}
|
||||
for _, fn := range firstStatusCheckPostHooks {
|
||||
if err := fn(cancelCtx, w); err != nil {
|
||||
// If we can't verify status we can't be expected to behave
|
||||
// properly so error and trigger shutdown
|
||||
event.WriteError(cancelCtx, op, fmt.Errorf("error running first status check post hook: %w", err))
|
||||
// We don't use a non-blocking select here to ensure that it
|
||||
// happens; we should catch blocks in tests but we want to
|
||||
// ensure the signal is being listened to
|
||||
w.conf.ServerSideShutdownCh <- struct{}{}
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Update address receivers and dialing listeners with new addrs
|
||||
func (w *Worker) updateAddresses(cancelCtx context.Context, addrs []string, addressReceivers *[]addressReceiver) {
|
||||
const op = "worker.(Worker).updateAddrs"
|
||||
|
||||
if len(addrs) > 0 {
|
||||
lastStatus := w.lastStatusSuccess.Load().(*LastStatusInformation)
|
||||
// Compare upstreams; update resolver if there is a difference, and emit an event with old and new addresses
|
||||
if lastStatus != nil && !strutil.EquivalentSlices(lastStatus.LastCalculatedUpstreams, addrs) {
|
||||
upstreamsMessage := fmt.Sprintf("Upstreams has changed; old upstreams were: %s, new upstreams are: %s", lastStatus.LastCalculatedUpstreams, addrs)
|
||||
event.WriteSysEvent(cancelCtx, op, upstreamsMessage)
|
||||
for _, as := range *addressReceivers {
|
||||
as.SetAddresses(addrs)
|
||||
}
|
||||
} else if lastStatus == nil {
|
||||
for _, as := range *addressReceivers {
|
||||
as.SetAddresses(addrs)
|
||||
}
|
||||
event.WriteSysEvent(cancelCtx, op, fmt.Sprintf("Upstreams after first status set to: %s", addrs))
|
||||
}
|
||||
}
|
||||
|
||||
// regardless of whether or not it's a new address, we need to set
|
||||
// them for secondary connections
|
||||
for _, as := range *addressReceivers {
|
||||
switch {
|
||||
case as.Type() == secondaryConnectionReceiverType:
|
||||
tmpAddrs := make([]string, len(addrs))
|
||||
copy(tmpAddrs, addrs)
|
||||
if len(tmpAddrs) == 0 {
|
||||
tmpAddrs = append(tmpAddrs, w.conf.RawConfig.Worker.InitialUpstreams...)
|
||||
}
|
||||
as.SetAddresses(tmpAddrs)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// cleanupConnections walks all sessions and shuts down all proxy connections.
|
||||
// After the local connections are terminated, they are requested to be marked
|
||||
// close on the controller.
|
||||
// Additionally, sessions without connections are cleaned up from the
|
||||
// local worker's state.
|
||||
//
|
||||
// Use ignoreSessionState to ignore the state checks, this closes all
|
||||
// connections, regardless of whether or not the session is still active.
|
||||
func (w *Worker) cleanupConnections(cancelCtx context.Context, ignoreSessionState bool, sessionManager session.Manager) {
|
||||
const op = "worker.(Worker).cleanupConnections"
|
||||
closeInfo := make(map[string]*session.ConnectionCloseData)
|
||||
cleanSessionIds := make([]string, 0)
|
||||
sessionManager.ForEachLocalSession(func(s session.Session) bool {
|
||||
switch {
|
||||
case ignoreSessionState,
|
||||
s.GetStatus() == pbs.SESSIONSTATUS_SESSIONSTATUS_CANCELING,
|
||||
s.GetStatus() == pbs.SESSIONSTATUS_SESSIONSTATUS_TERMINATED,
|
||||
time.Until(s.GetExpiration()) < 0:
|
||||
// Cancel connections without regard to individual connection
|
||||
// state.
|
||||
closedIds := s.CancelAllLocalConnections()
|
||||
localConns := s.GetLocalConnections()
|
||||
for _, connId := range closedIds {
|
||||
var bytesUp, bytesDown int64
|
||||
connInfo, ok := localConns[connId]
|
||||
if ok {
|
||||
bytesUp = connInfo.BytesUp()
|
||||
bytesDown = connInfo.BytesDown()
|
||||
}
|
||||
closeInfo[connId] = &session.ConnectionCloseData{
|
||||
SessionId: s.GetId(),
|
||||
BytesUp: bytesUp,
|
||||
BytesDown: bytesDown,
|
||||
}
|
||||
event.WriteSysEvent(cancelCtx, op, "terminated connection due to cancellation or expiration", "session_id", s.GetId(), "connection_id", connId)
|
||||
}
|
||||
|
||||
// If the session is no longer valid and all connections
|
||||
// are marked closed, clean up the session.
|
||||
if len(closedIds) == 0 {
|
||||
cleanSessionIds = append(cleanSessionIds, s.GetId())
|
||||
}
|
||||
|
||||
default:
|
||||
// Cancel connections *with* regard to individual connection
|
||||
// state (ie: only ones that the controller has requested be
|
||||
// terminated).
|
||||
for _, connId := range s.CancelOpenLocalConnections() {
|
||||
closeInfo[connId] = &session.ConnectionCloseData{SessionId: s.GetId()}
|
||||
event.WriteSysEvent(cancelCtx, op, "terminated connection due to cancellation or expiration", "session_id", s.GetId(), "connection_id", connId)
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
})
|
||||
|
||||
// Note that we won't clean these from the info map until the
|
||||
// next time we run this function
|
||||
if len(closeInfo) > 0 {
|
||||
// Call out to a helper to send the connection close requests to the
|
||||
// controller, and set the close time. This functionality is shared with
|
||||
// post-close functionality in the proxy handler.
|
||||
_ = sessionManager.RequestCloseConnections(cancelCtx, closeInfo)
|
||||
}
|
||||
// Forget sessions where the session is expired/canceled and all
|
||||
// connections are canceled and marked closed
|
||||
sessionManager.DeleteLocalSession(cleanSessionIds)
|
||||
}
|
||||
|
||||
func (w *Worker) lastSuccessfulStatusTime() time.Time {
|
||||
lastStatus := w.LastStatusSuccess()
|
||||
if lastStatus == nil {
|
||||
return w.workerStartTime
|
||||
}
|
||||
|
||||
return lastStatus.StatusTime
|
||||
}
|
||||
|
||||
func (w *Worker) isPastGrace() (bool, time.Time, time.Duration) {
|
||||
t := w.lastSuccessfulStatusTime()
|
||||
u := time.Duration(w.successfulStatusGracePeriod.Load())
|
||||
v := time.Since(t)
|
||||
return v > u, t, u
|
||||
}
|
||||
@@ -29,6 +29,8 @@ import (
|
||||
"github.com/mr-tron/base58"
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
"github.com/stretchr/testify/require"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
@@ -69,16 +71,8 @@ func (tw *TestWorker) Name() string {
|
||||
}
|
||||
|
||||
func (tw *TestWorker) UpstreamAddrs() []string {
|
||||
var addrs []string
|
||||
lastStatus := tw.w.LastStatusSuccess()
|
||||
if lastStatus == nil {
|
||||
return addrs
|
||||
}
|
||||
for _, v := range lastStatus.GetCalculatedUpstreams() {
|
||||
addrs = append(addrs, v.Address)
|
||||
}
|
||||
|
||||
return addrs
|
||||
lastRoutingInfo := tw.w.LastRoutingInfoSuccess()
|
||||
return lastRoutingInfo.GetCalculatedUpstreamAddresses()
|
||||
}
|
||||
|
||||
func (tw *TestWorker) ProxyAddrs() []string {
|
||||
@@ -204,6 +198,10 @@ type TestWorkerOpts struct {
|
||||
// The location of the worker's recording storage
|
||||
WorkerRecordingStoragePath string
|
||||
|
||||
// The interval between each respective worker RPC invocation
|
||||
// This sets the interval for SessionInfo, RoutingInfo and Statistics.
|
||||
WorkerRPCInterval time.Duration
|
||||
|
||||
// The name to use for the worker, otherwise one will be randomly
|
||||
// generated, unless provided in a non-nil Config
|
||||
Name string
|
||||
@@ -217,7 +215,7 @@ type TestWorkerOpts struct {
|
||||
|
||||
// The amount of time to wait before marking connections as closed when a
|
||||
// connection cannot be made back to the controller
|
||||
SuccessfulStatusGracePeriodDuration time.Duration
|
||||
SuccessfulControllerRPCGracePeriodDuration time.Duration
|
||||
|
||||
// Overrides worker's nonceFn, for cases where we want to have control
|
||||
// over the nonce we send to the Controller
|
||||
@@ -286,6 +284,9 @@ func NewTestWorker(t testing.TB, opts *TestWorkerOpts) *TestWorker {
|
||||
if opts.Name != "" {
|
||||
opts.Config.Worker.Name = opts.Name
|
||||
}
|
||||
if opts.WorkerRPCInterval > 0 {
|
||||
opts.Config.Worker.TestWorkerRPCInterval = opts.WorkerRPCInterval
|
||||
}
|
||||
}
|
||||
|
||||
if len(opts.InitialUpstreams) > 0 {
|
||||
@@ -317,8 +318,8 @@ func NewTestWorker(t testing.TB, opts *TestWorkerOpts) *TestWorker {
|
||||
tw.b.EnabledPlugins = append(tw.b.EnabledPlugins, base.EnabledPluginLoopback)
|
||||
tw.name = opts.Config.Worker.Name
|
||||
|
||||
if opts.SuccessfulStatusGracePeriodDuration != 0 {
|
||||
opts.Config.Worker.SuccessfulStatusGracePeriodDuration = opts.SuccessfulStatusGracePeriodDuration
|
||||
if opts.SuccessfulControllerRPCGracePeriodDuration != 0 {
|
||||
opts.Config.Worker.SuccessfulControllerRPCGracePeriodDuration = opts.SuccessfulControllerRPCGracePeriodDuration
|
||||
}
|
||||
|
||||
serverName, err := os.Hostname()
|
||||
@@ -401,14 +402,14 @@ func (tw *TestWorker) AddClusterWorkerMember(t testing.TB, opts *TestWorkerOpts)
|
||||
opts = new(TestWorkerOpts)
|
||||
}
|
||||
nextOpts := &TestWorkerOpts{
|
||||
WorkerAuthKms: tw.w.conf.WorkerAuthKms,
|
||||
DownstreamWorkerAuthKms: tw.w.conf.DownstreamWorkerAuthKms,
|
||||
WorkerAuthStorageKms: tw.w.conf.WorkerAuthStorageKms,
|
||||
Name: opts.Name,
|
||||
InitialUpstreams: tw.UpstreamAddrs(),
|
||||
Logger: tw.w.conf.Logger,
|
||||
SuccessfulStatusGracePeriodDuration: opts.SuccessfulStatusGracePeriodDuration,
|
||||
WorkerAuthDebuggingEnabled: tw.w.conf.WorkerAuthDebuggingEnabled,
|
||||
WorkerAuthKms: tw.w.conf.WorkerAuthKms,
|
||||
DownstreamWorkerAuthKms: tw.w.conf.DownstreamWorkerAuthKms,
|
||||
WorkerAuthStorageKms: tw.w.conf.WorkerAuthStorageKms,
|
||||
Name: opts.Name,
|
||||
InitialUpstreams: tw.UpstreamAddrs(),
|
||||
Logger: tw.w.conf.Logger,
|
||||
SuccessfulControllerRPCGracePeriodDuration: opts.SuccessfulControllerRPCGracePeriodDuration,
|
||||
WorkerAuthDebuggingEnabled: tw.w.conf.WorkerAuthDebuggingEnabled,
|
||||
}
|
||||
if nextOpts.Name == "" {
|
||||
var err error
|
||||
@@ -457,3 +458,98 @@ func NewAuthorizedPkiTestWorker(t *testing.T, repo *server.Repository, name stri
|
||||
require.NoError(t, err)
|
||||
return w, wr.GetPublicId()
|
||||
}
|
||||
|
||||
// mockServerCoordinationService is meant to stand in for a controller when testing
|
||||
// the methods defined by the server coordination service. It allows applying assertions and specifying
|
||||
// the return value of grpc methods by overwriting service methods.
|
||||
type mockServerCoordinationService struct {
|
||||
pbs.UnimplementedServerCoordinationServiceServer
|
||||
nextReqAssert func(*pbs.StatusRequest) (*pbs.StatusResponse, error)
|
||||
nextStatisticAssert func(*pbs.StatisticsRequest) (*pbs.StatisticsResponse, error)
|
||||
nextSessionInfoAssert func(*pbs.SessionInfoRequest) (*pbs.SessionInfoResponse, error)
|
||||
}
|
||||
|
||||
func (m mockServerCoordinationService) Status(ctx context.Context, req *pbs.StatusRequest) (*pbs.StatusResponse, error) {
|
||||
if m.nextReqAssert != nil {
|
||||
return m.nextReqAssert(req)
|
||||
}
|
||||
return nil, status.Error(codes.Unavailable, "Status not implemented")
|
||||
}
|
||||
|
||||
func (m mockServerCoordinationService) Statistics(ctx context.Context, req *pbs.StatisticsRequest) (*pbs.StatisticsResponse, error) {
|
||||
if m.nextStatisticAssert != nil {
|
||||
return m.nextStatisticAssert(req)
|
||||
}
|
||||
return nil, status.Error(codes.Unavailable, "Statistics not implemented")
|
||||
}
|
||||
|
||||
func (m mockServerCoordinationService) SessionInfo(ctx context.Context, req *pbs.SessionInfoRequest) (*pbs.SessionInfoResponse, error) {
|
||||
if m.nextSessionInfoAssert != nil {
|
||||
return m.nextSessionInfoAssert(req)
|
||||
}
|
||||
return nil, status.Error(codes.Unavailable, "SessionInfo not implemented")
|
||||
}
|
||||
|
||||
var _ pbs.ServerCoordinationServiceServer = (*mockServerCoordinationService)(nil)
|
||||
|
||||
// TestWaitForNextSuccessfulSessionInfoUpdate waits for the next successful session info. It's
|
||||
// used by testing in place of a more opaque and possibly unnecessarily long sleep for
|
||||
// things like initial controller check-in, etc.
|
||||
//
|
||||
// The timeout is aligned with the worker's session info grace period.
|
||||
func (w *Worker) TestWaitForNextSuccessfulSessionInfoUpdate(t testing.TB) {
|
||||
t.Helper()
|
||||
const op = "worker.(Worker).WaitForNextSuccessfulSessionInfoUpdate"
|
||||
waitStart := time.Now()
|
||||
ctx, cancel := context.WithTimeout(w.baseContext, time.Duration(w.successfulSessionInfoGracePeriod.Load()))
|
||||
defer cancel()
|
||||
t.Log("waiting for next session info report to controller")
|
||||
for {
|
||||
select {
|
||||
case <-time.After(time.Second):
|
||||
// pass
|
||||
|
||||
case <-ctx.Done():
|
||||
t.Error("error waiting for next session info report to controller")
|
||||
return
|
||||
}
|
||||
|
||||
si := w.lastSessionInfoSuccess.Load().(*lastSessionInfo)
|
||||
if si != nil && si.LastSuccessfulRequestTime.After(waitStart) {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
t.Log("next worker session info update sent successfully")
|
||||
}
|
||||
|
||||
// TestWaitForNextSuccessfulStatisticsUpdate waits for the next successful statistics. It's
|
||||
// used by testing in place of a more opaque and possibly unnecessarily long sleep for
|
||||
// things like initial controller check-in, etc.
|
||||
//
|
||||
// The timeout is aligned with twice the worker's statistics timeout duration.
|
||||
func (w *Worker) TestWaitForNextSuccessfulStatisticsUpdate(t testing.TB) {
|
||||
t.Helper()
|
||||
const op = "worker.(Worker).WaitForNextSuccessfulStatisticsUpdate"
|
||||
waitStart := time.Now()
|
||||
ctx, cancel := context.WithTimeout(w.baseContext, time.Duration(2*w.statisticsCallTimeoutDuration.Load()))
|
||||
defer cancel()
|
||||
t.Log("waiting for next statistics report to controller")
|
||||
for {
|
||||
select {
|
||||
case <-time.After(time.Second):
|
||||
// pass
|
||||
|
||||
case <-ctx.Done():
|
||||
t.Error("error waiting for next statistics report to controller")
|
||||
return
|
||||
}
|
||||
|
||||
si := w.lastStatisticsSuccess.Load().(*lastStatistics)
|
||||
if si != nil && si.LastSuccessfulRequestTime.After(waitStart) {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
t.Log("next worker statistics update sent successfully")
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -40,7 +41,6 @@ import (
|
||||
"github.com/hashicorp/go-secure-stdlib/base62"
|
||||
"github.com/hashicorp/go-secure-stdlib/mlock"
|
||||
"github.com/hashicorp/go-secure-stdlib/pluginutil/v2"
|
||||
"github.com/hashicorp/go-secure-stdlib/strutil"
|
||||
"github.com/hashicorp/nodeenrollment"
|
||||
nodeenet "github.com/hashicorp/nodeenrollment/net"
|
||||
nodeefile "github.com/hashicorp/nodeenrollment/storage/file"
|
||||
@@ -85,10 +85,10 @@ type graph interface {
|
||||
RootId() string
|
||||
}
|
||||
|
||||
// recorderManager updates the status updates with relevant recording
|
||||
// recorderManager updates the session info updates with relevant recording
|
||||
// information
|
||||
type recorderManager interface {
|
||||
// ReauthorizeAllExcept should be called with the result of the status update
|
||||
// ReauthorizeAllExcept should be called with the result of the session info update
|
||||
// to reauthorize all recorders for the relevant sessions except the ones provided
|
||||
ReauthorizeAllExcept(ctx context.Context, closedSessions []string) error
|
||||
// SessionsManaged gets the list of session ids managed by this recorderManager
|
||||
@@ -126,11 +126,17 @@ var hostServiceServerFactory func(
|
||||
const (
|
||||
authenticationStatusNeverAuthenticated uint32 = iota
|
||||
authenticationStatusFirstAuthentication
|
||||
authenticationStatusFirstStatusRpcSuccessful
|
||||
authenticationStatusFirstRoutingInfoRpcSuccessful
|
||||
)
|
||||
|
||||
type Worker struct {
|
||||
conf *Config
|
||||
conf *Config
|
||||
// receives address updates and contains the grpc resolver.
|
||||
addressReceivers []addressReceiver
|
||||
// confAddressReceiversLock is used to protect the conf field
|
||||
// and the addressReceivers field.
|
||||
confAddressReceiversLock sync.Mutex
|
||||
|
||||
logger hclog.Logger
|
||||
|
||||
baseContext context.Context
|
||||
@@ -145,17 +151,16 @@ type Worker struct {
|
||||
// (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
|
||||
|
||||
sessionManager session.Manager
|
||||
|
||||
recorderManager recorderManager
|
||||
|
||||
everAuthenticated *ua.Uint32
|
||||
lastStatusSuccess *atomic.Value
|
||||
workerStartTime time.Time
|
||||
operationalState *atomic.Value
|
||||
everAuthenticated *ua.Uint32
|
||||
lastSessionInfoSuccess *atomic.Value
|
||||
lastRoutingInfoSuccess *atomic.Value
|
||||
lastStatisticsSuccess *atomic.Value
|
||||
workerStartTime time.Time
|
||||
operationalState *atomic.Value
|
||||
// localStorageState is the current state of the local storage.
|
||||
// The local storage state is updated based on the local storage events.
|
||||
localStorageState *atomic.Value
|
||||
@@ -172,11 +177,9 @@ type Worker struct {
|
||||
// Used to generate a random nonce for Controller connections
|
||||
nonceFn randFn
|
||||
|
||||
// We store the current set in an atomic value so that we can add
|
||||
// reload-on-sighup behavior later
|
||||
tags *atomic.Value
|
||||
// This stores whether or not to send updated tags on the next status
|
||||
// request. It can be set via startup in New below, or (eventually) via
|
||||
// This stores whether or not to send updated tags on the next routing info
|
||||
// request. It can be set via startup in New below, or via
|
||||
// SIGHUP.
|
||||
updateTags *ua.Bool
|
||||
|
||||
@@ -195,10 +198,26 @@ type Worker struct {
|
||||
|
||||
// Timing variables. These are atomics for SIGHUP support, and are int64
|
||||
// because they are casted to time.Duration.
|
||||
successfulStatusGracePeriod *atomic.Int64
|
||||
statusCallTimeoutDuration *atomic.Int64
|
||||
successfulRoutingInfoGracePeriod *atomic.Int64
|
||||
successfulSessionInfoGracePeriod *atomic.Int64
|
||||
// Note: Statistics does not require a grace period,
|
||||
// because we do not perform any special action based
|
||||
// on whether it is successful or not, unlike for SessionInfo
|
||||
// and RoutingInfo.
|
||||
|
||||
statisticsCallTimeoutDuration *atomic.Int64
|
||||
sessionInfoCallTimeoutDuration *atomic.Int64
|
||||
routingInfoCallTimeoutDuration *atomic.Int64
|
||||
getDownstreamWorkersTimeoutDuration *atomic.Int64
|
||||
|
||||
// The time intervals at which the worker will invoke the controller RPCs.
|
||||
// Defaults to common.SessionInfoInterval, common.RoutingInfoInterval
|
||||
// and common.StatisticsInterval and is only overridden by the
|
||||
// TestWorkerRPCInterval test config.
|
||||
sessionInfoInterval time.Duration
|
||||
routingInfoInterval time.Duration
|
||||
statisticsInterval time.Duration
|
||||
|
||||
// AuthRotationNextRotation is useful in tests to understand how long to
|
||||
// sleep
|
||||
AuthRotationNextRotation atomic.Pointer[time.Time]
|
||||
@@ -208,8 +227,6 @@ type Worker struct {
|
||||
TestOverrideX509VerifyCertPool *x509.CertPool
|
||||
TestOverrideAuthRotationPeriod time.Duration
|
||||
|
||||
statusLock sync.Mutex
|
||||
|
||||
downstreamConnManager *cluster.DownstreamManager
|
||||
|
||||
HostServiceServer wpbs.HostServiceServer
|
||||
@@ -230,7 +247,9 @@ func New(ctx context.Context, conf *Config) (*Worker, error) {
|
||||
logger: conf.Logger.Named("worker"),
|
||||
started: ua.NewBool(false),
|
||||
everAuthenticated: ua.NewUint32(authenticationStatusNeverAuthenticated),
|
||||
lastStatusSuccess: new(atomic.Value),
|
||||
lastSessionInfoSuccess: new(atomic.Value),
|
||||
lastRoutingInfoSuccess: new(atomic.Value),
|
||||
lastStatisticsSuccess: new(atomic.Value),
|
||||
controllerMultihopConn: new(atomic.Value),
|
||||
// controllerUpstreamMsgConn: new(atomic.Value),
|
||||
tags: new(atomic.Value),
|
||||
@@ -240,8 +259,11 @@ func New(ctx context.Context, conf *Config) (*Worker, error) {
|
||||
operationalState: new(atomic.Value),
|
||||
downstreamConnManager: cluster.NewDownstreamManager(),
|
||||
localStorageState: new(atomic.Value),
|
||||
successfulStatusGracePeriod: new(atomic.Int64),
|
||||
statusCallTimeoutDuration: new(atomic.Int64),
|
||||
successfulRoutingInfoGracePeriod: new(atomic.Int64),
|
||||
successfulSessionInfoGracePeriod: new(atomic.Int64),
|
||||
statisticsCallTimeoutDuration: new(atomic.Int64),
|
||||
sessionInfoCallTimeoutDuration: new(atomic.Int64),
|
||||
routingInfoCallTimeoutDuration: new(atomic.Int64),
|
||||
getDownstreamWorkersTimeoutDuration: new(atomic.Int64),
|
||||
upstreamConnectionState: new(atomic.Value),
|
||||
downstreamWorkers: new(atomic.Pointer[graphContainer]),
|
||||
@@ -249,7 +271,9 @@ func New(ctx context.Context, conf *Config) (*Worker, error) {
|
||||
|
||||
w.operationalState.Store(server.UnknownOperationalState)
|
||||
w.localStorageState.Store(server.UnknownLocalStorageState)
|
||||
w.lastStatusSuccess.Store((*LastStatusInformation)(nil))
|
||||
w.lastSessionInfoSuccess.Store((*lastSessionInfo)(nil))
|
||||
w.lastRoutingInfoSuccess.Store((*LastRoutingInfo)(nil))
|
||||
w.lastStatisticsSuccess.Store((*lastStatistics)(nil))
|
||||
scheme := strconv.FormatInt(time.Now().UnixNano(), 36)
|
||||
controllerResolver := manual.NewBuilderWithScheme(scheme)
|
||||
w.addressReceivers = []addressReceiver{&grpcResolverReceiver{controllerResolver}}
|
||||
@@ -365,17 +389,23 @@ func New(ctx context.Context, conf *Config) (*Worker, error) {
|
||||
err)
|
||||
}
|
||||
}
|
||||
switch conf.RawConfig.Worker.SuccessfulStatusGracePeriodDuration {
|
||||
switch conf.RawConfig.Worker.SuccessfulControllerRPCGracePeriodDuration {
|
||||
case 0:
|
||||
w.successfulStatusGracePeriod.Store(int64(server.DefaultLiveness))
|
||||
w.successfulRoutingInfoGracePeriod.Store(int64(server.DefaultLiveness))
|
||||
w.successfulSessionInfoGracePeriod.Store(int64(server.DefaultLiveness))
|
||||
default:
|
||||
w.successfulStatusGracePeriod.Store(int64(conf.RawConfig.Worker.SuccessfulStatusGracePeriodDuration))
|
||||
w.successfulRoutingInfoGracePeriod.Store(int64(conf.RawConfig.Worker.SuccessfulControllerRPCGracePeriodDuration))
|
||||
w.successfulSessionInfoGracePeriod.Store(int64(conf.RawConfig.Worker.SuccessfulControllerRPCGracePeriodDuration))
|
||||
}
|
||||
switch conf.RawConfig.Worker.StatusCallTimeoutDuration {
|
||||
switch conf.RawConfig.Worker.ControllerRPCCallTimeoutDuration {
|
||||
case 0:
|
||||
w.statusCallTimeoutDuration.Store(int64(common.DefaultStatusTimeout))
|
||||
w.routingInfoCallTimeoutDuration.Store(int64(common.DefaultRoutingInfoTimeout))
|
||||
w.statisticsCallTimeoutDuration.Store(int64(common.DefaultStatisticsTimeout))
|
||||
w.sessionInfoCallTimeoutDuration.Store(int64(common.DefaultSessionInfoTimeout))
|
||||
default:
|
||||
w.statusCallTimeoutDuration.Store(int64(conf.RawConfig.Worker.StatusCallTimeoutDuration))
|
||||
w.routingInfoCallTimeoutDuration.Store(int64(conf.RawConfig.Worker.ControllerRPCCallTimeoutDuration))
|
||||
w.statisticsCallTimeoutDuration.Store(int64(conf.RawConfig.Worker.ControllerRPCCallTimeoutDuration))
|
||||
w.sessionInfoCallTimeoutDuration.Store(int64(conf.RawConfig.Worker.ControllerRPCCallTimeoutDuration))
|
||||
}
|
||||
switch conf.RawConfig.Worker.GetDownstreamWorkersTimeoutDuration {
|
||||
case 0:
|
||||
@@ -384,7 +414,18 @@ func New(ctx context.Context, conf *Config) (*Worker, error) {
|
||||
w.getDownstreamWorkersTimeoutDuration.Store(int64(conf.RawConfig.Worker.GetDownstreamWorkersTimeoutDuration))
|
||||
}
|
||||
// FIXME: This is really ugly, but works.
|
||||
session.CloseCallTimeout.Store(w.successfulStatusGracePeriod.Load())
|
||||
session.CloseCallTimeout.Store(w.successfulSessionInfoGracePeriod.Load())
|
||||
|
||||
w.sessionInfoInterval = common.SessionInfoInterval
|
||||
w.routingInfoInterval = common.RoutingInfoInterval
|
||||
w.statisticsInterval = common.StatisticsInterval
|
||||
// Override the routing info interval if it is set in the config.
|
||||
// This should only be used by tests.
|
||||
if conf.RawConfig.Worker.TestWorkerRPCInterval > 0 {
|
||||
w.sessionInfoInterval = conf.RawConfig.Worker.TestWorkerRPCInterval
|
||||
w.routingInfoInterval = conf.RawConfig.Worker.TestWorkerRPCInterval
|
||||
w.statisticsInterval = conf.RawConfig.Worker.TestWorkerRPCInterval
|
||||
}
|
||||
|
||||
if reverseConnReceiverFactory != nil {
|
||||
var err error
|
||||
@@ -443,10 +484,36 @@ func (w *Worker) Reload(ctx context.Context, newConf *config.Config) {
|
||||
|
||||
w.parseAndStoreTags(newConf.Worker.Tags)
|
||||
|
||||
if !strutil.EquivalentSlices(newConf.Worker.InitialUpstreams, w.conf.RawConfig.Worker.InitialUpstreams) {
|
||||
w.statusLock.Lock()
|
||||
defer w.statusLock.Unlock()
|
||||
switch newConf.Worker.SuccessfulControllerRPCGracePeriod {
|
||||
case 0:
|
||||
w.successfulRoutingInfoGracePeriod.Store(int64(server.DefaultLiveness))
|
||||
w.successfulSessionInfoGracePeriod.Store(int64(server.DefaultLiveness))
|
||||
default:
|
||||
w.successfulRoutingInfoGracePeriod.Store(int64(newConf.Worker.SuccessfulControllerRPCGracePeriodDuration))
|
||||
w.successfulSessionInfoGracePeriod.Store(int64(newConf.Worker.SuccessfulControllerRPCGracePeriodDuration))
|
||||
}
|
||||
switch newConf.Worker.ControllerRPCCallTimeoutDuration {
|
||||
case 0:
|
||||
w.routingInfoCallTimeoutDuration.Store(int64(common.DefaultRoutingInfoTimeout))
|
||||
w.statisticsCallTimeoutDuration.Store(int64(common.DefaultStatisticsTimeout))
|
||||
w.sessionInfoCallTimeoutDuration.Store(int64(common.DefaultSessionInfoTimeout))
|
||||
default:
|
||||
w.routingInfoCallTimeoutDuration.Store(int64(newConf.Worker.ControllerRPCCallTimeoutDuration))
|
||||
w.statisticsCallTimeoutDuration.Store(int64(newConf.Worker.ControllerRPCCallTimeoutDuration))
|
||||
w.sessionInfoCallTimeoutDuration.Store(int64(newConf.Worker.ControllerRPCCallTimeoutDuration))
|
||||
}
|
||||
switch newConf.Worker.GetDownstreamWorkersTimeoutDuration {
|
||||
case 0:
|
||||
w.getDownstreamWorkersTimeoutDuration.Store(int64(server.DefaultLiveness))
|
||||
default:
|
||||
w.getDownstreamWorkersTimeoutDuration.Store(int64(newConf.Worker.GetDownstreamWorkersTimeoutDuration))
|
||||
}
|
||||
// See comment about this in worker.go
|
||||
session.CloseCallTimeout.Store(w.successfulRoutingInfoGracePeriod.Load())
|
||||
|
||||
w.confAddressReceiversLock.Lock()
|
||||
defer w.confAddressReceiversLock.Unlock()
|
||||
if !slices.Equal(newConf.Worker.InitialUpstreams, w.conf.RawConfig.Worker.InitialUpstreams) {
|
||||
upstreamsMessage := fmt.Sprintf(
|
||||
"Initial Upstreams has changed; old upstreams were: %s, new upstreams are: %s",
|
||||
w.conf.RawConfig.Worker.InitialUpstreams,
|
||||
@@ -461,27 +528,6 @@ func (w *Worker) Reload(ctx context.Context, newConf *config.Config) {
|
||||
ar.InitialAddresses(w.conf.RawConfig.Worker.InitialUpstreams)
|
||||
}
|
||||
}
|
||||
|
||||
switch newConf.Worker.SuccessfulStatusGracePeriodDuration {
|
||||
case 0:
|
||||
w.successfulStatusGracePeriod.Store(int64(server.DefaultLiveness))
|
||||
default:
|
||||
w.successfulStatusGracePeriod.Store(int64(newConf.Worker.SuccessfulStatusGracePeriodDuration))
|
||||
}
|
||||
switch newConf.Worker.StatusCallTimeoutDuration {
|
||||
case 0:
|
||||
w.statusCallTimeoutDuration.Store(int64(common.DefaultStatusTimeout))
|
||||
default:
|
||||
w.statusCallTimeoutDuration.Store(int64(newConf.Worker.StatusCallTimeoutDuration))
|
||||
}
|
||||
switch newConf.Worker.GetDownstreamWorkersTimeoutDuration {
|
||||
case 0:
|
||||
w.getDownstreamWorkersTimeoutDuration.Store(int64(server.DefaultLiveness))
|
||||
default:
|
||||
w.getDownstreamWorkersTimeoutDuration.Store(int64(newConf.Worker.GetDownstreamWorkersTimeoutDuration))
|
||||
}
|
||||
// See comment about this in worker.go
|
||||
session.CloseCallTimeout.Store(w.successfulStatusGracePeriod.Load())
|
||||
}
|
||||
|
||||
func (w *Worker) Start() error {
|
||||
@@ -612,9 +658,6 @@ func (w *Worker) Start() error {
|
||||
return fmt.Errorf("error marshaling worker auth fetch credentials request: %w", err)
|
||||
}
|
||||
w.WorkerAuthRegistrationRequest = base58.FastBase58Encoding(reqBytes)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error encoding worker auth registration request: %w", err)
|
||||
}
|
||||
currentKeyId, err := nodeenrollment.KeyIdFromPkix(nodeCreds.CertificatePublicKeyPkix)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error deriving worker auth key id: %w", err)
|
||||
@@ -659,7 +702,7 @@ func (w *Worker) Start() error {
|
||||
w.tickerWg.Add(2)
|
||||
go func() {
|
||||
defer w.tickerWg.Done()
|
||||
w.startStatusTicking(w.baseContext, w.sessionManager, &w.addressReceivers, w.recorderManager)
|
||||
w.startRoutingInfoTicking(w.baseContext)
|
||||
}()
|
||||
go func() {
|
||||
defer w.tickerWg.Done()
|
||||
@@ -669,7 +712,7 @@ func (w *Worker) Start() error {
|
||||
if w.downstreamReceiver != nil {
|
||||
w.tickerWg.Add(2)
|
||||
servNameFn := func() string {
|
||||
if s := w.LastStatusSuccess(); s != nil {
|
||||
if s := w.LastRoutingInfoSuccess(); s != nil {
|
||||
return s.WorkerId
|
||||
}
|
||||
return "unknown worker id"
|
||||
@@ -706,24 +749,30 @@ func (w *Worker) GracefulShutdown() error {
|
||||
event.WriteSysEvent(w.baseContext, op, "worker entering graceful shutdown")
|
||||
w.operationalState.Store(server.ShutdownOperationalState)
|
||||
|
||||
// As long as some status has been sent in the past, wait for 2 status
|
||||
// updates to be sent since we've updated our operational state.
|
||||
lastStatusTime := w.lastSuccessfulStatusTime()
|
||||
if lastStatusTime != w.workerStartTime {
|
||||
for i := 0; i < 2; i++ {
|
||||
for {
|
||||
if lastStatusTime != w.lastSuccessfulStatusTime() {
|
||||
lastStatusTime = w.lastSuccessfulStatusTime()
|
||||
break
|
||||
}
|
||||
time.Sleep(time.Millisecond * 250)
|
||||
// As long as some routing info has been sent in the past, wait for 1 routing info
|
||||
// update to be sent since we've updated our operational state.
|
||||
lastRoutingInfoTime := w.lastSuccessfulRoutingInfoTime()
|
||||
if !lastRoutingInfoTime.Equal(w.workerStartTime) {
|
||||
WaitForRoutingInfo:
|
||||
for !lastRoutingInfoTime.Before(w.lastSuccessfulRoutingInfoTime()) {
|
||||
select {
|
||||
case <-w.baseContext.Done():
|
||||
event.WriteSysEvent(w.baseContext, op, "context done waiting for routing info to be sent")
|
||||
break WaitForRoutingInfo
|
||||
case <-time.After(time.Millisecond * 250):
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Wait for running proxy connections to drain
|
||||
WaitForConnectionDrain:
|
||||
for proxy.ProxyState.CurrentProxiedConnections() > 0 {
|
||||
time.Sleep(time.Millisecond * 250)
|
||||
select {
|
||||
case <-w.baseContext.Done():
|
||||
event.WriteSysEvent(w.baseContext, op, "context done waiting for connections to be drained")
|
||||
break WaitForConnectionDrain
|
||||
case <-time.After(time.Millisecond * 250):
|
||||
}
|
||||
}
|
||||
event.WriteSysEvent(w.baseContext, op, "worker connections have drained")
|
||||
|
||||
@@ -767,30 +816,31 @@ func (w *Worker) Shutdown() error {
|
||||
// Shut down all connections.
|
||||
w.cleanupConnections(w.baseContext, true, w.sessionManager)
|
||||
|
||||
// Wait for next status request to succeed. Don't wait too long; time it out
|
||||
// at our default liveness value, which is also our default status grace
|
||||
// period timeout
|
||||
waitStatusStart := time.Now()
|
||||
nextStatusCtx, nextStatusCancel := context.WithTimeout(w.baseContext, server.DefaultLiveness)
|
||||
defer nextStatusCancel()
|
||||
for {
|
||||
if err := nextStatusCtx.Err(); err != nil {
|
||||
event.WriteError(w.baseContext, op, err, event.WithInfoMsg("error waiting for next status report to controller"))
|
||||
break
|
||||
// Wait for next routing info request to succeed. Don't wait too long; time it out
|
||||
// at our default liveness value.
|
||||
nextRoutingInfoCtx, nextRoutingInfoCancel := context.WithTimeout(w.baseContext, server.DefaultLiveness)
|
||||
defer nextRoutingInfoCancel()
|
||||
lastRoutingInfoTime := w.lastSuccessfulRoutingInfoTime()
|
||||
if !lastRoutingInfoTime.Equal(w.workerStartTime) {
|
||||
WaitForRoutingInfo:
|
||||
for !lastRoutingInfoTime.Before(w.lastSuccessfulRoutingInfoTime()) {
|
||||
select {
|
||||
case <-nextRoutingInfoCtx.Done():
|
||||
event.WriteError(w.baseContext, op, nextRoutingInfoCtx.Err(), event.WithInfoMsg("error waiting for next routing info report to controller"))
|
||||
break WaitForRoutingInfo
|
||||
case <-time.After(time.Millisecond * 250):
|
||||
}
|
||||
}
|
||||
|
||||
if w.lastSuccessfulStatusTime().After(waitStatusStart) {
|
||||
break
|
||||
}
|
||||
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
|
||||
// Proceed with remainder of shutdown.
|
||||
w.baseCancel()
|
||||
// Lock to protect w.addressReceivers
|
||||
w.confAddressReceiversLock.Lock()
|
||||
for _, ar := range w.addressReceivers {
|
||||
ar.SetAddresses(nil)
|
||||
}
|
||||
w.confAddressReceiversLock.Unlock()
|
||||
|
||||
if w.storageEventListener != nil {
|
||||
err := w.storageEventListener.Shutdown(w.baseContext)
|
||||
@@ -853,10 +903,10 @@ func (w *Worker) getSessionTls(sessionManager session.Manager) func(hello *tls.C
|
||||
return nil, fmt.Errorf("could not find session ID in SNI or ALPN protos")
|
||||
}
|
||||
|
||||
lastSuccess := w.LastStatusSuccess()
|
||||
lastSuccess := w.LastRoutingInfoSuccess()
|
||||
if lastSuccess == nil {
|
||||
event.WriteSysEvent(ctx, op, "no last status information found at session acceptance time")
|
||||
return nil, fmt.Errorf("no last status information found at session acceptance time")
|
||||
event.WriteSysEvent(ctx, op, "no last routing information found at session acceptance time")
|
||||
return nil, fmt.Errorf("no last routing information found at session acceptance time")
|
||||
}
|
||||
|
||||
timeoutContext, cancel := context.WithTimeout(w.baseContext, session.ValidateSessionTimeout)
|
||||
|
||||
@@ -30,6 +30,14 @@ func NewWorkerProxyServiceServer(
|
||||
}
|
||||
}
|
||||
|
||||
func (ws *workerProxyServiceServer) Statistics(ctx context.Context, req *pbs.StatisticsRequest) (*pbs.StatisticsResponse, error) {
|
||||
return pbs.NewServerCoordinationServiceClient(ws.cc).Statistics(ctx, req)
|
||||
}
|
||||
|
||||
func (ws *workerProxyServiceServer) SessionInfo(ctx context.Context, req *pbs.SessionInfoRequest) (*pbs.SessionInfoResponse, error) {
|
||||
return pbs.NewServerCoordinationServiceClient(ws.cc).SessionInfo(ctx, req)
|
||||
}
|
||||
|
||||
func (ws *workerProxyServiceServer) Status(ctx context.Context, req *pbs.StatusRequest) (*pbs.StatusResponse, error) {
|
||||
resp, err := pbs.NewServerCoordinationServiceClient(ws.cc).Status(ctx, req)
|
||||
|
||||
@@ -46,6 +54,18 @@ func (ws *workerProxyServiceServer) ListHcpbWorkers(ctx context.Context, req *pb
|
||||
return pbs.NewServerCoordinationServiceClient(ws.cc).ListHcpbWorkers(ctx, req)
|
||||
}
|
||||
|
||||
func (ws *workerProxyServiceServer) RoutingInfo(ctx context.Context, req *pbs.RoutingInfoRequest) (*pbs.RoutingInfoResponse, error) {
|
||||
resp, err := pbs.NewServerCoordinationServiceClient(ws.cc).RoutingInfo(ctx, req)
|
||||
|
||||
if resp != nil {
|
||||
// We don't currently support distributing new addreses to workers
|
||||
// multiple hops away so ensure they're stripped out
|
||||
resp.CalculatedUpstreamAddresses = nil
|
||||
}
|
||||
|
||||
return resp, err
|
||||
}
|
||||
|
||||
func (ws *workerProxyServiceServer) LookupSession(ctx context.Context, req *pbs.LookupSessionRequest) (*pbs.LookupSessionResponse, error) {
|
||||
return pbs.NewSessionServiceClient(ws.cc).LookupSession(ctx, req)
|
||||
}
|
||||
|
||||
@@ -371,7 +371,7 @@ func Test_Worker_getSessionTls(t *testing.T) {
|
||||
conf.RawConfig = &config.Config{SharedConfig: &configutil.SharedConfig{DisableMlock: true}}
|
||||
w, err := New(context.Background(), conf)
|
||||
require.NoError(t, err)
|
||||
w.lastStatusSuccess.Store(&LastStatusInformation{StatusResponse: &services.StatusResponse{}, StatusTime: time.Now(), LastCalculatedUpstreams: nil})
|
||||
w.lastRoutingInfoSuccess.Store(&LastRoutingInfo{RoutingInfoResponse: &services.RoutingInfoResponse{}, RoutingInfoTime: time.Now(), LastCalculatedUpstreams: nil})
|
||||
w.baseContext = context.Background()
|
||||
|
||||
t.Run("success", func(t *testing.T) {
|
||||
|
||||
Reference in new issue
Block a user