Download this file
| 1 | package team |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "os" |
| 6 | "path/filepath" |
| 7 | "time" |
| 8 | ) |
| 9 | |
| 10 | // withStoreGuard serializes the database commit and the following witness |
| 11 | // write, including replacement handles and processes. The lock file is |
| 12 | // permanent; unlinking it would let another opener lock a different inode. |
| 13 | func (s *Store) withStoreGuard(ctx context.Context, fn func() error) error { |
| 14 | s.writeMu.Lock() |
| 15 | defer s.writeMu.Unlock() |
| 16 | if s.broken != nil { |
| 17 | return fail(CodeStaleStore, "store must be reopened after incomplete commit: %v", s.broken) |
| 18 | } |
| 19 | f, err := os.OpenFile(s.path+".lock", os.O_CREATE|os.O_RDWR, 0o600) |
| 20 | if err != nil { |
| 21 | return err |
| 22 | } |
| 23 | defer f.Close() |
| 24 | for { |
| 25 | if err := ctx.Err(); err != nil { |
| 26 | return err |
| 27 | } |
| 28 | locked, err := tryStoreLock(f) |
| 29 | if err != nil { |
| 30 | return err |
| 31 | } |
| 32 | if locked { |
| 33 | defer unlockStoreFile(f) |
| 34 | return fn() |
| 35 | } |
| 36 | timer := time.NewTimer(10 * time.Millisecond) |
| 37 | select { |
| 38 | case <-ctx.Done(): |
| 39 | timer.Stop() |
| 40 | return ctx.Err() |
| 41 | case <-timer.C: |
| 42 | } |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | // The database and its lock must have one path even when a caller uses a |
| 47 | // relative path or a symlink. Hard-linked SQLite databases are unsupported. |
| 48 | func canonicalStorePath(path string) (string, error) { |
| 49 | abs, err := filepath.Abs(path) |
| 50 | if err != nil { |
| 51 | return "", err |
| 52 | } |
| 53 | resolved, err := filepath.EvalSymlinks(abs) |
| 54 | if err == nil { |
| 55 | return resolved, nil |
| 56 | } |
| 57 | if !os.IsNotExist(err) { |
| 58 | return "", err |
| 59 | } |
| 60 | if _, statErr := os.Lstat(abs); !os.IsNotExist(statErr) { |
| 61 | return "", err // an existing dangling symlink cannot name a second lock |
| 62 | } |
| 63 | dir, err := filepath.EvalSymlinks(filepath.Dir(abs)) |
| 64 | if err != nil { |
| 65 | return "", err |
| 66 | } |
| 67 | return filepath.Join(dir, filepath.Base(abs)), nil |
| 68 | } |
| 69 | |