Debian Codegraph @

cache/internal/lock/lock.go

raw
1 // Copyright (c) Microsoft Corporation. All rights reserved.
2 // Licensed under the MIT License. See LICENSE in the project root for license information.
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 // timeout lets tests set the default amount of time allowed to acquire the lock
20 var timeout = 5 * time.Second
21
22 // flocker helps tests fake flock
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 // Lock uses a file lock to coordinate access to resources shared with other processes.
31 // Callers are responsible for preventing races within a process. Lock applies advisory
32 // locks on Linux and macOS and is therefore unreliable on these platforms when several
33 // processes concurrently try to acquire the lock.
34 type Lock struct {
35 f flocker
36 retryDelay time.Duration
37 }
38
39 // New is the constructor for Lock. "p" is the path to the lock file.
40 func New(p string, retryDelay time.Duration) (*Lock, error) {
41 // ensure all dirs in the path exist before flock tries to create the file
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 // Lock acquires the file lock on behalf of the process. The behavior of concurrent
50 // and repeated calls is undefined. For example, Linux may or may not allow goroutines
51 // scheduled on different threads to hold the lock simultaneously.
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 // flock opens the file before locking it and returns errors due to an existing
60 // lock or one acquired by another process after this process has opened the
61 // file. We ignore some errors here because in such cases we want to retry until
62 // the deadline.
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 // Unlock releases the lock and deletes the lock file.
79 func (l *Lock) Unlock() error {
80 err := l.f.Unlock()
81 if err == nil {
82 err = os.Remove(l.f.Path())
83 }
84 // ignore errors caused by another process deleting the file or locking between the above Unlock and Remove
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 }