chore: fix data race in goroutine runner

Discovered with `go test -race`:

```
WARNING: DATA RACE
Read at 0x00c0000cf2f8 by goroutine 25:
  github.com/talos-systems/talos/internal/app/machined/pkg/system/runner/goroutine.(*goroutineRunner).Stop()
      /home/smira/Documents/autonomy/talos/internal/app/machined/pkg/system/runner/goroutine/goroutine.go:111 +0x3e
  github.com/talos-systems/talos/internal/app/machined/pkg/system/runner/goroutine_test.(*GoroutineSuite).TestStop()
      /home/smira/Documents/autonomy/talos/internal/app/machined/pkg/system/runner/goroutine/goroutine_test.go:115 +0x345
  runtime.call32()
      /usr/local/go/src/runtime/asm_amd64.s:519 +0x3a
  reflect.Value.Call()
      /usr/local/go/src/reflect/value.go:308 +0xc0
  github.com/stretchr/testify/suite.Run.func2()
      /home/smira/Documents/go/pkg/mod/github.com/stretchr/testify@v1.3.1-0.20190311161405-34c6fa2dc709/suite/suite.go:133 +0x2ec
  testing.tRunner()
      /usr/local/go/src/testing/testing.go:865 +0x163

Previous write at 0x00c0000cf2f8 by goroutine 26:
  github.com/talos-systems/talos/internal/app/machined/pkg/system/runner/goroutine.(*goroutineRunner).Run()
      /home/smira/Documents/autonomy/talos/internal/app/machined/pkg/system/runner/goroutine/goroutine.go:65 +0xcb
  github.com/talos-systems/talos/internal/app/machined/pkg/system/runner/goroutine_test.(*GoroutineSuite).TestStop.func3()
      /home/smira/Documents/autonomy/talos/internal/app/machined/pkg/system/runner/goroutine/goroutine_test.go:104 +0x4a
```

Signed-off-by: Andrey Smirnov <smirnov.andrey@gmail.com>
This commit is contained in:
Andrey Smirnov 2019-08-02 22:25:00 +03:00 committed by Andrew Rynhard
parent 37c1703f06
commit 8362f58e7a

View File

@ -48,6 +48,8 @@ func NewRunner(data *userdata.UserData, id string, main FuncMain, setters ...run
opts: runner.DefaultOptions(), opts: runner.DefaultOptions(),
} }
r.ctx, r.ctxCancel = context.WithCancel(context.Background())
for _, setter := range setters { for _, setter := range setters {
setter(r.opts) setter(r.opts)
} }
@ -62,8 +64,6 @@ func (r *goroutineRunner) Open(ctx context.Context) error {
// Run implements the Runner interface. // Run implements the Runner interface.
func (r *goroutineRunner) Run(eventSink events.Recorder) error { func (r *goroutineRunner) Run(eventSink events.Recorder) error {
r.ctx, r.ctxCancel = context.WithCancel(context.Background())
r.wg.Add(1) r.wg.Add(1)
defer r.wg.Done() defer r.wg.Done()
@ -112,6 +112,8 @@ func (r *goroutineRunner) Stop() error {
r.wg.Wait() r.wg.Wait()
r.ctx, r.ctxCancel = context.WithCancel(context.Background())
return nil return nil
} }