@@ -10,7 +10,6 @@ import (
10
10
"os/user"
11
11
"path/filepath"
12
12
"sync"
13
- "sync/atomic"
14
13
"time"
15
14
16
15
"github.com/google/uuid"
@@ -104,7 +103,6 @@ type Runner struct {
104
103
closed chan struct {}
105
104
closeMutex sync.Mutex
106
105
cron * cron.Cron
107
- initialized atomic.Bool
108
106
scripts []runnerScript
109
107
dataDir string
110
108
scriptCompleted ScriptCompletedFunc
@@ -113,6 +111,9 @@ type Runner struct {
113
111
// execute startup scripts, and scripts on a cron schedule. Both will increment
114
112
// this counter.
115
113
scriptsExecuted * prometheus.CounterVec
114
+
115
+ initMutex sync.Mutex
116
+ initialized bool
116
117
}
117
118
118
119
// DataDir returns the directory where scripts data is stored.
@@ -154,10 +155,12 @@ func WithPostStartScripts(scripts ...codersdk.WorkspaceAgentScript) InitOption {
154
155
// It also schedules any scripts that have a schedule.
155
156
// This function must be called before Execute.
156
157
func (r * Runner ) Init (scripts []codersdk.WorkspaceAgentScript , scriptCompleted ScriptCompletedFunc , opts ... InitOption ) error {
157
- if r .initialized .Load () {
158
+ r .initMutex .Lock ()
159
+ defer r .initMutex .Unlock ()
160
+ if r .initialized {
158
161
return xerrors .New ("init: already initialized" )
159
162
}
160
- r .initialized . Store ( true )
163
+ r .initialized = true
161
164
r .scripts = toRunnerScript (scripts ... )
162
165
r .scriptCompleted = scriptCompleted
163
166
for _ , opt := range opts {
@@ -227,6 +230,18 @@ const (
227
230
228
231
// Execute runs a set of scripts according to a filter.
229
232
func (r * Runner ) Execute (ctx context.Context , option ExecuteOption ) error {
233
+ initErr := func () error {
234
+ r .initMutex .Lock ()
235
+ defer r .initMutex .Unlock ()
236
+ if ! r .initialized {
237
+ return xerrors .New ("execute: not initialized" )
238
+ }
239
+ return nil
240
+ }()
241
+ if initErr != nil {
242
+ return initErr
243
+ }
244
+
230
245
var eg errgroup.Group
231
246
for _ , script := range r .scripts {
232
247
runScript := (option == ExecuteStartScripts && script .RunOnStart ) ||
0 commit comments