/
Gateway.php
611 lines (557 loc) · 18.9 KB
/
Gateway.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
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
<?php
/**
* This file is part of workerman.
*-----
* Licensed under The MIT License
* For full copyright and license information, please see the MIT-LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @author walkor<walkor@workerman.net>
* @copyright walkor<walkor@workerman.net>
* @link http://www.workerman.net/
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
namespace GatewayWorker;
use Workerman\Connection\TcpConnection;
use \Workerman\Worker;
use \Workerman\Lib\Timer;
use \Workerman\Protocols\GatewayProtocol;
use \GatewayWorker\Lib\Lock;
use \GatewayWorker\Lib\Store;
use \Workerman\Autoloader;
/**
*
* Gateway,基于Worker开发
* 用于转发客户端的数据给Worker处理,以及转发Worker的数据给客户端
*
* @author walkor<walkor@workerman.net>
*
*/
class Gateway extends Worker
{
/**
* 本机ip
* @var 单机部署默认127.0.0.1,如果是分布式部署,需要设置成本机ip
*/
public $lanIp = '127.0.0.1';
/**
* gateway内部通讯起始端口,每个gateway实例应该都不同,步长1000
* @var int
*/
public $startPort = 2000;
/**
* 是否可以平滑重启,gateway不能平滑重启,否则会导致连接断开
* @var bool
*/
public $reloadable = false;
/**
* 心跳时间间隔
* @var int
*/
public $pingInterval = 0;
/**
* $pingNotResponseLimit*$pingInterval时间内,客户端未发送任何数据,断开客户端连接
* @var int
*/
public $pingNotResponseLimit = 0;
/**
* 服务端向客户端发送的心跳数据
* @var string
*/
public $pingData = '';
/**
* 路由函数
* @var callback
*/
public $router = null;
/**
* 保存客户端的所有connection对象
* @var array
*/
protected $_clientConnections = array();
/**
* 保存所有worker的内部连接的connection对象
* @var array
*/
protected $_workerConnections = array();
/**
* gateway内部监听worker内部连接的worker
* @var Worker
*/
protected $_innerTcpWorker = null;
/**
* gateway内部监听udp数据的worker
* @var Worker
*/
protected $_innerUdpWorker = null;
/**
* 当worker启动时
* @var callback
*/
protected $_onWorkerStart = null;
/**
* 当有客户端连接时
* @var callback
*/
protected $_onConnect = null;
/**
* 当客户端发来消息时
* @var callback
*/
protected $_onMessage = null;
/**
* 当客户端连接关闭时
* @var callback
*/
protected $_onClose = null;
/**
* 当worker停止时
* @var callback
*/
protected $_onWorkerStop = null;
/**
* 进程启动时间
* @var int
*/
protected $_startTime = 0;
/**
* 构造函数
* @param string $socket_name
* @param array $context_option
*/
public function __construct($socket_name, $context_option = array())
{
parent::__construct($socket_name, $context_option);
$this->router = array("\\GatewayWorker\\Gateway", 'routerRand');
$backrace = debug_backtrace();
$this->_appInitPath = dirname($backrace[0]['file']);
}
/**
* 运行
* @see Workerman.Worker::run()
*/
public function run()
{
// 保存用户的回调,当对应的事件发生时触发
$this->_onWorkerStart = $this->onWorkerStart;
$this->onWorkerStart = array($this, 'onWorkerStart');
// 保存用户的回调,当对应的事件发生时触发
$this->_onConnect = $this->onConnect;
$this->onConnect = array($this, 'onClientConnect');
// onMessage禁止用户设置回调
$this->onMessage = array($this, 'onClientMessage');
// 保存用户的回调,当对应的事件发生时触发
$this->_onClose = $this->onClose;
$this->onClose = array($this, 'onClientClose');
// 保存用户的回调,当对应的事件发生时触发
$this->_onWorkerStop = $this->onWorkerStop;
$this->onWorkerStop = array($this, 'onWorkerStop');
// 记录进程启动的时间
$this->_startTime = time();
// 运行父方法
parent::run();
}
/**
* 当客户端发来数据时,转发给worker处理
* @param TcpConnection $connection
* @param mixed $data
*/
public function onClientMessage($connection, $data)
{
$connection->pingNotResponseCount = -1;
$this->sendToWorker(GatewayProtocol::CMD_ON_MESSAGE, $connection, $data);
}
/**
* 当客户端连接上来时,初始化一些客户端的数据
* 包括全局唯一的client_id、初始化session等
* @param unknown_type $connection
*/
public function onClientConnect($connection)
{
// 分配一个全局唯一的client_id
$connection->globalClientId = $this->createGlobalClientId();
// 保存该连接的内部通讯的数据包报头,避免每次重新初始化
$connection->gatewayHeader = array(
'local_ip' => $this->lanIp,
'local_port' => $this->lanPort,
'client_ip'=>$connection->getRemoteIp(),
'client_port'=>$connection->getRemotePort(),
'client_id'=>$connection->globalClientId,
);
// 连接的session
$connection->session = '';
// 该连接的心跳参数
$connection->pingNotResponseCount = -1;
// 保存客户端连接connection对象
$this->_clientConnections[$connection->globalClientId] = $connection;
// 保存该连接的内部gateway通讯地址
$address = $this->lanIp.':'.$this->lanPort;
$this->storeClientAddress($connection->globalClientId, $address);
// 如果用户有自定义onConnect回调,则执行
if($this->_onConnect)
{
call_user_func($this->_onConnect, $connection);
}
// 如果设置了Event::onConnect,则通知worker进程,让worker执行onConnect
if(method_exists('Event','onConnect'))
{
$this->sendToWorker(GatewayProtocol::CMD_ON_CONNECTION, $connection);
}
}
/**
* 发送数据给worker进程
* @param int $cmd
* @param TcpConnection $connection
* @param mixed $body
*/
protected function sendToWorker($cmd, $connection, $body = '')
{
$gateway_data = $connection->gatewayHeader;
$gateway_data['cmd'] = $cmd;
$gateway_data['body'] = $body;
$gateway_data['ext_data'] = $connection->session;
if($this->_workerConnections)
{
// 调用路由函数,选择一个worker把请求转发给它
$worker_connection = call_user_func($this->router, $this->_workerConnections, $connection, $cmd, $body);
if(false === $worker_connection->send($gateway_data))
{
$msg = "SendBufferToWorker fail. May be the send buffer are overflow";
$this->log($msg);
return false;
}
}
// 没有可用的worker
else
{
// gateway启动后1-2秒内SendBufferToWorker fail是正常现象,因为与worker的连接还没建立起来,所以不记录日志,只是关闭连接
$time_diff = 2;
if(time() - $this->_startTime >= $time_diff)
{
$msg = "SendBufferToWorker fail. The connections between Gateway and BusinessWorker are not ready";
$this->log($msg);
}
$connection->destroy();
return false;
}
return true;
}
/**
* 随机路由,返回worker connection对象
* @param array $worker_connections
* @param TcpConnection $client_connection
* @param int $cmd
* @param mixed $buffer
* @return TcpConnection
*/
public static function routerRand($worker_connections, $client_connection, $cmd, $buffer)
{
return $worker_connections[array_rand($worker_connections)];
}
/**
* 保存客户端连接的gateway通讯地址
* @param int $global_client_id
* @param string $address
* @return bool
*/
protected function storeClientAddress($global_client_id, $address)
{
if(!Store::instance('gateway')->set('client_id-'.$global_client_id, $address))
{
$msg = 'storeClientAddress fail.';
if(get_class(Store::instance('gateway')) == 'Memcached')
{
$msg .= " reason :".Store::instance('gateway')->getResultMessage();
}
$this->log($msg);
return false;
}
return true;
}
/**
* 删除客户端gateway通讯地址
* @param int $global_client_id
* @return void
*/
protected function delClientAddress($global_client_id)
{
Store::instance('gateway')->delete('client_id-'.$global_client_id);
}
/**
* 当客户端关闭时
* @param unknown_type $connection
*/
public function onClientClose($connection)
{
// 尝试通知worker,触发Event::onClose
if(method_exists('Event','onClose'))
{
$this->sendToWorker(GatewayProtocol::CMD_ON_CLOSE, $connection);
}
// 清理连接的数据
$this->delClientAddress($connection->globalClientId);
unset($this->_clientConnections[$connection->globalClientId]);
if($this->_onClose)
{
call_user_func($this->_onClose, $connection);
}
}
/**
* 创建一个workerman集群全局唯一的client_id
* @return int|false
*/
protected function createGlobalClientId()
{
$global_socket_key = 'GLOBAL_CLIENT_ID_KEY';
$store = Store::instance('gateway');
$global_client_id = $store->increment($global_socket_key);
if(!$global_client_id || $global_client_id > 2147483646)
{
$store->set($global_socket_key, 0);
$global_client_id = $store->increment($global_socket_key);
}
if(!$global_client_id)
{
$msg = "createGlobalClientId fail :";
if(get_class($store) == 'Memcached')
{
$msg .= $store->getResultMessage();
}
$this->log($msg);
}
return $global_client_id;
}
/**
* 当Gateway启动的时候触发的回调函数
* @return void
*/
public function onWorkerStart()
{
// 分配一个内部通讯端口
$this->lanPort = function_exists('posix_getppid') ? $this->startPort - posix_getppid() + posix_getpid() : $this->startPort;
if($this->lanPort<0 || $this->lanPort >=65535)
{
$this->lanPort = rand($this->startPort, 65535);
}
// 如果有设置心跳,则定时执行
if($this->pingInterval > 0)
{
Timer::add($this->pingInterval, array($this, 'ping'));
}
// 初始化gateway内部的监听,用于监听worker的连接已经连接上发来的数据
$this->_innerTcpWorker = new Worker("GatewayProtocol://{$this->lanIp}:{$this->lanPort}");
$this->_innerTcpWorker->listen();
$this->_innerUdpWorker = new Worker("GatewayProtocol://{$this->lanIp}:{$this->lanPort}");
$this->_innerUdpWorker->transport = 'udp';
$this->_innerUdpWorker->listen();
// 重新设置自动加载根目录
Autoloader::setRootPath($this->_appInitPath);
// 设置内部监听的相关回调
$this->_innerTcpWorker->onMessage = array($this, 'onWorkerMessage');
$this->_innerUdpWorker->onMessage = array($this, 'onWorkerMessage');
$this->_innerTcpWorker->onConnect = array($this, 'onWorkerConnect');
$this->_innerTcpWorker->onClose = array($this, 'onWorkerClose');
// 注册gateway的内部通讯地址,worker去连这个地址,以便gateway与worker之间建立起TCP长连接
if(!$this->registerAddress())
{
$this->log('registerAddress fail and exit');
Worker::stopAll();
}
if($this->_onWorkerStart)
{
call_user_func($this->_onWorkerStart, $this);
}
}
/**
* 当worker通过内部通讯端口连接到gateway时
* @param TcpConnection $connection
*/
public function onWorkerConnect($connection)
{
$connection->remoteAddress = $connection->getRemoteIp().':'.$connection->getRemotePort();
if(TcpConnection::$defaultMaxSendBufferSize == $connection->maxSendBufferSize)
{
$connection->maxSendBufferSize = 10*1024*1024;
}
$this->_workerConnections[$connection->remoteAddress] = $connection;
}
/**
* 当worker发来数据时
* @param TcpConnection $connection
* @param mixed $data
* @throws \Exception
*/
public function onWorkerMessage($connection, $data)
{
$cmd = $data['cmd'];
switch($cmd)
{
// 向某客户端发送数据,Gateway::sendToClient($client_id, $message);
case GatewayProtocol::CMD_SEND_TO_ONE:
if(isset($this->_clientConnections[$data['client_id']]))
{
$this->_clientConnections[$data['client_id']]->send($data['body']);
}
break;
// 关闭客户端连接,Gateway::closeClient($client_id);
case GatewayProtocol::CMD_KICK:
if(isset($this->_clientConnections[$data['client_id']]))
{
$this->_clientConnections[$data['client_id']]->destroy();
}
break;
// 广播, Gateway::sendToAll($message, $client_id_array)
case GatewayProtocol::CMD_SEND_TO_ALL:
// $client_id_array不为空时,只广播给$client_id_array指定的客户端
if($data['ext_data'])
{
$client_id_array = unpack('N*', $data['ext_data']);
foreach($client_id_array as $client_id)
{
if(isset($this->_clientConnections[$client_id]))
{
$this->_clientConnections[$client_id]->send($data['body']);
}
}
}
// $client_id_array为空时,广播给所有在线客户端
else
{
foreach($this->_clientConnections as $client_connection)
{
$client_connection->send($data['body']);
}
}
break;
// 更新客户端session
case GatewayProtocol::CMD_UPDATE_SESSION:
if(isset($this->_clientConnections[$data['client_id']]))
{
$this->_clientConnections[$data['client_id']]->session = $data['ext_data'];
}
break;
// 获得客户端在线状态 Gateway::getOnlineStatus()
case GatewayProtocol::CMD_GET_ONLINE_STATUS:
$online_status = json_encode(array_keys($this->_clientConnections));
$connection->send($online_status);
break;
// 判断某个client_id是否在线 Gateway::isOnline($client_id)
case GatewayProtocol::CMD_IS_ONLINE:
$connection->send((int)isset($this->_clientConnections[$data['client_id']]));
break;
default :
$err_msg = "gateway inner pack err cmd=$cmd";
throw new \Exception($err_msg);
}
}
/**
* 当worker连接关闭时
* @param TcpConnection $connection
*/
public function onWorkerClose($connection)
{
//$this->log("{$connection->remoteAddress} CLOSE INNER_CONNECTION\n");
unset($this->_workerConnections[$connection->remoteAddress]);
}
/**
* 存储当前Gateway的内部通信地址
* @param string $address
* @return bool
*/
protected function registerAddress()
{
$address = $this->lanIp.':'.$this->lanPort;
// key
$key = 'GLOBAL_GATEWAY_ADDRESS';
try
{
$store = Store::instance('gateway');
}
catch(\Exception $msg)
{
$this->log($msg);
return false;
}
// 为保证原子性,需要加锁
Lock::get();
if(!$store->hSet($key, $address, $address))
{
Lock::release();
return false;
}
Lock::release();
return true;
}
/**
* 删除当前Gateway的内部通信地址
* @param string $address
* @return bool
*/
protected function unregisterAddress()
{
$address = $this->lanIp.':'.$this->lanPort;
$key = 'GLOBAL_GATEWAY_ADDRESS';
try
{
$store = Store::instance('gateway');
}
catch (\Exception $msg)
{
$this->log($msg);
return false;
}
// 为保证原子性,需要加锁
Lock::get();
if(!$store->hDel($key, $address))
{
Lock::release();
$msg = "unregisterAddress fail";
$this->log($msg);
return;
}
Lock::release();
return true;
}
/**
* 心跳逻辑
* @return void
*/
public function ping()
{
// 遍历所有客户端连接
foreach($this->_clientConnections as $connection)
{
// 上次发送的心跳还没有回复次数大于限定值就断开
if($this->pingNotResponseLimit > 0 && $connection->pingNotResponseCount >= $this->pingNotResponseLimit)
{
$connection->destroy();
continue;
}
// $connection->pingNotResponseCount为-1说明最近客户端有发来消息,则不给客户端发送心跳
if($connection->pingNotResponseCount++ >= 0)
{
if($this->pingData)
{
$connection->send($this->pingData);
}
}
}
}
/**
* 当gateway关闭时触发,清理数据
* @return void
*/
public function onWorkerStop()
{
$this->unregisterAddress();
foreach($this->_clientConnections as $connection)
{
$this->delClientAddress($connection->globalClientId);
}
// 尝试触发用户设置的回调
if($this->_onWorkerStop)
{
call_user_func($this->_onWorkerStop, $this);
}
}
}