Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix/datarace when concurrent save the same file #836

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ GOARCH := $(if $(GOARCH),$(GOARCH),amd64)
GOENV := GO111MODULE=on CGO_ENABLED=0 GOOS=$(GOOS) GOARCH=$(GOARCH)
GO := $(GOENV) go
GOBUILD := $(GO) build $(BUILD_FLAG)
GOTEST := GO111MODULE=on CGO_ENABLED=1 $(GO) test -p 3
GOTEST := GO111MODULE=on CGO_ENABLED=1 go test -p 3
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's better to revert this change.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I want to run tests with -race, but which need CGO was enabled. Seems there is no effective to set GO111MODULE=on CGO_ENABLED=1 before $(GO), such as

$ make race
TIUP_HOME=/root/.go/src/github.com/pingcap/tiup/tests/tiup GO111MODULE=on CGO_ENABLED=1 GO111MODULE=on CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go test -p 3 -race ./...  || { $(tools/bin/failpoint-ctl disable); exit 1; }
go test: -race requires cgo; enable cgo by setting CGO_ENABLED=1
make: *** [Makefile:97: race] Error 1

SHELL := /usr/bin/env bash

COMMIT := $(shell git describe --no-match --always --dirty)
Expand Down Expand Up @@ -93,6 +93,10 @@ unit-test:
mkdir -p cover
TIUP_HOME=$(shell pwd)/tests/tiup $(GOTEST) ./... -covermode=count -coverprofile cover/cov.unit-test.out

race: failpoint-enable
TIUP_HOME=$(shell pwd)/tests/tiup $(GOTEST) -race ./... || { $(FAILPOINT_DISABLE); exit 1; }
@$(FAILPOINT_DISABLE)

failpoint-enable: tools/bin/failpoint-ctl
@$(FAILPOINT_ENABLE)

Expand Down
2 changes: 1 addition & 1 deletion pkg/cluster/task/builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -384,7 +384,7 @@ func (b *Builder) DeploySpark(inst spec.Instance, sparkVersion, srcPath, deployD
)
}

// TLSCert geenrates certificate for instance and transfer it to the server
// TLSCert generates certificate for instance and transfers it to the server
func (b *Builder) TLSCert(inst spec.Instance, ca *crypto.CertificateAuthority, paths meta.DirPaths) *Builder {
b.tasks = append(b.tasks, &TLSCert{
ca: ca,
Expand Down
15 changes: 15 additions & 0 deletions pkg/file/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,17 @@ import (
"os"
"path/filepath"
"strings"
"sync"
"time"

"github.com/pingcap/errors"
)

var (
fileLocks = make(map[string]*sync.Mutex)
filesLock = sync.Mutex{}
)

// SaveFileWithBackup will backup the file before save it.
// e.g., backup meta.yaml as meta-2006-01-02T15:04:05Z07:00.yaml
// backup the files in the same dir of path if backupDir is empty.
Expand All @@ -25,6 +31,15 @@ func SaveFileWithBackup(path string, data []byte, backupDir string) error {
return errors.Errorf("%s is directory", path)
}

filesLock.Lock()
defer filesLock.Unlock()
if _, ok := fileLocks[path]; !ok {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The fileLocks itself is not thread safe, so I think the datarace is still exists. eg.

# assume the fileLocks is empty as initial state.
# thread 1 start
if _, ok := fileLocks["/path/a"]; !ok { # the ok is false because fileLocks is empty
# thread 1 hang after check !ok but before fileLocks[path] = &sync.Mutex{}

# thread 2 start
if _, ok := fileLocks["/path/a"]; !ok { # the ok is false because fileLocks is empty and thread 1 doesn't assign it yet
    fileLocks["/path/a"] = &sync.Mutex{} # assign a new mutex and success
}

fileLocks["/path/a"].Lock()
# thread 2 enter critical area

# thread 1 start
fileLocks["/path/a"] = &sync.Mutex{} # assign a new mutex and success
fileLocks["/path/a"].Lock() # this will success because thread 1 reset fileLocks["/path/a"]
# thread 1 enter critical area

In this case, both threads enter into the same critical area.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for your suggestion, sorry to forget that the map needs to be locked in concurrent access.

fileLocks[path] = &sync.Mutex{}
}

fileLocks[path].Lock()
defer fileLocks[path].Unlock()

// backup file
if !os.IsNotExist(err) {
base := filepath.Base(path)
Expand Down
43 changes: 43 additions & 0 deletions pkg/file/file_test.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
package file

import (
"bytes"
"io/ioutil"
"math/rand"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
"testing"
"time"

"github.com/pingcap/check"
)
Expand Down Expand Up @@ -78,3 +82,42 @@ func (s *fileSuite) TestSaveFileWithBackup(c *check.C) {
c.Assert(err, check.IsNil)
c.Assert(string(data), check.Equals, "9")
}

func (s *fileSuite) TestConcurrentSaveFileWithBackup(c *check.C) {
dir := c.MkDir()
name := "meta.yaml"
data := []byte("concurrent-save-file-with-backup")

rand.Seed(time.Now().UnixNano())
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
defer wg.Done()
time.Sleep(time.Duration(rand.Intn(100)+4) * time.Millisecond)
err := SaveFileWithBackup(filepath.Join(dir, name), data, "")
c.Assert(err, check.IsNil)
}()
}

wg.Wait()

// Verify the saved files.
var paths []string
err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
// simply filter the not relate files.
if strings.Contains(path, "meta") {
paths = append(paths, path)
}
return nil
})

c.Assert(err, check.IsNil)
c.Assert(len(paths), check.Equals, 10)
for _, path := range paths {
body, err := ioutil.ReadFile(path)
c.Assert(err, check.IsNil)
c.Assert(len(body), check.Equals, len(data))
c.Assert(bytes.Equal(body, data), check.IsTrue)
}
}