-
Notifications
You must be signed in to change notification settings - Fork 437
/
SignalExtension.php
100 lines (81 loc) · 2.87 KB
/
SignalExtension.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
<?php
namespace Enqueue\Consumption\Extension;
use Enqueue\Consumption\Context\PostConsume;
use Enqueue\Consumption\Context\PostMessageReceived;
use Enqueue\Consumption\Context\PreConsume;
use Enqueue\Consumption\Context\Start;
use Enqueue\Consumption\Exception\LogicException;
use Enqueue\Consumption\PostConsumeExtensionInterface;
use Enqueue\Consumption\PostMessageReceivedExtensionInterface;
use Enqueue\Consumption\PreConsumeExtensionInterface;
use Enqueue\Consumption\StartExtensionInterface;
use Psr\Log\LoggerInterface;
class SignalExtension implements StartExtensionInterface, PreConsumeExtensionInterface, PostMessageReceivedExtensionInterface, PostConsumeExtensionInterface
{
/**
* @var bool
*/
protected $interruptConsumption = false;
/**
* @var LoggerInterface|null
*/
protected $logger;
public function onStart(Start $context): void
{
if (false == extension_loaded('pcntl')) {
throw new LogicException('The pcntl extension is required in order to catch signals.');
}
pcntl_async_signals(true);
pcntl_signal(SIGTERM, [$this, 'handleSignal']);
pcntl_signal(SIGQUIT, [$this, 'handleSignal']);
pcntl_signal(SIGINT, [$this, 'handleSignal']);
$this->logger = $context->getLogger();
$this->interruptConsumption = false;
}
public function onPreConsume(PreConsume $context): void
{
$this->logger = $context->getLogger();
if ($this->shouldBeStopped($context->getLogger())) {
$context->interruptExecution();
}
}
public function onPostMessageReceived(PostMessageReceived $context): void
{
if ($this->shouldBeStopped($context->getLogger())) {
$context->interruptExecution();
}
}
public function onPostConsume(PostConsume $context): void
{
if ($this->shouldBeStopped($context->getLogger())) {
$context->interruptExecution();
}
}
public function handleSignal(int $signal): void
{
if ($this->logger) {
$this->logger->debug(sprintf('[SignalExtension] Caught signal: %s', $signal));
}
switch ($signal) {
case SIGTERM: // 15 : supervisor default stop
case SIGQUIT: // 3 : kill -s QUIT
case SIGINT: // 2 : ctrl+c
if ($this->logger) {
$this->logger->debug('[SignalExtension] Interrupt consumption');
}
$this->interruptConsumption = true;
break;
default:
break;
}
}
private function shouldBeStopped(LoggerInterface $logger): bool
{
if ($this->interruptConsumption) {
$logger->debug('[SignalExtension] Interrupt execution');
$this->interruptConsumption = false;
return true;
}
return false;
}
}