|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Vectorial1024\LaravelProcessAsync; |
| 6 | + |
| 7 | +use InvalidArgumentException; |
| 8 | +use loophp\phposinfo\OsInfo; |
| 9 | +use RuntimeException; |
| 10 | + |
| 11 | +/** |
| 12 | + * Represents the status of an async task: "running" or "stopped". |
| 13 | + * |
| 14 | + * This does not tell you whether it was a success/failure, since it depends on the user's custom result checking. |
| 15 | + */ |
| 16 | +class AsyncTaskStatus |
| 17 | +{ |
| 18 | + private const MSG_CANNOT_CHECK_STATUS = "Could not check the status of the AsyncTask."; |
| 19 | + |
| 20 | + /** |
| 21 | + * The cached task ID for quick ID reusing. We will most probably reuse this ID many times. |
| 22 | + * @var string|null |
| 23 | + */ |
| 24 | + private string|null $encodedTaskID = null; |
| 25 | + |
| 26 | + /** |
| 27 | + * Indicates whether the task is stopped. |
| 28 | + * |
| 29 | + * Note: the criteria is "pretty sure it is stopped"; once the task is stopped, it stays stopped. |
| 30 | + * @var bool |
| 31 | + */ |
| 32 | + private bool $isStopped = false; |
| 33 | + |
| 34 | + /** |
| 35 | + * The last known PID of the task runner. |
| 36 | + * @var int|null If null, it means the PID is unknown or expired. |
| 37 | + */ |
| 38 | + private int|null $lastKnownPID = null; |
| 39 | + |
| 40 | + /** |
| 41 | + * Constructs a status object. |
| 42 | + * @param string $taskID The task ID of the async task so to check its status. |
| 43 | + */ |
| 44 | + public function __construct( |
| 45 | + public readonly string $taskID |
| 46 | + ) { |
| 47 | + if ($taskID === "") { |
| 48 | + // why no blank IDs? because this will produce blank output via base64 encode. |
| 49 | + throw new InvalidArgumentException("AsyncTask IDs cannot be blank"); |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + /** |
| 54 | + * Returns the task ID encoded in base64, mainly for result checking. |
| 55 | + * @return string The encoded task ID. |
| 56 | + */ |
| 57 | + public function getEncodedTaskID(): string |
| 58 | + { |
| 59 | + if ($this->encodedTaskID === null) { |
| 60 | + $this->encodedTaskID = base64_encode($this->taskID); |
| 61 | + } |
| 62 | + return $this->encodedTaskID; |
| 63 | + } |
| 64 | + |
| 65 | + /** |
| 66 | + * Checks and returns whether the AsyncTask is still running. |
| 67 | + * |
| 68 | + * On Windows, this may take some time due to underlying bottlenecks. |
| 69 | + * |
| 70 | + * Note: when this method detects that the task has stopped running, it will not recheck whether the task has restarted. |
| 71 | + * Use a fresh status object to track the (restarted) task. |
| 72 | + * @return bool If true, indicates the task is still running. |
| 73 | + */ |
| 74 | + public function isRunning(): bool |
| 75 | + { |
| 76 | + if ($this->isStopped) { |
| 77 | + return false; |
| 78 | + } |
| 79 | + // prove it is running |
| 80 | + $isRunning = $this->proveTaskIsRunning(); |
| 81 | + if (!$isRunning) { |
| 82 | + $this->isStopped = true; |
| 83 | + } |
| 84 | + return $isRunning; |
| 85 | + } |
| 86 | + |
| 87 | + /** |
| 88 | + * Attempts to prove whether the AsyncTask is still running |
| 89 | + * @return bool If false, then the task is shown to have been stopped. |
| 90 | + */ |
| 91 | + private function proveTaskIsRunning(): bool |
| 92 | + { |
| 93 | + if ($this->lastKnownPID === null) { |
| 94 | + // we don't know where the task runner is at; find it! |
| 95 | + return $this->findTaskRunnerProcess(); |
| 96 | + } |
| 97 | + // we know the task runner; is it still running? |
| 98 | + return $this->observeTaskRunnerProcess(); |
| 99 | + } |
| 100 | + |
| 101 | + /** |
| 102 | + * Attempts to find the task runner process (if exists), and writes down its PID. |
| 103 | + * @return bool If true, then the task runner is successfully found. |
| 104 | + */ |
| 105 | + private function findTaskRunnerProcess(): bool |
| 106 | + { |
| 107 | + // find the runner in the system |
| 108 | + // we might have multiple PIDs; in this case, pick the first one that appears |
| 109 | + /* |
| 110 | + * note: while the OS may allow reading multiple properties at the same time, |
| 111 | + * we won't risk it because localizations might produce unexpected strings or unusual separators |
| 112 | + * an example would be CJK potentially having an alternate character to replace ":" |
| 113 | + */ |
| 114 | + if (OsInfo::isWindows()) { |
| 115 | + // Windows uses GCIM to discover processes |
| 116 | + $results = []; |
| 117 | + $encodedTaskID = $this->getEncodedTaskID(); |
| 118 | + $expectedCmdName = "artisan async:run"; |
| 119 | + // we can assume we are in cmd, but wcim in cmd is deprecated, and the replacement gcim requires powershell |
| 120 | + $results = []; |
| 121 | + $fullCmd = "powershell echo \"\"(gcim Win32_Process -Filter \\\"CommandLine LIKE '%id=\'$encodedTaskID\'%'\\\").ProcessId\"\""; |
| 122 | + \Illuminate\Support\Facades\Log::info($fullCmd); |
| 123 | + exec("powershell echo \"\"(gcim Win32_Process -Filter \\\"CommandLine LIKE '%id=\'$encodedTaskID\'%'\\\").ProcessId\"\"", $results); |
| 124 | + // will output many lines, each line being a PID |
| 125 | + foreach ($results as $candidatePID) { |
| 126 | + $candidatePID = (int) $candidatePID; |
| 127 | + // then use gcim again to see the cmd args |
| 128 | + $cmdArgs = exec("powershell echo \"\"(gcim Win32_Process -Filter \\\"ProcessId = $candidatePID\\\").CommandLine\"\""); |
| 129 | + if ($cmdArgs === false) { |
| 130 | + throw new RuntimeException(self::MSG_CANNOT_CHECK_STATUS); |
| 131 | + } |
| 132 | + if (!str_contains($cmdArgs, $expectedCmdName)) { |
| 133 | + // not really |
| 134 | + continue; |
| 135 | + } |
| 136 | + $executable = exec("powershell echo \"\"(gcim Win32_Process -Filter \\\"ProcessId = $candidatePID\\\").Name\"\""); |
| 137 | + if ($executable === false) { |
| 138 | + throw new RuntimeException(self::MSG_CANNOT_CHECK_STATUS); |
| 139 | + } |
| 140 | + if ($executable !== "php.exe") { |
| 141 | + // not really |
| 142 | + // note: we currently hard-code "php" as the executable name |
| 143 | + continue; |
| 144 | + } |
| 145 | + // all checks passed; it is this one |
| 146 | + $this->lastKnownPID = $candidatePID; |
| 147 | + return true; |
| 148 | + } |
| 149 | + return false; |
| 150 | + } |
| 151 | + // assume anything not Windows to be Unix |
| 152 | + // find the runner on Unix systems via pgrep |
| 153 | + $results = []; |
| 154 | + $encodedTaskID = $this->getEncodedTaskID(); |
| 155 | + exec("pgrep -f id='$encodedTaskID'", $results); |
| 156 | + // we may find multiple records here if we are using timeouts |
| 157 | + // this is because there will be one parent timeout process and another actual child artisan process |
| 158 | + // we want the child artisan process |
| 159 | + $expectedCmdName = "artisan async:run"; |
| 160 | + foreach ($results as $candidatePID) { |
| 161 | + $candidatePID = (int) $candidatePID; |
| 162 | + // then use ps to see what really is it |
| 163 | + $fullCmd = exec("ps -p $candidatePID -o args="); |
| 164 | + if ($fullCmd === false) { |
| 165 | + throw new RuntimeException(self::MSG_CANNOT_CHECK_STATUS); |
| 166 | + } |
| 167 | + if (!str_contains($fullCmd, $expectedCmdName)) { |
| 168 | + // not really |
| 169 | + continue; |
| 170 | + } |
| 171 | + $executable = exec("ps -p $candidatePID -o comm="); |
| 172 | + if ($executable === false) { |
| 173 | + throw new RuntimeException(self::MSG_CANNOT_CHECK_STATUS); |
| 174 | + } |
| 175 | + if ($executable !== "php") { |
| 176 | + // not really |
| 177 | + // note: we currently hard-code "php" as the executable name |
| 178 | + continue; |
| 179 | + } |
| 180 | + // this is it! |
| 181 | + $this->lastKnownPID = $candidatePID; |
| 182 | + return true; |
| 183 | + } |
| 184 | + return false; |
| 185 | + } |
| 186 | + |
| 187 | + /** |
| 188 | + * Given a previously-noted PID of the task runner, see if the task runner is still alive. |
| 189 | + * @return bool If true, then the task runner is still running. |
| 190 | + */ |
| 191 | + private function observeTaskRunnerProcess(): bool |
| 192 | + { |
| 193 | + // since we should have remembered the PID, we can just query whether it still exists |
| 194 | + // supposedly, the PID has not rolled over yet, right...? |
| 195 | + if (OsInfo::isWindows()) { |
| 196 | + // Windows can also use Get-Process to probe processes |
| 197 | + $echoedPid = exec("powershell (Get-Process -id {$this->lastKnownPID}).Id"); |
| 198 | + if ($echoedPid === false) { |
| 199 | + throw new RuntimeException(self::MSG_CANNOT_CHECK_STATUS); |
| 200 | + } |
| 201 | + $echoedPid = (int) $echoedPid; |
| 202 | + return $this->lastKnownPID === $echoedPid; |
| 203 | + } |
| 204 | + // assume anything not Windows to be Unix |
| 205 | + $echoedPid = exec("ps -p {$this->lastKnownPID} -o pid="); |
| 206 | + if ($echoedPid === false) { |
| 207 | + throw new RuntimeException(self::MSG_CANNOT_CHECK_STATUS); |
| 208 | + } |
| 209 | + $echoedPid = (int) $echoedPid; |
| 210 | + return $this->lastKnownPID === $echoedPid; |
| 211 | + } |
| 212 | +} |
0 commit comments