forked from walkor/workerman
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Worker.php
2249 lines (2065 loc) · 70.3 KB
/
Worker.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
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
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?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<[email protected]>
* @copyright walkor<[email protected]>
* @link http://www.workerman.net/
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
namespace Workerman;
require_once __DIR__ . '/Lib/Constants.php';
use Workerman\Events\EventInterface;
use Workerman\Connection\ConnectionInterface;
use Workerman\Connection\TcpConnection;
use Workerman\Connection\UdpConnection;
use Workerman\Lib\Timer;
use Workerman\Events\Select;
use Exception;
/**
* Worker class
* A container for listening ports
*/
class Worker
{
/**
* Version.
*
* @var string
*/
const VERSION = '3.5.6';
/**
* Status starting.
*
* @var int
*/
const STATUS_STARTING = 1;
/**
* Status running.
*
* @var int
*/
const STATUS_RUNNING = 2;
/**
* Status shutdown.
*
* @var int
*/
const STATUS_SHUTDOWN = 4;
/**
* Status reloading.
*
* @var int
*/
const STATUS_RELOADING = 8;
/**
* After sending the restart command to the child process KILL_WORKER_TIMER_TIME seconds,
* if the process is still living then forced to kill.
*
* @var int
*/
const KILL_WORKER_TIMER_TIME = 2;
/**
* Default backlog. Backlog is the maximum length of the queue of pending connections.
*
* @var int
*/
const DEFAULT_BACKLOG = 102400;
/**
* Max udp package size.
*
* @var int
*/
const MAX_UDP_PACKAGE_SIZE = 65535;
/**
* Worker id.
*
* @var int
*/
public $id = 0;
/**
* Name of the worker processes.
*
* @var string
*/
public $name = 'none';
/**
* Number of worker processes.
*
* @var int
*/
public $count = 1;
/**
* Unix user of processes, needs appropriate privileges (usually root).
*
* @var string
*/
public $user = '';
/**
* Unix group of processes, needs appropriate privileges (usually root).
*
* @var string
*/
public $group = '';
/**
* reloadable.
*
* @var bool
*/
public $reloadable = true;
/**
* reuse port.
*
* @var bool
*/
public $reusePort = false;
/**
* Emitted when worker processes start.
*
* @var callback
*/
public $onWorkerStart = null;
/**
* Emitted when a socket connection is successfully established.
*
* @var callback
*/
public $onConnect = null;
/**
* Emitted when data is received.
*
* @var callback
*/
public $onMessage = null;
/**
* Emitted when the other end of the socket sends a FIN packet.
*
* @var callback
*/
public $onClose = null;
/**
* Emitted when an error occurs with connection.
*
* @var callback
*/
public $onError = null;
/**
* Emitted when the send buffer becomes full.
*
* @var callback
*/
public $onBufferFull = null;
/**
* Emitted when the send buffer becomes empty.
*
* @var callback
*/
public $onBufferDrain = null;
/**
* Emitted when worker processes stoped.
*
* @var callback
*/
public $onWorkerStop = null;
/**
* Emitted when worker processes get reload signal.
*
* @var callback
*/
public $onWorkerReload = null;
/**
* Transport layer protocol.
*
* @var string
*/
public $transport = 'tcp';
/**
* Store all connections of clients.
*
* @var array
*/
public $connections = array();
/**
* Application layer protocol.
*
* @var string
*/
public $protocol = null;
/**
* Root path for autoload.
*
* @var string
*/
protected $_autoloadRootPath = '';
/**
* Pause accept new connections or not.
*
* @var bool
*/
protected $_pauseAccept = true;
/**
* Is worker stopping ?
* @var bool
*/
public $stopping = false;
/**
* Daemonize.
*
* @var bool
*/
public static $daemonize = false;
/**
* Stdout file.
*
* @var string
*/
public static $stdoutFile = '/dev/null';
/**
* The file to store master process PID.
*
* @var string
*/
public static $pidFile = '';
/**
* Log file.
*
* @var mixed
*/
public static $logFile = '';
/**
* Global event loop.
*
* @var Events\EventInterface
*/
public static $globalEvent = null;
/**
* Emitted when the master process get reload signal.
*
* @var callback
*/
public static $onMasterReload = null;
/**
* Emitted when the master process terminated.
*
* @var callback
*/
public static $onMasterStop = null;
/**
* EventLoopClass
*
* @var string
*/
public static $eventLoopClass = '';
/**
* The PID of master process.
*
* @var int
*/
protected static $_masterPid = 0;
/**
* Listening socket.
*
* @var resource
*/
protected $_mainSocket = null;
/**
* Socket name. The format is like this http://0.0.0.0:80 .
*
* @var string
*/
protected $_socketName = '';
/**
* Context of socket.
*
* @var resource
*/
protected $_context = null;
/**
* All worker instances.
*
* @var array
*/
protected static $_workers = array();
/**
* All worker porcesses pid.
* The format is like this [worker_id=>[pid=>pid, pid=>pid, ..], ..]
*
* @var array
*/
protected static $_pidMap = array();
/**
* All worker processes waiting for restart.
* The format is like this [pid=>pid, pid=>pid].
*
* @var array
*/
protected static $_pidsToRestart = array();
/**
* Mapping from PID to worker process ID.
* The format is like this [worker_id=>[0=>$pid, 1=>$pid, ..], ..].
*
* @var array
*/
protected static $_idMap = array();
/**
* Current status.
*
* @var int
*/
protected static $_status = self::STATUS_STARTING;
/**
* Maximum length of the worker names.
*
* @var int
*/
protected static $_maxWorkerNameLength = 12;
/**
* Maximum length of the socket names.
*
* @var int
*/
protected static $_maxSocketNameLength = 12;
/**
* Maximum length of the process user names.
*
* @var int
*/
protected static $_maxUserNameLength = 12;
/**
* The file to store status info of current worker process.
*
* @var string
*/
protected static $_statisticsFile = '';
/**
* Start file.
*
* @var string
*/
protected static $_startFile = '';
/**
* OS.
*
* @var string
*/
protected static $_OS = 'linux';
/**
* Processes for windows.
*
* @var array
*/
protected static $_processForWindows = array();
/**
* Status info of current worker process.
*
* @var array
*/
protected static $_globalStatistics = array(
'start_timestamp' => 0,
'worker_exit_info' => array()
);
/**
* Available event loops.
*
* @var array
*/
protected static $_availableEventLoops = array(
'libevent' => '\Workerman\Events\Libevent',
'event' => '\Workerman\Events\Event',
'swoole' => '\Workerman\Events\Swoole'
);
/**
* PHP built-in protocols.
*
* @var array
*/
protected static $_builtinTransports = array(
'tcp' => 'tcp',
'udp' => 'udp',
'unix' => 'unix',
'ssl' => 'tcp'
);
/**
* Graceful stop or not.
*
* @var string
*/
protected static $_gracefulStop = false;
/**
* Run all worker instances.
*
* @return void
*/
public static function runAll()
{
static::checkSapiEnv();
static::init();
static::parseCommand();
static::daemonize();
static::initWorkers();
static::installSignal();
static::saveMasterPid();
static::displayUI();
static::forkWorkers();
static::resetStd();
static::monitorWorkers();
}
/**
* Check sapi.
*
* @return void
*/
protected static function checkSapiEnv()
{
// Only for cli.
if (php_sapi_name() != "cli") {
exit("only run in command line mode \n");
}
if (DIRECTORY_SEPARATOR === '\\') {
self::$_OS = 'windows';
}
}
/**
* Init.
*
* @return void
*/
protected static function init()
{
// Start file.
$backtrace = debug_backtrace();
static::$_startFile = $backtrace[count($backtrace) - 1]['file'];
$unique_prefix = str_replace('/', '_', static::$_startFile);
// Pid file.
if (empty(static::$pidFile)) {
static::$pidFile = __DIR__ . "/../$unique_prefix.pid";
}
// Log file.
if (empty(static::$logFile)) {
static::$logFile = __DIR__ . '/../workerman.log';
}
$log_file = (string)static::$logFile;
if (!is_file($log_file)) {
touch($log_file);
chmod($log_file, 0622);
}
// State.
static::$_status = static::STATUS_STARTING;
// For statistics.
static::$_globalStatistics['start_timestamp'] = time();
static::$_statisticsFile = sys_get_temp_dir() . "/$unique_prefix.status";
// Process title.
static::setProcessTitle('WorkerMan: master process start_file=' . static::$_startFile);
// Init data for worker id.
static::initId();
// Timer init.
Timer::init();
}
/**
* Init All worker instances.
*
* @return void
*/
protected static function initWorkers()
{
if (static::$_OS !== 'linux') {
return;
}
foreach (static::$_workers as $worker) {
// Worker name.
if (empty($worker->name)) {
$worker->name = 'none';
}
// Get maximum length of worker name.
$worker_name_length = strlen($worker->name);
if (static::$_maxWorkerNameLength < $worker_name_length) {
static::$_maxWorkerNameLength = $worker_name_length;
}
// Get maximum length of socket name.
$socket_name_length = strlen($worker->getSocketName());
if (static::$_maxSocketNameLength < $socket_name_length) {
static::$_maxSocketNameLength = $socket_name_length;
}
// Get unix user of the worker process.
if (empty($worker->user)) {
$worker->user = static::getCurrentUser();
} else {
if (posix_getuid() !== 0 && $worker->user != static::getCurrentUser()) {
static::log('Warning: You must have the root privileges to change uid and gid.');
}
}
// Get maximum length of unix user name.
$user_name_length = strlen($worker->user);
if (static::$_maxUserNameLength < $user_name_length) {
static::$_maxUserNameLength = $user_name_length;
}
// Listen.
if (!$worker->reusePort) {
$worker->listen();
}
}
}
/**
* Get all worker instances.
*
* @return array
*/
public static function getAllWorkers()
{
return static::$_workers;
}
/**
* Get global event-loop instance.
*
* @return EventInterface
*/
public static function getEventLoop()
{
return static::$globalEvent;
}
/**
* Init idMap.
* return void
*/
protected static function initId()
{
foreach (static::$_workers as $worker_id => $worker) {
$new_id_map = array();
$worker->count = $worker->count <= 0 ? 1 : $worker->count;
for($key = 0; $key < $worker->count; $key++) {
$new_id_map[$key] = isset(static::$_idMap[$worker_id][$key]) ? static::$_idMap[$worker_id][$key] : 0;
}
static::$_idMap[$worker_id] = $new_id_map;
}
}
/**
* Get unix user of current porcess.
*
* @return string
*/
protected static function getCurrentUser()
{
$user_info = posix_getpwuid(posix_getuid());
return $user_info['name'];
}
/**
* Display staring UI.
*
* @return void
*/
protected static function displayUI()
{
global $argv;
if (in_array('-q', $argv)) {
return;
}
if (static::$_OS !== 'linux') {
static::safeEcho("----------------------- WORKERMAN -----------------------------\r\n");
static::safeEcho('Workerman version:'. static::VERSION. " PHP version:". PHP_VERSION. "\r\n");
static::safeEcho("------------------------ WORKERS -------------------------------\r\n");
static::safeEcho("worker listen processes status\r\n");
return;
}
static::safeEcho("\033[1A\n\033[K-----------------------\033[47;30m WORKERMAN \033[0m-----------------------------\r\n\033[0m");
static::safeEcho('Workerman version:'. static::VERSION. " PHP version:". PHP_VERSION. "\r\n");
static::safeEcho("------------------------\033[47;30m WORKERS \033[0m-------------------------------\r\n");
static::safeEcho("\033[47;30muser\033[0m". str_pad('',
static::$_maxUserNameLength + 2 - strlen('user')). "\033[47;30mworker\033[0m". str_pad('',
static::$_maxWorkerNameLength + 2 - strlen('worker')). "\033[47;30mlisten\033[0m". str_pad('',
static::$_maxSocketNameLength + 2 - strlen('listen')). "\033[47;30mprocesses\033[0m \033[47;30m". "status\033[0m\n");
foreach (static::$_workers as $worker) {
static::safeEcho(str_pad($worker->user, static::$_maxUserNameLength + 2). str_pad($worker->name,
static::$_maxWorkerNameLength + 2). str_pad($worker->getSocketName(),
static::$_maxSocketNameLength + 2). str_pad(' ' . $worker->count, 9). " \033[32;40m [OK] \033[0m\n");
}
static::safeEcho("----------------------------------------------------------------\n");
if (static::$daemonize) {
static::safeEcho("Input \"php $argv[0] stop\" to stop. Start success.\n\n");
} else {
static::safeEcho("Press Ctrl+C to stop. Start success.\n");
}
}
/**
* Parse command.
*
* @return void
*/
protected static function parseCommand()
{
if (static::$_OS !== 'linux') {
return;
}
global $argv;
// Check argv;
$start_file = $argv[0];
$available_commands = array(
'start',
'stop',
'restart',
'reload',
'status',
'connections',
);
$usage = "Usage: php yourfile <command> [mode]\nCommands: \nstart\t\tStart worker in DEBUG mode.\n\t\tUse mode -d to start in DAEMON mode.\nstop\t\tStop worker.\n\t\tUse mode -g to stop gracefully.\nrestart\t\tRestart workers.\n\t\tUse mode -d to start in DAEMON mode.\n\t\tUse mode -g to stop gracefully.\nreload\t\tReload codes.\n\t\tUse mode -g to reload gracefully.\nstatus\t\tGet worker status.\n\t\tUse mode -d to show live status.\nconnections\tGet worker connections.\n";
if (!isset($argv[1]) || !in_array($argv[1], $available_commands)) {
if (isset($argv[1])) echo 'Unknown command: ' . $argv[1] . "\n";
exit($usage);
}
// Get command.
$command = trim($argv[1]);
$command2 = isset($argv[2]) ? $argv[2] : '';
// Start command.
$mode = '';
if ($command === 'start') {
if ($command2 === '-d' || static::$daemonize) {
$mode = 'in DAEMON mode';
} else {
$mode = 'in DEBUG mode';
}
}
static::log("Workerman[$start_file] $command $mode");
// Get master process PID.
$master_pid = is_file(static::$pidFile) ? file_get_contents(static::$pidFile) : 0;
$master_is_alive = $master_pid && @posix_kill($master_pid, 0) && posix_getpid() != $master_pid;
// Master is still alive?
if ($master_is_alive) {
if ($command === 'start') {
static::log("Workerman[$start_file] already running");
exit;
}
} elseif ($command !== 'start' && $command !== 'restart') {
static::log("Workerman[$start_file] not run");
exit;
}
// execute command.
switch ($command) {
case 'start':
if ($command2 === '-d') {
static::$daemonize = true;
}
break;
case 'status':
while (1) {
if (is_file(static::$_statisticsFile)) {
@unlink(static::$_statisticsFile);
}
// Master process will send SIGUSR2 signal to all child processes.
posix_kill($master_pid, SIGUSR2);
// Sleep 1 second.
sleep(1);
// Clear terminal.
if ($command2 === '-d') {
echo "\33[H\33[2J\33(B\33[m";
}
// Echo status data.
echo static::formatStatusData();
if ($command2 !== '-d') {
exit(0);
}
echo "\nPress Ctrl+C to quit.\n\n";
}
exit(0);
case 'connections':
if (is_file(static::$_statisticsFile)) {
@unlink(static::$_statisticsFile);
}
// Master process will send SIGIO signal to all child processes.
posix_kill($master_pid, SIGIO);
// Waiting amoment.
usleep(500000);
// Display statisitcs data from a disk file.
@readfile(static::$_statisticsFile);
exit(0);
case 'restart':
case 'stop':
if ($command2 === '-g') {
static::$_gracefulStop = true;
$sig = SIGTERM;
static::log("Workerman[$start_file] is gracefully stopping ...");
} else {
static::$_gracefulStop = false;
$sig = SIGINT;
static::log("Workerman[$start_file] is stopping ...");
}
// Send stop signal to master process.
$master_pid && posix_kill($master_pid, $sig);
// Timeout.
$timeout = 5;
$start_time = time();
// Check master process is still alive?
while (1) {
$master_is_alive = $master_pid && posix_kill($master_pid, 0);
if ($master_is_alive) {
// Timeout?
if (!static::$_gracefulStop && time() - $start_time >= $timeout) {
static::log("Workerman[$start_file] stop fail");
exit;
}
// Waiting amoment.
usleep(10000);
continue;
}
// Stop success.
static::log("Workerman[$start_file] stop success");
if ($command === 'stop') {
exit(0);
}
if ($command2 === '-d') {
static::$daemonize = true;
}
break;
}
break;
case 'reload':
if($command2 === '-g'){
$sig = SIGQUIT;
}else{
$sig = SIGUSR1;
}
posix_kill($master_pid, $sig);
exit;
default :
if (isset($command)) echo 'Unknown command: ' . $command . "\n";
exit($usage);
}
}
/**
* Format status data.
*
* @return string
*/
protected static function formatStatusData()
{
static $total_request_cache = array();
$info = @file(static::$_statisticsFile, FILE_IGNORE_NEW_LINES);
if (!$info) {
return '';
}
$status_str = '';
$current_total_request = array();
$worker_info = json_decode($info[0], true);
ksort($worker_info, SORT_NUMERIC);
unset($info[0]);
$data_waiting_sort = array();
$read_process_status = false;
$total_requests = 0;
$total_qps = 0;
$total_connections = 0;
$total_fails = 0;
$total_memory = 0;
$total_timers = 0;
$maxLen1 = static::$_maxSocketNameLength;
$maxLen2 = static::$_maxWorkerNameLength;
foreach($info as $key => $value) {
if (!$read_process_status) {
$status_str .= $value . "\n";
if (preg_match('/^pid.*?memory.*?listening/', $value)) {
$read_process_status = true;
}
continue;
}
if(preg_match('/^[0-9]+/', $value, $pid_math)) {
$pid = $pid_math[0];
$data_waiting_sort[$pid] = $value;
if(preg_match('/^\S+?\s+?(\S+?)\s+?(\S+?)\s+?(\S+?)\s+?(\S+?)\s+?(\S+?)\s+?(\S+?)\s+?(\S+?)\s+?/', $value, $match)) {
$total_memory += intval(str_ireplace('M','',$match[1]));
$maxLen1 = max($maxLen1,strlen($match[2]));
$maxLen2 = max($maxLen2,strlen($match[3]));
$total_connections += intval($match[4]);
$total_fails += intval($match[5]);
$total_timers += intval($match[6]);
$current_total_request[$pid] = $match[7];
$total_requests += intval($match[7]);
}
}
}
foreach($worker_info as $pid => $info) {
if (!isset($data_waiting_sort[$pid])) {
$status_str .= "$pid\t" . str_pad('N/A', 7) . " "
. str_pad($info['listen'], static::$_maxSocketNameLength) . " "
. str_pad($info['name'], static::$_maxWorkerNameLength) . " "
. str_pad('N/A', 11) . " " . str_pad('N/A', 9) . " "
. str_pad('N/A', 7) . " " . str_pad('N/A', 13) . " N/A [busy] \n";
continue;
}
//$qps = isset($total_request_cache[$pid]) ? $current_total_request[$pid]
if (!isset($total_request_cache[$pid]) || !isset($current_total_request[$pid])) {
$qps = 0;
} else {
$qps = $current_total_request[$pid] - $total_request_cache[$pid];
$total_qps += $qps;
}
$status_str .= $data_waiting_sort[$pid]. " " . str_pad($qps, 6) ." [idle]\n";
}
$total_request_cache = $current_total_request;
$status_str .= "----------------------------------------------PROCESS STATUS---------------------------------------------------\n";
$status_str .= "Summary\t" . str_pad($total_memory.'M', 7) . " "
. str_pad('-', $maxLen1) . " "
. str_pad('-', $maxLen2) . " "
. str_pad($total_connections, 11) . " " . str_pad($total_fails, 9) . " "
. str_pad($total_timers, 7) . " " . str_pad($total_requests, 13) . " "
. str_pad($total_qps,6)." [Summary] \n";
return $status_str;
}
/**
* Install signal handler.
*
* @return void
*/
protected static function installSignal()
{
if (static::$_OS !== 'linux') {
return;
}
// stop
pcntl_signal(SIGINT, array('\Workerman\Worker', 'signalHandler'), false);
// graceful stop
pcntl_signal(SIGTERM, array('\Workerman\Worker', 'signalHandler'), false);
// reload
pcntl_signal(SIGUSR1, array('\Workerman\Worker', 'signalHandler'), false);
// graceful reload
pcntl_signal(SIGQUIT, array('\Workerman\Worker', 'signalHandler'), false);
// status
pcntl_signal(SIGUSR2, array('\Workerman\Worker', 'signalHandler'), false);
// connection status
pcntl_signal(SIGIO, array('\Workerman\Worker', 'signalHandler'), false);
// ignore
pcntl_signal(SIGPIPE, SIG_IGN, false);
}
/**
* Reinstall signal handler.
*
* @return void
*/
protected static function reinstallSignal()
{
if (static::$_OS !== 'linux') {
return;
}
// uninstall stop signal handler
pcntl_signal(SIGINT, SIG_IGN, false);
// uninstall graceful stop signal handler
pcntl_signal(SIGTERM, SIG_IGN, false);
// uninstall reload signal handler
pcntl_signal(SIGUSR1, SIG_IGN, false);
// uninstall graceful reload signal handler
pcntl_signal(SIGQUIT, SIG_IGN, false);
// uninstall status signal handler
pcntl_signal(SIGUSR2, SIG_IGN, false);
// reinstall stop signal handler
static::$globalEvent->add(SIGINT, EventInterface::EV_SIGNAL, array('\Workerman\Worker', 'signalHandler'));
// reinstall graceful stop signal handler
static::$globalEvent->add(SIGTERM, EventInterface::EV_SIGNAL, array('\Workerman\Worker', 'signalHandler'));
// reinstall reload signal handler
static::$globalEvent->add(SIGUSR1, EventInterface::EV_SIGNAL, array('\Workerman\Worker', 'signalHandler'));
// reinstall graceful reload signal handler
static::$globalEvent->add(SIGQUIT, EventInterface::EV_SIGNAL, array('\Workerman\Worker', 'signalHandler'));
// reinstall status signal handler
static::$globalEvent->add(SIGUSR2, EventInterface::EV_SIGNAL, array('\Workerman\Worker', 'signalHandler'));
// reinstall connection status signal handler
static::$globalEvent->add(SIGIO, EventInterface::EV_SIGNAL, array('\Workerman\Worker', 'signalHandler'));
}
/**
* Signal handler.
*
* @param int $signal
*/
public static function signalHandler($signal)
{
switch ($signal) {
// Stop.
case SIGINT:
static::$_gracefulStop = false;
static::stopAll();
break;
// Graceful stop.
case SIGTERM:
static::$_gracefulStop = true;
static::stopAll();
break;
// Reload.
case SIGQUIT:
case SIGUSR1:
if($signal === SIGQUIT){
static::$_gracefulStop = true;
}else{
static::$_gracefulStop = false;
}
static::$_pidsToRestart = static::getAllWorkerPids();
static::reload();
break;
// Show status.
case SIGUSR2:
static::writeStatisticsToStatusFile();
break;
// Show connection status.
case SIGIO:
static::writeConnectionsStatisticsToStatusFile();
break;
}
}
/**
* Run as deamon mode.
*