| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | |
| 21 | package lockutil |
| 22 | |
| 23 | import ( |
| 24 | "fmt" |
| 25 | "os" |
| 26 | "syscall" |
| 27 | "unsafe" |
| 28 | |
| 29 | "github.com/sirupsen/logrus" |
| 30 | ) |
| 31 | |
| 32 | |
| 33 | var ( |
| 34 | modkernel32 = syscall.NewLazyDLL("kernel32.dll") |
| 35 | procLockFileEx = modkernel32.NewProc("LockFileEx") |
| 36 | procUnlockFileEx = modkernel32.NewProc("UnlockFileEx") |
| 37 | ) |
| 38 | |
| 39 | |
| 40 | const flagLockfileExclusiveLock = 0x00000002 |
| 41 | |
| 42 | func WithDirLock(dir string, fn func() error) error { |
| 43 | dirFile, err := os.OpenFile(dir+".lock", os.O_CREATE, 0o644) |
| 44 | if err != nil { |
| 45 | return err |
| 46 | } |
| 47 | defer dirFile.Close() |
| 48 | if err := lockFileEx( |
| 49 | syscall.Handle(dirFile.Fd()), |
| 50 | flagLockfileExclusiveLock, |
| 51 | 0, |
| 52 | 1, |
| 53 | 0, |
| 54 | &syscall.Overlapped{}, |
| 55 | ); err != nil { |
| 56 | return fmt.Errorf("failed to lock %#q: %w", dir, err) |
| 57 | } |
| 58 | |
| 59 | defer func() { |
| 60 | if err := unlockFileEx( |
| 61 | syscall.Handle(dirFile.Fd()), |
| 62 | 0, |
| 63 | 1, |
| 64 | 0, |
| 65 | &syscall.Overlapped{}, |
| 66 | ); err != nil { |
| 67 | logrus.WithError(err).Errorf("failed to unlock %#q", dir) |
| 68 | } |
| 69 | }() |
| 70 | return fn() |
| 71 | } |
| 72 | |
| 73 | func lockFileEx(h syscall.Handle, flags, reserved, locklow, lockhigh uint32, ol *syscall.Overlapped) (err error) { |
| 74 | r, _, err := procLockFileEx.Call(uintptr(h), uintptr(flags), uintptr(reserved), uintptr(locklow), uintptr(lockhigh), uintptr(unsafe.Pointer(ol))) |
| 75 | if r == 0 { |
| 76 | return err |
| 77 | } |
| 78 | return nil |
| 79 | } |
| 80 | |
| 81 | func unlockFileEx(h syscall.Handle, reserved, locklow, lockhigh uint32, ol *syscall.Overlapped) (err error) { |
| 82 | r, _, err := procUnlockFileEx.Call(uintptr(h), uintptr(reserved), uintptr(locklow), uintptr(lockhigh), uintptr(unsafe.Pointer(ol)), 0) |
| 83 | if r == 0 { |
| 84 | return err |
| 85 | } |
| 86 | return nil |
| 87 | } |