1
|
|
|
<?php |
2
|
|
|
|
|
|
|
|
3
|
|
|
namespace Hhxsv5\LaravelS\Swoole; |
4
|
|
|
|
5
|
|
|
use Hhxsv5\LaravelS\Components\MetricCollectorInterface; |
6
|
|
|
use Hhxsv5\LaravelS\Illuminate\LogTrait; |
7
|
|
|
use Hhxsv5\LaravelS\Swoole\Process\ProcessTitleTrait; |
8
|
|
|
use Hhxsv5\LaravelS\Swoole\Socket\PortInterface; |
9
|
|
|
use Hhxsv5\LaravelS\Swoole\Task\BaseTask; |
10
|
|
|
use Hhxsv5\LaravelS\Swoole\Task\Event; |
11
|
|
|
use Hhxsv5\LaravelS\Swoole\Task\Listener; |
12
|
|
|
use Hhxsv5\LaravelS\Swoole\Task\Task; |
13
|
|
|
use Swoole\Http\Request as SwooleRequest; |
14
|
|
|
use Swoole\Http\Response as SwooleResponse; |
15
|
|
|
use Swoole\Http\Server as HttpServer; |
16
|
|
|
use Swoole\Server\Port; |
17
|
|
|
use Swoole\Table; |
18
|
|
|
use Swoole\WebSocket\Server as WebSocketServer; |
19
|
|
|
|
20
|
|
|
class Server |
|
|
|
|
21
|
|
|
{ |
22
|
|
|
use LogTrait; |
23
|
|
|
use ProcessTitleTrait; |
24
|
|
|
|
25
|
|
|
/**@var array */ |
|
|
|
|
26
|
|
|
protected $conf; |
27
|
|
|
|
28
|
|
|
/**@var HttpServer|WebSocketServer */ |
|
|
|
|
29
|
|
|
protected $swoole; |
30
|
|
|
|
31
|
|
|
/**@var bool */ |
|
|
|
|
32
|
|
|
protected $enableWebSocket = false; |
33
|
|
|
|
34
|
|
|
protected function __construct(array $conf) |
|
|
|
|
35
|
|
|
{ |
36
|
|
|
$this->conf = $conf; |
37
|
|
|
$this->enableWebSocket = !empty($this->conf['websocket']['enable']); |
38
|
|
|
|
39
|
|
|
$ip = isset($conf['listen_ip']) ? $conf['listen_ip'] : '127.0.0.1'; |
40
|
|
|
$port = isset($conf['listen_port']) ? $conf['listen_port'] : 5200; |
41
|
|
|
$socketType = isset($conf['socket_type']) ? (int)$conf['socket_type'] : SWOOLE_SOCK_TCP; |
42
|
|
|
|
43
|
|
|
if ($socketType === SWOOLE_SOCK_UNIX_STREAM) { |
44
|
|
|
$socketDir = dirname($ip); |
45
|
|
|
if (!file_exists($socketDir) && !mkdir($socketDir) && !is_dir($socketDir)) { |
46
|
|
|
throw new \RuntimeException(sprintf('Directory "%s" was not created', $socketDir)); |
47
|
|
|
} |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
$settings = isset($conf['swoole']) ? $conf['swoole'] : []; |
51
|
|
|
$settings['enable_static_handler'] = !empty($conf['handle_static']); |
52
|
|
|
|
53
|
|
|
$serverClass = $this->enableWebSocket ? WebSocketServer::class : HttpServer::class; |
54
|
|
|
if (isset($settings['ssl_cert_file'], $settings['ssl_key_file'])) { |
55
|
|
|
$this->swoole = new $serverClass($ip, $port, SWOOLE_PROCESS, $socketType | SWOOLE_SSL); |
56
|
|
|
} else { |
57
|
|
|
$this->swoole = new $serverClass($ip, $port, SWOOLE_PROCESS, $socketType); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
// Disable Coroutine |
61
|
|
|
$settings['enable_coroutine'] = false; |
62
|
|
|
|
63
|
|
|
$this->swoole->set($settings); |
64
|
|
|
|
65
|
|
|
$this->bindBaseEvents(); |
66
|
|
|
$this->bindHttpEvents(); |
67
|
|
|
$this->bindTaskEvents(); |
68
|
|
|
$this->bindWebSocketEvents(); |
69
|
|
|
$this->bindPortEvents(); |
70
|
|
|
$this->bindSwooleTables(); |
71
|
|
|
|
72
|
|
|
// Disable Hook |
73
|
|
|
class_exists('Swoole\Coroutine') && \Swoole\Coroutine::set(['hook_flags' => false]); |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
protected function bindBaseEvents() |
|
|
|
|
77
|
|
|
{ |
78
|
|
|
$this->swoole->on('Start', [$this, 'onStart']); |
79
|
|
|
$this->swoole->on('Shutdown', [$this, 'onShutdown']); |
80
|
|
|
$this->swoole->on('ManagerStart', [$this, 'onManagerStart']); |
81
|
|
|
$this->swoole->on('ManagerStop', [$this, 'onManagerStop']); |
82
|
|
|
$this->swoole->on('WorkerStart', [$this, 'onWorkerStart']); |
83
|
|
|
$this->swoole->on('WorkerStop', [$this, 'onWorkerStop']); |
84
|
|
|
$this->swoole->on('WorkerError', [$this, 'onWorkerError']); |
85
|
|
|
$this->swoole->on('PipeMessage', [$this, 'onPipeMessage']); |
86
|
|
|
} |
87
|
|
|
|
88
|
|
|
protected function bindHttpEvents() |
|
|
|
|
89
|
|
|
{ |
90
|
|
|
$this->swoole->on('Request', [$this, 'onRequest']); |
91
|
|
|
} |
92
|
|
|
|
93
|
|
|
protected function bindTaskEvents() |
|
|
|
|
94
|
|
|
{ |
95
|
|
|
if (!empty($this->conf['swoole']['task_worker_num'])) { |
96
|
|
|
$this->swoole->on('Task', [$this, 'onTask']); |
97
|
|
|
$this->swoole->on('Finish', [$this, 'onFinish']); |
98
|
|
|
} |
99
|
|
|
} |
100
|
|
|
|
101
|
|
|
protected function triggerWebSocketEvent($event, array $params) |
|
|
|
|
102
|
|
|
{ |
103
|
|
|
return $this->callWithCatchException(function () use ($event, $params) { |
|
|
|
|
104
|
|
|
$handler = $this->getWebSocketHandler(); |
105
|
|
|
|
106
|
|
|
if (method_exists($handler, $event)) { |
107
|
|
|
call_user_func_array([$handler, $event], $params); |
108
|
|
|
} elseif ($event === 'onHandShake') { |
109
|
|
|
// Set default HandShake |
110
|
|
|
call_user_func_array([$this, 'onHandShake'], $params); |
111
|
|
|
} |
112
|
|
|
}); |
|
|
|
|
113
|
|
|
} |
114
|
|
|
|
115
|
|
|
protected function bindWebSocketEvents() |
|
|
|
|
116
|
|
|
{ |
117
|
|
|
if ($this->enableWebSocket) { |
118
|
|
|
$this->swoole->on('HandShake', function () { |
|
|
|
|
119
|
|
|
return $this->triggerWebSocketEvent('onHandShake', func_get_args()); |
120
|
|
|
}); |
|
|
|
|
121
|
|
|
|
122
|
|
|
$this->swoole->on('Open', function () { |
|
|
|
|
123
|
|
|
$this->triggerWebSocketEvent('onOpen', func_get_args()); |
124
|
|
|
}); |
|
|
|
|
125
|
|
|
|
126
|
|
|
$this->swoole->on('Message', function () { |
|
|
|
|
127
|
|
|
$this->triggerWebSocketEvent('onMessage', func_get_args()); |
128
|
|
|
}); |
|
|
|
|
129
|
|
|
|
130
|
|
|
$this->swoole->on('Close', function (WebSocketServer $server, $fd, $reactorId) { |
|
|
|
|
131
|
|
|
$clientInfo = $server->getClientInfo($fd); |
132
|
|
|
if (isset($clientInfo['websocket_status']) && $clientInfo['websocket_status'] === \WEBSOCKET_STATUS_FRAME) { |
133
|
|
|
$this->triggerWebSocketEvent('onClose', func_get_args()); |
134
|
|
|
} |
135
|
|
|
// else ignore the close event for http server |
136
|
|
|
}); |
|
|
|
|
137
|
|
|
} |
138
|
|
|
} |
139
|
|
|
|
140
|
|
|
protected function triggerPortEvent(Port $port, $handlerClass, $event, array $params) |
|
|
|
|
141
|
|
|
{ |
142
|
|
|
return $this->callWithCatchException(function () use ($port, $handlerClass, $event, $params) { |
|
|
|
|
143
|
|
|
$handler = $this->getSocketHandler($port, $handlerClass); |
144
|
|
|
|
145
|
|
|
if (method_exists($handler, $event)) { |
146
|
|
|
call_user_func_array([$handler, $event], $params); |
147
|
|
|
} elseif ($event === 'onHandShake') { |
148
|
|
|
// Set default HandShake |
149
|
|
|
call_user_func_array([$this, 'onHandShake'], $params); |
150
|
|
|
} |
151
|
|
|
}); |
|
|
|
|
152
|
|
|
} |
153
|
|
|
|
154
|
|
|
protected function bindPortEvents() |
|
|
|
|
155
|
|
|
{ |
156
|
|
|
$sockets = empty($this->conf['sockets']) ? [] : $this->conf['sockets']; |
157
|
|
|
foreach ($sockets as $socket) { |
158
|
|
|
if (isset($socket['enable']) && !$socket['enable']) { |
159
|
|
|
continue; |
160
|
|
|
} |
161
|
|
|
|
162
|
|
|
$port = $this->swoole->addListener($socket['host'], $socket['port'], $socket['type']); |
163
|
|
|
if (!($port instanceof Port)) { |
164
|
|
|
$errno = method_exists($this->swoole, 'getLastError') ? $this->swoole->getLastError() : 'unknown'; |
165
|
|
|
$errstr = sprintf('listen %s:%s failed: errno=%s', $socket['host'], $socket['port'], $errno); |
166
|
|
|
$this->error($errstr); |
167
|
|
|
continue; |
168
|
|
|
} |
169
|
|
|
|
170
|
|
|
$port->set(empty($socket['settings']) ? [] : $socket['settings']); |
171
|
|
|
|
172
|
|
|
$handlerClass = $socket['handler']; |
173
|
|
|
|
174
|
|
|
$events = [ |
175
|
|
|
'Open', |
176
|
|
|
'HandShake', |
177
|
|
|
'Request', |
178
|
|
|
'Message', |
179
|
|
|
'Connect', |
180
|
|
|
'Close', |
181
|
|
|
'Receive', |
182
|
|
|
'Packet', |
183
|
|
|
'BufferFull', |
184
|
|
|
'BufferEmpty', |
185
|
|
|
]; |
186
|
|
|
foreach ($events as $event) { |
187
|
|
|
$port->on($event, function () use ($port, $handlerClass, $event) { |
|
|
|
|
188
|
|
|
$this->triggerPortEvent($port, $handlerClass, 'on' . $event, func_get_args()); |
189
|
|
|
}); |
|
|
|
|
190
|
|
|
} |
191
|
|
|
} |
192
|
|
|
} |
193
|
|
|
|
194
|
|
|
protected function getWebSocketHandler() |
|
|
|
|
195
|
|
|
{ |
196
|
|
|
static $handler = null; |
197
|
|
|
if ($handler !== null) { |
198
|
|
|
return $handler; |
199
|
|
|
} |
200
|
|
|
|
201
|
|
|
$handlerClass = $this->conf['websocket']['handler']; |
202
|
|
|
$t = new $handlerClass(); |
203
|
|
|
if (!($t instanceof WebSocketHandlerInterface)) { |
204
|
|
|
throw new \InvalidArgumentException(sprintf('%s must implement the interface %s', get_class($t), WebSocketHandlerInterface::class)); |
205
|
|
|
} |
206
|
|
|
$handler = $t; |
207
|
|
|
return $handler; |
208
|
|
|
} |
209
|
|
|
|
210
|
|
|
protected function getSocketHandler(Port $port, $handlerClass) |
|
|
|
|
211
|
|
|
{ |
212
|
|
|
static $handlers = []; |
213
|
|
|
$portHash = spl_object_hash($port); |
214
|
|
|
if (isset($handlers[$portHash])) { |
215
|
|
|
return $handlers[$portHash]; |
216
|
|
|
} |
217
|
|
|
$t = new $handlerClass($port); |
218
|
|
|
if (!($t instanceof PortInterface)) { |
219
|
|
|
throw new \InvalidArgumentException(sprintf('%s must extend the abstract class TcpSocket/UdpSocket', get_class($t))); |
220
|
|
|
} |
221
|
|
|
$handlers[$portHash] = $t; |
222
|
|
|
return $handlers[$portHash]; |
223
|
|
|
} |
224
|
|
|
|
225
|
|
|
protected function bindSwooleTables() |
|
|
|
|
226
|
|
|
{ |
227
|
|
|
$tables = isset($this->conf['swoole_tables']) ? (array)$this->conf['swoole_tables'] : []; |
228
|
|
|
foreach ($tables as $name => $table) { |
229
|
|
|
$t = new Table($table['size']); |
230
|
|
|
foreach ($table['column'] as $column) { |
231
|
|
|
if (isset($column['size'])) { |
232
|
|
|
$t->column($column['name'], $column['type'], $column['size']); |
233
|
|
|
} else { |
234
|
|
|
$t->column($column['name'], $column['type']); |
235
|
|
|
} |
236
|
|
|
} |
237
|
|
|
$t->create(); |
238
|
|
|
$name .= 'Table'; // Avoid naming conflicts |
239
|
|
|
$this->swoole->{$name} = $t; |
240
|
|
|
} |
241
|
|
|
} |
242
|
|
|
|
243
|
|
|
public function onStart(HttpServer $server) |
|
|
|
|
244
|
|
|
{ |
245
|
|
|
$this->setProcessTitle(sprintf('%s laravels: master process', $this->conf['process_prefix'])); |
246
|
|
|
|
247
|
|
|
if (version_compare(SWOOLE_VERSION, '1.9.5', '<')) { |
248
|
|
|
file_put_contents($this->conf['swoole']['pid_file'], $server->master_pid); |
249
|
|
|
} |
250
|
|
|
} |
251
|
|
|
|
252
|
|
|
public function onShutdown(HttpServer $server) |
|
|
|
|
253
|
|
|
{ |
254
|
|
|
} |
255
|
|
|
|
256
|
|
|
public function onManagerStart(HttpServer $server) |
|
|
|
|
257
|
|
|
{ |
258
|
|
|
$this->setProcessTitle(sprintf('%s laravels: manager process', $this->conf['process_prefix'])); |
259
|
|
|
} |
260
|
|
|
|
261
|
|
|
public function onManagerStop(HttpServer $server) |
|
|
|
|
262
|
|
|
{ |
263
|
|
|
} |
264
|
|
|
|
265
|
|
|
public function onWorkerStart(HttpServer $server, $workerId) |
|
|
|
|
266
|
|
|
{ |
267
|
|
|
$processName = $workerId >= $server->setting['worker_num'] ? 'task worker' : 'worker'; |
268
|
|
|
$this->setProcessTitle(sprintf('%s laravels: %s process %d', $this->conf['process_prefix'], $processName, $workerId)); |
269
|
|
|
|
270
|
|
|
if (function_exists('opcache_reset')) { |
271
|
|
|
opcache_reset(); |
272
|
|
|
} |
273
|
|
|
if (function_exists('apc_clear_cache')) { |
274
|
|
|
apc_clear_cache(); |
275
|
|
|
} |
276
|
|
|
|
277
|
|
|
clearstatcache(); |
278
|
|
|
|
279
|
|
|
// Disable Hook |
280
|
|
|
class_exists('Swoole\Runtime') && \Swoole\Runtime::enableCoroutine(false); |
|
|
|
|
281
|
|
|
} |
282
|
|
|
|
283
|
|
|
public function onWorkerStop(HttpServer $server, $workerId) |
|
|
|
|
284
|
|
|
{ |
285
|
|
|
} |
286
|
|
|
|
287
|
|
|
public function onWorkerError(HttpServer $server, $workerId, $workerPId, $exitCode, $signal) |
|
|
|
|
288
|
|
|
{ |
289
|
|
|
$this->error(sprintf('worker[%d] error: exitCode=%s, signal=%s', $workerId, $exitCode, $signal)); |
290
|
|
|
} |
291
|
|
|
|
292
|
|
|
public function onPipeMessage(HttpServer $server, $srcWorkerId, $message) |
|
|
|
|
293
|
|
|
{ |
294
|
|
|
if ($message instanceof BaseTask) { |
295
|
|
|
$server->task($message); |
296
|
|
|
// $this->onTask($server, null, $srcWorkerId, $message); |
297
|
|
|
} elseif ($message instanceof MetricCollectorInterface) { |
298
|
|
|
$message->collect([ |
|
|
|
|
299
|
|
|
'process_id' => $server->worker_id, |
300
|
|
|
'process_type' => $server->taskworker ? 'task' : 'worker', |
301
|
|
|
]); |
|
|
|
|
302
|
|
|
} |
303
|
|
|
} |
304
|
|
|
|
305
|
|
|
public function onRequest(SwooleRequest $swooleRequest, SwooleResponse $swooleResponse) |
|
|
|
|
306
|
|
|
{ |
307
|
|
|
} |
308
|
|
|
|
309
|
|
|
public function onHandShake(SwooleRequest $request, SwooleResponse $response) |
|
|
|
|
310
|
|
|
{ |
311
|
|
|
if (!isset($request->header['sec-websocket-key'])) { |
312
|
|
|
// Bad protocol implementation: it is not RFC6455. |
313
|
|
|
$response->end(); |
314
|
|
|
return; |
315
|
|
|
} |
316
|
|
|
$secKey = $request->header['sec-websocket-key']; |
317
|
|
|
if (!preg_match('#^[+/0-9A-Za-z]{21}[AQgw]==$#', $secKey) || 16 !== strlen(base64_decode($secKey))) { |
318
|
|
|
// Header Sec-WebSocket-Key is illegal; |
319
|
|
|
$response->end(); |
320
|
|
|
return; |
321
|
|
|
} |
322
|
|
|
|
323
|
|
|
$headers = [ |
324
|
|
|
'Upgrade' => 'websocket', |
325
|
|
|
'Connection' => 'Upgrade', |
326
|
|
|
'Sec-WebSocket-Accept' => base64_encode(sha1($secKey . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11', true)), |
327
|
|
|
'Sec-WebSocket-Version' => '13', |
328
|
|
|
]; |
329
|
|
|
|
330
|
|
|
// WebSocket connection to 'ws://127.0.0.1:5200/' |
331
|
|
|
// failed: Error during WebSocket handshake: |
332
|
|
|
// Response must not include 'Sec-WebSocket-Protocol' header if not present in request: websocket |
333
|
|
|
if (isset($request->header['sec-websocket-protocol'])) { |
334
|
|
|
$headers['Sec-WebSocket-Protocol'] = $request->header['sec-websocket-protocol']; |
335
|
|
|
} |
336
|
|
|
|
337
|
|
|
foreach ($headers as $key => $value) { |
338
|
|
|
$response->header($key, $value); |
339
|
|
|
} |
340
|
|
|
|
341
|
|
|
$response->status(101); |
342
|
|
|
$response->end(); |
343
|
|
|
} |
344
|
|
|
|
345
|
|
|
public function onTask(HttpServer $server, $taskId, $srcWorkerId, $data) |
|
|
|
|
346
|
|
|
{ |
347
|
|
|
if ($data instanceof Event) { |
348
|
|
|
$this->handleEvent($data); |
349
|
|
|
} elseif ($data instanceof Task) { |
350
|
|
|
if ($this->handleTask($data) && method_exists($data, 'finish')) { |
351
|
|
|
return $data; |
352
|
|
|
} |
353
|
|
|
} |
354
|
|
|
} |
355
|
|
|
|
356
|
|
|
public function onFinish(HttpServer $server, $taskId, $data) |
|
|
|
|
357
|
|
|
{ |
358
|
|
|
if ($data instanceof Task) { |
359
|
|
|
$data->finish(); |
360
|
|
|
} |
361
|
|
|
} |
362
|
|
|
|
363
|
|
|
protected function handleEvent(Event $event) |
|
|
|
|
364
|
|
|
{ |
365
|
|
|
$listenerClasses = $event->getListeners(); |
366
|
|
|
foreach ($listenerClasses as $listenerClass) { |
367
|
|
|
/**@var Listener $listener */ |
|
|
|
|
368
|
|
|
$listener = new $listenerClass(); |
369
|
|
|
if (!($listener instanceof Listener)) { |
370
|
|
|
throw new \InvalidArgumentException(sprintf('%s must extend the abstract class %s', $listenerClass, Listener::class)); |
371
|
|
|
} |
372
|
|
|
|
373
|
|
|
$result = $this->callWithCatchException(function () use ($listener, $event) { |
|
|
|
|
374
|
|
|
return $listener->handle($event); |
375
|
|
|
}, [], $event->getTries()); |
|
|
|
|
376
|
|
|
|
377
|
|
|
if ($result === false) { // Stop propagating this event to subsequent listeners |
378
|
|
|
break; |
379
|
|
|
} |
380
|
|
|
} |
381
|
|
|
} |
382
|
|
|
|
383
|
|
|
protected function handleTask(Task $task) |
|
|
|
|
384
|
|
|
{ |
385
|
|
|
return $this->callWithCatchException(function () use ($task) { |
|
|
|
|
386
|
|
|
$task->handle(); |
387
|
|
|
return true; |
388
|
|
|
}, [], $task->getTries()); |
|
|
|
|
389
|
|
|
} |
390
|
|
|
|
391
|
|
|
protected function fireEvent($event, $interface, array $arguments) |
|
|
|
|
392
|
|
|
{ |
393
|
|
|
if (isset($this->conf['event_handlers'][$event])) { |
394
|
|
|
$eventHandlers = (array)$this->conf['event_handlers'][$event]; |
395
|
|
|
foreach ($eventHandlers as $eventHandler) { |
396
|
|
|
if (!isset(class_implements($eventHandler)[$interface])) { |
397
|
|
|
throw new \InvalidArgumentException(sprintf( |
|
|
|
|
398
|
|
|
'%s must implement the interface %s', |
|
|
|
|
399
|
|
|
$eventHandler, |
|
|
|
|
400
|
|
|
$interface |
|
|
|
|
401
|
|
|
) |
|
|
|
|
402
|
|
|
); |
403
|
|
|
} |
404
|
|
|
$this->callWithCatchException(function () use ($eventHandler, $arguments) { |
|
|
|
|
405
|
|
|
call_user_func_array([(new $eventHandler), 'handle'], $arguments); |
406
|
|
|
}); |
|
|
|
|
407
|
|
|
} |
408
|
|
|
} |
409
|
|
|
} |
410
|
|
|
|
411
|
|
|
public function run() |
|
|
|
|
412
|
|
|
{ |
413
|
|
|
$this->swoole->start(); |
414
|
|
|
} |
415
|
|
|
} |
416
|
|
|
|