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
@@ -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