Thanks to visit codestin.com
Credit goes to github.com

Skip to content

fix: fix data race in agentscripts.Runner #17630

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 1 commit into from
May 1, 2025
Merged
Changes from all commits
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
23 changes: 19 additions & 4 deletions agent/agentscripts/agentscripts.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import (
"os/user"
"path/filepath"
"sync"
"sync/atomic"
"time"

"github.com/google/uuid"
Expand Down Expand Up @@ -104,7 +103,6 @@ type Runner struct {
closed chan struct{}
closeMutex sync.Mutex
cron *cron.Cron
initialized atomic.Bool
scripts []runnerScript
dataDir string
scriptCompleted ScriptCompletedFunc
Expand All @@ -113,6 +111,9 @@ type Runner struct {
// execute startup scripts, and scripts on a cron schedule. Both will increment
// this counter.
scriptsExecuted *prometheus.CounterVec

initMutex sync.Mutex
initialized bool
}

// DataDir returns the directory where scripts data is stored.
Expand Down Expand Up @@ -154,10 +155,12 @@ func WithPostStartScripts(scripts ...codersdk.WorkspaceAgentScript) InitOption {
// It also schedules any scripts that have a schedule.
// This function must be called before Execute.
func (r *Runner) Init(scripts []codersdk.WorkspaceAgentScript, scriptCompleted ScriptCompletedFunc, opts ...InitOption) error {
if r.initialized.Load() {
r.initMutex.Lock()
defer r.initMutex.Unlock()
if r.initialized {
return xerrors.New("init: already initialized")
}
r.initialized.Store(true)
r.initialized = true
r.scripts = toRunnerScript(scripts...)
r.scriptCompleted = scriptCompleted
for _, opt := range opts {
Expand Down Expand Up @@ -227,6 +230,18 @@ const (

// Execute runs a set of scripts according to a filter.
func (r *Runner) Execute(ctx context.Context, option ExecuteOption) error {
initErr := func() error {
r.initMutex.Lock()
defer r.initMutex.Unlock()
if !r.initialized {
return xerrors.New("execute: not initialized")
}
return nil
}()
if initErr != nil {
return initErr
}

var eg errgroup.Group
for _, script := range r.scripts {
runScript := (option == ExecuteStartScripts && script.RunOnStart) ||
Expand Down
Loading