Skip to content

Instantly share code, notes, and snippets.

@mpl
Created January 21, 2016 16:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mpl/39c7d4893291366719fd to your computer and use it in GitHub Desktop.
Save mpl/39c7d4893291366719fd to your computer and use it in GitHub Desktop.
/*
Copyright 2013 The Go Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package lock
import (
"bufio"
"bytes"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"testing"
"time"
)
func TestLock(t *testing.T) {
testLock(t, false)
}
func TestLockPortable(t *testing.T) {
return
testLock(t, true)
}
func TestLockInChild(t *testing.T) {
f := os.Getenv("TEST_LOCK_FILE")
if f == "" {
// not child
return
}
lock := Lock
if v, _ := strconv.ParseBool(os.Getenv("TEST_LOCK_PORTABLE")); v {
lock = lockPortable
}
lk, err := lock(f)
if err != nil {
if v, _ := strconv.ParseBool(os.Getenv("TEST_LOCK_WAITRETRY")); v {
for scan := bufio.NewScanner(os.Stdin); scan.Scan(); {
lk, err = lock(f)
if err != nil {
log.Fatalf("2nd lock attempt failed: %v", err)
}
break
}
} else {
log.Fatalf("Lock failed: %v", err)
}
}
if v, _ := strconv.ParseBool(os.Getenv("TEST_LOCK_CRASH")); v {
// Simulate a crash, or at least not unlocking the
// lock. We still exit 0 just to simplify the parent
// process exec code.
os.Exit(0)
}
lk.Close()
}
func testLock(t *testing.T, portable bool) {
lock := Lock
if portable {
lock = lockPortable
}
td, err := ioutil.TempDir("", "")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(td)
path := filepath.Join(td, "foo.lock")
retryC := make(chan struct{})
childLock := func(crash, retry bool) error {
cmd := exec.Command(os.Args[0], "-test.run=LockInChild$")
cmd.Env = []string{"TEST_LOCK_FILE=" + path}
if portable {
cmd.Env = append(cmd.Env, "TEST_LOCK_PORTABLE=1")
}
if crash {
cmd.Env = append(cmd.Env, "TEST_LOCK_CRASH=1")
}
if retry {
cmd.Env = append(cmd.Env, "TEST_LOCK_WAITRETRY=1")
var stdin, stderr, stdout bytes.Buffer
cmd.Stdin = &stdin
cmd.Stdout = &stdout
cmd.Stderr = &stderr
if err := cmd.Start(); err != nil {
return fmt.Errorf("Child Process lock of %s failed to start: %v %s %s", path, err, stdout.String(), stderr.String())
}
<-retryC
if _, err := io.Copy(&stdin, strings.NewReader("retry")); err != nil {
return fmt.Errorf("failed to make child Process lock of %s retry a lock: %v %s %s", path, err, stdout.String(), stderr.String())
}
c := make(chan error)
go func() {
c <- cmd.Wait()
}()
select {
case <-time.After(5*time.Second):
return fmt.Errorf("timed out waiting for child Process retry lock of %s: %v %s %s", path, err, stdout.String(), stderr.String())
case err := <-c:
t.Logf("Child output: %q (err %v)", stdout.String(), err)
if err != nil {
return fmt.Errorf("Child Process retry lock of %s failed: %v %s %s", path, err, stdout.String(), stderr.String())
}
}
return nil
}
out, err := cmd.CombinedOutput()
t.Logf("Child output: %q (err %v)", out, err)
if err != nil {
return fmt.Errorf("Child Process lock of %s failed: %v %s", path, err, out)
}
return nil
}
t.Logf("Locking in crashing child...")
if err := childLock(true, false); err != nil {
t.Fatalf("first lock in child process: %v", err)
}
t.Logf("Locking+unlocking in child...")
if err := childLock(false, false); err != nil {
t.Fatalf("lock in child process after crashing child: %v", err)
}
t.Logf("Locking in parent...")
lk1, err := lock(path)
if err != nil {
t.Fatal(err)
}
t.Logf("Again in parent...")
_, err = lock(path)
if err == nil {
t.Fatal("expected second lock to fail")
}
go func() {
t.Logf("Locking in child...")
if childLock(false, true) != nil {
t.Fatalf("lock in child process should have failed, retried, and then succeeded: %v", err)
}
}()
t.Logf("Unlocking lock in parent")
if err := lk1.Close(); err != nil {
t.Fatal(err)
}
retryC <- struct{}{}
lk3, err := lock(path)
if err != nil {
t.Fatal(err)
}
lk3.Close()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment