K3s Flock Integration Test (#3887)

* Upgraded flock with shared and integration test.

Signed-off-by: dereknola <derek.nola@suse.com>

Co-authored-by: Brian Downs <brian.downs@gmail.com>
pull/3929/head
Derek Nola 3 years ago committed by GitHub
parent e322924781
commit ed5991f13b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -0,0 +1,34 @@
package flock_test
import (
"testing"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/rancher/k3s/pkg/flock"
)
const lockfile = "/tmp/testlock.test"
var lock int
var _ = Describe("file locks", func() {
When("a new exclusive lock is created", func() {
It("starts up with no problems", func() {
var err error
lock, err = flock.Acquire(lockfile)
Expect(err).ToNot(HaveOccurred())
})
It("has a write lock on the file", func() {
Expect(flock.CheckLock(lockfile)).To(BeTrue())
})
It("release the lock correctly", func() {
Expect(flock.Release(lock)).To(Succeed())
Expect(flock.CheckLock(lockfile)).To(BeFalse())
})
})
})
func TestFlock(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Flock Suite")
}

@ -18,7 +18,12 @@ limitations under the License.
package flock
import "golang.org/x/sys/unix"
import (
"os/exec"
"strings"
"golang.org/x/sys/unix"
)
// Acquire creates an exclusive lock on a file for the duration of the process, or until Release(d).
// This method is reentrant.
@ -30,7 +35,28 @@ func Acquire(path string) (int, error) {
return lock, unix.Flock(lock, unix.LOCK_EX)
}
// AcquireShared creates a shared lock on a file for the duration of the process, or until Release(d).
// This method is reentrant.
func AcquireShared(path string) (int, error) {
lock, err := unix.Open(path, unix.O_CREAT|unix.O_RDWR, 0600)
if err != nil {
return -1, err
}
return lock, unix.Flock(lock, unix.LOCK_SH)
}
// Release removes an existing lock held by this process.
func Release(lock int) error {
return unix.Flock(lock, unix.LOCK_UN)
}
// CheckLock checks whether any process is using the lock
func CheckLock(path string) bool {
lockByte, _ := exec.Command("lsof", "-w", "-F", "ln", path).Output()
locks := string(lockByte)
if locks == "" {
return false
}
readWriteLock := strings.Split(locks, "\n")[2]
return readWriteLock == "lR" || readWriteLock == "lW"
}

Loading…
Cancel
Save