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
@@ -37,7 +37,7 @@ type sessionConnectionCleanupJob struct {
|
||||
// The amount of time to give disconnected workers before marking their
|
||||
// connections as closed. This should be larger than the liveness setting
|
||||
// for the worker.
|
||||
workerStatusGracePeriod *atomic.Int64
|
||||
workerRPCGracePeriod *atomic.Int64
|
||||
|
||||
// The total number of connections closed in the last run.
|
||||
totalClosed *atomic.Int64
|
||||
@@ -47,22 +47,22 @@ type sessionConnectionCleanupJob struct {
|
||||
func newSessionConnectionCleanupJob(
|
||||
ctx context.Context,
|
||||
writer db.Writer,
|
||||
workerStatusGracePeriod *atomic.Int64,
|
||||
workerRPCGracePeriod *atomic.Int64,
|
||||
) (*sessionConnectionCleanupJob, error) {
|
||||
const op = "session.newNewSessionConnectionCleanupJob"
|
||||
switch {
|
||||
case writer == nil:
|
||||
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing db writer")
|
||||
case workerStatusGracePeriod == nil:
|
||||
case workerRPCGracePeriod == nil:
|
||||
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing grace period")
|
||||
case workerStatusGracePeriod.Load() == 0:
|
||||
case workerRPCGracePeriod.Load() == 0:
|
||||
return nil, errors.New(ctx, errors.InvalidParameter, op, "grace period is zero")
|
||||
}
|
||||
|
||||
return &sessionConnectionCleanupJob{
|
||||
writer: writer,
|
||||
workerStatusGracePeriod: workerStatusGracePeriod,
|
||||
totalClosed: new(atomic.Int64),
|
||||
writer: writer,
|
||||
workerRPCGracePeriod: workerRPCGracePeriod,
|
||||
totalClosed: new(atomic.Int64),
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -100,7 +100,7 @@ func (j *sessionConnectionCleanupJob) Run(ctx context.Context, _ time.Duration)
|
||||
j.totalClosed.Store(0)
|
||||
|
||||
// Run the atomic dead worker cleanup job.
|
||||
gracePeriod := time.Duration(j.workerStatusGracePeriod.Load())
|
||||
gracePeriod := time.Duration(j.workerRPCGracePeriod.Load())
|
||||
results, err := j.closeConnectionsForDeadWorkers(ctx, gracePeriod)
|
||||
if err != nil {
|
||||
return errors.Wrap(ctx, err, op)
|
||||
|
||||
@@ -16,7 +16,6 @@ import (
|
||||
"github.com/hashicorp/boundary/internal/kms"
|
||||
"github.com/hashicorp/boundary/internal/scheduler"
|
||||
"github.com/hashicorp/boundary/internal/server"
|
||||
"github.com/hashicorp/boundary/internal/types/scope"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
@@ -54,6 +53,19 @@ func TestSessionConnectionCleanupJob(t *testing.T) {
|
||||
worker1 := server.TestKmsWorker(t, conn, wrapper)
|
||||
worker2 := server.TestKmsWorker(t, conn, wrapper)
|
||||
|
||||
updateServer := func(t *testing.T, w *server.Worker) *server.Worker {
|
||||
t.Helper()
|
||||
pubId := w.GetPublicId()
|
||||
w.PublicId = ""
|
||||
wkr, err := server.TestUpsertAndReturnWorker(ctx, t, w, serversRepo, server.WithPublicId(pubId))
|
||||
require.NoError(err)
|
||||
err = serversRepo.UpsertSessionInfo(ctx, pubId)
|
||||
require.NoError(err)
|
||||
return wkr
|
||||
}
|
||||
worker1 = updateServer(t, worker1)
|
||||
worker2 = updateServer(t, worker2)
|
||||
|
||||
// Create a few sessions on each, activate, and authorize a connection
|
||||
var connIds []string
|
||||
connIdsByWorker := make(map[string][]string)
|
||||
@@ -95,7 +107,7 @@ func TestSessionConnectionCleanupJob(t *testing.T) {
|
||||
|
||||
// Create the job.
|
||||
job, err := newSessionConnectionCleanupJob(ctx, rw, gracePeriod)
|
||||
job.workerStatusGracePeriod = gracePeriod // by-pass factory assert so we dont have to wait so long
|
||||
job.workerRPCGracePeriod = gracePeriod // by-pass factory assert so we dont have to wait so long
|
||||
require.NoError(err)
|
||||
|
||||
// sleep the status grace period.
|
||||
@@ -103,11 +115,7 @@ func TestSessionConnectionCleanupJob(t *testing.T) {
|
||||
|
||||
// Push an upsert to the first worker so that its status has been
|
||||
// updated.
|
||||
_, err = serversRepo.UpsertWorkerStatus(ctx, server.NewWorker(scope.Global.String(),
|
||||
server.WithName(worker1.GetName()),
|
||||
server.WithAddress(worker1.GetAddress())),
|
||||
server.WithPublicId(worker1.GetPublicId()))
|
||||
require.NoError(err)
|
||||
worker1 = updateServer(t, worker1)
|
||||
|
||||
// Run the job.
|
||||
require.NoError(job.Run(ctx, 0))
|
||||
@@ -280,6 +288,8 @@ func TestCloseConnectionsForDeadWorkers(t *testing.T) {
|
||||
w.PublicId = ""
|
||||
wkr, err := server.TestUpsertAndReturnWorker(ctx, t, w, serversRepo, server.WithPublicId(pubId))
|
||||
require.NoError(err)
|
||||
err = serversRepo.UpsertSessionInfo(ctx, pubId)
|
||||
require.NoError(err)
|
||||
return wkr
|
||||
}
|
||||
|
||||
@@ -372,13 +382,11 @@ func TestCloseConnectionsForDeadWorkers(t *testing.T) {
|
||||
require.NoError(err)
|
||||
// Assert that we have one result with the appropriate ID and
|
||||
// number of connections closed. Due to how things are
|
||||
require.Equal([]closeConnectionsForDeadWorkersResult{
|
||||
{
|
||||
WorkerId: worker1.PublicId,
|
||||
LastUpdateTime: timestampPbAsUTC(t, worker1.GetLastStatusTime().AsTime()),
|
||||
NumberConnectionsClosed: 12, // 18 per server, with 6 closed already
|
||||
},
|
||||
}, result)
|
||||
require.Len(result, 1)
|
||||
require.Equal(worker1.PublicId, result[0].WorkerId)
|
||||
require.Equal(12, result[0].NumberConnectionsClosed)
|
||||
require.WithinDuration(timestampPbAsUTC(t, worker1.GetLastStatusTime().AsTime()), result[0].LastUpdateTime, time.Second)
|
||||
|
||||
// Expect all connections closed on worker1
|
||||
requireConnectionStatus(t, worker1ConnIds, true)
|
||||
// Expect appropriate split connection state on worker2
|
||||
@@ -396,18 +404,19 @@ func TestCloseConnectionsForDeadWorkers(t *testing.T) {
|
||||
result, err := job.closeConnectionsForDeadWorkers(ctx, gracePeriod)
|
||||
require.NoError(err)
|
||||
// Assert that we have one result with the appropriate ID and number of connections closed.
|
||||
require.ElementsMatch([]closeConnectionsForDeadWorkersResult{
|
||||
{
|
||||
WorkerId: worker2.PublicId,
|
||||
LastUpdateTime: timestampPbAsUTC(t, worker2.GetLastStatusTime().AsTime()),
|
||||
NumberConnectionsClosed: 12, // 18 per server, with 6 closed already
|
||||
},
|
||||
{
|
||||
WorkerId: worker3.PublicId,
|
||||
LastUpdateTime: timestampPbAsUTC(t, worker3.GetLastStatusTime().AsTime()),
|
||||
NumberConnectionsClosed: 12, // 18 per server, with 6 closed already
|
||||
},
|
||||
}, result)
|
||||
expectedWorkers := map[string]*server.Worker{
|
||||
worker2.PublicId: worker2,
|
||||
worker3.PublicId: worker3,
|
||||
}
|
||||
require.Len(result, len(expectedWorkers))
|
||||
for _, r := range result {
|
||||
expectedWorker, ok := expectedWorkers[r.WorkerId]
|
||||
require.True(ok)
|
||||
require.Equal(expectedWorker.PublicId, r.WorkerId)
|
||||
require.Equal(12, r.NumberConnectionsClosed)
|
||||
require.WithinDuration(timestampPbAsUTC(t, expectedWorker.GetLastStatusTime().AsTime()), r.LastUpdateTime, time.Second)
|
||||
}
|
||||
|
||||
// Expect all connections closed on worker1
|
||||
requireConnectionStatus(t, worker1ConnIds, true)
|
||||
// Expect all connections closed on worker2
|
||||
|
||||
@@ -18,14 +18,14 @@ import (
|
||||
const deleteTerminatedThreshold = time.Hour
|
||||
|
||||
// RegisterJobs registers session related jobs with the provided scheduler.
|
||||
func RegisterJobs(ctx context.Context, scheduler *scheduler.Scheduler, w db.Writer, r db.Reader, k *kms.Kms, workerStatusGracePeriod *atomic.Int64) error {
|
||||
func RegisterJobs(ctx context.Context, scheduler *scheduler.Scheduler, w db.Writer, r db.Reader, k *kms.Kms, workerRPCGracePeriod *atomic.Int64) error {
|
||||
const op = "session.RegisterJobs"
|
||||
|
||||
if workerStatusGracePeriod == nil {
|
||||
if workerRPCGracePeriod == nil {
|
||||
return errors.New(ctx, errors.InvalidParameter, op, "nil grace period")
|
||||
}
|
||||
|
||||
sessionConnectionCleanupJob, err := newSessionConnectionCleanupJob(ctx, w, workerStatusGracePeriod)
|
||||
sessionConnectionCleanupJob, err := newSessionConnectionCleanupJob(ctx, w, workerRPCGracePeriod)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error creating session cleanup job: %w", err)
|
||||
}
|
||||
|
||||
@@ -297,11 +297,11 @@ where
|
||||
with
|
||||
dead_workers (worker_id, last_update_time) as (
|
||||
select
|
||||
w.public_id as worker_id,
|
||||
w.last_status_time as last_update_time
|
||||
from server_worker w
|
||||
w.worker_id as worker_id,
|
||||
w.last_request_time as last_update_time
|
||||
from server_worker_session_info_request w
|
||||
where
|
||||
w.last_status_time < wt_sub_seconds_from_now(@grace_period_seconds)
|
||||
w.last_request_time < wt_sub_seconds_from_now(@grace_period_seconds)
|
||||
),
|
||||
closed_connections (connection_id, worker_id) as (
|
||||
update session_connection
|
||||
|
||||
@@ -108,7 +108,7 @@ func (r *ConnectionRepository) updateBytesUpBytesDown(ctx context.Context, conns
|
||||
// we shouldn't update bytes up and down if the connection
|
||||
// has already been closed. This also guards against
|
||||
// potential data races where a connection closure request
|
||||
// and a worker status update happen close to each other in
|
||||
// and a worker statistics update happen close to each other in
|
||||
// terms of timing.
|
||||
db.WithWhere("closed_reason is null"),
|
||||
)
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
// Copyright (c) HashiCorp, Inc.
|
||||
// SPDX-License-Identifier: BUSL-1.1
|
||||
|
||||
package session
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/hashicorp/boundary/internal/errors"
|
||||
"github.com/hashicorp/boundary/internal/event"
|
||||
)
|
||||
|
||||
// CloseOrphanedConnections closes the orphaned connections for a given worker.
|
||||
func CloseOrphanedConnections(ctx context.Context, repo *ConnectionRepository, workerId string, connections []*Connection) ([]string, error) {
|
||||
const op = "session.CloseOrphanedConnections"
|
||||
if repo == nil {
|
||||
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing connection repository")
|
||||
}
|
||||
if workerId == "" {
|
||||
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing worker id")
|
||||
}
|
||||
connectionIds := []string{}
|
||||
for _, c := range connections {
|
||||
connectionIds = append(connectionIds, c.GetPublicId())
|
||||
}
|
||||
closed, err := repo.closeOrphanedConnections(ctx, workerId, connectionIds)
|
||||
if len(closed) > 0 {
|
||||
event.WriteSysEvent(ctx, op, "marked unclaimed connections as closed", "worker_id", workerId, "count", len(closed))
|
||||
}
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("failed to close orphaned connections for worker %q", workerId))
|
||||
}
|
||||
return closed, nil
|
||||
}
|
||||
|
||||
// UpdateConnectionBytesUpDown processes the connection statistics for a given worker.
|
||||
func UpdateConnectionBytesUpDown(ctx context.Context, repo *ConnectionRepository, connections []*Connection) error {
|
||||
const op = "session.UpdateConnectionBytesUpDown"
|
||||
if repo == nil {
|
||||
return errors.New(ctx, errors.InvalidParameter, op, "missing connection repository")
|
||||
}
|
||||
err := repo.updateBytesUpBytesDown(ctx, connections...)
|
||||
if err != nil {
|
||||
return errors.Wrap(ctx, err, op, errors.WithMsg("failed to update bytes up and down for worker connection statistics"))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,534 @@
|
||||
// Copyright (c) HashiCorp, Inc.
|
||||
// SPDX-License-Identifier: BUSL-1.1
|
||||
|
||||
package session
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/hashicorp/boundary/internal/authtoken"
|
||||
"github.com/hashicorp/boundary/internal/db"
|
||||
"github.com/hashicorp/boundary/internal/host/static"
|
||||
"github.com/hashicorp/boundary/internal/iam"
|
||||
"github.com/hashicorp/boundary/internal/kms"
|
||||
"github.com/hashicorp/boundary/internal/server"
|
||||
"github.com/hashicorp/boundary/internal/server/store"
|
||||
"github.com/hashicorp/boundary/internal/target"
|
||||
"github.com/hashicorp/boundary/internal/target/tcp"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestCloseOrphanedConnections(t *testing.T) {
|
||||
t.Parallel()
|
||||
conn, _ := db.TestSetup(t, "postgres")
|
||||
rw := db.New(conn)
|
||||
wrapper := db.TestWrapper(t)
|
||||
testKms := kms.TestKms(t, conn, wrapper)
|
||||
connRepo, err := NewConnectionRepository(context.Background(), rw, rw, testKms)
|
||||
require.NoError(t, err)
|
||||
sessRepo, err := NewRepository(context.Background(), rw, rw, testKms)
|
||||
require.NoError(t, err)
|
||||
|
||||
serverRepo, _ := server.NewRepository(context.Background(), rw, rw, testKms)
|
||||
_, err = serverRepo.UpsertController(context.Background(), &store.Controller{
|
||||
PrivateId: "test_controller1",
|
||||
Address: "127.0.0.1",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
connRepo *ConnectionRepository
|
||||
setup func() (workerId string, conns []*Connection, expectedClosedConnections []string)
|
||||
wantErrMsg string
|
||||
}{
|
||||
{
|
||||
name: "missing connection repository",
|
||||
setup: func() (workerId string, conns []*Connection, expectedClosedConnections []string) {
|
||||
return
|
||||
},
|
||||
wantErrMsg: "session.CloseOrphanedConnections: missing connection repository: parameter violation: error #100",
|
||||
},
|
||||
{
|
||||
name: "empty worker id",
|
||||
connRepo: &ConnectionRepository{},
|
||||
setup: func() (workerId string, conns []*Connection, expectedClosedConnections []string) {
|
||||
return
|
||||
},
|
||||
wantErrMsg: "session.CloseOrphanedConnections: missing worker id: parameter violation: error #100",
|
||||
},
|
||||
{
|
||||
name: "nil sessions",
|
||||
connRepo: connRepo,
|
||||
setup: func() (workerId string, conns []*Connection, expectedClosedConnections []string) {
|
||||
w := server.TestKmsWorker(t, conn, wrapper)
|
||||
workerId = w.GetPublicId()
|
||||
return
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "empty connections",
|
||||
connRepo: connRepo,
|
||||
setup: func() (workerId string, conns []*Connection, expectedClosedConnections []string) {
|
||||
w := server.TestKmsWorker(t, conn, wrapper)
|
||||
workerId = w.GetPublicId()
|
||||
conns = make([]*Connection, 0)
|
||||
return
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "ignore unknown connection",
|
||||
connRepo: connRepo,
|
||||
setup: func() (workerId string, conns []*Connection, expectedClosedConnections []string) {
|
||||
w := server.TestKmsWorker(t, conn, wrapper)
|
||||
workerId = w.GetPublicId()
|
||||
conns = []*Connection{
|
||||
{
|
||||
PublicId: "c_dne",
|
||||
},
|
||||
}
|
||||
return
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "session already canceled",
|
||||
connRepo: connRepo,
|
||||
setup: func() (workerId string, conns []*Connection, expectedClosedConnections []string) {
|
||||
w := server.TestKmsWorker(t, conn, wrapper)
|
||||
org, prj := iam.TestScopes(t, iam.TestRepo(t, conn, wrapper))
|
||||
authToken := authtoken.TestAuthToken(t, conn, testKms, org.GetPublicId())
|
||||
userId := authToken.GetIamUserId()
|
||||
hostCatalog := static.TestCatalogs(t, conn, prj.GetPublicId(), 1)[0]
|
||||
hostSet := static.TestSets(t, conn, hostCatalog.GetPublicId(), 1)[0]
|
||||
host := static.TestHosts(t, conn, hostCatalog.GetPublicId(), 1)[0]
|
||||
static.TestSetMembers(t, conn, hostSet.GetPublicId(), []*static.Host{host})
|
||||
tar := tcp.TestTarget(
|
||||
context.Background(),
|
||||
t, conn, prj.GetPublicId(), "test",
|
||||
target.WithHostSources([]string{hostSet.GetPublicId()}),
|
||||
target.WithSessionConnectionLimit(-1),
|
||||
)
|
||||
s1 := TestSession(t, conn, wrapper, ComposedOf{
|
||||
UserId: userId,
|
||||
HostId: host.GetPublicId(),
|
||||
TargetId: tar.GetPublicId(),
|
||||
HostSetId: hostSet.GetPublicId(),
|
||||
AuthTokenId: authToken.GetPublicId(),
|
||||
ProjectId: prj.GetPublicId(),
|
||||
Endpoint: "tcp://127.0.0.1:22",
|
||||
ConnectionLimit: 10,
|
||||
})
|
||||
s1, _, err = sessRepo.ActivateSession(context.Background(), s1.PublicId, s1.Version, TestTofu(t))
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, err)
|
||||
_, err = connRepo.AuthorizeConnection(context.Background(), s1.PublicId, w.PublicId)
|
||||
require.NoError(t, err)
|
||||
_, err = sessRepo.CancelSession(context.Background(), s1.PublicId, s1.Version)
|
||||
require.NoError(t, err)
|
||||
workerId = w.GetPublicId()
|
||||
conns = []*Connection{}
|
||||
return
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "active session",
|
||||
connRepo: connRepo,
|
||||
setup: func() (workerId string, conns []*Connection, expectedClosedConnections []string) {
|
||||
w := server.TestKmsWorker(t, conn, wrapper)
|
||||
org, prj := iam.TestScopes(t, iam.TestRepo(t, conn, wrapper))
|
||||
authToken := authtoken.TestAuthToken(t, conn, testKms, org.GetPublicId())
|
||||
userId := authToken.GetIamUserId()
|
||||
hostCatalog := static.TestCatalogs(t, conn, prj.GetPublicId(), 1)[0]
|
||||
hostSet := static.TestSets(t, conn, hostCatalog.GetPublicId(), 1)[0]
|
||||
host := static.TestHosts(t, conn, hostCatalog.GetPublicId(), 1)[0]
|
||||
static.TestSetMembers(t, conn, hostSet.GetPublicId(), []*static.Host{host})
|
||||
tar := tcp.TestTarget(
|
||||
context.Background(),
|
||||
t, conn, prj.GetPublicId(), "test",
|
||||
target.WithHostSources([]string{hostSet.GetPublicId()}),
|
||||
target.WithSessionConnectionLimit(-1),
|
||||
)
|
||||
s1 := TestSession(t, conn, wrapper, ComposedOf{
|
||||
UserId: userId,
|
||||
HostId: host.GetPublicId(),
|
||||
TargetId: tar.GetPublicId(),
|
||||
HostSetId: hostSet.GetPublicId(),
|
||||
AuthTokenId: authToken.GetPublicId(),
|
||||
ProjectId: prj.GetPublicId(),
|
||||
Endpoint: "tcp://127.0.0.1:22",
|
||||
ConnectionLimit: 10,
|
||||
})
|
||||
s1, _, err = sessRepo.ActivateSession(context.Background(), s1.PublicId, s1.Version, TestTofu(t))
|
||||
require.NoError(t, err)
|
||||
c1, err := connRepo.AuthorizeConnection(context.Background(), s1.PublicId, w.GetPublicId())
|
||||
require.NoError(t, err)
|
||||
workerId = w.GetPublicId()
|
||||
conns = []*Connection{
|
||||
{
|
||||
PublicId: c1.GetPublicId(),
|
||||
},
|
||||
}
|
||||
return
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "closed session",
|
||||
connRepo: connRepo,
|
||||
setup: func() (workerId string, conns []*Connection, expectedClosedConnections []string) {
|
||||
w := server.TestKmsWorker(t, conn, wrapper)
|
||||
org, prj := iam.TestScopes(t, iam.TestRepo(t, conn, wrapper))
|
||||
authToken := authtoken.TestAuthToken(t, conn, testKms, org.GetPublicId())
|
||||
userId := authToken.GetIamUserId()
|
||||
hostCatalog := static.TestCatalogs(t, conn, prj.GetPublicId(), 1)[0]
|
||||
hostSet := static.TestSets(t, conn, hostCatalog.GetPublicId(), 1)[0]
|
||||
host := static.TestHosts(t, conn, hostCatalog.GetPublicId(), 1)[0]
|
||||
static.TestSetMembers(t, conn, hostSet.GetPublicId(), []*static.Host{host})
|
||||
tar := tcp.TestTarget(
|
||||
context.Background(),
|
||||
t, conn, prj.GetPublicId(), "test",
|
||||
target.WithHostSources([]string{hostSet.GetPublicId()}),
|
||||
target.WithSessionConnectionLimit(-1),
|
||||
)
|
||||
s1 := TestSession(t, conn, wrapper, ComposedOf{
|
||||
UserId: userId,
|
||||
HostId: host.GetPublicId(),
|
||||
TargetId: tar.GetPublicId(),
|
||||
HostSetId: hostSet.GetPublicId(),
|
||||
AuthTokenId: authToken.GetPublicId(),
|
||||
ProjectId: prj.GetPublicId(),
|
||||
Endpoint: "tcp://127.0.0.1:22",
|
||||
ConnectionLimit: 10,
|
||||
})
|
||||
s1, _, err = sessRepo.ActivateSession(context.Background(), s1.PublicId, s1.Version, TestTofu(t))
|
||||
require.NoError(t, err)
|
||||
c1, err := connRepo.AuthorizeConnection(context.Background(), s1.PublicId, w.PublicId)
|
||||
require.NoError(t, err)
|
||||
_, err = sessRepo.CancelSession(context.Background(), s1.PublicId, s1.Version)
|
||||
require.NoError(t, err)
|
||||
|
||||
workerId = w.GetPublicId()
|
||||
conns = []*Connection{
|
||||
{
|
||||
PublicId: c1.GetPublicId(),
|
||||
},
|
||||
}
|
||||
return
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "multiple closed sessions",
|
||||
connRepo: connRepo,
|
||||
setup: func() (workerId string, conns []*Connection, expectedClosedConnections []string) {
|
||||
w := server.TestKmsWorker(t, conn, wrapper)
|
||||
org, prj := iam.TestScopes(t, iam.TestRepo(t, conn, wrapper))
|
||||
authToken := authtoken.TestAuthToken(t, conn, testKms, org.GetPublicId())
|
||||
userId := authToken.GetIamUserId()
|
||||
hostCatalog := static.TestCatalogs(t, conn, prj.GetPublicId(), 1)[0]
|
||||
hostSet := static.TestSets(t, conn, hostCatalog.GetPublicId(), 1)[0]
|
||||
host := static.TestHosts(t, conn, hostCatalog.GetPublicId(), 1)[0]
|
||||
static.TestSetMembers(t, conn, hostSet.GetPublicId(), []*static.Host{host})
|
||||
tar := tcp.TestTarget(
|
||||
context.Background(),
|
||||
t, conn, prj.GetPublicId(), "test",
|
||||
target.WithHostSources([]string{hostSet.GetPublicId()}),
|
||||
target.WithSessionConnectionLimit(-1),
|
||||
)
|
||||
s1 := TestSession(t, conn, wrapper, ComposedOf{
|
||||
UserId: userId,
|
||||
HostId: host.GetPublicId(),
|
||||
TargetId: tar.GetPublicId(),
|
||||
HostSetId: hostSet.GetPublicId(),
|
||||
AuthTokenId: authToken.GetPublicId(),
|
||||
ProjectId: prj.GetPublicId(),
|
||||
Endpoint: "tcp://127.0.0.1:22",
|
||||
ConnectionLimit: 10,
|
||||
})
|
||||
s1, _, err = sessRepo.ActivateSession(context.Background(), s1.PublicId, s1.Version, TestTofu(t))
|
||||
require.NoError(t, err)
|
||||
c1, err := connRepo.AuthorizeConnection(context.Background(), s1.PublicId, w.PublicId)
|
||||
require.NoError(t, err)
|
||||
_, err = sessRepo.CancelSession(context.Background(), s1.PublicId, s1.Version)
|
||||
require.NoError(t, err)
|
||||
|
||||
s2 := TestSession(t, conn, wrapper, ComposedOf{
|
||||
UserId: userId,
|
||||
HostId: host.GetPublicId(),
|
||||
TargetId: tar.GetPublicId(),
|
||||
HostSetId: hostSet.GetPublicId(),
|
||||
AuthTokenId: authToken.GetPublicId(),
|
||||
ProjectId: prj.GetPublicId(),
|
||||
Endpoint: "tcp://127.0.0.1:22",
|
||||
ConnectionLimit: 10,
|
||||
})
|
||||
s2, _, err = sessRepo.ActivateSession(context.Background(), s2.PublicId, s2.Version, TestTofu(t))
|
||||
require.NoError(t, err)
|
||||
c2, err := connRepo.AuthorizeConnection(context.Background(), s2.PublicId, w.PublicId)
|
||||
require.NoError(t, err)
|
||||
_, err = sessRepo.CancelSession(context.Background(), s2.PublicId, s2.Version)
|
||||
require.NoError(t, err)
|
||||
|
||||
workerId = w.GetPublicId()
|
||||
conns = []*Connection{
|
||||
{
|
||||
PublicId: c1.GetPublicId(),
|
||||
},
|
||||
{
|
||||
PublicId: c2.GetPublicId(),
|
||||
},
|
||||
}
|
||||
return
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "close orphaned connections",
|
||||
connRepo: func() *ConnectionRepository {
|
||||
connRepo, err := NewConnectionRepository(context.Background(), rw, rw, testKms, WithWorkerStateDelay(0))
|
||||
require.NoError(t, err)
|
||||
return connRepo
|
||||
}(),
|
||||
setup: func() (workerId string, conns []*Connection, expectedClosedConnections []string) {
|
||||
w := server.TestKmsWorker(t, conn, wrapper)
|
||||
org, prj := iam.TestScopes(t, iam.TestRepo(t, conn, wrapper))
|
||||
authToken := authtoken.TestAuthToken(t, conn, testKms, org.GetPublicId())
|
||||
userId := authToken.GetIamUserId()
|
||||
hostCatalog := static.TestCatalogs(t, conn, prj.GetPublicId(), 1)[0]
|
||||
hostSet := static.TestSets(t, conn, hostCatalog.GetPublicId(), 1)[0]
|
||||
host := static.TestHosts(t, conn, hostCatalog.GetPublicId(), 1)[0]
|
||||
static.TestSetMembers(t, conn, hostSet.GetPublicId(), []*static.Host{host})
|
||||
tar := tcp.TestTarget(
|
||||
context.Background(),
|
||||
t, conn, prj.GetPublicId(), "test",
|
||||
target.WithHostSources([]string{hostSet.GetPublicId()}),
|
||||
target.WithSessionConnectionLimit(-1),
|
||||
)
|
||||
s1 := TestSession(t, conn, wrapper, ComposedOf{
|
||||
UserId: userId,
|
||||
HostId: host.GetPublicId(),
|
||||
TargetId: tar.GetPublicId(),
|
||||
HostSetId: hostSet.GetPublicId(),
|
||||
AuthTokenId: authToken.GetPublicId(),
|
||||
ProjectId: prj.GetPublicId(),
|
||||
Endpoint: "tcp://127.0.0.1:22",
|
||||
ConnectionLimit: 10,
|
||||
})
|
||||
s1, _, err = sessRepo.ActivateSession(context.Background(), s1.PublicId, s1.Version, TestTofu(t))
|
||||
require.NoError(t, err)
|
||||
c1, err := connRepo.AuthorizeConnection(context.Background(), s1.PublicId, w.PublicId)
|
||||
require.NoError(t, err)
|
||||
s2 := TestSession(t, conn, wrapper, ComposedOf{
|
||||
UserId: userId,
|
||||
HostId: host.GetPublicId(),
|
||||
TargetId: tar.GetPublicId(),
|
||||
HostSetId: hostSet.GetPublicId(),
|
||||
AuthTokenId: authToken.GetPublicId(),
|
||||
ProjectId: prj.GetPublicId(),
|
||||
Endpoint: "tcp://127.0.0.1:22",
|
||||
ConnectionLimit: 10,
|
||||
})
|
||||
s2, _, err = sessRepo.ActivateSession(context.Background(), s2.PublicId, s2.Version, TestTofu(t))
|
||||
require.NoError(t, err)
|
||||
c2, err := connRepo.AuthorizeConnection(context.Background(), s2.PublicId, w.PublicId)
|
||||
require.NoError(t, err)
|
||||
require.NotEqual(t, c1.PublicId, c2.PublicId)
|
||||
workerId = w.GetPublicId()
|
||||
conns = []*Connection{
|
||||
{
|
||||
PublicId: c2.GetPublicId(),
|
||||
},
|
||||
}
|
||||
expectedClosedConnections = []string{c1.PublicId}
|
||||
return
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "multiple sessions and orphaned connections",
|
||||
connRepo: func() *ConnectionRepository {
|
||||
connRepo, err := NewConnectionRepository(context.Background(), rw, rw, testKms, WithWorkerStateDelay(0))
|
||||
require.NoError(t, err)
|
||||
return connRepo
|
||||
}(),
|
||||
setup: func() (workerId string, conns []*Connection, expectedClosedConnections []string) {
|
||||
w := server.TestKmsWorker(t, conn, wrapper)
|
||||
org, prj := iam.TestScopes(t, iam.TestRepo(t, conn, wrapper))
|
||||
authToken := authtoken.TestAuthToken(t, conn, testKms, org.GetPublicId())
|
||||
userId := authToken.GetIamUserId()
|
||||
hostCatalog := static.TestCatalogs(t, conn, prj.GetPublicId(), 1)[0]
|
||||
hostSet := static.TestSets(t, conn, hostCatalog.GetPublicId(), 1)[0]
|
||||
host := static.TestHosts(t, conn, hostCatalog.GetPublicId(), 1)[0]
|
||||
static.TestSetMembers(t, conn, hostSet.GetPublicId(), []*static.Host{host})
|
||||
tar := tcp.TestTarget(
|
||||
context.Background(),
|
||||
t, conn, prj.GetPublicId(), "test",
|
||||
target.WithHostSources([]string{hostSet.GetPublicId()}),
|
||||
target.WithSessionConnectionLimit(-1),
|
||||
)
|
||||
s1 := TestSession(t, conn, wrapper, ComposedOf{
|
||||
UserId: userId,
|
||||
HostId: host.GetPublicId(),
|
||||
TargetId: tar.GetPublicId(),
|
||||
HostSetId: hostSet.GetPublicId(),
|
||||
AuthTokenId: authToken.GetPublicId(),
|
||||
ProjectId: prj.GetPublicId(),
|
||||
Endpoint: "tcp://127.0.0.1:22",
|
||||
ConnectionLimit: 10,
|
||||
})
|
||||
s1, _, err = sessRepo.ActivateSession(context.Background(), s1.PublicId, s1.Version, TestTofu(t))
|
||||
require.NoError(t, err)
|
||||
c1, err := connRepo.AuthorizeConnection(context.Background(), s1.PublicId, w.PublicId)
|
||||
require.NoError(t, err)
|
||||
_, err = sessRepo.CancelSession(context.Background(), s1.PublicId, s1.Version)
|
||||
require.NoError(t, err)
|
||||
|
||||
s2 := TestSession(t, conn, wrapper, ComposedOf{
|
||||
UserId: userId,
|
||||
HostId: host.GetPublicId(),
|
||||
TargetId: tar.GetPublicId(),
|
||||
HostSetId: hostSet.GetPublicId(),
|
||||
AuthTokenId: authToken.GetPublicId(),
|
||||
ProjectId: prj.GetPublicId(),
|
||||
Endpoint: "tcp://127.0.0.1:22",
|
||||
ConnectionLimit: 10,
|
||||
})
|
||||
s2, _, err = sessRepo.ActivateSession(context.Background(), s2.PublicId, s2.Version, TestTofu(t))
|
||||
require.NoError(t, err)
|
||||
c2, err := connRepo.AuthorizeConnection(context.Background(), s2.PublicId, w.PublicId)
|
||||
require.NoError(t, err)
|
||||
c3, err := connRepo.AuthorizeConnection(context.Background(), s2.PublicId, w.PublicId)
|
||||
require.NoError(t, err)
|
||||
_, err = sessRepo.CancelSession(context.Background(), s2.PublicId, s2.Version)
|
||||
require.NoError(t, err)
|
||||
|
||||
workerId = w.GetPublicId()
|
||||
conns = []*Connection{
|
||||
{
|
||||
PublicId: c1.GetPublicId(),
|
||||
},
|
||||
{
|
||||
PublicId: c2.GetPublicId(),
|
||||
},
|
||||
}
|
||||
expectedClosedConnections = []string{c3.PublicId}
|
||||
return
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
assert, require := assert.New(t), require.New(t)
|
||||
require.NotNil(tc.setup)
|
||||
workerId, stats, expectedClosedConnections := tc.setup()
|
||||
actualClosedConnections, err := CloseOrphanedConnections(context.Background(), tc.connRepo, workerId, stats)
|
||||
if tc.wantErrMsg != "" {
|
||||
require.Error(err)
|
||||
assert.ErrorContains(err, tc.wantErrMsg)
|
||||
assert.Empty(actualClosedConnections)
|
||||
return
|
||||
}
|
||||
require.NoError(err)
|
||||
assert.Equal(expectedClosedConnections, actualClosedConnections)
|
||||
for _, connectionId := range expectedClosedConnections {
|
||||
conn, err := connRepo.LookupConnection(context.Background(), connectionId)
|
||||
require.NoError(err)
|
||||
assert.Equal(ConnectionSystemError, ClosedReason(conn.ClosedReason))
|
||||
assert.Equal(StatusClosed, ConnectionStatusFromString(conn.Status))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateConnectionBytesUpDown(t *testing.T) {
|
||||
t.Parallel()
|
||||
conn, _ := db.TestSetup(t, "postgres")
|
||||
rw := db.New(conn)
|
||||
wrapper := db.TestWrapper(t)
|
||||
testKms := kms.TestKms(t, conn, wrapper)
|
||||
connRepo, err := NewConnectionRepository(context.Background(), rw, rw, testKms)
|
||||
require.NoError(t, err)
|
||||
sessRepo, err := NewRepository(context.Background(), rw, rw, testKms)
|
||||
require.NoError(t, err)
|
||||
|
||||
serverRepo, _ := server.NewRepository(context.Background(), rw, rw, testKms)
|
||||
_, err = serverRepo.UpsertController(context.Background(), &store.Controller{
|
||||
PrivateId: "test_controller1",
|
||||
Address: "127.0.0.1",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
t.Run("nil connection repo", func(t *testing.T) {
|
||||
assert, require := assert.New(t), require.New(t)
|
||||
err := UpdateConnectionBytesUpDown(context.Background(), nil, nil)
|
||||
require.Error(err)
|
||||
assert.ErrorContains(err, "missing connection repository")
|
||||
})
|
||||
|
||||
t.Run("bytes up and bytes down", func(t *testing.T) {
|
||||
assert, require := assert.New(t), require.New(t)
|
||||
w := server.TestKmsWorker(t, conn, wrapper)
|
||||
org, prj := iam.TestScopes(t, iam.TestRepo(t, conn, wrapper))
|
||||
authToken := authtoken.TestAuthToken(t, conn, testKms, org.GetPublicId())
|
||||
userId := authToken.GetIamUserId()
|
||||
hostCatalog := static.TestCatalogs(t, conn, prj.GetPublicId(), 1)[0]
|
||||
hostSet := static.TestSets(t, conn, hostCatalog.GetPublicId(), 1)[0]
|
||||
host := static.TestHosts(t, conn, hostCatalog.GetPublicId(), 1)[0]
|
||||
static.TestSetMembers(t, conn, hostSet.GetPublicId(), []*static.Host{host})
|
||||
tar := tcp.TestTarget(
|
||||
context.Background(),
|
||||
t, conn, prj.GetPublicId(), "test",
|
||||
target.WithHostSources([]string{hostSet.GetPublicId()}),
|
||||
target.WithSessionConnectionLimit(-1),
|
||||
)
|
||||
s1 := TestSession(t, conn, wrapper, ComposedOf{
|
||||
UserId: userId,
|
||||
HostId: host.GetPublicId(),
|
||||
TargetId: tar.GetPublicId(),
|
||||
HostSetId: hostSet.GetPublicId(),
|
||||
AuthTokenId: authToken.GetPublicId(),
|
||||
ProjectId: prj.GetPublicId(),
|
||||
Endpoint: "tcp://127.0.0.1:22",
|
||||
ConnectionLimit: 10,
|
||||
})
|
||||
s1, _, err = sessRepo.ActivateSession(context.Background(), s1.PublicId, s1.Version, TestTofu(t))
|
||||
require.NoError(err)
|
||||
c1, err := connRepo.AuthorizeConnection(context.Background(), s1.PublicId, w.GetPublicId())
|
||||
require.NoError(err)
|
||||
|
||||
// write to active session
|
||||
var expectedBytesUp int64 = 1024
|
||||
var expectedBytesDown int64 = 2048
|
||||
conns := []*Connection{
|
||||
{
|
||||
PublicId: c1.GetPublicId(),
|
||||
BytesUp: expectedBytesUp,
|
||||
BytesDown: expectedBytesDown,
|
||||
},
|
||||
}
|
||||
err = UpdateConnectionBytesUpDown(context.Background(), connRepo, conns)
|
||||
require.NoError(err)
|
||||
conn, err := connRepo.LookupConnection(context.Background(), c1.PublicId)
|
||||
require.NoError(err)
|
||||
assert.Equal(StatusAuthorized, ConnectionStatusFromString(conn.Status))
|
||||
assert.Equal(expectedBytesUp, conn.BytesUp)
|
||||
assert.Equal(expectedBytesDown, conn.BytesDown)
|
||||
|
||||
// write to canceled session
|
||||
_, err = sessRepo.CancelSession(context.Background(), s1.PublicId, s1.Version)
|
||||
require.NoError(err)
|
||||
expectedBytesUp = 4096
|
||||
expectedBytesDown = 8192
|
||||
conns = []*Connection{
|
||||
{
|
||||
PublicId: c1.GetPublicId(),
|
||||
BytesUp: expectedBytesUp,
|
||||
BytesDown: expectedBytesDown,
|
||||
},
|
||||
}
|
||||
err = UpdateConnectionBytesUpDown(context.Background(), connRepo, conns)
|
||||
require.NoError(err)
|
||||
conn, err = connRepo.LookupConnection(context.Background(), c1.PublicId)
|
||||
require.NoError(err)
|
||||
assert.Equal(expectedBytesUp, conn.BytesUp)
|
||||
assert.Equal(expectedBytesDown, conn.BytesDown)
|
||||
})
|
||||
}
|
||||
Reference in new issue
Block a user