Skip to content

Commit b2261dc

Browse files
committed
avoid data race when writing task states
In #31 we fixed a panic when adding a task event, but the fix was incomplete and just panicked again later under heavy concurrent use. This PR fixes the follow-up panic but also fixes a data race that popped up when testing the fix with a build that used `-race`.
1 parent 867e796 commit b2261dc

File tree

1 file changed

+5
-7
lines changed

1 file changed

+5
-7
lines changed

allocrunnersim/allocrunnersim.go

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import (
1515
cinterfaces "github.com/hashicorp/nomad/client/interfaces"
1616
"github.com/hashicorp/nomad/client/pluginmanager/drivermanager"
1717
cstructs "github.com/hashicorp/nomad/client/structs"
18+
"github.com/hashicorp/nomad/helper"
1819
"github.com/hashicorp/nomad/helper/pointer"
1920
"github.com/hashicorp/nomad/nomad/structs"
2021
"github.com/hashicorp/nomad/plugins/device"
@@ -160,7 +161,6 @@ func (ar *simulatedAllocRunner) Run() {
160161
}
161162
event.PopulateEventDisplayMessage()
162163
taskStates[task.Name].Events = append(taskStates[task.Name].Events, event)
163-
164164
taskStates[task.Name].StartedAt = time.Now()
165165
taskStates[task.Name].State = structs.TaskStateRunning
166166
}
@@ -213,6 +213,7 @@ func (ar *simulatedAllocRunner) clientAlloc(taskStates map[string]*structs.TaskS
213213
defer ar.allocStateLock.Unlock()
214214

215215
// store task states for AllocState to expose
216+
taskStates = helper.DeepCopyMap(taskStates)
216217
ar.allocState.TaskStates = taskStates
217218

218219
a := &structs.Allocation{
@@ -345,7 +346,7 @@ func (ar *simulatedAllocRunner) stopAll() {
345346
// Ensure we have a current copy of the task states, so that we append and
346347
// create a correct and full list.
347348
ar.allocStateLock.RLock()
348-
taskStates := ar.allocState.TaskStates
349+
taskStates := helper.DeepCopyMap(ar.allocState.TaskStates)
349350
ar.allocStateLock.RUnlock()
350351

351352
// Perform the task kill, which essentially is the shutdown notification.
@@ -375,11 +376,8 @@ func (ar *simulatedAllocRunner) stopAll() {
375376
}
376377
event.PopulateEventDisplayMessage()
377378
taskStates[task.Name].Events = append(taskStates[task.Name].Events, event)
378-
379-
ar.allocStateLock.Lock()
380-
ar.allocState.TaskStates[task.Name].FinishedAt = time.Now()
381-
ar.allocState.TaskStates[task.Name].State = structs.TaskStateDead
382-
ar.allocStateLock.Unlock()
379+
taskStates[task.Name].FinishedAt = time.Now()
380+
taskStates[task.Name].State = structs.TaskStateDead
383381
}
384382
ar.updateAllocAndSendUpdate(taskStates)
385383

0 commit comments

Comments
 (0)