-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtouchfile.go
287 lines (258 loc) · 7.71 KB
/
touchfile.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
// Package touchfile provides a mechanism to create, lock, and manage a touch
// file for coordinating access between different processes.
//
// Mutexes are used to coordinate between goroutines. Touch files are used to
// coordinate between different processes. Because touch files aren't truly
// atomic, this package uses flock to acquire a voluntary lock on the file.
//
// This package creates a temporary file (unless otherwise specified) to use as
// a lock file. A voluntary lock is acquired on the file using the flock system
// call.
//
// WARNING: Like all go code related to concurrency, this module is NOT
// reentrant. And because go doesn't have a way to detect reentrancy, it's up
// to the caller to avoid deadlocks caused by concurrent access to this module.
//
// WARNING: Because flock is used, this module may not be compatible with all
// file systems (notably networked file systems like NFS).
//
// Example usage:
//
// Basic usage:
//
// ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
// defer cancel()
//
// tf, err := touchfile.NewTouchFile("/tmp/mylockfile")
// if err != nil {
// log.Fatalf("failed to create touch file: %v", err)
// }
//
// if err := tf.Lock(ctx, touchfile.Exclusive); err != nil {
// log.Fatalf("failed to acquire lock: %v", err)
// }
// defer func() {
// if err := tf.Unlock(); err != nil {
// log.Printf("failed to release lock: %v", err)
// }
// }()
//
// Global lock using the program binary:
//
// program, err := os.Executable()
// if err != nil {
// log.Fatalf("failed to determine executable path: %v", err)
// }
//
// tf, err := touchfile.NewTouchFile(program)
// ...
//
// Using WithLock for a critical section:
//
// tf, err := touchfile.NewTouchFile("/tmp/mylockfile")
// if err != nil {
// log.Fatalf("failed to create touch file: %v", err)
// }
//
// err = tf.WithLock(ctx, touchfile.Exclusive, func() error {
// // Critical section
// fmt.Println("Doing some work while holding the lock")
// return nil
// })
// if err != nil {
// log.Fatalf("operation failed: %v", err)
// }
package touchfile
import (
"context"
"fmt"
"log"
"os"
"path/filepath"
"sync"
"time"
"github.com/gofrs/flock"
)
// TouchFile struct holds the path to the touch file and a flock instance for
// advisory locking. A mutex is included to ensure safe access across multiple
// goroutines.
type TouchFile struct {
mu sync.Mutex
lock *flock.Flock
path string
}
// LockType is an enum for the type of lock to acquire on the touch file.
type LockType int
const (
// An Exclusive lock prevents any other processes or threads from acquiring
// any type of lock on the touch file.
Exclusive LockType = iota
// A Shared lock allows multiple processes or threads to acquire another
// Shared lock on the touch file, while preventing an Exclusive lock.
Shared
)
const lockRetryInterval = 10 * time.Millisecond
// NewTouchFile creates a TouchFile using flock for advisory locking. If the
// provided path is empty, a temporary file path will be used instead. The path
// is converted to an absolute path.
//
// Example:
//
// tf, err := touchfile.NewTouchFile("/tmp/mylockfile")
// if err != nil {
// log.Fatalf("failed to create touch file: %v", err)
// }
func NewTouchFile(path string) (*TouchFile, error) {
absPath, err := createTouchFile(path)
if err != nil {
return nil, err
}
return &TouchFile{
mu: sync.Mutex{},
lock: flock.New(absPath),
path: absPath,
}, nil
}
func createTouchFile(path string) (string, error) {
if path == "" {
tmpFile, err := os.CreateTemp("", "touchfile-")
if err != nil {
return "", err
}
path = tmpFile.Name()
tmpFile.Close()
}
absPath, err := filepath.Abs(path)
if err != nil {
return "", fmt.Errorf("unable to determine absolute path: %v", err)
}
// Verify that the parent directory exists
dir := filepath.Dir(absPath)
_, err = os.Stat(dir)
if os.IsNotExist(err) {
return "", fmt.Errorf("parent directory does not exist: %s", dir)
}
return absPath, nil
}
// Path returns the path to the touch file.
func (tf *TouchFile) Path() string {
tf.mu.Lock()
defer tf.mu.Unlock()
return tf.path
}
// Lock attempts to acquire the file lock. It will keep attempting to acquire
// the lock until the provided context times out or is canceled. If the lock
// cannot be acquired within the context's deadline, an error is returned.
//
// Example:
//
// ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
// defer cancel()
//
// tf, err := touchfile.NewTouchFile("/tmp/mylockfile")
// if err != nil {
// log.Fatalf("failed to create touch file: %v", err)
// }
//
// if err := tf.Lock(ctx, touchfile.Shared); err != nil {
// log.Fatalf("failed to acquire shared lock: %v", err)
// }
// defer func() {
// if err := tf.Unlock(); err != nil {
// log.Printf("failed to release lock: %v", err)
// }
// }()
func (tf *TouchFile) Lock(ctx context.Context, lockType LockType) error {
tf.mu.Lock()
defer tf.mu.Unlock()
var locked bool
var err error
switch lockType {
case Shared:
locked, err = tf.lockShared(ctx)
case Exclusive:
locked, err = tf.lockExclusive(ctx)
}
if err != nil {
return fmt.Errorf("failed to acquire lock on file %s: %w", tf.path, err)
}
if !locked {
return fmt.Errorf("unable to acquire lock on file %s within context timeout", tf.path)
}
return nil
}
// SharedLock attempts to acquire a Shared lock on the touch file.
func (tf *TouchFile) SharedLock(ctx context.Context) error {
return tf.Lock(ctx, Shared)
}
// ExclusiveLock attempts to acquire an Exclusive lock on the touch file.
func (tf *TouchFile) ExclusiveLock(ctx context.Context) error {
return tf.Lock(ctx, Exclusive)
}
func (tf *TouchFile) lockShared(ctx context.Context) (bool, error) {
return tf.lock.TryRLockContext(ctx, lockRetryInterval)
}
func (tf *TouchFile) lockExclusive(ctx context.Context) (bool, error) {
return tf.lock.TryLockContext(ctx, lockRetryInterval)
}
// Unlock releases the lock on the touch file. If an error occurs during
// unlocking, it is returned to the caller.
//
// Example:
//
// tf, err := touchfile.NewTouchFile("/tmp/mylockfile")
// if err != nil {
// log.Fatalf("failed to create touch file: %v", err)
// }
//
// ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
// defer cancel()
//
// if err := tf.Lock(ctx, touchfile.Exclusive); err != nil {
// log.Fatalf("failed to acquire lock: %v", err)
// }
//
// if err := tf.Unlock(); err != nil {
// log.Printf("failed to release lock: %v", err)
// }
func (tf *TouchFile) Unlock() error {
tf.mu.Lock()
defer tf.mu.Unlock()
if err := tf.lock.Unlock(); err != nil {
return fmt.Errorf("failed to unlock file at %s: %w", tf.path, err)
}
return nil
}
// WithLock is a convenience function that locks the touch file, executes the
// provided function, and then unlocks the touch file. If the lock cannot be
// acquired, the function will return an error. The lock is always released
// after the function is executed, even if the function returns an error.
//
// Example:
//
// ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
// defer cancel()
//
// tf, err := touchfile.NewTouchFile("/tmp/mylockfile")
// if err != nil {
// log.Fatalf("failed to create touch file: %v", err)
// }
//
// err = tf.WithLock(ctx, touchfile.Exclusive, func() error {
// fmt.Println("Doing some work while holding the lock")
// return nil
// })
// if err != nil {
// log.Fatalf("operation failed: %v", err)
// }
func (tf *TouchFile) WithLock(ctx context.Context, lockType LockType, f func() error) error {
if err := tf.Lock(ctx, lockType); err != nil {
return err
}
defer func() {
if err := tf.Unlock(); err != nil {
log.Printf("failed to unlock touch file at %s: %v\n", tf.path, err)
}
}()
return f()
}