-
Notifications
You must be signed in to change notification settings - Fork 2
/
Lock.php
653 lines (582 loc) · 16.8 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
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
<?php
namespace Aternos\Lock;
use Aternos\Etcd\Client;
use Aternos\Etcd\ClientInterface;
use Aternos\Etcd\Exception\Status\DeadlineExceededException;
use Aternos\Etcd\Exception\Status\InvalidResponseStatusCodeException;
use Aternos\Etcd\Exception\Status\UnavailableException;
use Aternos\Etcd\Exception\Status\UnknownException;
/**
* Class Lock
*
* @package Aternos\Lock
*/
class Lock
{
/**
* see Lock::setClient()
*
* @var ClientInterface|null
*/
protected static ?ClientInterface $client = null;
/**
* see Lock::setPrefix()
*
* @var string
*/
protected static string $prefix = "lock/";
/**
* see Lock::setDefaultIdentifier()
*
* @var string|null
*/
protected static ?string $defaultIdentifier = null;
/**
* 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 etcd client (Aternos\Etcd\Client)
*
* Uses a localhost client if not set
*
* @param ClientInterface $client
*/
public static function setClient(ClientInterface $client): void
{
static::$client = $client;
}
/**
* Set the prefix for all etcd keys (default "lock/")
*
* @param string $prefix
*/
public static function setPrefix(string $prefix): void
{
static::$prefix = $prefix;
}
/**
* Set the default identifier
*
* Should be the same for the same synchronous process/request, but should be random
* enough to never be the same. Can be created with uniqid(). Will fallback to uniqid().
* If there is already a lock with the same identifier, that lock is used for this lock.
*
* Can be set individually on every lock if necessary (see Lock::__construct).
*
* @param string|null $defaultIdentifier
*/
public static function setDefaultIdentifier(?string $defaultIdentifier = null): void
{
if ($defaultIdentifier === null) {
$defaultIdentifier = uniqid();
}
static::$defaultIdentifier = $defaultIdentifier;
}
/**
* 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 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 less 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;
}
/**
* Identifier of the current lock
*
* Probably the same as Lock::$defaultIdentifier if not overwritten in Lock::__construct()
*
* @var string|null
*/
protected ?string $identifier = null;
/**
* Unique key for the resource
*
* @var string|null
*/
protected ?string $key = null;
/**
* Timeout time of the lock
*
* The lock will be released if this timeout is reached
*
* @var int|null
*/
protected ?int $time = null;
/**
* Is this an exclusive lock (true) or shared (false)
*
* @var bool
*/
protected bool $exclusive = false;
/**
* 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|bool
*/
protected string|bool $previousLockString = false;
/**
* Current parsed locks
*
* @var LockEntry[]
*/
protected array $locks = [];
/**
* Retry counter
*
* @var int
*/
protected int $retries = 0;
/**
* Automatically try to break the lock on destruct if possible
*
* @var bool
*/
protected bool $breakOnDestruct = true;
/**
* Create a lock
*
* @param string $key Can be anything, should describe the resource in a unique way
*/
public function __construct(string $key)
{
$this->key = $key;
$this->etcdKey = static::$prefix . $this->key;
}
/**
* Try to acquire lock
*
* @param bool $exclusive
* @param int $time
* @param int $wait
* @param string|null $identifier
* @return bool
* @throws InvalidResponseStatusCodeException
* @throws TooManySaveRetriesException
*/
public function lock(bool $exclusive = false, int $time = 120, int $wait = 300, ?string $identifier = null): bool
{
$this->exclusive = $exclusive;
$this->time = $time;
if (static::$defaultIdentifier === null) {
static::setDefaultIdentifier();
}
if ($identifier === null) {
$this->identifier = static::$defaultIdentifier;
} else {
$this->identifier = $identifier;
}
$this->retries = 0;
do {
$this->waitForOtherLocks($wait, $exclusive);
$retry = false;
if ($this->canLock()) {
$retry = !$this->addOrUpdateLock();
}
} while ($retry);
return !!$this->isLocked();
}
/**
* @param int $wait
* @param bool $exclusive
* @return bool
* @throws InvalidResponseStatusCodeException
*/
public function waitForOtherLocks(int $wait = 300, bool $exclusive = false): bool
{
$startTime = time();
$this->exclusive = $exclusive;
$this->update();
while (!$this->canLock() && $startTime + $wait > time()) {
sleep(static::$waitRetryInterval);
$this->update();
}
return $this->canLock();
}
/**
* Check if is locked and returns time until lock runs out or false
*
* @return bool|int
*/
public function isLocked(): bool|int
{
foreach ($this->locks as $lock) {
if ($lock->isBy($this->identifier)) {
$remaining = $lock->getRemainingTime();
return ($remaining > 0) ? $remaining : false;
}
}
return false;
}
/**
* Get the used identifier for this lock
*
* @return string|null
*/
public function getIdentifier(): ?string
{
return $this->identifier;
}
/**
* Dis/enable automatic lock break on object destruct
*
* @param bool $breakOnDestruct
*/
public function setBreakOnDestruct(bool $breakOnDestruct): void
{
$this->breakOnDestruct = $breakOnDestruct;
}
/**
* Refresh the lock
*
* @param int $time Time until the lock should be released automatically
* @param int $remainingThreshold The lock will only be refreshed if the remaining time is below this threshold (0 to disable)
* @return boolean
* @throws InvalidResponseStatusCodeException
* @throws TooManySaveRetriesException
*/
public function refresh(int $time = 60, int $remainingThreshold = 30): bool
{
if ($remainingThreshold > 0 && $this->isLocked() > $remainingThreshold) {
return true;
}
$this->update();
$this->time = $time;
$this->retries = 0;
do {
if (!$this->canLock()) {
return false;
}
$retry = !$this->addOrUpdateLock();
} while ($retry);
return true;
}
/**
* Break the lock
*
* Should be only used if you have the lock
*
* @return boolean
* @throws InvalidResponseStatusCodeException
* @throws TooManySaveRetriesException
*/
public function break(): bool
{
$this->update();
$this->retries = 0;
$this->removeLock();
return true;
}
/**
* Generate the lock object
*
* @return LockEntry
*/
protected function generateLock(): LockEntry
{
return new LockEntry($this->identifier, time() + $this->time, $this->exclusive);
}
/**
* Remove a lock from the locking array and save the locks
*
* @return bool
* @throws InvalidResponseStatusCodeException
* @throws TooManySaveRetriesException
*/
protected function removeLock(): bool
{
do {
foreach ($this->locks as $i => $lock) {
if ($lock->isBy($this->identifier)) {
unset($this->locks[$i]);
}
}
$success = $this->saveLocks();
} while ($success === false);
return true;
}
/**
* Add a lock to the locking array or update the current lock
*
* A 'false' return value can/should be retried, see Lock::saveLocks()
*
* @return bool
* @throws InvalidResponseStatusCodeException
* @throws TooManySaveRetriesException
*/
protected function addOrUpdateLock(): bool
{
foreach ($this->locks as $lock) {
if ($lock->isBy($this->identifier)) {
$lock->setRemaining($this->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 InvalidResponseStatusCodeException
* @throws TooManySaveRetriesException
*/
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::getClient()->deleteIf($this->etcdKey, $previousLocks, !$delayRetry);
break;
} catch (UnavailableException | DeadlineExceededException | UnknownException $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::getClient()->putIf($this->etcdKey, $lockString, $previousLocks, !$delayRetry);
break;
} catch (UnavailableException | DeadlineExceededException | UnknownException $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;
}
}
/**
* Get an Aternos\Etcd\Client instance
*
* @return ClientInterface
*/
protected function getClient(): ClientInterface
{
if (static::$client === null) {
static::$client = new Client();
}
return static::$client;
}
/**
* 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
*
* @throws InvalidResponseStatusCodeException
*/
public function update(): void
{
$etcdLockString = false;
for ($i = 1; $i <= static::$maxUnavailableRetries; $i++) {
try {
$etcdLockString = static::getClient()->get($this->etcdKey);
break;
} catch (UnavailableException | DeadlineExceededException | UnknownException $e) {
if ($i === static::$maxUnavailableRetries) {
throw $e;
} else {
sleep(static::$delayPerUnavailableRetry);
continue;
}
}
}
$this->updateFromString($etcdLockString);
}
/**
* Update the locks array from a JSON string
*
* @param string|bool $lockString
*/
protected function updateFromString(string|bool $lockString): void
{
$this->previousLockString = $lockString;
if ($lockString) {
$this->locks = LockEntry::fromJson($lockString);
} else {
$this->locks = [];
}
}
/**
* Break the lock on destruction of this object
*
* @throws InvalidResponseStatusCodeException
* @throws TooManySaveRetriesException
*/
public function __destruct()
{
if ($this->breakOnDestruct && $this->isLocked()) {
$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;
}
}