| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
package lock |
| 5 |
|
| 6 |
import ( |
| 7 |
"context" |
| 8 |
"errors" |
| 9 |
"fmt" |
| 10 |
"os" |
| 11 |
"path/filepath" |
| 12 |
"runtime" |
| 13 |
"syscall" |
| 14 |
"time" |
| 15 |
|
| 16 |
"github.com/AzureAD/microsoft-authentication-extensions-for-go/cache/internal/flock" |
| 17 |
) |
| 18 |
|
| 19 |
|
| 20 |
var timeout = 5 * time.Second |
| 21 |
|
| 22 |
|
| 23 |
type flocker interface { |
| 24 |
Fh() *os.File |
| 25 |
Path() string |
| 26 |
TryLockContext(context.Context, time.Duration) (bool, error) |
| 27 |
Unlock() error |
| 28 |
} |
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
type Lock struct { |
| 35 |
f flocker |
| 36 |
retryDelay time.Duration |
| 37 |
} |
| 38 |
|
| 39 |
|
| 40 |
func New(p string, retryDelay time.Duration) (*Lock, error) { |
| 41 |
|
| 42 |
err := os.MkdirAll(filepath.Dir(p), os.ModePerm) |
| 43 |
if err != nil { |
| 44 |
return nil, err |
| 45 |
} |
| 46 |
return &Lock{f: flock.New(p), retryDelay: retryDelay}, nil |
| 47 |
} |
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
|
| 52 |
func (l *Lock) Lock(ctx context.Context) error { |
| 53 |
if _, hasDeadline := ctx.Deadline(); !hasDeadline { |
| 54 |
var cancel context.CancelFunc |
| 55 |
ctx, cancel = context.WithTimeout(ctx, timeout) |
| 56 |
defer cancel() |
| 57 |
} |
| 58 |
for { |
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
locked, err := l.f.TryLockContext(ctx, l.retryDelay) |
| 64 |
if err != nil { |
| 65 |
if !(errors.Is(err, os.ErrPermission) || isWindowsSharingViolation(err)) { |
| 66 |
return err |
| 67 |
} |
| 68 |
} else if locked { |
| 69 |
if fh := l.f.Fh(); fh != nil { |
| 70 |
s := fmt.Sprintf("{%d} {%s}", os.Getpid(), os.Args[0]) |
| 71 |
_, _ = fh.WriteString(s) |
| 72 |
} |
| 73 |
return nil |
| 74 |
} |
| 75 |
} |
| 76 |
} |
| 77 |
|
| 78 |
|
| 79 |
func (l *Lock) Unlock() error { |
| 80 |
err := l.f.Unlock() |
| 81 |
if err == nil { |
| 82 |
err = os.Remove(l.f.Path()) |
| 83 |
} |
| 84 |
|
| 85 |
if errors.Is(err, os.ErrNotExist) || errors.Is(err, os.ErrPermission) || isWindowsSharingViolation(err) { |
| 86 |
return nil |
| 87 |
} |
| 88 |
return err |
| 89 |
} |
| 90 |
|
| 91 |
func isWindowsSharingViolation(err error) bool { |
| 92 |
return runtime.GOOS == "windows" && errors.Is(err, syscall.Errno(32)) |
| 93 |
} |