Skip to content
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

task runner to avoid running task if terminal #5890

Merged
merged 2 commits into from
Jul 2, 2019
Merged
Show file tree
Hide file tree
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
84 changes: 84 additions & 0 deletions client/allocrunner/alloc_runner_unix_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,3 +131,87 @@ func TestAllocRunner_Restore_RunningTerminal(t *testing.T) {
require.Equal(t, events[2].Type, structs.TaskStarted)
require.Equal(t, events[3].Type, structs.TaskTerminated)
}

// TestAllocRunner_Restore_CompletedBatch asserts that restoring a completed
// batch alloc doesn't run it again
func TestAllocRunner_Restore_CompletedBatch(t *testing.T) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Name/comment mismatch

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Test looks good, but just to verify:

  • Does it fail without your fixes?
  • Does it pass with -race?

Copy link
Contributor Author

@notnoop notnoop Jul 2, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, it passes with -race and was failing before - here is a sample build failure [1] when adding test alone. The failure snippet is:

goroutine 87 [chan receive, 14 minutes]:
github.com/hashicorp/nomad/client/allocrunner.destroy(0xc000342780)
	/home/travis/gopath/src/github.com/hashicorp/nomad/client/allocrunner/alloc_runner_test.go:27 +0x54
runtime.Goexit()
	/home/travis/.gimme/versions/go1.12.6.linux.amd64/src/runtime/panic.go:406 +0xed
testing.(*common).FailNow(0xc000449b00)
	/home/travis/.gimme/versions/go1.12.6.linux.amd64/src/testing/testing.go:609 +0x39
github.com/hashicorp/nomad/vendor/github.com/stretchr/testify/require.Fail(0x18348e0, 0xc000449b00, 0x15fc0e0, 0x1a, 0x0, 0x0, 0x0)
	/home/travis/gopath/src/github.com/hashicorp/nomad/vendor/github.com/stretchr/testify/require/require.go:285 +0xf0
github.com/hashicorp/nomad/client/allocrunner.TestAllocRunner_Restore_CompletedBatch(0xc000449b00)
	/home/travis/gopath/src/github.com/hashicorp/nomad/client/allocrunner/alloc_runner_unix_test.go:204 +0xb22
testing.tRunner(0xc000449b00, 0x1639ae0)
	/home/travis/.gimme/versions/go1.12.6.linux.amd64/src/testing/testing.go:865 +0xc0
created by testing.(*T).Run
	/home/travis/.gimme/versions/go1.12.6.linux.amd64/src/testing/testing.go:916 +0x35a

As seen in stack trace, we fail in line 204 [1] because AR.wait() times out, then times out again in destroy defer call.

I'll follow up in another PR to change the destroy defer call so that it errors rather than blocks indefinitely on failures to make tracking these errors better.

[1] https://travis-ci.org/hashicorp/nomad/jobs/553113545
[2] https://github.com/hashicorp/nomad/compare/b-dont-start-completed-allocs-2-test-only?expand=1
[3] https://github.com/hashicorp/nomad/compare/b-dont-start-completed-allocs-2-test-only?expand=1#diff-41decefd2f35059b5c0b95166e275653R204

t.Parallel()

// 1. Run task and wait for it to complete
// 2. Start new alloc runner
// 3. Assert task didn't run again

alloc := mock.Alloc()
alloc.Job.Type = structs.JobTypeBatch
task := alloc.Job.TaskGroups[0].Tasks[0]
task.Driver = "mock_driver"
task.Config = map[string]interface{}{
"run_for": "2ms",
}

conf, cleanup := testAllocRunnerConfig(t, alloc.Copy())
defer cleanup()

// Maintain state for subsequent run
conf.StateDB = state.NewMemDB(conf.Logger)

// Start and wait for task to be running
ar, err := NewAllocRunner(conf)
require.NoError(t, err)
go ar.Run()
defer destroy(ar)

testutil.WaitForResult(func() (bool, error) {
s := ar.AllocState()
if s.ClientStatus != structs.AllocClientStatusComplete {
return false, fmt.Errorf("expected complete, got %s", s.ClientStatus)
}
return true, nil
}, func(err error) {
require.NoError(t, err)
})

// once job finishes, it shouldn't run again
require.False(t, ar.shouldRun())
initialRunEvents := ar.AllocState().TaskStates[task.Name].Events
require.Len(t, initialRunEvents, 4)

ls, ts, err := conf.StateDB.GetTaskRunnerState(alloc.ID, task.Name)
require.NoError(t, err)
require.NotNil(t, ls)
require.Equal(t, structs.TaskStateDead, ts.State)

// Start a new alloc runner and assert it gets stopped
conf2, cleanup2 := testAllocRunnerConfig(t, alloc)
defer cleanup2()

// Use original statedb to maintain hook state
conf2.StateDB = conf.StateDB

// Restore, start, and wait for task to be killed
ar2, err := NewAllocRunner(conf2)
require.NoError(t, err)

require.NoError(t, ar2.Restore())

go ar2.Run()
defer destroy(ar2)

// AR waitCh must be closed even when task doesn't run again
select {
case <-ar2.WaitCh():
case <-time.After(10 * time.Second):
require.Fail(t, "alloc.waitCh wasn't closed")
}

// TR waitCh must be closed too!
select {
case <-ar2.tasks[task.Name].WaitCh():
case <-time.After(10 * time.Second):
require.Fail(t, "tr.waitCh wasn't closed")
}

// Assert that events are unmodified, which they would if task re-run
events := ar2.AllocState().TaskStates[task.Name].Events
require.Equal(t, initialRunEvents, events)
}
20 changes: 19 additions & 1 deletion client/allocrunner/taskrunner/task_runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -394,6 +394,24 @@ func (tr *TaskRunner) Run() {
defer close(tr.waitCh)
var result *drivers.ExitResult

tr.stateLock.RLock()
dead := tr.state.State == structs.TaskStateDead
tr.stateLock.RUnlock()

// if restoring a dead task, ensure that task is cleared and all post hooks
// are called without additional state updates
if dead {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

here I only check if the task itself is dead - I suspect we should be checking if the restore alloc had a terminated alloc state. I suspect that an alloc with tasks with mixed status causes some some complications?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually, this is the right behavior. An alloc is considering running if one task completes, and all allocs will be killed if leader task dies or a task failed enough times. Until that happens, we should treat other tasks as running.

// do cleanup functions without emitting any additional events/work
// to handle cases where we restored a dead task where client terminated
// after task finished before completing post-run actions.
tr.clearDriverHandle()
tr.stateUpdater.TaskStateUpdated()
if err := tr.stop(); err != nil {
tr.logger.Error("stop failed on terminal task", "error", err)
}
return
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we may also want to call tr.TaskStateUpdated() since task states are persisted before the AR is notified. Therefore I think the following could happen:

  1. 2 tasks in an alloc start: a leader service, and a sidecar
  2. Leader task exits, persists TaskStateDead
  3. agent crashes before TaskStateUpdated is called
  4. agent restarts, returns here due to TaskStateDead

At this point I do not think anything will have told the sidecar service to exit despite its leader dying. If you call TaskStateUpdated here, then all of the leader died detection logic in AR will be run: https://github.com/hashicorp/nomad/blob/master/client/allocrunner/alloc_runner.go#L415-L438

This could be done in a followup PR as well since I think your changes improve the situation.

}

// Updates are handled asynchronously with the other hooks but each
// triggered update - whether due to alloc updates or a new vault token
// - should be handled serially.
Expand Down Expand Up @@ -899,7 +917,7 @@ func (tr *TaskRunner) Restore() error {
}

alloc := tr.Alloc()
if alloc.TerminalStatus() || alloc.Job.Type == structs.JobTypeSystem {
if tr.state.State == structs.TaskStateDead || alloc.TerminalStatus() || alloc.Job.Type == structs.JobTypeSystem {
return nil
}

Expand Down