forked from php-pm/php-pm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRequestHandler.php
More file actions
424 lines (361 loc) · 13.4 KB
/
RequestHandler.php
File metadata and controls
424 lines (361 loc) · 13.4 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
415
416
417
418
419
420
421
422
423
424
<?php
namespace PHPPM;
use React\EventLoop\LoopInterface;
use React\EventLoop\TimerInterface;
use React\Socket\UnixConnector;
use React\Socket\TimeoutConnector;
use React\Socket\ConnectionInterface;
use Symfony\Component\Console\Output\OutputInterface;
class RequestHandler
{
use ProcessCommunicationTrait;
/**
* @var float
*/
protected $start;
/**
* @var float
*/
protected $requestSentAt;
/**
* @var ConnectionInterface
*/
private $incoming;
/**
* @var ConnectionInterface|null
*/
private $connection;
/**
* @var LoopInterface
*/
private $loop;
/**
* @var OutputInterface
*/
private $output;
/**
* @var SlavePool
*/
private $slaves;
/**
* Timeout in seconds for master to worker connection.
*
* @var int
*/
private $timeout = 10;
/**
* Max amount of time a script is allowed to run in the worker before closing.
*
* @var int
*/
private $maxExecutionTime;
/**
* Timer that handles stopping the worker if script has excceed the max execution time
*
* @var TimerInterface|null
*/
private $maxExecutionTimer;
/**
* @var Slave|null instance
*/
private $slave;
private $redirectionTries = 0;
private $incomingBuffer = '';
private $lastOutgoingData = ''; // Used to track abnormal responses
public function __construct($socketPath, LoopInterface $loop, OutputInterface $output, SlavePool $slaves, $maxExecutionTime)
{
$this->setSocketPath($socketPath);
$this->loop = $loop;
$this->output = $output;
$this->slaves = $slaves;
$this->maxExecutionTime = $maxExecutionTime;
}
/**
* Handle incoming client connection
*
* @param ConnectionInterface $incoming
*/
public function handle(ConnectionInterface $incoming)
{
$this->incoming = $incoming;
$this->incoming->on('data', [$this, 'handleData']);
$this->start = \microtime(true);
$this->requestSentAt = \microtime(true);
$this->getNextSlave();
if ($this->maxExecutionTime > 0) {
$this->maxExecutionTimer = $this->loop->addTimer($this->maxExecutionTime, [$this, 'maxExecutionTimeExceeded']);
}
}
/**
* Buffer incoming data until slave connection is available
* and headers have been received
*
* @param string $data
*/
public function handleData($data)
{
$this->incomingBuffer .= $data;
if ($this->connection && $this->isHeaderEnd($this->incomingBuffer)) {
$remoteAddress = (string) $this->incoming->getRemoteAddress();
$headersToReplace = [
'X-PHP-PM-Remote-IP' => \trim(\parse_url($remoteAddress, PHP_URL_HOST), '[]'),
'X-PHP-PM-Remote-Port' => \trim(\parse_url($remoteAddress, PHP_URL_PORT), '[]'),
'Connection' => 'close'
];
$buffer = $this->replaceHeader($this->incomingBuffer, $headersToReplace);
$this->connection->write($buffer);
$this->incoming->removeListener('data', [$this, 'handleData']);
$this->incoming->pipe($this->connection);
}
}
/**
* Get next free slave from pool
* Asynchronously keep trying until slave becomes available
*/
public function getNextSlave()
{
// client went away while waiting for worker
if (!$this->incoming->isWritable()) {
return;
}
$available = $this->slaves->getByStatus(Slave::READY);
if (\count($available)) {
// pick first slave
$slave = \array_shift($available);
// slave available -> connect
if ($this->tryOccupySlave($slave)) {
return;
}
}
// keep retrying until slave becomes available, unless timeout has been exceeded
if (\time() < ($this->requestSentAt + $this->timeout)) {
// add a small delay to avoid busy waiting
$this->loop->addTimer(.01, [$this, 'getNextSlave']);
} else {
// Return a "503 Service Unavailable" response
$this->output->writeln(\sprintf('No worker processes available to handle the request and timeout %d seconds exceeded', $this->timeout));
$this->incoming->write($this->createErrorResponse('503 Service Temporarily Unavailable', 'Service Temporarily Unavailable'));
$this->incoming->end();
}
}
private function createErrorResponse($code, $text)
{
return \sprintf(
'HTTP/1.1 %s'."\n".
'Date: %s'."\n".
'Content-Type: text/plain'."\n".
'Content-Length: %s'."\n".
"\n".
'%s',
$code,
\gmdate('D, d M Y H:i:s T'),
\strlen($text),
$text
);
}
/**
* Slave available handler
*
* @param Slave $slave available slave instance
* @return bool Slave is available
*/
public function tryOccupySlave(Slave $slave)
{
if ($slave->isExpired()) {
$slave->close();
$this->output->writeln(\sprintf('Restart worker #%d because it reached its TTL', $slave->getPort()));
$slave->getConnection()->close();
return false;
}
$this->redirectionTries++;
$this->slave = $slave;
$this->verboseTimer(function ($took) {
return \sprintf('<info>took abnormal %.3f seconds for choosing next free worker</info>', $took);
});
// mark slave as busy
$this->slave->occupy();
$connector = new UnixConnector($this->loop);
$connector = new TimeoutConnector($connector, $this->timeout, $this->loop);
$socketPath = $this->getSlaveSocketPath($this->slave->getPort());
$connector->connect($socketPath)->then(
[$this, 'slaveConnected'],
[$this, 'slaveConnectFailed']
);
return true;
}
/**
* Handle successful slave connection
*
* @param ConnectionInterface $connection Slave connection
*/
public function slaveConnected(ConnectionInterface $connection)
{
$this->connection = $connection;
$this->verboseTimer(function ($took) {
return \sprintf('<info>Took abnormal %.3f seconds for connecting to worker %d</info>', $took, $this->slave->getPort());
});
// call handler once in case entire request as already been buffered
$this->handleData('');
// close slave connection when client goes away
$this->incoming->on('close', [$this->connection, 'close']);
// update slave availability
$this->connection->on('close', [$this, 'slaveClosed']);
// keep track of the last sent data to detect if slave exited abnormally
$this->connection->on('data', function ($data) {
$this->lastOutgoingData = $data;
});
// relay data to client
$this->connection->pipe($this->incoming, ['end' => false]);
}
/**
* Stop the worker if the max execution time has been exceeded and return 504
*/
public function maxExecutionTimeExceeded()
{
// client went away while waiting for worker
if (!$this->incoming->isWritable()) {
return false;
}
$this->incoming->write($this->createErrorResponse('504 Gateway Timeout', 'Maximum execution time exceeded'));
$this->lastOutgoingData = 'not empty'; // Avoid triggering 502
$this->output->writeln(\sprintf('Maximum execution time of %d seconds exceeded. Closing worker.', $this->maxExecutionTime));
// mark slave as closed
if ($this->slave) {
$this->slave->close();
$this->slave->getConnection()->close();
}
}
/**
* Handle slave disconnected
*
* Typically called after slave has finished handling request
*/
public function slaveClosed()
{
$this->verboseTimer(function ($took) {
return \sprintf('<info>Worker %d took abnormal %.3f seconds for handling a connection</info>', $this->slave->getPort(), $took);
});
//Don't send anything if the client already closed the connection
if ($this->incoming->isWritable()) {
// Return a "502 Bad Gateway" response if the response was empty
if ($this->lastOutgoingData == '') {
$this->output->writeln('Script did not return a valid HTTP response. Maybe it has called exit() prematurely?');
$this->incoming->write($this->createErrorResponse('502 Bad Gateway', 'Slave returned an invalid HTTP response. Maybe the script has called exit() prematurely?'));
}
$this->incoming->end();
}
if ($this->maxExecutionTime > 0) {
$this->loop->cancelTimer($this->maxExecutionTimer);
//Explicitly null the property to avoid a cyclic memory reference
$this->maxExecutionTimer = null;
}
if ($this->slave->getStatus() === Slave::LOCKED) {
// slave was locked, so mark as closed now.
$this->slave->close();
$this->output->writeln(\sprintf('Marking locked worker #%d as closed', $this->slave->getPort()));
$this->slave->getConnection()->close();
} elseif ($this->slave->getStatus() !== Slave::CLOSED) {
// if slave has already closed its connection to master,
// it probably died and is already terminated
// mark slave as available
$this->slave->release();
/** @var ConnectionInterface $connection */
$connection = $this->slave->getConnection();
$maxRequests = $this->slave->getMaxRequests();
if ($this->slave->getHandledRequests() >= $maxRequests) {
$this->slave->close();
$this->output->writeln(\sprintf('Restart worker #%d because it reached max requests of %d', $this->slave->getPort(), $maxRequests));
$connection->close();
}
// Enforce memory limit
$memoryLimit = $this->slave->getMemoryLimit();
if ($memoryLimit > 0 && $this->slave->getUsedMemory() >= $memoryLimit) {
$this->slave->close();
$this->output->writeln(\sprintf('Restart worker #%d because it reached memory limit of %d', $this->slave->getPort(), $memoryLimit));
$connection->close();
}
}
}
/**
* Handle failed slave connection
*
* Connection may fail because of timeouts or crashed or dying worker.
* Since the worker may only very busy or dying it's put back into the
* available worker list. If it is really dying it will be removed from the
* worker list by the connection:close event.
*
* @param \Exception $e slave connection error
*/
public function slaveConnectFailed(\Exception $e)
{
$this->slave->release();
$this->verboseTimer(function ($took) use ($e) {
return \sprintf(
'<error>Connection to worker %d failed. Try #%d, took %.3fs ' .
'(timeout %ds). Error message: [%d] %s</error>',
$this->slave->getPort(),
$this->redirectionTries,
$took,
$this->timeout,
$e->getCode(),
$e->getMessage()
);
}, true);
// should not get any more access to this slave instance
$this->slave = null;
// try next free slave, let loop schedule it (stack friendly)
// after 10th retry add 10ms delay, keep increasing until timeout
$delay = \min($this->timeout, \floor($this->redirectionTries / 10) / 100);
$this->loop->addTimer($delay, [$this, 'getNextSlave']);
}
/**
* Section timer. Measure execution time hand output if verbose mode.
*
* @param callable $callback
* @param bool $always Invoke callback regardless of execution time
*/
protected function verboseTimer($callback, $always = false)
{
$took = \microtime(true) - $this->start;
if (($always || $took > 1) && $this->output->isVeryVerbose()) {
$message = $callback($took);
$this->output->writeln($message);
}
$this->start = \microtime(true);
}
/**
* Checks whether the end of the header is in $buffer.
*
* @param string $buffer
*
* @return bool
*/
protected function isHeaderEnd($buffer)
{
return false !== \strpos($buffer, "\r\n\r\n");
}
/**
* Replaces or injects header
*
* @param string $header
* @param string[] $headersToReplace
*
* @return string
*/
protected function replaceHeader($header, $headersToReplace)
{
$result = $header;
foreach ($headersToReplace as $key => $value) {
if (false !== $headerPosition = \stripos($result, $key . ':')) {
// check how long the header is
$length = \strpos(\substr($header, $headerPosition), "\r\n");
$result = \substr_replace($result, "$key: $value", $headerPosition, $length);
} else {
// $key is not in header yet, add it at the end
$end = \strpos($result, "\r\n\r\n");
$result = \substr_replace($result, "\r\n$key: $value", $end, 0);
}
}
return $result;
}
}