-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathSignalTrait.php
More file actions
414 lines (362 loc) · 12.8 KB
/
SignalTrait.php
File metadata and controls
414 lines (362 loc) · 12.8 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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
<?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter Queue.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Queue\Compatibility;
use Closure;
use CodeIgniter\CLI\CLI;
if (trait_exists('CodeIgniter\CLI\SignalTrait')) {
trait SignalTrait
{
use \CodeIgniter\CLI\SignalTrait;
}
} else {
/**
* Signal Trait
*
* Provides PCNTL signal handling capabilities for CLI commands.
* Requires the PCNTL extension (Unix only).
*
* Bundled compatibility version for CI4 < 4.7
*/
trait SignalTrait
{
/**
* Whether the process should continue running (false = termination requested).
*/
private bool $running = true;
/**
* Whether signals are currently blocked.
*/
private bool $signalsBlocked = false;
/**
* Array of registered signals.
*
* @var list<int>
*/
private array $registeredSignals = [];
/**
* Signal-to-method mapping.
*
* @var array<int, string>
*/
private array $signalMethodMap = [];
/**
* Cached result of PCNTL extension availability.
*/
private static ?bool $isPcntlAvailable = null;
/**
* Cached result of POSIX extension availability.
*/
private static ?bool $isPosixAvailable = null;
/**
* Check if PCNTL extension is available (cached).
*/
protected function isPcntlAvailable(): bool
{
if (self::$isPcntlAvailable === null) {
if (is_windows()) {
self::$isPcntlAvailable = false;
} else {
self::$isPcntlAvailable = extension_loaded('pcntl');
if (! self::$isPcntlAvailable) {
CLI::write('PCNTL extension is not available. Signal handling will be disabled.', 'yellow');
}
}
}
return self::$isPcntlAvailable;
}
/**
* Check if POSIX extension is available (cached).
*/
protected function isPosixAvailable(): bool
{
if (self::$isPosixAvailable === null) {
self::$isPosixAvailable = is_windows() ? false : extension_loaded('posix');
}
return self::$isPosixAvailable;
}
/**
* Register signal handlers.
*
* @param list<int> $signals List of signals to handle
* @param array<int, string> $methodMap Optional signal-to-method mapping
*/
protected function registerSignals(
array $signals = [],
array $methodMap = [],
): void {
if (! $this->isPcntlAvailable()) {
return;
}
if ($signals === []) {
$signals = [SIGTERM, SIGINT, SIGHUP, SIGQUIT];
}
if (! $this->isPosixAvailable() && (in_array(SIGTSTP, $signals, true) || in_array(SIGCONT, $signals, true))) {
CLI::write('POSIX extension is not available. SIGTSTP and SIGCONT signals will be disabled.', 'yellow');
$signals = array_diff($signals, [SIGTSTP, SIGCONT]);
// Remove from method map as well
unset($methodMap[SIGTSTP], $methodMap[SIGCONT]);
if ($signals === []) {
return;
}
}
// Enable async signals for immediate response
pcntl_async_signals(true);
$this->signalMethodMap = $methodMap;
foreach ($signals as $signal) {
if (pcntl_signal($signal, [$this, 'handleSignal'])) {
$this->registeredSignals[] = $signal;
} else {
$signal = $this->getSignalName($signal);
CLI::write("Failed to register signal handler for {$signal}.", 'red');
}
}
}
/**
* Handle incoming signals.
*/
protected function handleSignal(int $signal): void
{
$this->callCustomHandler($signal);
// Apply standard Unix signal behavior for registered signals
switch ($signal) {
case SIGTERM:
case SIGINT:
case SIGQUIT:
case SIGHUP:
$this->running = false;
break;
case SIGTSTP:
// Restore default handler and re-send signal to actually suspend
pcntl_signal(SIGTSTP, SIG_DFL);
posix_kill(posix_getpid(), SIGTSTP);
break;
case SIGCONT:
// Re-register SIGTSTP handler after resume
pcntl_signal(SIGTSTP, [$this, 'handleSignal']);
break;
}
}
/**
* Call custom signal handler if one is mapped for this signal.
* Falls back to generic onInterruption() method if no explicit mapping exists.
*/
private function callCustomHandler(int $signal): void
{
// Check for explicit mapping first
$method = $this->signalMethodMap[$signal] ?? null;
if ($method !== null && method_exists($this, $method)) {
$this->{$method}($signal);
return;
}
// If no explicit mapping, try generic catch-all method
if (method_exists($this, 'onInterruption')) { // @phpstan-ignore-line
$this->onInterruption($signal);
}
}
/**
* Check if command should terminate.
*/
protected function shouldTerminate(): bool
{
return ! $this->running;
}
/**
* Check if the process is currently running (not terminated).
*/
protected function isRunning(): bool
{
return $this->running;
}
/**
* Request immediate termination.
*/
protected function requestTermination(): void
{
$this->running = false;
}
/**
* Reset all states (for testing or restart scenarios).
*/
protected function resetState(): void
{
$this->running = true;
// Unblock signals if they were blocked
if ($this->signalsBlocked) {
$this->unblockSignals();
}
}
/**
* Execute a callable with ALL signals blocked to prevent ANY interruption during critical operations.
*
* This blocks ALL interruptible signals including:
* - Termination signals (SIGTERM, SIGINT, etc.)
* - Pause/resume signals (SIGTSTP, SIGCONT)
* - Custom signals (SIGUSR1, SIGUSR2)
*
* Only SIGKILL (unblockable) can still terminate the process.
* Use this for database transactions, file operations, or any critical atomic operations.
*
* @template TReturn
*
* @param Closure():TReturn $operation
*
* @return TReturn
*/
protected function withSignalsBlocked(Closure $operation)
{
$this->blockSignals();
try {
return $operation();
} finally {
$this->unblockSignals();
}
}
/**
* Block ALL interruptible signals during critical sections.
* Only SIGKILL (unblockable) can terminate the process.
*/
protected function blockSignals(): void
{
if (! $this->signalsBlocked && $this->isPcntlAvailable()) {
// Block ALL signals that could interrupt critical operations
pcntl_sigprocmask(SIG_BLOCK, [
SIGTERM, SIGINT, SIGHUP, SIGQUIT, // Termination signals
SIGTSTP, SIGCONT, // Pause/resume signals
SIGUSR1, SIGUSR2, // Custom signals
SIGPIPE, SIGALRM, // Other common signals
]);
$this->signalsBlocked = true;
}
}
/**
* Unblock previously blocked signals.
*/
protected function unblockSignals(): void
{
if ($this->signalsBlocked && $this->isPcntlAvailable()) {
// Unblock the same signals we blocked
pcntl_sigprocmask(SIG_UNBLOCK, [
SIGTERM, SIGINT, SIGHUP, SIGQUIT, // Termination signals
SIGTSTP, SIGCONT, // Pause/resume signals
SIGUSR1, SIGUSR2, // Custom signals
SIGPIPE, SIGALRM, // Other common signals
]);
$this->signalsBlocked = false;
}
}
/**
* Check if signals are currently blocked.
*/
protected function signalsBlocked(): bool
{
return $this->signalsBlocked;
}
/**
* Add or update signal-to-method mapping at runtime.
*/
protected function mapSignal(int $signal, string $method): void
{
$this->signalMethodMap[$signal] = $method;
}
/**
* Get human-readable signal name.
*/
protected function getSignalName(int $signal): string
{
return match ($signal) {
SIGTERM => 'SIGTERM',
SIGINT => 'SIGINT',
SIGHUP => 'SIGHUP',
SIGQUIT => 'SIGQUIT',
SIGUSR1 => 'SIGUSR1',
SIGUSR2 => 'SIGUSR2',
SIGPIPE => 'SIGPIPE',
SIGALRM => 'SIGALRM',
SIGTSTP => 'SIGTSTP',
SIGCONT => 'SIGCONT',
default => "Signal {$signal}",
};
}
/**
* Unregister all signals (cleanup).
*/
protected function unregisterSignals(): void
{
if (! $this->isPcntlAvailable()) {
return;
}
foreach ($this->registeredSignals as $signal) {
pcntl_signal($signal, SIG_DFL);
}
$this->registeredSignals = [];
$this->signalMethodMap = [];
}
/**
* Check if signals are registered.
*/
protected function hasSignals(): bool
{
return $this->registeredSignals !== [];
}
/**
* Get list of registered signals.
*
* @return list<int>
*/
protected function getSignals(): array
{
return $this->registeredSignals;
}
/**
* Get comprehensive process state information.
*
* @return array{
* pid: int,
* running: bool,
* pcntl_available: bool,
* registered_signals: int,
* registered_signals_names: array<int, string>,
* signals_blocked: bool,
* explicit_mappings: int,
* memory_usage_mb: float,
* memory_peak_mb: float,
* session_id?: false|int,
* process_group?: false|int,
* has_controlling_terminal?: bool
* }
*/
protected function getProcessState(): array
{
$pid = getmypid();
$state = [
// Process identification
'pid' => $pid,
'running' => $this->running,
// Signal handling status
'pcntl_available' => $this->isPcntlAvailable(),
'registered_signals' => count($this->registeredSignals),
'registered_signals_names' => array_map([$this, 'getSignalName'], $this->registeredSignals),
'signals_blocked' => $this->signalsBlocked,
'explicit_mappings' => count($this->signalMethodMap),
// System resources
'memory_usage_mb' => round(memory_get_usage(true) / 1024 / 1024, 2),
'memory_peak_mb' => round(memory_get_peak_usage(true) / 1024 / 1024, 2),
];
// Add terminal control info if POSIX extension is available
if ($this->isPosixAvailable()) {
$state['session_id'] = posix_getsid($pid);
$state['process_group'] = posix_getpgid($pid);
$state['has_controlling_terminal'] = posix_isatty(STDIN);
}
return $state;
}
}
}