PluginProbe ʕ •ᴥ•ʔ
WP STAGING – WordPress Backup, Restore, Migration & Clone / 4.1.1
WP STAGING – WordPress Backup, Restore, Migration & Clone v4.1.1
4.9.1 4.9.0 4.8.1 trunk 3.0.0 3.0.1 3.0.2 3.0.3 3.0.4 3.0.5 3.0.6 3.1.0 3.1.1 3.1.2 3.1.3 3.1.4 3.10.0 3.2.0 3.3.1 3.3.2 3.3.3 3.4.1 3.4.3 3.5.0 3.6.0 3.7.1 3.8.0 3.8.1 3.8.2 3.8.3 3.8.4 3.8.5 3.8.6 3.8.7 3.9.0 3.9.1 3.9.2 3.9.3 3.9.4 4.0.0 4.1.0 4.1.1 4.1.2 4.1.3 4.1.4 4.2.0 4.2.1 4.3.0 4.3.1 4.3.2 4.4.0 4.5.0 4.6.0 4.7.0 4.7.1 4.7.2 4.7.3 4.8.0
wp-staging / Framework / Job / ProcessLock.php
wp-staging / Framework / Job Last commit date
Ajax 1 year ago Dto 1 year ago Exception 1 year ago Interfaces 1 year ago Task 1 year ago AbstractJob.php 1 year ago JobProvider.php 1 year ago JobServiceProvider.php 1 year ago ProcessLock.php 1 year ago
ProcessLock.php
92 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 // Process is locked.
87 $timeLeft = absint($timeout - (time() - $processLocked));
88
89 throw ProcessLockedException::processAlreadyLocked($timeLeft);
90 }
91 }
92