Repository navigation
Expand file tree
/
Copy pathAbstractLeaseLockingService.java
More file actions
421 lines (379 loc) · 14.5 KB
/
Copy pathAbstractLeaseLockingService.java
File metadata and controls
421 lines (379 loc) · 14.5 KB
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
package me.desair.tus.server.upload;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import me.desair.tus.server.exception.TusException;
import me.desair.tus.server.exception.UploadAlreadyLockedException;
import me.desair.tus.server.util.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Abstract base class for distributed lease-based implementations of {@link UploadLockingService}.
*
* <p>Provides centralized concurrency coordination and lifecycle management including:
*
* <ul>
* <li>Template-based lock acquisition and TOCTOU-safe expired lock eviction.
* <li>Centralized lock status inspection.
* <li>JVM-local and cross-node/cross-pod lock contention signaling and watchdog polling.
* <li>Clean background daemon executor shutdown upon service close.
* </ul>
*/
public abstract class AbstractLeaseLockingService extends AbstractCloseableResourceService
implements UploadLockingService {
private static final Logger log = LoggerFactory.getLogger(AbstractLeaseLockingService.class);
/**
* Safety buffer in milliseconds added beyond a lease's expiration timestamp to absorb NTP clock
* skew and network latency between distributed cluster nodes.
*/
public static final long CLOCK_SKEW_SAFETY_MARGIN_MS = 2000L;
public static final long DEFAULT_JITTER_MIN_MS = 20L;
public static final long DEFAULT_JITTER_MAX_MS = 60L;
protected final long leaseDurationMs;
protected final long pollIntervalMs;
protected UploadIdFactory idFactory;
protected long jitterMinMs = DEFAULT_JITTER_MIN_MS;
protected long jitterMaxMs = DEFAULT_JITTER_MAX_MS;
protected final Map<UploadId, InputStream> activeInputStreams = new ConcurrentHashMap<>();
protected final ScheduledExecutorService watchdogExecutor;
/**
* Returns whether the given lease is expired, taking into account the {@link
* #CLOCK_SKEW_SAFETY_MARGIN_MS} clock drift buffer.
*
* @param lease The lease data to check
* @param now Current timestamp in milliseconds
* @return true if the lease is null or expired beyond the clock skew margin; false otherwise
*/
protected boolean isLeaseExpired(LeaseData lease, long now) {
if (lease == null) {
return true;
}
return lease.isExpired(now, CLOCK_SKEW_SAFETY_MARGIN_MS);
}
/**
* Constructs an {@link AbstractLeaseLockingService} and initializes the background contention
* watchdog daemon.
*
* @param idFactory The factory used to parse and generate upload identifiers
* @param leaseDurationMs Lock lease duration in milliseconds
* @param pollIntervalMs Watchdog polling interval in milliseconds
* @param shutdownHookName Name of the JVM shutdown hook thread, or null if none
* @param watchdogThreadName Name prefix for the background contention watchdog thread
*/
protected AbstractLeaseLockingService(
UploadIdFactory idFactory,
long leaseDurationMs,
long pollIntervalMs,
String shutdownHookName,
String watchdogThreadName) {
super(shutdownHookName);
this.idFactory = Objects.requireNonNull(idFactory, "The idFactory cannot be null");
this.leaseDurationMs = leaseDurationMs;
this.pollIntervalMs = pollIntervalMs;
// Use a multi-threaded daemon scheduled executor (scaling from 2 to 4 threads based on
// available processors) so that stop signal polling and lease heartbeats across concurrent
// uploads do not suffer head-of-line blocking during cloud network I/O.
int poolSize = Math.max(2, Math.min(Runtime.getRuntime().availableProcessors(), 4));
this.watchdogExecutor =
Utils.scheduleWatchdog(
watchdogThreadName,
poolSize,
this::checkStopSignals,
pollIntervalMs,
pollIntervalMs,
TimeUnit.MILLISECONDS);
}
/**
* Constructor allowing injection of a custom or null watchdog executor (e.g. for testing).
*
* @param idFactory The factory used to parse and generate upload identifiers
* @param leaseDurationMs Lock lease duration in milliseconds
* @param pollIntervalMs Watchdog polling interval in milliseconds
* @param shutdownHookName Name of the JVM shutdown hook thread, or null if none
* @param watchdogExecutor Custom executor service, or null
*/
protected AbstractLeaseLockingService(
UploadIdFactory idFactory,
long leaseDurationMs,
long pollIntervalMs,
String shutdownHookName,
ScheduledExecutorService watchdogExecutor) {
super(shutdownHookName);
this.idFactory = Objects.requireNonNull(idFactory, "The idFactory cannot be null");
this.leaseDurationMs = leaseDurationMs;
this.pollIntervalMs = pollIntervalMs;
this.watchdogExecutor = watchdogExecutor;
}
@Override
public UploadLock lockUploadByUri(String requestUri) throws TusException, IOException {
UploadId uploadId = idFactory.readUploadId(requestUri);
if (uploadId == null) {
return null;
}
String holderId = UUID.randomUUID().toString();
UploadLock lock = acquireOrEvictExpiredLock(uploadId, holderId, requestUri);
if (lock == null) {
throw new UploadAlreadyLockedException(
"Upload with URI " + requestUri + " is currently locked");
}
return lock;
}
@Override
public UploadLock lockUpload(UploadId uploadId) throws TusException, IOException {
if (uploadId == null) {
return null;
}
String holderId = UUID.randomUUID().toString();
UploadLock lock = acquireOrEvictExpiredLock(uploadId, holderId, uploadId.toString());
if (lock == null) {
throw new UploadAlreadyLockedException("Upload with ID " + uploadId + " is currently locked");
}
return lock;
}
@Override
public boolean isLocked(UploadId id) {
if (id == null) {
return false;
}
return !isLockExpired(id);
}
@Override
public void setIdFactory(UploadIdFactory idFactory) {
this.idFactory = Objects.requireNonNull(idFactory, "The idFactory cannot be null");
}
@Override
public void registerInputStream(String requestUri, InputStream inputStream) {
if (requestUri != null && inputStream != null) {
UploadId uploadId = idFactory.readUploadId(requestUri);
if (uploadId != null) {
activeInputStreams.put(uploadId, inputStream);
}
}
}
@Override
public void unregisterInputStream(String requestUri) {
if (requestUri != null) {
UploadId uploadId = idFactory.readUploadId(requestUri);
if (uploadId != null) {
// Remove stream registration once transfer completes or fails so the background watchdog
// stops polling storage for stop signals on this upload ID.
activeInputStreams.remove(uploadId);
}
}
}
@Override
public void requestLockRelease(String requestUri) {
if (requestUri == null) {
return;
}
UploadId uploadId = idFactory.readUploadId(requestUri);
if (uploadId != null) {
// 1. Interrupt active local input stream in this JVM directly by UploadId
InputStream activeStream = activeInputStreams.remove(uploadId);
if (activeStream != null) {
Utils.interruptStream(activeStream);
}
// 2. Write a .stop signal to notify remote cluster replicas / pods
writeStopSignal(uploadId);
}
}
@Override
public void cleanupLock(UploadId id) throws IOException {
if (id != null) {
clearStopSignal(id);
}
}
/**
* Clears any lingering contention stop signal for the given upload ID.
*
* @param uploadId The upload identifier
*/
protected void clearStopSignal(UploadId uploadId) {}
/**
* Returns the shared scheduled executor used for background watchdog polling.
*
* @return The scheduled executor service
*/
public ScheduledExecutorService getWatchdogExecutor() {
return watchdogExecutor;
}
@Override
protected void cleanupOnClose() throws IOException {
Utils.shutdownExecutor(watchdogExecutor);
for (InputStream stream : activeInputStreams.values()) {
Utils.interruptStream(stream);
}
activeInputStreams.clear();
doCleanupOnClose();
}
/**
* Subclass hook for additional cleanup upon service close. Default implementation does nothing.
*
* @throws IOException If closing fails
*/
protected void doCleanupOnClose() throws IOException {}
/**
* Attempts lock acquisition or safe eviction of an expired lock with multi-layer TOCTOU
* mitigations.
*
* @param uploadId The upload identifier
* @param holderId The unique identifier of the lock contender
* @param requestUri The target upload request URI
* @return Acquired {@link UploadLock} handle, or null if lock is held by another active node
* @throws TusException If a protocol error occurs
* @throws IOException If an I/O error occurs
*/
protected UploadLock acquireOrEvictExpiredLock(
UploadId uploadId, String holderId, String requestUri) throws TusException, IOException {
long now = System.currentTimeMillis();
long expiresAt = now + leaseDurationMs;
LeaseData leaseData =
new LeaseData(holderId, requestUri, leaseDurationMs, expiresAt, now, null, null);
UploadLock lock = tryAcquireLock(uploadId, leaseData, false);
if (lock != null) {
return lock;
}
// Lock acquisition encountered an existing lock. Inspect expiration status.
if (isLockExpired(uploadId)) {
// Lock is expired or abandoned: evict and retry acquisition
boolean evicted = evictExpiredLock(uploadId);
if (evicted) {
now = System.currentTimeMillis();
leaseData.setAcquiredAt(now);
leaseData.setExpiresAt(now + leaseDurationMs);
lock = tryAcquireLock(uploadId, leaseData, true);
if (lock != null) {
return lock;
}
}
}
return null;
}
/**
* Subclass implementation of primary lock acquisition, indicating whether this call is an
* eviction retry after deleting an expired lock. Default implementation delegates to {@link
* #tryAcquireLock(UploadId, LeaseData)}.
*
* @param uploadId The upload identifier
* @param leaseData The lease metadata describing the lock to acquire
* @param isEvictionRetry True if this acquisition follows an expired lock eviction
* @return Acquired {@link UploadLock}, or null if already held
* @throws IOException If an I/O error occurs
*/
protected UploadLock tryAcquireLock(
UploadId uploadId, LeaseData leaseData, boolean isEvictionRetry) throws IOException {
return tryAcquireLock(uploadId, leaseData);
}
/**
* Subclass implementation of atomic primary lock acquisition.
*
* @param uploadId The upload identifier
* @param leaseData The lease metadata describing the lock to acquire
* @return Acquired {@link UploadLock}, or null if already held
* @throws IOException If an I/O error occurs
*/
protected abstract UploadLock tryAcquireLock(UploadId uploadId, LeaseData leaseData)
throws IOException;
/**
* Subclass implementation determining if an upload lock is currently expired or abandoned.
*
* @param uploadId The upload identifier
* @return true if the lock does not exist, has expired, or is abandoned; false if actively held
*/
protected abstract boolean isLockExpired(UploadId uploadId);
/**
* Subclass implementation safely evicting an expired lock with TOCTOU safeguards.
*
* @param uploadId The upload identifier
* @return true if successfully evicted, false if eviction lost a race or was aborted
*/
protected abstract boolean evictExpiredLock(UploadId uploadId);
/**
* Writes a contention interrupt stop signal to the underlying storage mechanism.
*
* @param uploadId The upload identifier
*/
protected abstract void writeStopSignal(UploadId uploadId);
/**
* Checks for a contention interrupt stop signal for an active input stream.
*
* @param uploadId The upload identifier
* @param inputStream The active request input stream
*/
protected abstract void checkStopSignalForUpload(UploadId uploadId, InputStream inputStream);
/** Polls active streams against stop signals across replicas. */
public void checkStopSignals() {
for (Map.Entry<UploadId, InputStream> entry : activeInputStreams.entrySet()) {
checkStopSignalForUpload(entry.getKey(), entry.getValue());
}
}
/**
* Applies randomized jitter backoff to settle concurrent in-flight writes and arbitrate lock
* acquisition races on storage backends lacking atomic conditional writes.
*
* <p>If {@code maxMs <= 0}, this method returns immediately without sleeping, allowing callers to
* bypass jitter on backends with guaranteed atomic conditional writes (e.g. AWS S3).
*
* @param minMs Minimum jitter duration in milliseconds
* @param maxMs Maximum jitter duration in milliseconds
*/
protected void applyJitter(long minMs, long maxMs) {
if (maxMs <= 0) {
return;
}
try {
long jitterMs = (minMs >= maxMs) ? minMs : minMs + (long) (Math.random() * (maxMs - minMs));
if (jitterMs > 0) {
Thread.sleep(jitterMs);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
/**
* Applies randomized jitter backoff using the configured {@link #getJitterMinMs()} and {@link
* #getJitterMaxMs()} bounds.
*/
protected void applyJitter() {
applyJitter(jitterMinMs, jitterMaxMs);
}
/**
* Returns the configured minimum jitter duration in milliseconds.
*
* @return Minimum jitter duration in milliseconds
*/
public long getJitterMinMs() {
return jitterMinMs;
}
/**
* Returns the configured maximum jitter duration in milliseconds.
*
* @return Maximum jitter duration in milliseconds
*/
public long getJitterMaxMs() {
return jitterMaxMs;
}
/**
* Configures the jitter bounds used during lock acquisition read-after-write verification.
*
* @param minMs Minimum jitter duration in milliseconds (must be >= 0)
* @param maxMs Maximum jitter duration in milliseconds (must be >= minMs)
* @throws IllegalArgumentException If minMs is negative or maxMs is less than minMs
*/
public void setJitter(long minMs, long maxMs) {
if (minMs < 0) {
throw new IllegalArgumentException("jitterMinMs cannot be negative: " + minMs);
}
if (maxMs < minMs) {
throw new IllegalArgumentException(
"jitterMaxMs (" + maxMs + ") cannot be less than jitterMinMs (" + minMs + ")");
}
this.jitterMinMs = minMs;
this.jitterMaxMs = maxMs;
}
}