From 65cba73971c8950a35c6e8029ffecad1b3bf6d65 Mon Sep 17 00:00:00 2001 From: Trock Date: Wed, 16 Mar 2022 14:24:50 +0800 Subject: [PATCH] fix(leaderredis): data race --- .github/workflows/go.yml | 2 +- leader/example_cronjob_test.go | 3 ++- leader/leaderredis/redis.go | 6 ++++++ 3 files changed, 9 insertions(+), 2 deletions(-) diff --git a/.github/workflows/go.yml b/.github/workflows/go.yml index ad463b16..73a48158 100644 --- a/.github/workflows/go.yml +++ b/.github/workflows/go.yml @@ -9,7 +9,7 @@ jobs: build: strategy: matrix: - go-version: [1.18.0-beta2] + go-version: [1.18.x] runs-on: ubuntu-latest services: redis: diff --git a/leader/example_cronjob_test.go b/leader/example_cronjob_test.go index 34658a0b..197f9c33 100644 --- a/leader/example_cronjob_test.go +++ b/leader/example_cronjob_test.go @@ -3,11 +3,12 @@ package leader_test import ( "context" "fmt" + "os" + "github.com/DoNewsCode/core" "github.com/DoNewsCode/core/di" "github.com/DoNewsCode/core/leader" "github.com/DoNewsCode/core/otetcd" - "os" "github.com/robfig/cron/v3" ) diff --git a/leader/leaderredis/redis.go b/leader/leaderredis/redis.go index f3c54ce4..67551ca2 100644 --- a/leader/leaderredis/redis.go +++ b/leader/leaderredis/redis.go @@ -5,6 +5,7 @@ import ( "context" "fmt" "os" + "sync" "time" "github.com/DoNewsCode/core/contract" @@ -19,6 +20,7 @@ type RedisDriver struct { expiration time.Duration pollInterval time.Duration cancel func() + lock sync.Mutex sha string } @@ -73,7 +75,9 @@ func (r *RedisDriver) Campaign(ctx context.Context, toLeader func(bool)) error { // The node is elected as leader toLeader(true) + r.lock.Lock() ctx, r.cancel = context.WithCancel(ctx) + r.lock.Unlock() for { select { @@ -90,9 +94,11 @@ func (r *RedisDriver) Campaign(ctx context.Context, toLeader func(bool)) error { // Resign gives up the leadership using redis. If the current node is not a leader, this is an no op. func (r *RedisDriver) Resign(ctx context.Context) error { + r.lock.Lock() if r.cancel != nil { r.cancel() } + r.lock.Unlock() hostname, _ := os.Hostname() if r.sha == "" { var err error