Init initializes the runner with the provided scripts. It also schedules any scripts that have a schedule. This function must be called before Execute.
(scripts []codersdk.WorkspaceAgentScript, scriptCompleted ScriptCompletedFunc, opts ...InitOption)
| 126 | // It also schedules any scripts that have a schedule. |
| 127 | // This function must be called before Execute. |
| 128 | func (r *Runner) Init(scripts []codersdk.WorkspaceAgentScript, scriptCompleted ScriptCompletedFunc, opts ...InitOption) error { |
| 129 | r.initMutex.Lock() |
| 130 | defer r.initMutex.Unlock() |
| 131 | if r.initialized { |
| 132 | return xerrors.New("init: already initialized") |
| 133 | } |
| 134 | r.initialized = true |
| 135 | r.scripts = scripts |
| 136 | r.scriptCompleted = scriptCompleted |
| 137 | for _, opt := range opts { |
| 138 | opt(r) |
| 139 | } |
| 140 | r.Logger.Info(r.cronCtx, "initializing agent scripts", slog.F("script_count", len(scripts)), slog.F("log_dir", r.LogDir)) |
| 141 | |
| 142 | err := r.Filesystem.MkdirAll(r.ScriptBinDir(), 0o700) |
| 143 | if err != nil { |
| 144 | return xerrors.Errorf("create script bin dir: %w", err) |
| 145 | } |
| 146 | |
| 147 | for _, script := range r.scripts { |
| 148 | if script.Cron == "" { |
| 149 | continue |
| 150 | } |
| 151 | _, err := r.cron.AddFunc(script.Cron, func() { |
| 152 | err := r.trackRun(r.cronCtx, script, ExecuteCronScripts) |
| 153 | if err != nil { |
| 154 | r.Logger.Warn(context.Background(), "run agent script on schedule", slog.Error(err)) |
| 155 | } |
| 156 | }) |
| 157 | if err != nil { |
| 158 | return xerrors.Errorf("add schedule: %w", err) |
| 159 | } |
| 160 | } |
| 161 | return nil |
| 162 | } |
| 163 | |
| 164 | // StartCron starts the cron scheduler. |
| 165 | // This is done async to allow for the caller to execute scripts prior. |