Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

feat: add lifecycle.Executor to manage autostart and autostop#1183

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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
johnstcn merged 28 commits intomainfromcj/gh-271/sched-autostart
May 11, 2022
Merged
Show file tree
Hide file tree
Changes fromall commits
Commits
Show all changes
28 commits
Select commitHold shift + click to select a range
a145d6d
feat: add lifecycle.Executor to autostart workspaces.
johnstcnApr 19, 2022
8f401ca
refactor: do not expose Store in coderdtest.Options
johnstcnApr 26, 2022
6d8f5fe
fixup! refactor: do not expose Store in coderdtest.Options
johnstcnApr 26, 2022
cfd0d1e
stop accessing db directly, only query workspaces with autostart enabled
johnstcnApr 26, 2022
ce63810
refactor unit tests, add tests for autostop
johnstcnApr 26, 2022
579f362
make the new tests pass with some refactoring
johnstcnApr 30, 2022
6e88f67
gitignore *.swp
johnstcnApr 30, 2022
2b1a383
remove unused methods
johnstcnApr 30, 2022
f31588e
fixup! remove unused methods
johnstcnApr 30, 2022
80e0581
fix: range over channel, add continue to default switch case
johnstcnMay 9, 2022
d176478
add test for deleted workspace
johnstcnMay 9, 2022
bd97c1a
workspaces.sql: remove unused methods
johnstcnMay 10, 2022
0931d25
unexport test helper methods
johnstcnMay 10, 2022
faebe2e
chore: rename package autostart/lifecycle to lifecycle/executor
johnstcnMay 10, 2022
abc0854
add test to ensure workspaces are not autostarted before time
johnstcnMay 10, 2022
e53946a
wire up executor to coderd
johnstcnMay 10, 2022
364a27c
fix: executor: skip workspaces whose last build was not successful
johnstcnMay 10, 2022
e96414f
address PR comments
johnstcnMay 11, 2022
b5bf50e
add goleak TestMain
johnstcnMay 11, 2022
d37cc2b
fmt
johnstcnMay 11, 2022
d11f5d7
mustTransitionWorkspace should return the updated workspace
johnstcnMay 11, 2022
f6388b4
remove usage of require.Eventually/Never which is flaky on Windows
johnstcnMay 11, 2022
fd0f8a3
make lifecycle executor spawn a new goroutine automatically
johnstcnMay 11, 2022
7b6f2e1
rename unit tests
johnstcnMay 11, 2022
a7143bd
s/doBuild/build
johnstcnMay 11, 2022
7d9b696
rename parent package lifecycle to autobuild
johnstcnMay 11, 2022
5cba737
add unit test for behaviour with an updated template
johnstcnMay 11, 2022
7627372
add ticket to reference TODO
johnstcnMay 11, 2022
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
1 change: 1 addition & 0 deletions.gitignore
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -37,3 +37,4 @@ site/out/
.terraform/

.vscode/*.log
**/*.swp
2 changes: 1 addition & 1 deletioncli/autostart.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,7 +7,7 @@ import (

"github.com/spf13/cobra"

"github.com/coder/coder/coderd/autostart/schedule"
"github.com/coder/coder/coderd/autobuild/schedule"
"github.com/coder/coder/codersdk"
)

Expand Down
2 changes: 1 addition & 1 deletioncli/autostop.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,7 +7,7 @@ import (

"github.com/spf13/cobra"

"github.com/coder/coder/coderd/autostart/schedule"
"github.com/coder/coder/coderd/autobuild/schedule"
"github.com/coder/coder/codersdk"
)

Expand Down
6 changes: 6 additions & 0 deletionscli/server.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -39,6 +39,7 @@ import (
"github.com/coder/coder/cli/cliui"
"github.com/coder/coder/cli/config"
"github.com/coder/coder/coderd"
"github.com/coder/coder/coderd/autobuild/executor"
"github.com/coder/coder/coderd/database"
"github.com/coder/coder/coderd/database/databasefake"
"github.com/coder/coder/coderd/devtunnel"
Expand DownExpand Up@@ -343,6 +344,11 @@ func server() *cobra.Command {
return xerrors.Errorf("notify systemd: %w", err)
}

lifecyclePoller := time.NewTicker(time.Minute)
defer lifecyclePoller.Stop()
lifecycleExecutor := executor.New(cmd.Context(), options.Database, logger, lifecyclePoller.C)
lifecycleExecutor.Run()

// Because the graceful shutdown includes cleaning up workspaces in dev mode, we're
// going to make it harder to accidentally skip the graceful shutdown by hitting ctrl+c
// two or more times. So the stopChan is unlimited in size and we don't call
Expand Down
222 changes: 222 additions & 0 deletionscoderd/autobuild/executor/lifecycle_executor.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,222 @@
package executor

import (
"context"
"encoding/json"
"time"

"cdr.dev/slog"

"github.com/coder/coder/coderd/autobuild/schedule"
"github.com/coder/coder/coderd/database"

"github.com/google/uuid"
"github.com/moby/moby/pkg/namesgenerator"
"golang.org/x/xerrors"
)

// Executor automatically starts or stops workspaces.
type Executor struct {
ctx context.Context
db database.Store
log slog.Logger
tick <-chan time.Time
}

// New returns a new autobuild executor.
func New(ctx context.Context, db database.Store, log slog.Logger, tick <-chan time.Time) *Executor {
le := &Executor{
ctx: ctx,
db: db,
tick: tick,
log: log,
}
return le
}

// Run will cause executor to start or stop workspaces on every
// tick from its channel. It will stop when its context is Done, or when
// its channel is closed.
func (e *Executor) Run() {
go func() {
for t := range e.tick {
if err := e.runOnce(t); err != nil {
e.log.Error(e.ctx, "error running once", slog.Error(err))
}
}
}()
}

func (e *Executor) runOnce(t time.Time) error {
currentTick := t.Truncate(time.Minute)
return e.db.InTx(func(db database.Store) error {
eligibleWorkspaces, err := db.GetWorkspacesAutostartAutostop(e.ctx)
if err != nil {
return xerrors.Errorf("get eligible workspaces for autostart or autostop: %w", err)
}

for _, ws := range eligibleWorkspaces {
// Determine the workspace state based on its latest build.
priorHistory, err := db.GetWorkspaceBuildByWorkspaceIDWithoutAfter(e.ctx, ws.ID)
if err != nil {
e.log.Warn(e.ctx, "get latest workspace build",
slog.F("workspace_id", ws.ID),
slog.Error(err),
)
continue
}

priorJob, err := db.GetProvisionerJobByID(e.ctx, priorHistory.JobID)
if err != nil {
e.log.Warn(e.ctx, "get last provisioner job for workspace %q: %w",
slog.F("workspace_id", ws.ID),
slog.Error(err),
)
continue
}

if !priorJob.CompletedAt.Valid || priorJob.Error.String != "" {
e.log.Warn(e.ctx, "last workspace build did not complete successfully, skipping",
slog.F("workspace_id", ws.ID),
slog.F("error", priorJob.Error.String),
)
continue
}

var validTransition database.WorkspaceTransition
var sched *schedule.Schedule
switch priorHistory.Transition {
case database.WorkspaceTransitionStart:
validTransition = database.WorkspaceTransitionStop
sched, err = schedule.Weekly(ws.AutostopSchedule.String)
if err != nil {
e.log.Warn(e.ctx, "workspace has invalid autostop schedule, skipping",
slog.F("workspace_id", ws.ID),
slog.F("autostart_schedule", ws.AutostopSchedule.String),
)
continue
}
case database.WorkspaceTransitionStop:
validTransition = database.WorkspaceTransitionStart
sched, err = schedule.Weekly(ws.AutostartSchedule.String)
if err != nil {
e.log.Warn(e.ctx, "workspace has invalid autostart schedule, skipping",
slog.F("workspace_id", ws.ID),
slog.F("autostart_schedule", ws.AutostartSchedule.String),
)
continue
}
default:
e.log.Debug(e.ctx, "last transition not valid for autostart or autostop",
slog.F("workspace_id", ws.ID),
slog.F("latest_build_transition", priorHistory.Transition),
)
continue
}

// Round time down to the nearest minute, as this is the finest granularity cron supports.
// Truncate is probably not necessary here, but doing it anyway to be sure.
nextTransitionAt := sched.Next(priorHistory.CreatedAt).Truncate(time.Minute)
if currentTick.Before(nextTransitionAt) {
e.log.Debug(e.ctx, "skipping workspace: too early",
slog.F("workspace_id", ws.ID),
slog.F("next_transition_at", nextTransitionAt),
slog.F("transition", validTransition),
slog.F("current_tick", currentTick),
)
continue
}

e.log.Info(e.ctx, "scheduling workspace transition",
slog.F("workspace_id", ws.ID),
slog.F("transition", validTransition),
)

if err := build(e.ctx, db, ws, validTransition, priorHistory, priorJob); err != nil {
e.log.Error(e.ctx, "unable to transition workspace",
slog.F("workspace_id", ws.ID),
slog.F("transition", validTransition),
slog.Error(err),
)
}
}
return nil
})
}

// TODO(cian): this function duplicates most of api.postWorkspaceBuilds. Refactor.
// See: https://github.com/coder/coder/issues/1401
func build(ctx context.Context, store database.Store, workspace database.Workspace, trans database.WorkspaceTransition, priorHistory database.WorkspaceBuild, priorJob database.ProvisionerJob) error {
template, err := store.GetTemplateByID(ctx, workspace.TemplateID)
if err != nil {
return xerrors.Errorf("get workspace template: %w", err)
}

priorHistoryID := uuid.NullUUID{
UUID: priorHistory.ID,
Valid: true,
}

var newWorkspaceBuild database.WorkspaceBuild
// This must happen in a transaction to ensure history can be inserted, and
// the prior history can update it's "after" column to point at the new.
workspaceBuildID := uuid.New()
input, err := json.Marshal(struct {
WorkspaceBuildID string `json:"workspace_build_id"`
}{
WorkspaceBuildID: workspaceBuildID.String(),
})
if err != nil {
return xerrors.Errorf("marshal provision job: %w", err)
}
provisionerJobID := uuid.New()
now := database.Now()
newProvisionerJob, err := store.InsertProvisionerJob(ctx, database.InsertProvisionerJobParams{
ID: provisionerJobID,
CreatedAt: now,
UpdatedAt: now,
InitiatorID: workspace.OwnerID,
OrganizationID: template.OrganizationID,
Provisioner: template.Provisioner,
Type: database.ProvisionerJobTypeWorkspaceBuild,
StorageMethod: priorJob.StorageMethod,
StorageSource: priorJob.StorageSource,
Input: input,
})
if err != nil {
return xerrors.Errorf("insert provisioner job: %w", err)
}
newWorkspaceBuild, err = store.InsertWorkspaceBuild(ctx, database.InsertWorkspaceBuildParams{
ID: workspaceBuildID,
CreatedAt: now,
UpdatedAt: now,
WorkspaceID: workspace.ID,
TemplateVersionID: priorHistory.TemplateVersionID,
BeforeID: priorHistoryID,
Name: namesgenerator.GetRandomName(1),
ProvisionerState: priorHistory.ProvisionerState,
InitiatorID: workspace.OwnerID,
Transition: trans,
JobID: newProvisionerJob.ID,
})
if err != nil {
return xerrors.Errorf("insert workspace build: %w", err)
}

if priorHistoryID.Valid {
// Update the prior history entries "after" column.
err = store.UpdateWorkspaceBuildByID(ctx, database.UpdateWorkspaceBuildByIDParams{
ID: priorHistory.ID,
ProvisionerState: priorHistory.ProvisionerState,
UpdatedAt: now,
AfterID: uuid.NullUUID{
UUID: newWorkspaceBuild.ID,
Valid: true,
},
})
if err != nil {
return xerrors.Errorf("update prior workspace build: %w", err)
}
}
return nil
}
Loading

[8]ページ先頭

©2009-2025 Movatter.jp