Move ctx and cancel func setup into the Replicator.Start (#6115)

Previously a sequence of events like:

Start
Stop
Start
Stop

would segfault on the second stop because the original ctx and cancel func were only initialized during the constructor and not during Start.
This commit is contained in:
Matt Keeler 2019-07-12 10:10:48 -04:00 committed by GitHub
parent 16220815b3
commit 6cc936d64b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 30 additions and 3 deletions

View file

@ -61,7 +61,6 @@ func NewReplicator(config *ReplicatorConfig) (*Replicator, error) {
if config.Logger == nil { if config.Logger == nil {
config.Logger = log.New(os.Stderr, "", log.LstdFlags) config.Logger = log.New(os.Stderr, "", log.LstdFlags)
} }
ctx, cancel := context.WithCancel(context.Background())
limiter := rate.NewLimiter(rate.Limit(config.Rate), config.Burst) limiter := rate.NewLimiter(rate.Limit(config.Rate), config.Burst)
maxWait := config.MaxRetryWait maxWait := config.MaxRetryWait
@ -77,8 +76,6 @@ func NewReplicator(config *ReplicatorConfig) (*Replicator, error) {
return &Replicator{ return &Replicator{
name: config.Name, name: config.Name,
running: false, running: false,
cancel: cancel,
ctx: ctx,
limiter: limiter, limiter: limiter,
waiter: waiter, waiter: waiter,
replicate: config.ReplicateFn, replicate: config.ReplicateFn,
@ -94,6 +91,8 @@ func (r *Replicator) Start() {
return return
} }
r.ctx, r.cancel = context.WithCancel(context.Background())
go r.run() go r.run()
r.running = true r.running = true

View file

@ -0,0 +1,28 @@
package consul
import (
"context"
"testing"
"github.com/stretchr/testify/require"
)
func TestReplicationRestart(t *testing.T) {
config := ReplicatorConfig{
Name: "mock",
ReplicateFn: func(ctx context.Context, lastRemoteIndex uint64) (uint64, bool, error) {
return 1, false, nil
},
Rate: 1,
Burst: 1,
}
repl, err := NewReplicator(&config)
require.NoError(t, err)
repl.Start()
repl.Stop()
repl.Start()
// Previously this would have segfaulted
repl.Stop()
}