Return error if adding when runner hasn't been started

Before this used to block
This commit is contained in:
IamTheFij 2024-10-23 13:34:16 -07:00
parent 24d091b787
commit 86a55d16ea
2 changed files with 15 additions and 3 deletions

View File

@ -48,6 +48,7 @@ func NewShellRunnerWithShell(shell string) *ShellRunner {
callbacks: make(chan func(), MAX_RESULTS), callbacks: make(chan func(), MAX_RESULTS),
shell: shell, shell: shell,
activeCmds: make(map[*exec.Cmd]struct{}), activeCmds: make(map[*exec.Cmd]struct{}),
isStopped: true,
} }
} }
@ -75,16 +76,18 @@ func (sr *ShellRunner) Start() {
} }
} }
}() }()
sr.isStopped = false
} }
// AddCommand adds a shell command to be executed with an optional callback. // AddCommand adds a shell command to be executed with an optional callback.
// No commands can be added if the runner has been stopped. // No commands can be added if the runner has been stopped or not yet started.
func (sr *ShellRunner) AddCommand(command string, callback func(*CommandResult)) error { func (sr *ShellRunner) AddCommand(command string, callback func(*CommandResult)) error {
sr.mu.Lock() sr.mu.Lock()
defer sr.mu.Unlock() defer sr.mu.Unlock()
if sr.isStopped { if sr.isStopped {
return errors.New("runner has been stopped, cannot add new commands") return errors.New("runner is stopped, cannot add new commands")
} }
sr.cmdQueue <- func() *CommandResult { sr.cmdQueue <- func() *CommandResult {

View File

@ -78,7 +78,7 @@ func TestShellRunnerCallback(t *testing.T) {
// Make sure stop and kill both exit gracefully after the runner is stopped // Make sure stop and kill both exit gracefully after the runner is stopped
runner.Stop() runner.Stop()
runner.Stop() runner.Kill()
} }
func TestShellRunnerKillWithTimeout(t *testing.T) { func TestShellRunnerKillWithTimeout(t *testing.T) {
@ -122,3 +122,12 @@ func TestStopPreventsNewCommands(t *testing.T) {
t.Fatal("expected error when adding command after stop, but got none") t.Fatal("expected error when adding command after stop, but got none")
} }
} }
func TestAddingPriorToStart(t *testing.T) {
runner := tortoise.NewShellRunner()
err := runner.AddCommand("echo should not run", nil)
if err == nil {
t.Fatal("Should have failed to add prior to starting runner")
}
}