1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Umbrellio\TableSync\Integration\Laravel\Console\Commands; |
6
|
|
|
|
7
|
|
|
use Safe; |
8
|
|
|
use Umbrellio\TableSync\Integration\Laravel\Console\ProcessManagerCommand; |
9
|
|
|
use Umbrellio\TableSync\Integration\Laravel\Exceptions\CannotTerminateWorker; |
10
|
|
|
|
11
|
|
|
class TerminateCommand extends ProcessManagerCommand |
12
|
|
|
{ |
13
|
|
|
private const WAIT_WORKER_TIMEOUT = 5; |
14
|
|
|
|
15
|
|
|
protected $signature = 'table_sync:terminate {--force}'; |
16
|
|
|
protected $description = 'Terminate table_sync worker.'; |
17
|
|
|
|
18
|
|
|
public function handle(): void |
19
|
|
|
{ |
20
|
|
|
if (!$this->pidManager->pidExists()) { |
21
|
|
|
$this->error('Table sync worker pid not found.'); |
22
|
|
|
return; |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
$pid = $this->pidManager->readPid(); |
26
|
|
|
|
27
|
|
|
if ($this->option('force')) { |
28
|
|
|
$this->killProcess($pid); |
29
|
|
|
$this->pidManager->removePid(); |
30
|
|
|
return; |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
$this->terminateProcess($pid); |
34
|
|
|
$this->waitUntilWorkerTerminate(); |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
private function killProcess(int $pid): void |
38
|
|
|
{ |
39
|
|
|
Safe\posix_kill($pid, SIGKILL); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
private function terminateProcess(int $pid): void |
43
|
|
|
{ |
44
|
|
|
Safe\posix_kill($pid, SIGTERM); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
private function waitUntilWorkerTerminate(): void |
48
|
|
|
{ |
49
|
|
|
$i = 0; |
50
|
|
|
while ($this->pidManager->pidExists()) { |
51
|
|
|
Safe\sleep(1); |
52
|
|
|
$this->checkTimeout(++$i); |
53
|
|
|
} |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
private function checkTimeout(int $secondsSpent): void |
57
|
|
|
{ |
58
|
|
|
if ($secondsSpent >= self::WAIT_WORKER_TIMEOUT) { |
59
|
|
|
throw new CannotTerminateWorker('Exceeded worker termination timeout'); |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|