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