- Notifications
You must be signed in to change notification settings - Fork927
feat(agent): add script data dir for binaries and files#12205
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
Uh oh!
There was an error while loading.Please reload this page.
Merged
Changes fromall commits
Commits
Show all changes
11 commits Select commitHold shift + click to select a range
ebab733
feat(agent): add script data dir for binaries and files
mafredri61007e8
add agentscript test
mafredri7f438cc
handle window paths
mafredric30a1c3
fix path test
mafredrie4053c8
cleanup datadir
mafredri35968dd
always log
mafredri0f6f254
add log dir log for good measure
mafredrifddefbd
update golden files
mafredri58ee327
try to fix test on Win
mafredri7dbfc2b
Apply suggestions from code review
mafredri3234143
execute async to ensure log processing
mafredriFile filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Diff view
Diff view
There are no files selected for viewing
31 changes: 26 additions & 5 deletionsagent/agent.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -66,6 +66,7 @@ type Options struct { | ||
Filesystem afero.Fs | ||
LogDir string | ||
TempDir string | ||
ScriptDataDir string | ||
ExchangeToken func(ctx context.Context) (string, error) | ||
Client Client | ||
ReconnectingPTYTimeout time.Duration | ||
@@ -112,9 +113,19 @@ func New(options Options) Agent { | ||
if options.LogDir == "" { | ||
if options.TempDir != os.TempDir() { | ||
options.Logger.Debug(context.Background(), "log dir not set, using temp dir", slog.F("temp_dir", options.TempDir)) | ||
} else { | ||
options.Logger.Debug(context.Background(), "using log dir", slog.F("log_dir", options.LogDir)) | ||
} | ||
options.LogDir = options.TempDir | ||
} | ||
if options.ScriptDataDir == "" { | ||
if options.TempDir != os.TempDir() { | ||
options.Logger.Debug(context.Background(), "script data dir not set, using temp dir", slog.F("temp_dir", options.TempDir)) | ||
mafredri marked this conversation as resolved. Show resolvedHide resolvedUh oh!There was an error while loading.Please reload this page. | ||
} else { | ||
options.Logger.Debug(context.Background(), "using script data dir", slog.F("script_data_dir", options.ScriptDataDir)) | ||
} | ||
options.ScriptDataDir = options.TempDir | ||
} | ||
if options.ExchangeToken == nil { | ||
options.ExchangeToken = func(ctx context.Context) (string, error) { | ||
return "", nil | ||
@@ -152,6 +163,7 @@ func New(options Options) Agent { | ||
filesystem: options.Filesystem, | ||
logDir: options.LogDir, | ||
tempDir: options.TempDir, | ||
scriptDataDir: options.ScriptDataDir, | ||
lifecycleUpdate: make(chan struct{}, 1), | ||
lifecycleReported: make(chan codersdk.WorkspaceAgentLifecycle, 1), | ||
lifecycleStates: []agentsdk.PostLifecycleRequest{{State: codersdk.WorkspaceAgentLifecycleCreated}}, | ||
@@ -183,6 +195,7 @@ type agent struct { | ||
filesystem afero.Fs | ||
logDir string | ||
tempDir string | ||
scriptDataDir string | ||
// ignorePorts tells the api handler which ports to ignore when | ||
// listing all listening ports. This is helpful to hide ports that | ||
// are used by the agent, that the user does not care about. | ||
@@ -249,11 +262,12 @@ func (a *agent) init(ctx context.Context) { | ||
} | ||
a.sshServer = sshSrv | ||
a.scriptRunner = agentscripts.New(agentscripts.Options{ | ||
LogDir: a.logDir, | ||
DataDirBase: a.scriptDataDir, | ||
Logger: a.logger, | ||
SSHServer: sshSrv, | ||
Filesystem: a.filesystem, | ||
PatchLogs: a.client.PatchLogs, | ||
}) | ||
// Register runner metrics. If the prom registry is nil, the metrics | ||
// will not report anywhere. | ||
@@ -954,6 +968,13 @@ func (a *agent) updateCommandEnv(current []string) (updated []string, err error) | ||
envs[k] = v | ||
} | ||
// Prepend the agent script bin directory to the PATH | ||
// (this is where Coder modules place their binaries). | ||
if _, ok := envs["PATH"]; !ok { | ||
envs["PATH"] = os.Getenv("PATH") | ||
} | ||
envs["PATH"] = fmt.Sprintf("%s%c%s", a.scriptRunner.ScriptBinDir(), filepath.ListSeparator, envs["PATH"]) | ||
for k, v := range envs { | ||
updated = append(updated, fmt.Sprintf("%s=%s", k, v)) | ||
} | ||
8 changes: 8 additions & 0 deletionsagent/agent_test.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
49 changes: 43 additions & 6 deletionsagent/agentscripts/agentscripts.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -43,11 +43,12 @@ var ( | ||
// Options are a set of options for the runner. | ||
type Options struct { | ||
DataDirBase string | ||
LogDir string | ||
Logger slog.Logger | ||
SSHServer *agentssh.Server | ||
Filesystem afero.Fs | ||
PatchLogs func(ctx context.Context, req agentsdk.PatchLogs) error | ||
} | ||
// New creates a runner for the provided scripts. | ||
@@ -59,6 +60,7 @@ func New(opts Options) *Runner { | ||
cronCtxCancel: cronCtxCancel, | ||
cron: cron.New(cron.WithParser(parser)), | ||
closed: make(chan struct{}), | ||
dataDir: filepath.Join(opts.DataDirBase, "coder-script-data"), | ||
scriptsExecuted: prometheus.NewCounterVec(prometheus.CounterOpts{ | ||
Namespace: "agent", | ||
Subsystem: "scripts", | ||
@@ -78,13 +80,25 @@ type Runner struct { | ||
cron *cron.Cron | ||
initialized atomic.Bool | ||
scripts []codersdk.WorkspaceAgentScript | ||
dataDir string | ||
// scriptsExecuted includes all scripts executed by the workspace agent. Agents | ||
// execute startup scripts, and scripts on a cron schedule. Both will increment | ||
// this counter. | ||
scriptsExecuted *prometheus.CounterVec | ||
} | ||
// DataDir returns the directory where scripts data is stored. | ||
func (r *Runner) DataDir() string { | ||
return r.dataDir | ||
} | ||
// ScriptBinDir returns the directory where scripts can store executable | ||
// binaries. | ||
func (r *Runner) ScriptBinDir() string { | ||
return filepath.Join(r.dataDir, "bin") | ||
} | ||
func (r *Runner) RegisterMetrics(reg prometheus.Registerer) { | ||
if reg == nil { | ||
// If no registry, do nothing. | ||
@@ -104,6 +118,11 @@ func (r *Runner) Init(scripts []codersdk.WorkspaceAgentScript) error { | ||
r.scripts = scripts | ||
r.Logger.Info(r.cronCtx, "initializing agent scripts", slog.F("script_count", len(scripts)), slog.F("log_dir", r.LogDir)) | ||
err := r.Filesystem.MkdirAll(r.ScriptBinDir(), 0o700) | ||
if err != nil { | ||
return xerrors.Errorf("create script bin dir: %w", err) | ||
} | ||
for _, script := range scripts { | ||
if script.Cron == "" { | ||
continue | ||
@@ -208,7 +227,18 @@ func (r *Runner) run(ctx context.Context, script codersdk.WorkspaceAgentScript) | ||
if !filepath.IsAbs(logPath) { | ||
logPath = filepath.Join(r.LogDir, logPath) | ||
} | ||
scriptDataDir := filepath.Join(r.DataDir(), script.LogSourceID.String()) | ||
err := r.Filesystem.MkdirAll(scriptDataDir, 0o700) | ||
if err != nil { | ||
return xerrors.Errorf("%s script: create script temp dir: %w", scriptDataDir, err) | ||
} | ||
logger := r.Logger.With( | ||
slog.F("log_source_id", script.LogSourceID), | ||
slog.F("log_path", logPath), | ||
slog.F("script_data_dir", scriptDataDir), | ||
) | ||
logger.Info(ctx, "running agent script", slog.F("script", script.Script)) | ||
fileWriter, err := r.Filesystem.OpenFile(logPath, os.O_CREATE|os.O_RDWR, 0o600) | ||
@@ -238,6 +268,13 @@ func (r *Runner) run(ctx context.Context, script codersdk.WorkspaceAgentScript) | ||
cmd.WaitDelay = 10 * time.Second | ||
cmd.Cancel = cmdCancel(cmd) | ||
// Expose env vars that can be used in the script for storing data | ||
// and binaries. In the future, we may want to expose more env vars | ||
// for the script to use, like CODER_SCRIPT_DATA_DIR for persistent | ||
// storage. | ||
cmd.Env = append(cmd.Env, "CODER_SCRIPT_DATA_DIR="+scriptDataDir) | ||
cmd.Env = append(cmd.Env, "CODER_SCRIPT_BIN_DIR="+r.ScriptBinDir()) | ||
johnstcn marked this conversation as resolved. Show resolvedHide resolvedUh oh!There was an error while loading.Please reload this page. | ||
send, flushAndClose := agentsdk.LogsSender(script.LogSourceID, r.PatchLogs, logger) | ||
// If ctx is canceled here (or in a writer below), we may be | ||
// discarding logs, but that's okay because we're shutting down | ||
82 changes: 73 additions & 9 deletionsagent/agentscripts/agentscripts_test.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
9 changes: 9 additions & 0 deletionscli/agent.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
3 changes: 3 additions & 0 deletionscli/testdata/coder_agent_--help.golden
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.