Ajax
1 month ago
BackgroundProcessing
1 year ago
Dto
1 week ago
Exception
3 months ago
Interfaces
1 week ago
Jobs
5 months ago
Task
1 week ago
Traits
8 months ago
AbstractJob.php
1 month ago
JobProvider.php
1 year ago
JobServiceProvider.php
4 months ago
JobTransientCache.php
1 month ago
ProcessLock.php
1 year ago
ProcessLock.php
89 lines
| 1 | <?php |
| 2 | |
| 3 | namespace WPStaging\Framework\Job; |
| 4 | |
| 5 | use WPStaging\Core\WPStaging; |
| 6 | use WPStaging\Framework\Job\Exception\ProcessLockedException; |
| 7 | use WPStaging\Framework\Traits\ResourceTrait; |
| 8 | |
| 9 | class ProcessLock |
| 10 | { |
| 11 | use ResourceTrait; |
| 12 | |
| 13 | const LOCK_FILE_NAME = '.wpstg_process_locked'; |
| 14 | |
| 15 | private $lockFile; |
| 16 | |
| 17 | public function __construct() |
| 18 | { |
| 19 | $this->lockFile = trailingslashit(WPStaging::getContentDir()) . self::LOCK_FILE_NAME; |
| 20 | } |
| 21 | |
| 22 | /** |
| 23 | * @throws ProcessLockedException When the process is locked. |
| 24 | * @return void |
| 25 | */ |
| 26 | public function lockProcess() |
| 27 | { |
| 28 | $this->checkProcessLocked(); |
| 29 | file_put_contents($this->lockFile, time()); |
| 30 | } |
| 31 | |
| 32 | /** |
| 33 | * @return void |
| 34 | */ |
| 35 | public function unlockProcess() |
| 36 | { |
| 37 | if (!file_exists($this->lockFile)) { |
| 38 | return; |
| 39 | } |
| 40 | |
| 41 | unlink($this->lockFile); |
| 42 | } |
| 43 | |
| 44 | /** |
| 45 | * @param int|null $timeout The timeout, in seconds, to lock the process. Leave null to automatically set one. |
| 46 | * @return void |
| 47 | * |
| 48 | * @throws ProcessLockedException When the process is locked. |
| 49 | */ |
| 50 | public function checkProcessLocked($timeout = null) |
| 51 | { |
| 52 | if (is_null($timeout)) { |
| 53 | $timeout = min(120, $this->getTimeLimit()); |
| 54 | } |
| 55 | |
| 56 | if (!file_exists($this->lockFile)) { |
| 57 | return; |
| 58 | } |
| 59 | |
| 60 | $processLocked = file_get_contents($this->lockFile); |
| 61 | |
| 62 | if (!$processLocked) { |
| 63 | return; |
| 64 | } |
| 65 | |
| 66 | if (!is_numeric($processLocked)) { |
| 67 | $this->unlockProcess(); |
| 68 | |
| 69 | return; |
| 70 | } |
| 71 | |
| 72 | /* |
| 73 | * Something is locking the process. |
| 74 | * |
| 75 | * Let's make sure the lock was placed in the last couple minutes, or else we unstuck it, |
| 76 | * as a task is not supposed to run for this long (at least not in web requests). |
| 77 | * |
| 78 | * A process can get stuck when a Job fails to shutdown gracefully, for instance. |
| 79 | */ |
| 80 | if ($processLocked < time() - $timeout) { |
| 81 | $this->unlockProcess(); |
| 82 | |
| 83 | return; |
| 84 | } |
| 85 | |
| 86 | throw ProcessLockedException::processAlreadyLocked(); |
| 87 | } |
| 88 | } |
| 89 |