-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathSubprocessProcessor.php
More file actions
283 lines (245 loc) · 9.31 KB
/
SubprocessProcessor.php
File metadata and controls
283 lines (245 loc) · 9.31 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
<?php
declare(strict_types=1);
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org/)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org/)
* @link https://cakephp.org CakePHP(tm) Project
* @since 2.2.0
* @license https://opensource.org/licenses/MIT MIT License
*/
namespace Cake\Queue\Queue;
use Cake\Core\ContainerInterface;
use Cake\Queue\Job\Message;
use Interop\Queue\Message as QueueMessage;
use Psr\Log\LoggerInterface;
use RuntimeException;
/**
* Subprocess processor that executes jobs in isolated PHP processes.
*
* This processor spawns a new PHP process for each job, providing complete isolation
* between jobs. This is useful for development environments where code changes need
* to be reloaded without restarting the worker.
*
* Configuration options:
* - `command`: Full command to execute (default: 'php bin/cake.php queue subprocess_runner')
* - `timeout`: Maximum execution time in seconds (default: 300)
* - `maxOutputSize`: Maximum output size in bytes (default: 1048576 = 1MB)
*
* Example configuration:
* ```
* 'Queue' => [
* 'default' => [
* 'subprocess' => [
* 'command' => 'php bin/cake.php queue subprocess_runner',
* 'timeout' => 60,
* 'maxOutputSize' => 2097152, // 2MB
* ],
* ],
* ],
* ```
*
* Extends Processor to reuse event handling and processing logic (DRY principle).
*/
class SubprocessProcessor extends Processor
{
/**
* @param \Psr\Log\LoggerInterface $logger Logger instance
* @param array<string, mixed> $config Subprocess configuration options
* @param \Cake\Core\ContainerInterface|null $container DI container instance
*/
public function __construct(
LoggerInterface $logger,
protected readonly array $config = [],
?ContainerInterface $container = null,
) {
parent::__construct($logger, $container);
}
/**
* Execute the job in a subprocess.
*
* @param \Cake\Queue\Job\Message $jobMessage Job message wrapper
* @param \Interop\Queue\Message $queueMessage Original queue message
* @return object|string with __toString method implemented
*/
protected function executeJob(Message $jobMessage, QueueMessage $queueMessage): string|object
{
$jobData = $this->prepareJobData($queueMessage);
$subprocessResult = $this->executeInSubprocess($jobData);
return $this->handleSubprocessResult($subprocessResult, $queueMessage);
}
/**
* Handle subprocess result and return appropriate response.
*
* @param array<string, mixed> $result Subprocess result
* @param \Interop\Queue\Message $message Original message
* @return string
* @throws \RuntimeException
*/
protected function handleSubprocessResult(array $result, QueueMessage $message): string
{
if ($result['success']) {
return $result['result'];
}
if (isset($result['exception'])) {
$exception = $this->reconstructException($result['exception']);
$message->setProperty('jobException', $exception);
throw $exception;
}
throw new RuntimeException($result['error'] ?? 'Subprocess execution failed');
}
/**
* Prepare job data for subprocess execution.
*
* @param \Interop\Queue\Message $message Message
* @return array<string, mixed>
*/
protected function prepareJobData(QueueMessage $message): array
{
$body = json_decode($message->getBody(), true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new RuntimeException('Invalid JSON in message body');
}
$properties = $message->getProperties();
return [
'messageClass' => get_class($message),
'body' => $body,
'properties' => $properties,
'logger' => $this->config['logger'] ?? 'stderr',
];
}
/**
* Execute job in subprocess.
*
* @param array<string, mixed> $jobData Job data
* @return array<string, mixed>
*/
protected function executeInSubprocess(array $jobData): array
{
$command = $this->config['command'] ?? 'php bin/cake.php queue subprocess_runner';
$timeout = $this->config['timeout'] ?? 300;
$descriptors = [
0 => ['pipe', 'r'],
1 => ['pipe', 'w'],
2 => ['pipe', 'w'],
];
$process = proc_open($command, $descriptors, $pipes);
if (!is_resource($process)) {
throw new RuntimeException('Failed to create subprocess');
}
try {
$jobDataJson = json_encode($jobData);
if ($jobDataJson !== false) {
fwrite($pipes[0], $jobDataJson);
}
fclose($pipes[0]);
$output = '';
$errorOutput = '';
$startTime = time();
$maxOutputSize = $this->config['maxOutputSize'] ?? 1048576; // 1MB default
stream_set_blocking($pipes[1], false);
stream_set_blocking($pipes[2], false);
while (true) {
if ($timeout > 0 && (time() - $startTime) > $timeout) {
proc_terminate($process, 9);
return [
'success' => false,
'error' => sprintf('Subprocess execution timeout after %d seconds', $timeout),
];
}
$read = [$pipes[1], $pipes[2]];
$write = null;
$except = null;
$selectResult = stream_select($read, $write, $except, 1);
if ($selectResult === false) {
return [
'success' => false,
'error' => 'Stream select failed',
];
}
if (in_array($pipes[1], $read)) {
$chunk = fread($pipes[1], 8192);
if ($chunk !== false) {
if (strlen($output) + strlen($chunk) > $maxOutputSize) {
proc_terminate($process, 9);
return [
'success' => false,
'error' => sprintf('Subprocess output exceeded maximum size of %d bytes', $maxOutputSize),
];
}
$output .= $chunk;
}
}
if (in_array($pipes[2], $read)) {
$chunk = fread($pipes[2], 8192);
if ($chunk !== false) {
if (strlen($errorOutput) + strlen($chunk) > $maxOutputSize) {
proc_terminate($process, 9);
return [
'success' => false,
'error' => sprintf(
'Subprocess error output exceeded maximum size of %d bytes',
$maxOutputSize,
),
];
}
$errorOutput .= $chunk;
// Stream subprocess logs to parent's stderr in real-time
// Skip in PHPUnit test context to avoid test framework issues
if (!defined('PHPUNIT_COMPOSER_INSTALL') && !defined('__PHPUNIT_PHAR__')) {
fwrite(STDERR, $chunk);
}
}
}
if (feof($pipes[1]) && feof($pipes[2])) {
break;
}
}
} finally {
// Always cleanup resources
if (is_resource($pipes[1])) {
fclose($pipes[1]);
}
if (is_resource($pipes[2])) {
fclose($pipes[2]);
}
}
$exitCode = proc_close($process);
if ($exitCode !== 0 && empty($output)) {
return [
'success' => false,
'error' => sprintf('Subprocess exited with code %d. Error: %s', $exitCode, $errorOutput),
];
}
$result = json_decode($output, true);
if (json_last_error() !== JSON_ERROR_NONE) {
return [
'success' => false,
'error' => 'Invalid JSON output from subprocess: ' . $output,
];
}
return $result;
}
/**
* Reconstruct exception from array data.
*
* @param array<string, mixed> $exceptionData Exception data
* @return \RuntimeException
*/
protected function reconstructException(array $exceptionData): RuntimeException
{
$message = sprintf(
'%s: %s in %s:%d',
$exceptionData['class'] ?? 'Exception',
$exceptionData['message'] ?? 'Unknown error',
$exceptionData['file'] ?? 'unknown',
$exceptionData['line'] ?? 0,
);
return new RuntimeException($message, (int)($exceptionData['code'] ?? 0));
}
}