forked from php-pm/php-pm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProcessManager.php
More file actions
697 lines (590 loc) · 18.5 KB
/
ProcessManager.php
File metadata and controls
697 lines (590 loc) · 18.5 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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
<?php
declare(ticks = 1);
namespace PHPPM;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Process\PhpExecutableFinder;
use Symfony\Component\Process\ProcessUtils;
class ProcessManager
{
/**
* @var array
*/
protected $slaves = [];
/**
* @var \React\EventLoop\LibEventLoop|\React\EventLoop\StreamSelectLoop
*/
protected $loop;
/**
* @var \React\Socket\Server
*/
protected $controller;
/**
* @var \React\Socket\Server
*/
protected $web;
/**
* @var \React\SocketClient\TcpConnector
*/
protected $tcpConnector;
/**
* @var int
*/
protected $slaveCount = 1;
/**
* @var bool
*/
protected $waitForSlaves = true;
/**
* Whether the server is up and thus creates new slaves when they die or not.
*
* @var bool
*/
protected $isRunning = false;
/**
* @var int
*/
protected $index = 0;
/**
* @var string
*/
protected $bridge;
/**
* @var string
*/
protected $appBootstrap;
/**
* @var string|null
*/
protected $appenv;
/**
* @var bool
*/
protected $debug = false;
/**
* @var bool
*/
protected $logging = true;
/**
* @var string
*/
protected $host = '127.0.0.1';
/**
* @var int
*/
protected $port = 8080;
/**
* Whether the server is in the reload phase.
*
* @var bool
*/
protected $inReload = false;
/**
* @var OutputInterface
*/
protected $output;
/**
* How many requests each worker is allowed to handle until it will be restarted.
*
* @var int
*/
protected $maxRequests = 1000;
protected $filesToTrack = [];
protected $filesLastMTime = [];
/**
* ProcessManager constructor.
*
* @param OutputInterface $output
* @param int $port
* @param string $host
* @param int $slaveCount
*/
function __construct(OutputInterface $output, $port = 8080, $host = '127.0.0.1', $slaveCount = 8)
{
$this->output = $output;
$this->slaveCount = $slaveCount;
$this->host = $host;
$this->port = $port;
register_shutdown_function([$this, 'signal']);
}
/**
* Handles termination signals, so we can gracefully stop all servers.
*/
public function signal()
{
//this method is also called during startup when something crashed, so
//make sure we don't operate on nulls.
$this->output->writeln('<info>Termination received, exiting.</info>');
if ($this->controller) {
@$this->controller->shutdown();
}
if ($this->web) {
@$this->web->shutdown();
}
if ($this->loop) {
$this->loop->tick();
$this->loop->stop();
}
foreach ($this->slaves as $slave) {
if (is_resource($slave['process'])) {
proc_terminate($slave['process']);
}
if ($slave['pid']) {
//make sure its dead
posix_kill($slave['pid'], SIGKILL);
}
}
exit;
}
/**
* @param int $maxRequests
*/
public function setMaxRequests($maxRequests)
{
$this->maxRequests = $maxRequests;
}
/**
* @param string $bridge
*/
public function setBridge($bridge)
{
$this->bridge = $bridge;
}
/**
* @return string
*/
public function getBridge()
{
return $this->bridge;
}
/**
* @param string $appBootstrap
*/
public function setAppBootstrap($appBootstrap)
{
$this->appBootstrap = $appBootstrap;
}
/**
* @return string
*/
public function getAppBootstrap()
{
return $this->appBootstrap;
}
/**
* @param string|null $appenv
*/
public function setAppEnv($appenv)
{
$this->appenv = $appenv;
}
/**
* @return string
*/
public function getAppEnv()
{
return $this->appenv;
}
/**
* @return boolean
*/
public function isLogging()
{
return $this->logging;
}
/**
* @param boolean $logging
*/
public function setLogging($logging)
{
$this->logging = $logging;
}
/**
* @return boolean
*/
public function isDebug()
{
return $this->debug;
}
/**
* @param boolean $debug
*/
public function setDebug($debug)
{
$this->debug = $debug;
}
/**
* Starts the main loop. Blocks.
*
* @throws \React\Socket\ConnectionException
*/
public function run()
{
gc_disable(); //necessary, since connections will be dropped without reasons after several hundred connections.
$this->loop = \React\EventLoop\Factory::create();
$this->controller = new \React\Socket\Server($this->loop);
$this->controller->on('connection', array($this, 'onSlaveConnection'));
$this->controller->listen(5500);
$this->web = new \React\Socket\Server($this->loop);
$this->web->on('connection', array($this, 'onWeb'));
$this->web->listen($this->port, $this->host);
$this->tcpConnector = new \React\SocketClient\TcpConnector($this->loop);
$pcntl = new \MKraemer\ReactPCNTL\PCNTL($this->loop);
$pcntl->on(SIGTERM, [$this, 'signal']);
$pcntl->on(SIGINT, [$this, 'signal']);
$this->isRunning = true;
$loopClass = (new \ReflectionClass($this->loop))->getShortName();
$this->output->writeln("<info>Starting PHP-PM with {$this->slaveCount} workers, using {$loopClass} ...</info>");
for ($i = 0; $i < $this->slaveCount; $i++) {
$this->newInstance(5501 + $i);
}
$this->loop->run();
}
/**
* Handles incoming connections from $this->port. Basically redirects to a slave.
*
* @param \React\Socket\Connection $incoming incoming connection from react
*/
public function onWeb(\React\Socket\Connection $incoming)
{
if ($this->isDebug()) {
$this->checkChangedFiles();
}
// preload sent data from $incoming to $buffer, otherwise it would be lost,
// since getNextSlave is async.
$redirect = null;
$buffer = '';
$incoming->on(
'data',
function ($data) use (&$redirect, &$buffer) {
if (!$redirect) {
$buffer .= $data;
}
}
);
$this->getNextSlave(
function ($id) use ($incoming, &$buffer, &$redirect) {
$slave =& $this->slaves[$id];
$slave['busy'] = true;
$slave['connections']++;
$this->tcpConnector->create('127.0.0.1', $slave['port'])->then(
function (\React\Stream\Stream $stream) use (&$buffer, $redirect, $incoming, &$slave) {
$stream->write($buffer);
$stream->on(
'close',
function () use ($incoming, &$slave) {
$slave['busy'] = false;
$slave['connections']--;
$slave['requests']++;
$incoming->end();
if ($slave['requests'] > $this->maxRequests) {
$info['ready'] = false;
$slave['connection']->close();
}
if ($slave['closeWhenFree']) {
$slave['connection']->close();
}
}
);
$stream->on(
'data',
function ($data) use ($incoming) {
$incoming->write($data);
}
);
$incoming->on(
'data',
function ($data) use ($stream) {
$stream->write($data);
}
);
$incoming->on(
'close',
function () use ($stream) {
$stream->close();
}
);
}
);
}
);
}
/**
* Returns the next free slave. This method is async, so be aware of async calls between this call.
*
* @return integer
*/
protected function getNextSlave($cb)
{
$that = $this;
$checkSlave = function () use ($cb, $that, &$checkSlave) {
$minConnections = null;
$minPort = null;
foreach ($this->slaves as $slave) {
if (!$slave['ready']) {
continue;
}
// we pick a slave that currently handles the fewest connections
if (null === $minConnections || $slave['connections'] < $minConnections) {
$minConnections = $slave['connections'];
$minPort = $slave['port'];
}
}
if (null !== $minPort) {
$cb($minPort);
return;
}
$this->loop->futureTick($checkSlave);
};
$checkSlave();
}
/**
* Handles data communication from slave -> master
*
* @param \React\Socket\Connection $conn
*/
public function onSlaveConnection(\React\Socket\Connection $conn)
{
$buffer = '';
$conn->on(
'data',
\Closure::bind(
function ($data) use ($conn, &$buffer) {
$buffer .= $data;
if (substr($buffer, -1) === PHP_EOL) {
foreach (explode(PHP_EOL, $buffer) as $message) {
if ($message) {
$this->processMessage($message, $conn);
}
}
$buffer = '';
}
},
$this
)
);
$conn->on(
'close',
\Closure::bind(
function () use ($conn) {
foreach ($this->slaves as $id => $slave) {
if ($slave['connection'] === $conn) {
if ($this->output->isVerbose()) {
$this->output->writeln('Worker closed '.$slave['port']);
}
$slave['ready'] = false;
$slave['stdout']->close();
$slave['stderr']->close();
if (is_resource($slave['process'])) {
proc_terminate($slave['process'], SIGKILL);
}
posix_kill($slave['pid'], SIGKILL); //make sure its really dead
$this->newInstance($slave['port']);
return;
}
}
},
$this
)
);
}
/**
* A slave sent a message. Redirects to the appropriate `command*` method.
*
* @param array $data
* @param \React\Socket\Connection $conn
*
* @throws \Exception when invalid 'cmd' in $data.
*/
public function processMessage($data, \React\Socket\Connection $conn)
{
$array = json_decode($data, true);
$method = 'command' . ucfirst($array['cmd']);
if (is_callable(array($this, $method))) {
$this->$method($array, $conn);
} else {
echo($data);
throw new \Exception(sprintf('Command %s not found', $method));
}
}
/**
* A slave sent a `status` command.
*
* @param array $data
* @param \React\Socket\Connection $conn
*/
protected function commandStatus(array $data, \React\Socket\Connection $conn)
{
$conn->end(json_encode('todo'));
}
/**
* A slave sent a `register` command.
*
* @param array $data
* @param \React\Socket\Connection $conn
*/
protected function commandRegister(array $data, \React\Socket\Connection $conn)
{
$pid = (int)$data['pid'];
$port = (int)$data['port'];
if (!isset($this->slaves[$port]) || !$this->slaves[$port]['waitForRegister']) {
throw new \LogicException('A slaves wanted to register on master which was not expected. Emergency close. port='.$port);
}
if ($this->output->isVerbose()) {
$this->output->writeln('Worker registered '.$port);
}
$this->slaves[$port]['pid'] = $pid;
$this->slaves[$port]['connection'] = $conn;
$this->slaves[$port]['ready'] = true;
$this->slaves[$port]['waitForRegister'] = false;
if ($this->waitForSlaves && $this->slaveCount === count($this->slaves)) {
$this->waitForSlaves = false; // all slaves started
$this->output->writeln(
sprintf(
"%d slaves (starting at 5501) up and ready. Application is ready at http://%s:%s/",
$this->slaveCount,
$this->host,
$this->port
)
);
}
}
/**
* Prints logs.
*
* @Todo, integrate Monolog.
*
* @param array $data
* @param \React\Socket\Connection $conn
*/
protected function commandLog(array $data, \React\Socket\Connection $conn)
{
$this->output->writeln($data['message']);
}
/**
* @param array $data
* @param \React\Socket\Connection $conn
*/
protected function commandFiles(array $data, \React\Socket\Connection $conn)
{
$this->filesToTrack = array_unique(array_merge($this->filesToTrack, $data['files']));
}
/**
* Checks if tracked files have changed. If so, restart all slaves.
*
* This approach uses simple filemtime to check against modificiation. It is using this technique because
* all other file watching stuff have either big dependencies or do not work under all platforms without
* installing a pecl extension. Also this way is interestingly fast and is only used when debug=true.
*/
protected function checkChangedFiles()
{
$reload = false;
$filePath = '';
$start = microtime(true);
foreach ($this->filesToTrack as $filePath) {
$currentFileMTime = filemtime($filePath);
if (isset($this->filesLastMTime[$filePath])) {
if ($this->filesLastMTime[$filePath] !== $currentFileMTime) {
$this->filesLastMTime[$filePath] = $currentFileMTime;
$reload = true;
break;
}
} else {
$this->filesLastMTime[$filePath] = $currentFileMTime;
}
}
if ($reload) {
$this->output->writeln(
sprintf(
"<info>[%s] File changed %s (detection %f, %d). Reload workers.</info>",
date('d/M/Y:H:i:s O'),
$filePath,
microtime(true) - $start,
count($this->filesToTrack)
)
);
$this->reload();
}
}
/**
* Closed all salves, so we automatically reconnect. Necessary when files have changed.
*/
protected function reload()
{
$this->inReload = true;
foreach ($this->slaves as $pid => $info) {
$info['ready'] = false; //does not accept new connections
if ($info['busy']) {
$info['closeWhenFree'] = true;
} else {
$info['connection']->close();
}
};
$this->inReload = false;
}
/**
* Creates a new ProcessSlave instance and forks the process.
*
* @param integer $port
*/
function newInstance($port)
{
$dir = var_export(__DIR__, true);
$this->slaves[$port] = [
'ready' => false,
'pid' => null,
'port' => $port,
'closeWhenFree' => false,
'waitForRegister' => true,
'busy' => false,
'requests' => 0,
'connections' => 0,
'connection' => null,
];
if ($this->output->isVerbose()) {
$this->output->writeln('Start new worker '.$port);
}
$bridge = var_export($this->getBridge(), true);
$bootstrap = var_export($this->getAppBootstrap(), true);
$config = [
'port' => $port,
'app-env' => $this->getAppEnv(),
'debug' => $this->isDebug(),
'logging' => $this->isLogging(),
'static' => true
];
$config = var_export($config, true);
$script = <<<EOF
<?php
require_once file_exists($dir . '/vendor/autoload.php')
? $dir . '/vendor/autoload.php'
: $dir . '/../../autoload.php';
new \PHPPM\ProcessSlave($bridge, $bootstrap, $config);
EOF;
$executableFinder = new PhpExecutableFinder();
$commandline = $executableFinder->find() . '-cgi';
$file = tempnam(sys_get_temp_dir(), 'dbg');
file_put_contents($file, $script);
register_shutdown_function('unlink', $file);
$commandline .= ' -C -q ' . ProcessUtils::escapeArgument($file);
$descriptorspec = [
['pipe', 'r'], //stdin
['pipe', 'w'], //stdout
['pipe', 'w'], //stderr
];
$this->slaves[$port]['process'] = proc_open($commandline, $descriptorspec, $pipes);
$this->slaves[$port]['stdout'] = new \React\Stream\Stream($pipes[1], $this->loop);
$this->slaves[$port]['stderr'] = new \React\Stream\Stream($pipes[2], $this->loop);
$this->slaves[$port]['stdout']->on(
'data',
function ($data) {
$this->output->write($data);
}
);
$this->slaves[$port]['stderr']->on(
'data',
function ($data) {
$this->output->write("<error>$data</error>");
}
);
}
}