forked from php-pm/php-pm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProcessSlave.php
129 lines (108 loc) · 3.11 KB
/
ProcessSlave.php
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
<?php
namespace PHPPM;
class ProcessSlave
{
/**
* @var \React\EventLoop\LibEventLoop|\React\EventLoop\StreamSelectLoop
*/
protected $loop;
/**
* @var resource
*/
protected $client;
/**
* @var \React\Socket\Connection
*/
protected $connection;
/**
* @var string
*/
protected $bridgeName;
/**
* @var Bridges\BridgeInterface
*/
protected $bridge;
/**
* @var string|null
*/
protected $appenv;
public function __construct($bridgeName = null, $appBootstrap, $appenv, $appDebug)
{
$this->bridgeName = $bridgeName;
$this->bootstrap($appBootstrap, $appenv, $appDebug);
$this->connectToMaster();
$this->loop->run();
}
protected function shutdown()
{
echo "SHUTTING SLAVE PROCESS DOWN\n";
$this->bye();
exit;
}
/**
* @return Bridges\BridgeInterface
*/
protected function getBridge()
{
if (null === $this->bridge && $this->bridgeName) {
if (true === class_exists($this->bridgeName)) {
$bridgeClass = $this->bridgeName;
} else {
$bridgeClass = sprintf('PHPPM\Bridges\\%s', ucfirst($this->bridgeName));
}
$this->bridge = new $bridgeClass;
}
return $this->bridge;
}
protected function bootstrap($appBootstrap, $appenv, $appDebug)
{
if ($bridge = $this->getBridge()) {
$bridge->bootstrap($appBootstrap, $appenv, $appDebug);
}
}
public function connectToMaster()
{
$this->loop = \React\EventLoop\Factory::create();
$this->client = stream_socket_client('tcp://127.0.0.1:5500');
$this->connection = new \React\Socket\Connection($this->client, $this->loop);
$this->connection->on(
'close',
\Closure::bind(
function () {
$this->shutdown();
},
$this
)
);
$socket = new \React\Socket\Server($this->loop);
$http = new \React\Http\Server($socket);
$http->on('request', array($this, 'onRequest'));
$port = 5501;
while ($port < 5600) {
try {
$socket->listen($port);
break;
} catch( \React\Socket\ConnectionException $e ) {
$port++;
}
}
$this->connection->write(json_encode(array('cmd' => 'register', 'pid' => getmypid(), 'port' => $port)));
}
public function onRequest(\React\Http\Request $request, \React\Http\Response $response)
{
if ($bridge = $this->getBridge()) {
return $bridge->onRequest($request, $response);
} else {
$response->writeHead('404');
$response->end('No Bridge Defined.');
}
}
public function bye()
{
if ($this->connection->isWritable()) {
$this->connection->write(json_encode(array('cmd' => 'unregister', 'pid' => getmypid())));
$this->connection->close();
}
$this->loop->stop();
}
}