Skip to content

feat: add auto-locking/deleting workspace based on template config #8240

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
Jul 3, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
add some tests/fix some minor bugs
  • Loading branch information
sreya committed Jun 28, 2023
commit 0ce8aa3748290bd822c51468e5826772788d798b
2 changes: 1 addition & 1 deletion coderd/autobuild/lifecycle_executor.go
Original file line number Diff line number Diff line change
Expand Up @@ -245,7 +245,7 @@ func (e *Executor) runOnce(t time.Time) Stats {
// as well as the reason for why it is transitioning. It is possible
// for this function to return a nil error as well as an empty transition.
// In such cases it means no provisioning should occur but the workspace
// may be "transitioning" to a new state (such as a inactive, stopped
// may be "transitioning" to a new state (such as an inactive, stopped
// workspace transitioning to the locked state).
func getNextTransition(
ws database.Workspace,
Expand Down
1 change: 1 addition & 0 deletions coderd/database/dbfake/dbfake.go
Original file line number Diff line number Diff line change
Expand Up @@ -5229,6 +5229,7 @@ func (q *fakeQuerier) UpdateWorkspaceLockedAt(_ context.Context, arg database.Up
continue
}
workspace.LockedAt = arg.LockedAt
workspace.LastUsedAt = database.Now()
q.workspaces[index] = workspace
return nil
}
Expand Down
3 changes: 2 additions & 1 deletion coderd/database/queries.sql.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion coderd/database/queries/workspaces.sql
Original file line number Diff line number Diff line change
Expand Up @@ -474,6 +474,7 @@ WHERE
UPDATE
workspaces
SET
locked_at = $2
locked_at = $2,
last_used_at = now() at time zone 'utc'
WHERE
id = $1;
4 changes: 3 additions & 1 deletion coderd/workspaces_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2399,11 +2399,12 @@ func TestWorkspaceLock(t *testing.T) {
})
require.NoError(t, err)

workspace, err = client.Workspace(ctx, workspace.ID)
workspace = coderdtest.MustWorkspace(t, client, workspace.ID)
require.NoError(t, err, "fetch provisioned workspace")
require.NotNil(t, workspace.LockedAt)
require.WithinRange(t, *workspace.LockedAt, time.Now().Add(-time.Second*10), time.Now())

lastUsedAt := workspace.LastUsedAt
err = client.UpdateWorkspaceLock(ctx, workspace.ID, codersdk.UpdateWorkspaceLock{
Lock: false,
})
Expand All @@ -2412,6 +2413,7 @@ func TestWorkspaceLock(t *testing.T) {
workspace, err = client.Workspace(ctx, workspace.ID)
require.NoError(t, err, "fetch provisioned workspace")
require.Nil(t, workspace.LockedAt)
require.True(t, workspace.LastUsedAt.After(lastUsedAt))
})

t.Run("CannotStart", func(t *testing.T) {
Expand Down
93 changes: 93 additions & 0 deletions enterprise/coderd/workspaces_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
"github.com/coder/coder/coderd/autobuild"
"github.com/coder/coder/coderd/coderdtest"
"github.com/coder/coder/coderd/database"
"github.com/coder/coder/coderd/schedule"
"github.com/coder/coder/coderd/util/ptr"
"github.com/coder/coder/codersdk"
"github.com/coder/coder/enterprise/coderd"
Expand Down Expand Up @@ -235,6 +236,7 @@ func TestWorkspaceAutobuild(t *testing.T) {
t.Parallel()

var (
ctx = testutil.Context(t, testutil.WaitMedium)
ticker = make(chan time.Time)
statCh = make(chan autobuild.Stats)
inactiveTTL = time.Millisecond
Expand Down Expand Up @@ -277,6 +279,15 @@ func TestWorkspaceAutobuild(t *testing.T) {
ws = coderdtest.MustWorkspace(t, client, ws.ID)
// The workspace should be locked.
require.NotNil(t, ws.LockedAt)
lastUsedAt := ws.LastUsedAt

err := client.UpdateWorkspaceLock(ctx, ws.ID, codersdk.UpdateWorkspaceLock{Lock: false})
require.NoError(t, err)

// Assert that we updated our last_used_at so that we don't immediately
// retrigger another lock action.
ws = coderdtest.MustWorkspace(t, client, ws.ID)
require.True(t, ws.LastUsedAt.After(lastUsedAt))
})

t.Run("InactiveTTLTooEarly", func(t *testing.T) {
Expand Down Expand Up @@ -496,6 +507,88 @@ func TestWorkspaceAutobuild(t *testing.T) {
require.True(t, ok)
require.Equal(t, http.StatusGone, cerr.StatusCode())
})

t.Run("LockedNoAutostart", func(t *testing.T) {
t.Parallel()

var (
ctx = testutil.Context(t, testutil.WaitMedium)
tickCh = make(chan time.Time)
statsCh = make(chan autobuild.Stats)
client = coderdenttest.New(t, &coderdenttest.Options{
Options: &coderdtest.Options{
AutobuildTicker: tickCh,
IncludeProvisionerDaemon: true,
AutobuildStats: statsCh,
TemplateScheduleStore: &coderd.EnterpriseTemplateScheduleStore{},
},
})
inactiveTTL = time.Millisecond
)

user := coderdtest.CreateFirstUser(t, client)
_ = coderdenttest.AddFullLicense(t, client)

version := coderdtest.CreateTemplateVersion(t, client, user.OrganizationID, &echo.Responses{
Parse: echo.ParseComplete,
ProvisionPlan: echo.ProvisionComplete,
ProvisionApply: echo.ProvisionComplete,
})
coderdtest.AwaitTemplateVersionJob(t, client, version.ID)

template := coderdtest.CreateTemplate(t, client, user.OrganizationID, version.ID)

sched, err := schedule.Weekly("CRON_TZ=UTC 0 * * * *")
require.NoError(t, err)

ws := coderdtest.CreateWorkspace(t, client, user.OrganizationID, template.ID, func(cwr *codersdk.CreateWorkspaceRequest) {
cwr.AutostartSchedule = ptr.Ref(sched.String())
})
coderdtest.AwaitWorkspaceBuildJob(t, client, ws.LatestBuild.ID)
coderdtest.MustTransitionWorkspace(t, client, ws.ID, database.WorkspaceTransitionStart, database.WorkspaceTransitionStop)

// Assert that autostart works when the workspace isn't locked..
tickCh <- sched.Next(ws.LatestBuild.CreatedAt)
// Then: the workspace should eventually be started
stats := <-statsCh
require.NoError(t, stats.Error)
require.Len(t, stats.Transitions, 1)
require.Contains(t, stats.Transitions, ws.ID)
require.Equal(t, database.WorkspaceTransitionStart, stats.Transitions[ws.ID])
ws = coderdtest.MustWorkspace(t, client, ws.ID)
coderdtest.AwaitWorkspaceBuildJob(t, client, ws.LatestBuild.ID)

// Now that we've validated that the workspace is eligible for autostart
// lets cause it to become locked.
_, err = client.UpdateTemplateMeta(ctx, template.ID, codersdk.UpdateTemplateMeta{
InactivityTTLMillis: inactiveTTL.Milliseconds(),
})
require.NoError(t, err)
// Wait for the workspace to breach the inactivity threshold.
require.Eventually(t,
func() bool {
return database.Now().Sub(ws.LastUsedAt) > inactiveTTL
},
testutil.IntervalMedium, testutil.IntervalFast)

tickCh <- time.Now()
// Then: the workspace should eventually be started
stats = <-statsCh
require.NoError(t, stats.Error)
require.Len(t, stats.Transitions, 1)
require.Contains(t, stats.Transitions, ws.ID)
require.Equal(t, database.WorkspaceTransitionStop, stats.Transitions[ws.ID])
ws = coderdtest.MustWorkspace(t, client, ws.ID)
coderdtest.AwaitWorkspaceBuildJob(t, client, ws.LatestBuild.ID)
// The workspace should be locked now.
require.NotNil(t, ws.LockedAt)

// Assert that autostart is no longer triggered since workspace is locked.
tickCh <- sched.Next(ws.LatestBuild.CreatedAt)
// Then: the workspace should eventually be started
stats = <-statsCh
require.Len(t, stats.Transitions, 0)
})
}

func TestWorkspacesFiltering(t *testing.T) {
Expand Down