-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathLock.php
584 lines (522 loc) · 15.7 KB
/
Lock.php
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
<?php
namespace Aternos\Lock;
use Aternos\Lock\Storage\EtcdStorage;
use Aternos\Lock\Storage\StorageException;
use Aternos\Lock\Storage\StorageInterface;
use Exception;
/**
* LockInterface implementation using etcd-like storage
*
* @package Aternos\Lock
*/
class Lock extends AbstractLock
{
/**
* @see static::setStorage()
* @var StorageInterface|null
*/
protected static ?StorageInterface $storage = null;
/**
* see Lock::setPrefix()
*
* @var string
*/
protected static string $prefix = "lock/";
/**
* see Lock::setWaitRetryInterval()
*
* @var int
*/
protected static int $waitRetryInterval = 1;
/**
* see Lock::setMaxSaveRetries()
*
* @var int
*/
protected static int $maxSaveRetries = 100;
/**
* see Lock::setMaxDelayPerSaveRetry()
*
* @var int
*/
protected static int $maxDelayPerSaveRetry = 1000;
/**
* see Lock::setMaxUnavailableRetries()
*
* @var int
*/
protected static int $maxUnavailableRetries = 3;
/**
* see Lock::setDelayPerUnavailableRetry()
*
* @var int
*/
protected static int $delayPerUnavailableRetry = 1;
/**
* Set the storage interface used to store locks. If not set, {@link EtcdStorage} is used.
* @param StorageInterface $storage
* @return void
*/
public static function setStorage(StorageInterface $storage): void
{
static::$storage = $storage;
}
/**
* Get the storage interface used to store locks. If not set, {@link EtcdStorage} is used.
* @return StorageInterface
*/
protected static function getStorage(): StorageInterface
{
return static::$storage ??= new EtcdStorage();
}
/**
* Set the prefix for all etcd keys (default "lock/")
*
* @param string $prefix
*/
public static function setPrefix(string $prefix): void
{
static::$prefix = $prefix;
}
/**
* Set the interval (in seconds) used to retry the locking if it's already locked
*
* @param int $interval
*/
public static function setWaitRetryInterval(int $interval): void
{
static::$waitRetryInterval = $interval;
}
/**
* Set the maximum save retries until a request should fail (throw TooManySaveRetriesException)
*
* Default is 100
*
* @param int $retries
*/
public static function setMaxSaveRetries(int $retries): void
{
static::$maxSaveRetries = $retries;
}
/**
* Set the maximum delay in microseconds (1,000,000 microseconds = 1 second) that should be used for the random
* delay between retries.
*
* The delay is random and calculated like this: rand(0, $retries * $delayPerRetry)
*
* Lower value = faster retries (probably more retries necessary)
* Higher value = slower retries (probably fewer retries necessary)
*
* @param int $delayPerRetry
*/
public static function setMaxDelayPerSaveRetry(int $delayPerRetry): void
{
static::$maxDelayPerSaveRetry = $delayPerRetry;
}
/**
* Set the maximum retries in case of an UnavailableException from etcd
*
* @param int $retries
*/
public static function setMaxUnavailableRetries(int $retries): void
{
static::$maxUnavailableRetries = $retries;
}
/**
* Delay in seconds between retries in case of an UnavailableException from etcd
*
* @param int $delayPerRetry
*/
public static function setDelayPerUnavailableRetry(int $delayPerRetry): void
{
static::$delayPerUnavailableRetry = $delayPerRetry;
}
/**
* Full name of the key in etcd (prefix + key)
*
* @var string|null
*/
protected ?string $etcdKey = null;
/**
* Used to store the previous lock string
*
* Will be used in deleteIf and putIf requests to check
* if there was no change in etcd while processing the lock
*
* @var string
*/
protected ?string $previousLockString = null;
/**
* Current parsed locks
*
* @var LockEntry[]
*/
protected array $locks = [];
/**
* Retry counter
*
* @var int
*/
protected int $retries = 0;
/**
* Create a lock
*
* @param string $key Can be anything, should describe the resource in a unique way
* @param string|null $identifier An identifier for this lock, falls back to the default identifier if null
* @param int $time Timeout time of the lock in seconds. The lock will be released if this timeout is reached.
* @param bool $exclusive Is this lock exclusive (true) or shared (false)
* @param int $waitTime Time in seconds to wait for existing locks to be released.
* @param int|null $refreshTime Duration in seconds the timeout should be set to when refreshing the lock.
* If null the initial timeout will be used.
* @param float $refreshThreshold Maximum percentage of the refreshTime the existing lock may still be valid for
* to be refreshed. If the lock is valid for longer than this time, it won't be refreshed.
* @param bool $breakOnDestruct Automatically try to break the lock on destruct if possible
*/
public function __construct(
string $key,
?string $identifier = null,
bool $exclusive = false,
int $time = 120,
int $waitTime = 300,
?int $refreshTime = null,
float $refreshThreshold = 0.5,
bool $breakOnDestruct = true,
)
{
parent::__construct($key, $identifier, $exclusive, $time, $waitTime, $refreshTime, $refreshThreshold, $breakOnDestruct);
$this->etcdKey = static::$prefix . $this->key;
}
/**
* Try to acquire lock
*
* @return bool true if the lock was acquired, false if it was not
* @throws StorageException
* @throws TooManySaveRetriesException
*/
public function lock(): bool
{
$this->retries = 0;
do {
$this->waitForOtherLocks();
$retry = false;
if ($this->canLock()) {
$retry = !$this->addOrUpdateLock($this->time);
}
} while ($retry);
return $this->isLocked();
}
/**
* Wait for other locks to be released. This method will only wait if the timeout of the existing lock ends within
* the specified wait time. If the timeout of the existing lock ends after the wait time, this method will return
* immediately, even though the lock holder might voluntarily break the lock before the timeout.
*
* @param int|null $waitTime maximum time in seconds to wait for other locks
* @return bool
* @throws StorageException
*/
public function waitForOtherLocks(?int $waitTime = null): bool
{
$waitTime ??= $this->waitTime;
$startTime = time();
$this->update();
while (!$this->canLock() && $startTime + $waitTime > time()) {
sleep(static::$waitRetryInterval);
$this->update();
}
return $this->canLock();
}
/**
* Get the time until the lock runs out. This method will return -1 if the lock is not valid or other negative values
* if the lock has already run out.
*
* @return int
*/
public function getRemainingLockDuration(): int
{
foreach ($this->locks as $lock) {
if ($lock->isBy($this->identifier)) {
return $lock->getRemainingTime();
}
}
return -1;
}
/**
* Refresh the lock
*
* @return boolean
* @throws StorageException
* @throws TooManySaveRetriesException
*/
public function refresh(): bool
{
if (!$this->shouldRefresh()) {
return true;
}
$this->update();
$this->retries = 0;
do {
if (!$this->canLock()) {
return false;
}
$retry = !$this->addOrUpdateLock($this->getEffectiveRefreshTime());
} while ($retry);
return true;
}
/**
* Break the lock
*
* Should be only used if you have the lock
*
* @return void
* @throws StorageException
* @throws TooManySaveRetriesException
*/
public function break(): void
{
if (!$this->isLocked()) {
return;
}
$this->update();
$this->retries = 0;
$this->removeLock();
}
/**
* Generate the lock object
*
* @return LockEntry
*/
protected function generateLock(): LockEntry
{
return new LockEntry($this->identifier, time() + $this->time, $this->exclusive);
}
/**
* Returns true, if the remaining lock duration is less than the refresh threshold.
* @return bool
*/
protected function shouldRefresh(): bool
{
if ($this->refreshThreshold <= 0) {
return true;
}
$remaining = $this->getRemainingLockDuration();
$threshold = $this->refreshThreshold * $this->getEffectiveRefreshTime();
return $remaining < $threshold;
}
/**
* Remove a lock from the locking array and save the locks
*
* @return void
* @throws StorageException
* @throws TooManySaveRetriesException
*/
protected function removeLock(): void
{
do {
foreach ($this->locks as $i => $lock) {
if ($lock->isBy($this->identifier)) {
unset($this->locks[$i]);
}
}
$success = $this->saveLocks();
} while ($success === false);
}
/**
* Add a lock to the locking array or update the current lock
*
* A 'false' return value can/should be retried, see Lock::saveLocks()
*
* @param int $time
* @return bool
* @throws StorageException
* @throws TooManySaveRetriesException
*/
protected function addOrUpdateLock(int $time): bool
{
foreach ($this->locks as $lock) {
if ($lock->isBy($this->identifier)) {
$lock->setRemaining($time);
return $this->saveLocks();
}
}
$this->locks[] = $this->generateLock();
return $this->saveLocks();
}
/**
* Save the locks array in etcd
*
* A 'false' return value can/should be retried by calling the function again
* An infinite loop is (hopefully) prevented by the retries counter, an exception
* is thrown when there are too many retries
*
* Before calling this function again the locks should be checked again, if the locks
* changed since the last update, they will be updated by this function again.
*
* @return bool
* @throws StorageException
* @throws TooManySaveRetriesException
* @throws Exception
*/
protected function saveLocks(): bool
{
$previousLocks = $this->previousLockString;
foreach ($this->locks as $i => $lock) {
if ($lock->isExpired()) {
unset($this->locks[$i]);
}
}
$delayRetry = $this->retries >= 3;
$result = false;
if (count($this->locks) === 0) {
for ($i = 1; $i <= static::$maxUnavailableRetries; $i++) {
try {
$result = static::getStorage()->deleteIf($this->etcdKey, $previousLocks, !$delayRetry);
break;
} catch (StorageException $e) {
if ($i === static::$maxUnavailableRetries) {
throw $e;
} else {
sleep(static::$delayPerUnavailableRetry);
continue;
}
}
}
} else {
$lockString = json_encode(array_values($this->locks));
for ($i = 1; $i <= static::$maxUnavailableRetries; $i++) {
try {
$result = static::getStorage()->putIf($this->etcdKey, $lockString, $previousLocks, !$delayRetry);
break;
} catch (StorageException $e) {
if ($i === static::$maxUnavailableRetries) {
throw $e;
} else {
sleep(static::$delayPerUnavailableRetry);
continue;
}
}
}
}
if ($result !== true) {
if ($this->retries >= static::$maxSaveRetries) {
throw new TooManySaveRetriesException("Locking cancelled because of too many save retries (" . $this->retries . ").");
}
if ($delayRetry) {
usleep(rand(0, static::$maxDelayPerSaveRetry * $this->retries));
$this->update();
} else {
$this->updateFromString($result);
}
$this->retries++;
return false;
} else {
return true;
}
}
/**
* Check if it is possible to lock
*
* @return bool
*/
protected function canLock(): bool
{
foreach ($this->locks as $lock) {
if (!$lock->isBy($this->identifier) && $lock->isExclusive() && !$lock->isExpired()) {
return false;
}
if (!$lock->isBy($this->identifier) && $this->exclusive && !$lock->isExpired()) {
return false;
}
}
return true;
}
/**
* Update the locks array from etcd
*
* @return $this
* @throws StorageException
* @throws Exception
*/
public function update(): static
{
$etcdLockString = false;
for ($i = 1; $i <= static::$maxUnavailableRetries; $i++) {
try {
$etcdLockString = static::getStorage()->get($this->etcdKey);
break;
} catch (StorageException $e) {
if ($i === static::$maxUnavailableRetries) {
throw $e;
} else {
sleep(static::$delayPerUnavailableRetry);
continue;
}
}
}
return $this->updateFromString($etcdLockString);
}
/**
* Update the locks array from a JSON string
*
* @param ?string $lockString
* @return $this
*/
protected function updateFromString(?string $lockString): static
{
$this->previousLockString = $lockString;
if ($lockString) {
$this->locks = LockEntry::fromJson($lockString);
} else {
$this->locks = [];
}
return $this;
}
/**
* Break the lock on destruction of this object
*
* @throws StorageException
* @throws TooManySaveRetriesException
*/
public function __destruct()
{
if ($this->breakOnDestruct) {
$this->break();
}
}
/**
* @return LockEntry[]
*/
public function getLocks(): array
{
return $this->locks;
}
/**
* Check if lock is acquired by a different process
*
* @return bool
*/
public function isLockedByOther(): bool
{
foreach ($this->getLocks() as $lock) {
if ($lock->isExpired() || $lock->isBy($this->getIdentifier())) {
continue;
}
return true;
}
return false;
}
/**
* Check if lock is acquired exclusively by a different process
*
* @return bool
*/
public function isLockedByOtherExclusively(): bool
{
foreach ($this->getLocks() as $lock) {
if ($lock->isExpired() || $lock->isBy($this->getIdentifier()) || !$lock->isExclusive()) {
continue;
}
return true;
}
return false;
}
}