Add cleanup of dead connections no longer reported by a worker (#1220)

This commit is contained in:
Jeff Mitchell authored and GitHub committed 2021-05-14 13:23:12 -04:00
1 parent 0b5ac930ac
commit 6f34da8923
24 files changed
+741 -223

No files matched your search

+2 -2
View File
@@ -69,12 +69,12 @@ func NewConnection(sessionID, clientTcpAddress string, clientTcpPort uint32, end
return &c, nil
}
// AllocConnection will allocate a connection.
// AllocConnection will allocate a Connection.
func AllocConnection() Connection {
return Connection{}
}
// Clone creates a clone of the connection.
// Clone creates a clone of the Connection.
func (c *Connection) Clone() interface{} {
clone := &Connection{
PublicId: c.PublicId,
+17
View File
@@ -27,6 +27,8 @@ type options struct {
withTestTofu []byte
withListingConvert bool
withSessionIds []string
withServerId string
withDbOpts []db.Option
}
func getDefaultOptions() options {
@@ -91,3 +93,18 @@ func withListingConvert(withListingConvert bool) Option {
o.withListingConvert = withListingConvert
}
}
// WithServerId allows the specification of the server id to use for the
// operation.
func WithServerId(id string) Option {
return func(o *options) {
o.withServerId = id
}
}
// WithDbOpts passes through given DB options to the DB layer
func WithDbOpts(opts ...db.Option) Option {
return func(o *options) {
o.withDbOpts = opts
}
}
+10 -6
View File
@@ -2,13 +2,11 @@ package session
import (
"testing"
"time"
"github.com/golang/protobuf/ptypes"
"github.com/hashicorp/boundary/internal/db"
"github.com/hashicorp/boundary/internal/db/timestamp"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/types/known/timestamppb"
)
// Test_GetOpts provides unit tests for GetOpts and all the options
@@ -54,9 +52,8 @@ func Test_GetOpts(t *testing.T) {
assert.Equal(opts, testOpts)
})
t.Run("WithExpirationTime", func(t *testing.T) {
assert, require := assert.New(t), require.New(t)
now, err := ptypes.TimestampProto(time.Now())
require.NoError(err)
assert := assert.New(t)
now := timestamppb.Now()
opts := getOpts(WithExpirationTime(&timestamp.Timestamp{Timestamp: now}))
testOpts := getDefaultOptions()
testOpts.withExpirationTime = &timestamp.Timestamp{Timestamp: now}
@@ -78,4 +75,11 @@ func Test_GetOpts(t *testing.T) {
testOpts.withSessionIds = []string{"s_1", "s_2", "s_3"}
assert.Equal(opts, testOpts)
})
t.Run("WithServerId", func(t *testing.T) {
assert := assert.New(t)
opts := getOpts(WithServerId("worker1"))
testOpts := getDefaultOptions()
testOpts.withServerId = "worker1"
assert.Equal(opts, testOpts)
})
}
+49 -2
View File
@@ -89,12 +89,14 @@ select * from terminated;
authorizeConnectionCte = `
insert into session_connection (
session_id,
public_id
public_id,
server_id
)
with active_session as (
select
$1 as session_id,
$2 as public_id
$2 as public_id,
$3 as server_id
from
session s
where
@@ -232,4 +234,49 @@ where
)
)
`
// connectionsToCloseCte finds connections that are:
//
// * not closed
// * not announced by a given server in its latest update
//
// and marks them as closed.
connectionsToCloseCte = `
with
-- Find connections that are not closed so we can reference those IDs
unclosed_connections as (
select connection_id
from session_connection_state
where
-- It's the current state
end_time is null
and
-- Current state isn't closed state
state in ('authorized', 'connected')
and
-- It's not in limbo between when it moved into this state and when
-- it started being reported by the worker, which is roughly every
-- 2-3 seconds
start_time < now() - interval '10 seconds'
),
connections_to_close as (
select public_id
from session_connection
where
-- Related to the worker that just reported to us
server_id = $1
and
-- These are connection IDs that just got reported to us by the given
-- worker, so they should not be considered closed.
%s
-- Only unclosed ones
public_id in (select connection_id from unclosed_connections)
)
update session_connection
set
closed_reason = 'system error'
where
public_id in (select public_id from connections_to_close)
returning public_id
`
)
+63 -4
View File
@@ -3,13 +3,14 @@ package session
import (
"context"
"fmt"
"strings"
"github.com/hashicorp/boundary/internal/db"
"github.com/hashicorp/boundary/internal/errors"
)
// LookupConnection will look up a connection in the repository and return the connection
// with its states. If the connection is not found, it will return nil, nil, nil.
// with its states. If the connection is not found, it will return nil, nil, nil.
// No options are currently supported.
func (r *Repository) LookupConnection(ctx context.Context, connectionId string, _ ...Option) (*Connection, []*ConnectionState, error) {
const op = "session.(Repository).LookupConnection"
@@ -43,12 +44,21 @@ func (r *Repository) LookupConnection(ctx context.Context, connectionId string,
return &connection, states, nil
}
// ListConnections will sessions. Supports the WithLimit and WithOrder options.
func (r *Repository) ListConnections(ctx context.Context, sessionId string, opt ...Option) ([]*Connection, error) {
// ListConnections will connections by session ID. If session ID is *, all
// connections are returned. Supports the WithLimit and WithOrder options.
func (r *Repository) ListConnectionsBySessionId(ctx context.Context, sessionId string, opt ...Option) ([]*Connection, error) {
const op = "session.(Repository).ListConnections"
opts := getOpts(opt...)
var connections []*Connection
err := r.list(ctx, &connections, "session_id = ?", []interface{}{sessionId}, opts) // pass options, so WithLimit and WithOrder are supported
var args []interface{}
var where string
if sessionId != "*" {
where = "session_id = ?"
args = append(args, sessionId)
}
// The where clause will be ignored if args is empty, if we don't want to
// scope to a specific session ID
err := r.list(ctx, &connections, where, args, opts) // pass options, so WithLimit and WithOrder are supported
if err != nil {
return nil, errors.Wrap(err, op)
}
@@ -95,6 +105,55 @@ func (r *Repository) DeleteConnection(ctx context.Context, publicId string, _ ..
return rowsDeleted, nil
}
// CloseDeadConnectionsOnWorkerReport will run the connectionsToClose CTE to
// look for connections that should be marked closed because they are no longer
// claimed by a server. This does notdetect connections where the server is no
// longer reporting status; that's for a different CTE to be called by a
// heartbeat detector.
//
// The foundConns input should be the currently-claimed connections; the CTE
// uses a NOT IN clause to ensure these are excluded. It is not an error for
// this to be empty as the worker could claim no connections; in that case all
// connections will immediately transition to closed.
func (r *Repository) CloseDeadConnectionsOnWorkerReport(ctx context.Context, serverId string, foundConns []string) (int, error) {
const op = "session.(Repository).CloseDeadConnectionsOnWorkerReport"
if serverId == "" {
return db.NoRowsAffected, errors.New(errors.InvalidParameter, op, "missing server id")
}
args := make([]interface{}, 0, len(foundConns)+1)
args = append(args, serverId)
var publicIdStr string
if len(foundConns) > 0 {
publicIdStr = `public_id not in (%s) and`
params := make([]string, len(foundConns))
for i, connId := range foundConns {
params[i] = fmt.Sprintf("$%d", i+2) // Add one for server ID, and offsets start at 1
args = append(args, connId)
}
publicIdStr = fmt.Sprintf(publicIdStr, strings.Join(params, ","))
}
var rowsAffected int
_, err := r.writer.DoTx(
ctx,
db.StdRetryCnt,
db.ExpBackoff{},
func(reader db.Reader, w db.Writer) error {
var err error
rowsAffected, err = w.Exec(ctx, fmt.Sprintf(connectionsToCloseCte, publicIdStr), args)
if err != nil {
return errors.Wrap(err, op)
}
return nil
},
)
if err != nil {
return db.NoRowsAffected, errors.Wrap(err, op)
}
return rowsAffected, nil
}
func fetchConnectionStates(ctx context.Context, r db.Reader, connectionId string, opt ...db.Option) ([]*ConnectionState, error) {
const op = "session.fetchConnectionStates"
var states []*ConnectionState
+126 -7
View File
@@ -5,12 +5,12 @@ import (
"testing"
"time"
"github.com/golang/protobuf/ptypes"
"github.com/hashicorp/boundary/internal/db"
"github.com/hashicorp/boundary/internal/errors"
"github.com/hashicorp/boundary/internal/iam"
"github.com/hashicorp/boundary/internal/kms"
"github.com/hashicorp/boundary/internal/oplog"
"github.com/hashicorp/boundary/sdk/strutil"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -93,7 +93,7 @@ func TestRepository_ListConnection(t *testing.T) {
testConnections = append(testConnections, c)
}
assert.Equal(tt.createCnt, len(testConnections))
got, err := repo.ListConnections(context.Background(), tt.args.searchForSessionId, tt.args.opt...)
got, err := repo.ListConnectionsBySessionId(context.Background(), tt.args.searchForSessionId, tt.args.opt...)
if tt.wantErr {
require.Error(err)
return
@@ -115,15 +115,13 @@ func TestRepository_ListConnection(t *testing.T) {
2222,
)
}
got, err := repo.ListConnections(context.Background(), session.PublicId, WithOrderByCreateTime(db.AscendingOrderBy))
got, err := repo.ListConnectionsBySessionId(context.Background(), session.PublicId, WithOrderByCreateTime(db.AscendingOrderBy))
require.NoError(err)
assert.Equal(wantCnt, len(got))
for i := 0; i < len(got)-1; i++ {
first, err := ptypes.Timestamp(got[i].CreateTime.Timestamp)
require.NoError(err)
second, err := ptypes.Timestamp(got[i+1].CreateTime.Timestamp)
require.NoError(err)
first := got[i].CreateTime.Timestamp.AsTime()
second := got[i+1].CreateTime.Timestamp.AsTime()
assert.True(first.Before(second))
}
})
@@ -211,3 +209,124 @@ func TestRepository_DeleteConnection(t *testing.T) {
})
}
}
func TestRepository_CloseDeadConnectionsOnWorkerReport(t *testing.T) {
t.Parallel()
require, assert := require.New(t), assert.New(t)
conn, _ := db.TestSetup(t, "postgres")
rw := db.New(conn)
wrapper := db.TestWrapper(t)
iamRepo := iam.TestRepo(t, conn, wrapper)
kms := kms.TestKms(t, conn, wrapper)
repo, err := NewRepository(rw, rw, kms)
require.NoError(err)
ctx := context.Background()
numConns := 12
// Create two "workers". One will remain untouched while the other "goes
// away and comes back" (worker 2).
worker1 := TestWorker(t, conn, wrapper, WithServerId("worker1"))
worker2 := TestWorker(t, conn, wrapper, WithServerId("worker2"))
// Create a few sessions on each, activate, and authorize a connection
var connIds []string
var worker2ConnIds []string
for i := 0; i < numConns; i++ {
serverId := worker1.PrivateId
if i%2 == 0 {
serverId = worker2.PrivateId
}
sess := TestDefaultSession(t, conn, wrapper, iamRepo, WithServerId(serverId), WithDbOpts(db.WithSkipVetForWrite(true)))
sess, _, err = repo.ActivateSession(ctx, sess.GetPublicId(), sess.Version, serverId, "worker", []byte("foo"))
require.NoError(err)
c, cs, _, err := repo.AuthorizeConnection(ctx, sess.GetPublicId(), serverId)
require.NoError(err)
require.Len(cs, 1)
require.Equal(StatusAuthorized, cs[0].Status)
connIds = append(connIds, c.GetPublicId())
if i%2 == 0 {
worker2ConnIds = append(worker2ConnIds, c.GetPublicId())
}
}
// Mark half of the connections connected and leave the others authorized.
// This is just to ensure we have a spread when we test it out.
for i, connId := range connIds {
if i%2 == 0 {
_, cs, err := repo.ConnectConnection(ctx, ConnectWith{
ConnectionId: connId,
ClientTcpAddress: "127.0.0.1",
ClientTcpPort: 22,
EndpointTcpAddress: "127.0.0.1",
EndpointTcpPort: 22,
})
require.NoError(err)
require.Len(cs, 2)
var foundAuthorized, foundConnected bool
for _, status := range cs {
if status.Status == StatusAuthorized {
foundAuthorized = true
}
if status.Status == StatusConnected {
foundConnected = true
}
}
require.True(foundAuthorized)
require.True(foundConnected)
}
}
// There is a 10 second delay to account for time for the connections to
// transition
time.Sleep(15 * time.Second)
// Now, advertise only some of the connection IDs for worker 2. After,
// all connection IDs for worker 1 should be showing as non-closed, and
// the ones for worker 2 not advertised should be closed.
shouldStayOpen := worker2ConnIds[0:2]
count, err := repo.CloseDeadConnectionsOnWorkerReport(ctx, worker2.GetPrivateId(), shouldStayOpen)
require.NoError(err)
assert.Equal(4, count)
// For the ones we didn't specify, we expect those to now be closed. We
// expect all others to be open.
shouldBeClosed := worker2ConnIds[2:]
conns, err := repo.ListConnectionsBySessionId(ctx, "*")
require.NoError(err)
for _, conn := range conns {
_, states, err := repo.LookupConnection(ctx, conn.PublicId)
require.NoError(err)
var foundClosed bool
for _, state := range states {
if state.Status == StatusClosed {
foundClosed = true
break
}
}
assert.True(foundClosed == strutil.StrListContains(shouldBeClosed, conn.PublicId))
}
// Now, advertise none of the connection IDs for worker 2. This is mainly to
// test that handling the case where we do not include IDs works properly as
// it changes the where clause.
count, err = repo.CloseDeadConnectionsOnWorkerReport(ctx, worker1.GetPrivateId(), nil)
require.NoError(err)
assert.Equal(6, count)
// We now expect all but those blessed few to be closed
conns, err = repo.ListConnectionsBySessionId(ctx, "*")
require.NoError(err)
for _, conn := range conns {
_, states, err := repo.LookupConnection(ctx, conn.PublicId)
require.NoError(err)
var foundClosed bool
for _, state := range states {
if state.Status == StatusClosed {
foundClosed = true
break
}
}
assert.True(foundClosed != strutil.StrListContains(shouldStayOpen, conn.PublicId))
}
}
+8 -4
View File
@@ -165,7 +165,7 @@ func (r *Repository) LookupSession(ctx context.Context, sessionId string, _ ...O
return &session, authzSummary, nil
}
// ListSessions will sessions. Supports the WithLimit, WithScopeId and WithSessionIds options.
// ListSessions will sessions. Supports the WithLimit, WithScopeId, WithSessionIds, and WithServerId options.
func (r *Repository) ListSessions(ctx context.Context, opt ...Option) ([]*Session, error) {
const op = "session.(Repository).ListSessions"
opts := getOpts(opt...)
@@ -199,6 +199,10 @@ func (r *Repository) ListSessions(ctx context.Context, opt ...Option) ([]*Sessio
}
where = append(where, fmt.Sprintf("s.public_id in (%s)", strings.Join(idsInClause, ",")))
}
if opts.withServerId != "" {
inClauseCnt += 1
where, args = append(where, fmt.Sprintf("server_id = $%d", inClauseCnt)), append(args, opts.withServerId)
}
var limit string
switch {
@@ -388,9 +392,9 @@ func (r *Repository) TerminateCompletedSessions(ctx context.Context) (int, error
// * the hasn't expired based on the session.Expiration
// * number of connections already created is less than session.ConnectionLimit
// If authorization is success, it creates/stores a new connection in the repo
// and returns it, along with it's states. If the authorization fails, it
// and returns it, along with its states. If the authorization fails, it
// an error with Code InvalidSessionState.
func (r *Repository) AuthorizeConnection(ctx context.Context, sessionId string) (*Connection, []*ConnectionState, *ConnectionAuthzSummary, error) {
func (r *Repository) AuthorizeConnection(ctx context.Context, sessionId, workerId string) (*Connection, []*ConnectionState, *ConnectionAuthzSummary, error) {
const op = "session.(Repository).AuthorizeConnection"
if sessionId == "" {
return nil, nil, nil, errors.Wrap(status.Error(codes.FailedPrecondition, "missing session id"), op, errors.WithCode(errors.InvalidParameter))
@@ -408,7 +412,7 @@ func (r *Repository) AuthorizeConnection(ctx context.Context, sessionId string)
db.StdRetryCnt,
db.ExpBackoff{},
func(reader db.Reader, w db.Writer) error {
rowsAffected, err := w.Exec(ctx, authorizeConnectionCte, []interface{}{sessionId, connectionId})
rowsAffected, err := w.Exec(ctx, authorizeConnectionCte, []interface{}{sessionId, connectionId, workerId})
if err != nil {
return errors.Wrap(err, op, errors.WithMsg(fmt.Sprintf("unable to authorize connection %s", sessionId)))
}
+37 -11
View File
@@ -2,10 +2,10 @@ package session
import (
"context"
"fmt"
"testing"
"time"
"github.com/golang/protobuf/ptypes"
"github.com/hashicorp/boundary/internal/authtoken"
authtokenStore "github.com/hashicorp/boundary/internal/authtoken/store"
"github.com/hashicorp/boundary/internal/db"
@@ -15,6 +15,7 @@ import (
"github.com/hashicorp/boundary/internal/target"
targetStore "github.com/hashicorp/boundary/internal/target/store"
"github.com/lib/pq"
"google.golang.org/protobuf/types/known/timestamppb"
"github.com/hashicorp/boundary/internal/errors"
"github.com/hashicorp/boundary/internal/iam"
@@ -129,10 +130,8 @@ func TestRepository_ListSession(t *testing.T) {
assert.Equal(wantCnt, len(got))
for i := 0; i < len(got)-1; i++ {
first, err := ptypes.Timestamp(got[i].CreateTime.Timestamp)
require.NoError(err)
second, err := ptypes.Timestamp(got[i+1].CreateTime.Timestamp)
require.NoError(err)
first := got[i].CreateTime.Timestamp.AsTime()
second := got[i+1].CreateTime.Timestamp.AsTime()
assert.True(first.Before(second))
}
})
@@ -189,6 +188,32 @@ func TestRepository_ListSession(t *testing.T) {
assert.Equal(StatusActive, got[0].States[0].Status)
assert.Equal(StatusPending, got[0].States[1].Status)
})
t.Run("withServerId", func(t *testing.T) {
assert, require := assert.New(t), require.New(t)
require.NoError(conn.Where("1=1").Delete(AllocSession()).Error)
for i := 0; i < 6; i++ {
if i%2 == 0 {
TestWorker(t, conn, wrapper, WithServerId(fmt.Sprintf("server-%d", i/2)))
}
_ = TestSession(t, conn, wrapper, composedOf,
WithServerId(fmt.Sprintf("server-%d", i/2)),
WithDbOpts(db.WithSkipVetForWrite(true)),
)
}
got, err := repo.ListSessions(context.Background())
require.NoError(err)
assert.Equal(6, len(got))
for i := 0; i < 3; i++ {
serverId := fmt.Sprintf("server-%d", i)
got, err = repo.ListSessions(context.Background(), WithServerId(serverId))
require.NoError(err)
assert.Equal(2, len(got))
for _, item := range got {
assert.Equal(serverId, item.ServerId)
}
}
})
}
func TestRepository_ListSessions_Multiple_Scopes(t *testing.T) {
@@ -488,6 +513,7 @@ func TestRepository_AuthorizeConnect(t *testing.T) {
repo, err := NewRepository(rw, rw, kms)
require.NoError(t, err)
var testServer string
setupFn := func(exp *timestamp.Timestamp) *Session {
composedOf := TestSessionParams(t, conn, wrapper, iamRepo)
if exp != nil {
@@ -495,6 +521,7 @@ func TestRepository_AuthorizeConnect(t *testing.T) {
}
s := TestSession(t, conn, wrapper, composedOf)
srv := TestWorker(t, conn, wrapper)
testServer = srv.PrivateId
tofu := TestTofu(t)
_, _, err := repo.ActivateSession(context.Background(), s.PublicId, s.Version, srv.PrivateId, srv.Type, tofu)
require.NoError(t, err)
@@ -537,7 +564,7 @@ func TestRepository_AuthorizeConnect(t *testing.T) {
},
{
name: "expired-session",
session: setupFn(&timestamp.Timestamp{Timestamp: ptypes.TimestampNow()}),
session: setupFn(&timestamp.Timestamp{Timestamp: timestamppb.Now()}),
wantErr: true,
},
}
@@ -545,7 +572,7 @@ func TestRepository_AuthorizeConnect(t *testing.T) {
t.Run(tt.name, func(t *testing.T) {
assert, require := assert.New(t), require.New(t)
c, cs, authzInfo, err := repo.AuthorizeConnection(context.Background(), tt.session.PublicId)
c, cs, authzInfo, err := repo.AuthorizeConnection(context.Background(), tt.session.PublicId, testServer)
if tt.wantErr {
require.Error(err)
// TODO (jimlambrt 9/2020): add in tests for errorsIs once we
@@ -770,8 +797,7 @@ func TestRepository_TerminateCompletedSessions(t *testing.T) {
setupFn := func(limit int32, expireIn time.Duration, leaveOpen bool) *Session {
require.NotEqualf(t, int32(0), limit, "setupFn: limit cannot be zero")
exp, err := ptypes.TimestampProto(time.Now().Add(expireIn))
require.NoError(t, err)
exp := timestamppb.New(time.Now().Add(expireIn))
composedOf := TestSessionParams(t, conn, wrapper, iamRepo)
composedOf.ConnectionLimit = limit
composedOf.ExpirationTime = &timestamp.Timestamp{Timestamp: exp}
@@ -968,7 +994,7 @@ func TestRepository_TerminateCompletedSessions(t *testing.T) {
}
assert.Equal(args.wantTermed[found.PublicId].String(), found.TerminationReason)
t.Logf("terminated %s has a connection limit of %d", found.PublicId, found.ConnectionLimit)
conn, err := repo.ListConnections(context.Background(), found.PublicId)
conn, err := repo.ListConnectionsBySessionId(context.Background(), found.PublicId)
require.NoError(err)
for _, sc := range conn {
c, cs, err := repo.LookupConnection(context.Background(), sc.PublicId)
@@ -981,7 +1007,7 @@ func TestRepository_TerminateCompletedSessions(t *testing.T) {
} else {
t.Logf("not terminated %s has a connection limit of %d", found.PublicId, found.ConnectionLimit)
assert.Equal("", found.TerminationReason)
conn, err := repo.ListConnections(context.Background(), found.PublicId)
conn, err := repo.ListConnectionsBySessionId(context.Background(), found.PublicId)
require.NoError(err)
for _, sc := range conn {
cs, err := fetchConnectionStates(context.Background(), rw, sc.PublicId)
+2 -4
View File
@@ -5,13 +5,13 @@ import (
"testing"
"time"
"github.com/golang/protobuf/ptypes"
"github.com/hashicorp/boundary/internal/db"
"github.com/hashicorp/boundary/internal/db/timestamp"
"github.com/hashicorp/boundary/internal/errors"
"github.com/hashicorp/boundary/internal/iam"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/types/known/timestamppb"
)
func TestSession_Create(t *testing.T) {
@@ -21,9 +21,7 @@ func TestSession_Create(t *testing.T) {
iamRepo := iam.TestRepo(t, conn, wrapper)
composedOf := TestSessionParams(t, conn, wrapper, iamRepo)
future, err := ptypes.TimestampProto(time.Now().Add(time.Hour))
require.NoError(t, err)
exp := &timestamp.Timestamp{Timestamp: future}
exp := &timestamp.Timestamp{Timestamp: timestamppb.New(time.Now().Add(time.Hour))}
type args struct {
composedOf ComposedOf
+20 -14
View File
@@ -6,7 +6,6 @@ import (
"testing"
"time"
"github.com/golang/protobuf/ptypes"
"github.com/hashicorp/boundary/internal/auth/password"
"github.com/hashicorp/boundary/internal/authtoken"
"github.com/hashicorp/boundary/internal/db"
@@ -68,13 +67,14 @@ func TestState(t *testing.T, conn *gorm.DB, sessionId string, state Status) *Sta
return s
}
// TestSession creates a test session composed of c in the repository.
// TestSession creates a test session composed of c in the repository. Options
// are passed into New, and withServerId is handled locally.
func TestSession(t *testing.T, conn *gorm.DB, wrapper wrapping.Wrapper, c ComposedOf, opt ...Option) *Session {
t.Helper()
opts := getOpts(opt...)
require := require.New(t)
if c.ExpirationTime == nil {
future, err := ptypes.TimestampProto(time.Now().Add(time.Hour))
require.NoError(err)
future := timestamppb.New(time.Now().Add(time.Hour))
c.ExpirationTime = &timestamp.Timestamp{Timestamp: future}
}
rw := db.New(conn)
@@ -86,14 +86,15 @@ func TestSession(t *testing.T, conn *gorm.DB, wrapper wrapping.Wrapper, c Compos
_, certBytes, err := newCert(wrapper, c.UserId, id, c.ExpirationTime.Timestamp.AsTime())
require.NoError(err)
s.Certificate = certBytes
s.ServerId = opts.withServerId
if len(s.TofuToken) != 0 {
err = s.encrypt(context.Background(), wrapper)
}
require.NoError(err)
err = rw.Create(context.Background(), s)
err = rw.Create(context.Background(), s, opts.withDbOpts...)
require.NoError(err)
ss, err := fetchStates(context.Background(), rw, s.PublicId, db.WithOrder("start_time desc"))
ss, err := fetchStates(context.Background(), rw, s.PublicId, append(opts.withDbOpts, db.WithOrder("start_time desc"))...)
require.NoError(err)
s.States = ss
@@ -103,12 +104,10 @@ func TestSession(t *testing.T, conn *gorm.DB, wrapper wrapping.Wrapper, c Compos
// TestDefaultSession creates a test session in the repository using defaults.
func TestDefaultSession(t *testing.T, conn *gorm.DB, wrapper wrapping.Wrapper, iamRepo *iam.Repository, opt ...Option) *Session {
t.Helper()
require := require.New(t)
composedOf := TestSessionParams(t, conn, wrapper, iamRepo)
future, err := ptypes.TimestampProto(time.Now().Add(time.Hour))
require.NoError(err)
future := timestamppb.New(time.Now().Add(time.Hour))
exp := &timestamp.Timestamp{Timestamp: future}
return TestSession(t, conn, wrapper, composedOf, WithExpirationTime(exp))
return TestSession(t, conn, wrapper, composedOf, append(opt, WithExpirationTime(exp))...)
}
// TestSessionParams returns an initialized ComposedOf which can be used to
@@ -169,17 +168,24 @@ func TestTofu(t *testing.T) []byte {
return []byte(tofu)
}
func TestWorker(t *testing.T, conn *gorm.DB, wrapper wrapping.Wrapper) *servers.Server {
// TestWorker inserts a worker into the db to satisfy foreign key constraints.
// Supports the WithServerId option.
func TestWorker(t *testing.T, conn *gorm.DB, wrapper wrapping.Wrapper, opt ...Option) *servers.Server {
t.Helper()
rw := db.New(conn)
kms := kms.TestKms(t, conn, wrapper)
serversRepo, err := servers.NewRepository(rw, rw, kms)
require.NoError(t, err)
id, err := uuid.GenerateUUID()
require.NoError(t, err)
opts := getOpts(opt...)
id := opts.withServerId
if id == "" {
id, err = uuid.GenerateUUID()
require.NoError(t, err)
id = "test-session-worker-" + id
}
worker := &servers.Server{
PrivateId: "test-session-worker-" + id,
PrivateId: id,
Type: servers.ServerTypeWorker.String(),
Description: "Test Session Worker",
Address: "127.0.0.1",