Repository navigation
Expand file tree
/
Copy pathSignalExtension.php
More file actions
114 lines (94 loc) · 2.7 KB
/
Copy pathSignalExtension.php
File metadata and controls
114 lines (94 loc) · 2.7 KB
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
<?php
namespace Enqueue\Consumption\Extension;
use Enqueue\Consumption\Context;
use Enqueue\Consumption\EmptyExtensionTrait;
use Enqueue\Consumption\Exception\LogicException;
use Enqueue\Consumption\ExtensionInterface;
use Psr\Log\LoggerInterface;
class SignalExtension implements ExtensionInterface
{
use EmptyExtensionTrait;
/**
* @var bool
*/
protected $interruptConsumption = false;
/**
* @var LoggerInterface
*/
protected $logger;
/**
* {@inheritdoc}
*/
public function onStart(Context $context)
{
if (false == extension_loaded('pcntl')) {
throw new LogicException('The pcntl extension is required in order to catch signals.');
}
pcntl_signal(SIGTERM, [$this, 'handleSignal']);
pcntl_signal(SIGQUIT, [$this, 'handleSignal']);
pcntl_signal(SIGINT, [$this, 'handleSignal']);
$this->interruptConsumption = false;
}
/**
* @param Context $context
*/
public function onBeforeReceive(Context $context)
{
$this->logger = $context->getLogger();
pcntl_signal_dispatch();
$this->interruptExecutionIfNeeded($context);
}
/**
* {@inheritdoc}
*/
public function onPreReceived(Context $context)
{
$this->interruptExecutionIfNeeded($context);
}
/**
* {@inheritdoc}
*/
public function onPostReceived(Context $context)
{
pcntl_signal_dispatch();
$this->interruptExecutionIfNeeded($context);
}
/**
* {@inheritdoc}
*/
public function onIdle(Context $context)
{
pcntl_signal_dispatch();
$this->interruptExecutionIfNeeded($context);
}
/**
* @param Context $context
*/
public function interruptExecutionIfNeeded(Context $context)
{
if (false == $context->isExecutionInterrupted() && $this->interruptConsumption) {
$this->logger->debug('[SignalExtension] Interrupt execution');
$context->setExecutionInterrupted($this->interruptConsumption);
$this->interruptConsumption = false;
}
}
/**
* @param int $signal
*/
public function handleSignal($signal)
{
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
$this->logger->debug('[SignalExtension] Interrupt consumption');
$this->interruptConsumption = true;
break;
default:
break;
}
}
}