Skip to content

Commit

Permalink
fix(leaderredis): data race
Browse files Browse the repository at this point in the history
  • Loading branch information
GGXXLL committed Mar 16, 2022
1 parent 99ccd7a commit 65cba73
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 2 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/go.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
3 changes: 2 additions & 1 deletion leader/example_cronjob_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)
Expand Down
6 changes: 6 additions & 0 deletions leader/leaderredis/redis.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"context"
"fmt"
"os"
"sync"
"time"

"github.com/DoNewsCode/core/contract"
Expand All @@ -19,6 +20,7 @@ type RedisDriver struct {
expiration time.Duration
pollInterval time.Duration
cancel func()
lock sync.Mutex
sha string
}

Expand Down Expand Up @@ -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 {
Expand All @@ -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
Expand Down

0 comments on commit 65cba73

Please sign in to comment.