\GatewayWorkerGateway

Gateway,基于Worker 开发 用于转发客户端的数据给Worker处理,以及转发Worker的数据给客户端

Summary

Methods
Properties
Constants
runAll()
reloadAllWorkers()
getAllWorkers()
getEventLoop()
getMainSocket()
getUiColumns()
getSingleLineTotalLength()
signalHandler()
resetStd()
getStartFilesForWindows()
forkOneWorkerForWindows()
checkWorkerStatusForWindows()
setUserAndGroup()
stopAll()
checkIfChildRunning()
getStatus()
getGracefulStop()
checkErrors()
log()
safeEcho()
__construct()
listen()
unlisten()
pauseAccept()
resumeAccept()
getSocketName()
run()
stop()
acceptConnection()
acceptUdpConnection()
onClientMessage()
onClientConnect()
onWebsocketConnect()
routerRand()
routerBind()
onClientClose()
onWorkerStart()
onWorkerConnect()
onWorkerMessage()
onWorkerClose()
registerAddress()
ping()
pingBusinessWorker()
onWorkerStop()
$id
$name
$count
$user
$group
$reloadable
$reusePort
$onWorkerStart
$onConnect
$onMessage
$onClose
$onError
$onBufferFull
$onBufferDrain
$onWorkerStop
$onWorkerReload
$transport
$connections
$protocol
$stopping
$daemonize
$stdoutFile
$pidFile
$logFile
$globalEvent
$onMasterReload
$onMasterStop
$eventLoopClass
$processTitle
$lanIp
$lanPort
$startPort
$registerAddress
$pingInterval
$pingNotResponseLimit
$pingData
$secretKey
$router
$sendToWorkerBufferSize
$sendToClientBufferSize
$protocolAccelerate
$onBusinessWorkerConnected
$onBusinessWorkerClose
VERSION
STATUS_STARTING
STATUS_RUNNING
STATUS_SHUTDOWN
STATUS_RELOADING
KILL_WORKER_TIMER_TIME
DEFAULT_BACKLOG
MAX_UDP_PACKAGE_SIZE
UI_SAFE_LENGTH
PERSISTENCE_CONNECTION_PING_INTERVAL
checkSapiEnv()
init()
lock()
unlock()
initWorkers()
initId()
getCurrentUser()
displayUI()
parseCommand()
formatStatusData()
installSignal()
reinstallSignal()
daemonize()
saveMasterPid()
getEventLoopName()
getAllWorkerPids()
forkWorkers()
forkWorkersForLinux()
forkWorkersForWindows()
forkOneWorkerForLinux()
getId()
setProcessTitle()
monitorWorkers()
monitorWorkersForLinux()
monitorWorkersForWindows()
exitAndClearAll()
reload()
writeStatisticsToStatusFile()
writeConnectionsStatisticsToStatusFile()
getErrorType()
parseSocketAddress()
checkMasterIsAlive()
generateConnectionId()
sendToWorker()
preEncodeForClient()
$_autoloadRootPath
$_pauseAccept
$_masterPid
$_mainSocket
$_socketName
$_localSocket
$_context
$_workers
$_pidMap
$_pidsToRestart
$_idMap
$_status
$_maxWorkerNameLength
$_maxSocketNameLength
$_maxUserNameLength
$_maxProtoNameLength
$_maxProcessesNameLength
$_maxStatusNameLength
$_statisticsFile
$_startFile
$_OS
$_processForWindows
$_globalStatistics
$_availableEventLoops
$_builtinTransports
$_errorType
$_gracefulStop
$_outputStream
$_outputDecorated
$_clientConnections
$_uidConnections
$_groupConnections
$_workerConnections
$_innerTcpWorker
$_onWorkerStart
$_onConnect
$_onMessage
$_onClose
$_onWorkerStop
$_startTime
$_gatewayPort
$_connectionIdRecorder
N/A
outputStream()
No private properties found
N/A

Constants

VERSION

VERSION = '3.0.19' : string

版本

STATUS_STARTING

STATUS_STARTING = 1 : int

Status starting.

STATUS_RUNNING

STATUS_RUNNING = 2 : int

Status running.

STATUS_SHUTDOWN

STATUS_SHUTDOWN = 4 : int

Status shutdown.

STATUS_RELOADING

STATUS_RELOADING = 8 : int

Status reloading.

KILL_WORKER_TIMER_TIME

KILL_WORKER_TIMER_TIME = 2 : int

After sending the restart command to the child process KILL_WORKER_TIMER_TIME seconds, if the process is still living then forced to kill.

DEFAULT_BACKLOG

DEFAULT_BACKLOG = 102400 : int

Default backlog. Backlog is the maximum length of the queue of pending connections.

MAX_UDP_PACKAGE_SIZE

MAX_UDP_PACKAGE_SIZE = 65535 : int

Max udp package size.

UI_SAFE_LENGTH

UI_SAFE_LENGTH = 4 : int

The safe distance for columns adjacent

PERSISTENCE_CONNECTION_PING_INTERVAL

PERSISTENCE_CONNECTION_PING_INTERVAL = 25 : int

用于保持长连接的心跳时间间隔

Properties

$id

$id : int

Worker id.

Type

int

$name

$name : string

Name of the worker processes.

Type

string

$count

$count : int

Number of worker processes.

Type

int

$user

$user : string

Unix user of processes, needs appropriate privileges (usually root).

Type

string

$group

$group : string

Unix group of processes, needs appropriate privileges (usually root).

Type

string

$reloadable

$reloadable : bool

是否可以平滑重启,gateway 不能平滑重启,否则会导致连接断开

Type

bool

$reusePort

$reusePort : bool

reuse port.

Type

bool

$onWorkerStart

$onWorkerStart : callable

Emitted when worker processes start.

Type

callable

$onConnect

$onConnect : callable

Emitted when a socket connection is successfully established.

Type

callable

$onMessage

$onMessage : callable

Emitted when data is received.

Type

callable

$onClose

$onClose : callable

Emitted when the other end of the socket sends a FIN packet.

Type

callable

$onError

$onError : callable

Emitted when an error occurs with connection.

Type

callable

$onBufferFull

$onBufferFull : callable

Emitted when the send buffer becomes full.

Type

callable

$onBufferDrain

$onBufferDrain : callable

Emitted when the send buffer becomes empty.

Type

callable

$onWorkerStop

$onWorkerStop : callable

Emitted when worker processes stoped.

Type

callable

$onWorkerReload

$onWorkerReload : callable

Emitted when worker processes get reload signal.

Type

callable

$transport

$transport : string

Transport layer protocol.

Type

string

$connections

$connections : array

Store all connections of clients.

Type

array

$protocol

$protocol : string

Application layer protocol.

Type

string

$stopping

$stopping : bool

Is worker stopping ?

Type

bool

$daemonize

$daemonize : bool

Daemonize.

Type

bool

$stdoutFile

$stdoutFile : string

Stdout file.

Type

string

$pidFile

$pidFile : string

The file to store master process PID.

Type

string

$logFile

$logFile : mixed

Log file.

Type

mixed

$globalEvent

$globalEvent : \Workerman\Events\EventInterface

Global event loop.

Type

EventInterface

$onMasterReload

$onMasterReload : callable

Emitted when the master process get reload signal.

Type

callable

$onMasterStop

$onMasterStop : callable

Emitted when the master process terminated.

Type

callable

$eventLoopClass

$eventLoopClass : string

EventLoopClass

Type

string

$processTitle

$processTitle : string

Process title

Type

string

$lanIp

$lanIp : string

本机 IP 单机部署默认 127.0.0.1,如果是分布式部署,需要设置成本机 IP

Type

string

$lanPort

$lanPort : string

本机端口

Type

string

$startPort

$startPort : int

gateway 内部通讯起始端口,每个 gateway 实例应该都不同,步长1000

Type

int

$registerAddress

$registerAddress : string|array

注册服务地址,用于注册 Gateway BusinessWorker,使之能够通讯

Type

string|array

$pingInterval

$pingInterval : int

心跳时间间隔

Type

int

$pingNotResponseLimit

$pingNotResponseLimit : int

$pingNotResponseLimit * $pingInterval 时间内,客户端未发送任何数据,断开客户端连接

Type

int

$pingData

$pingData : string

服务端向客户端发送的心跳数据

Type

string

$secretKey

$secretKey : string

秘钥

Type

string

$router

$router : callable

路由函数

Type

callable

$sendToWorkerBufferSize

$sendToWorkerBufferSize : int

gateway进程转发给businessWorker进程的发送缓冲区大小

Type

int

$sendToClientBufferSize

$sendToClientBufferSize : int

gateway进程将数据发给客户端时每个客户端发送缓冲区大小

Type

int

$protocolAccelerate

$protocolAccelerate : bool

协议加速

Type

bool

$onBusinessWorkerConnected

$onBusinessWorkerConnected : callable|null

BusinessWorker 连接成功之后触发

Type

callable|null

$onBusinessWorkerClose

$onBusinessWorkerClose : callable|null

BusinessWorker 关闭时触发

Type

callable|null

$_autoloadRootPath

$_autoloadRootPath : string

Root path for autoload.

Type

string

$_pauseAccept

$_pauseAccept : bool

Pause accept new connections or not.

Type

bool

$_masterPid

$_masterPid : int

The PID of master process.

Type

int

$_mainSocket

$_mainSocket : resource

Listening socket.

Type

resource

$_socketName

$_socketName : string

Socket name. The format is like this http://0.0.0.0:80 .

Type

string

$_localSocket

$_localSocket : string

parse from _socketName avoid parse again in master or worker LocalSocket The format is like tcp://0.0.0.0:8080

Type

string

$_context

$_context : resource

Context of socket.

Type

resource

$_workers

$_workers : \Workerman\Worker[]

All worker instances.

Type

Worker[]

$_pidMap

$_pidMap : array

All worker processes pid.

The format is like this [worker_id=>[pid=>pid, pid=>pid, ..], ..]

Type

array

$_pidsToRestart

$_pidsToRestart : array

All worker processes waiting for restart.

The format is like this [pid=>pid, pid=>pid].

Type

array

$_idMap

$_idMap : array

Mapping from PID to worker process ID.

The format is like this [worker_id=>[0=>$pid, 1=>$pid, ..], ..].

Type

array

$_status

$_status : int

Current status.

Type

int

$_maxWorkerNameLength

$_maxWorkerNameLength : int

Maximum length of the worker names.

Type

int

$_maxSocketNameLength

$_maxSocketNameLength : int

Maximum length of the socket names.

Type

int

$_maxUserNameLength

$_maxUserNameLength : int

Maximum length of the process user names.

Type

int

$_maxProtoNameLength

$_maxProtoNameLength : int

Maximum length of the Proto names.

Type

int

$_maxProcessesNameLength

$_maxProcessesNameLength : int

Maximum length of the Processes names.

Type

int

$_maxStatusNameLength

$_maxStatusNameLength : int

Maximum length of the Status names.

Type

int

$_statisticsFile

$_statisticsFile : string

The file to store status info of current worker process.

Type

string

$_startFile

$_startFile : string

Start file.

Type

string

$_OS

$_OS : string

OS.

Type

string

$_processForWindows

$_processForWindows : array

Processes for windows.

Type

array

$_globalStatistics

$_globalStatistics : array

Status info of current worker process.

Type

array

$_availableEventLoops

$_availableEventLoops : array

Available event loops.

Type

array

$_builtinTransports

$_builtinTransports : array

PHP built-in protocols.

Type

array

$_errorType

$_errorType : array

PHP built-in error types.

Type

array

$_gracefulStop

$_gracefulStop : bool

Graceful stop or not.

Type

bool

$_outputStream

$_outputStream : resource

Standard output stream

Type

resource

$_outputDecorated

$_outputDecorated : bool

If $outputStream support decorated

Type

bool

$_clientConnections

$_clientConnections : array

保存客户端的所有 connection 对象

Type

array

$_uidConnections

$_uidConnections

uid 到 connection 的映射,一对多关系

$_groupConnections

$_groupConnections : array

group 到 connection 的映射,一对多关系

Type

array

$_workerConnections

$_workerConnections : array

保存所有 worker 的内部连接的 connection 对象

Type

array

$_innerTcpWorker

$_innerTcpWorker : \Workerman\Worker

gateway 内部监听 worker 内部连接的 worker

Type

Worker

$_onWorkerStart

$_onWorkerStart : callable

当 worker 启动时

Type

callable

$_onConnect

$_onConnect : callable

当有客户端连接时

Type

callable

$_onMessage

$_onMessage : callable

当客户端发来消息时

Type

callable

$_onClose

$_onClose : callable

当客户端连接关闭时

Type

callable

$_onWorkerStop

$_onWorkerStop : callable

当 worker 停止时

Type

callable

$_startTime

$_startTime : int

进程启动时间

Type

int

$_gatewayPort

$_gatewayPort : int

gateway 监听的端口

Type

int

$_connectionIdRecorder

$_connectionIdRecorder : int

connectionId 记录器

Type

int

Methods

runAll()

runAll() : void

Run all worker instances.

reloadAllWorkers()

reloadAllWorkers() : void

Reload all worker instances.

getAllWorkers()

getAllWorkers() : array

Get all worker instances.

Returns

array —

getEventLoop()

getEventLoop() : \Workerman\Events\EventInterface

Get global event-loop instance.

Returns

\Workerman\Events\EventInterface —

getMainSocket()

getMainSocket() : resource

Get main socket resource

Returns

resource —

getUiColumns()

getUiColumns() : array

Get UI columns to be shown in terminal

  1. $column_map: array('ui_column_name' => 'clas_property_name')
  2. Consider move into configuration in future

Returns

array —

getSingleLineTotalLength()

getSingleLineTotalLength() : int

Get single line total length for ui

Returns

int —

signalHandler()

signalHandler(int  $signal) : mixed

Signal handler.

Parameters

int $signal

Returns

mixed —

resetStd()

resetStd() : mixed

Redirect standard input and output.

Throws

\Exception

Returns

mixed —

getStartFilesForWindows()

getStartFilesForWindows() : array

Get start files for windows.

Returns

array —

forkOneWorkerForWindows()

forkOneWorkerForWindows(string  $start_file) : mixed

Fork one worker process.

Parameters

string $start_file

Returns

mixed —

checkWorkerStatusForWindows()

checkWorkerStatusForWindows() : void

check worker status for windows.

setUserAndGroup()

setUserAndGroup() : void

Set unix user and group for current process.

stopAll()

stopAll() : void

Stop.

checkIfChildRunning()

checkIfChildRunning() : mixed

check if child processes is really running

Returns

mixed —

getStatus()

getStatus() : \Workerman\number

Get process status.

Returns

\Workerman\number —

getGracefulStop()

getGracefulStop() : bool

If stop gracefully.

Returns

bool —

checkErrors()

checkErrors() : void

Check errors when current process exited.

log()

log(string  $msg) : void

Log.

Parameters

string $msg

safeEcho()

safeEcho(string  $msg, bool  $decorated = false) : bool

Safe Echo.

Parameters

string $msg
bool $decorated

Returns

bool —

__construct()

__construct(string  $socket_name, array  $context_option = array()) : mixed

构造函数

Parameters

string $socket_name
array $context_option

Returns

mixed —

listen()

listen() : mixed

Listen.

Throws

\Exception

Returns

mixed —

unlisten()

unlisten() : void

Unlisten.

pauseAccept()

pauseAccept() : void

Pause accept new connections.

resumeAccept()

resumeAccept() : void

Resume accept new connections.

getSocketName()

getSocketName() : string

Get socket name.

Returns

string —

run()

run() : void

Run worker instance.

stop()

stop() : void

Stop current worker instance.

acceptConnection()

acceptConnection(resource  $socket) : void

Accept a connection.

Parameters

resource $socket

acceptUdpConnection()

acceptUdpConnection(resource  $socket) : bool

For udp package.

Parameters

resource $socket

Returns

bool —

onClientMessage()

onClientMessage(\Workerman\Connection\TcpConnection  $connection, mixed  $data) : mixed

当客户端发来数据时,转发给worker处理

Parameters

\Workerman\Connection\TcpConnection $connection
mixed $data

Returns

mixed —

onClientConnect()

onClientConnect(\Workerman\Connection\TcpConnection  $connection) : mixed

当客户端连接上来时,初始化一些客户端的数据 包括全局唯一的client_id、初始化session等

Parameters

\Workerman\Connection\TcpConnection $connection

Returns

mixed —

onWebsocketConnect()

onWebsocketConnect( $connection,  $http_buffer) : mixed

websocket握手时触发

Parameters

$connection
$http_buffer

Returns

mixed —

routerRand()

routerRand(array  $worker_connections, \Workerman\Connection\TcpConnection  $client_connection, int  $cmd, mixed  $buffer) : \Workerman\Connection\TcpConnection

随机路由,返回 worker connection 对象

Parameters

array $worker_connections
\Workerman\Connection\TcpConnection $client_connection
int $cmd
mixed $buffer

Returns

\Workerman\Connection\TcpConnection —

routerBind()

routerBind(array  $worker_connections, \Workerman\Connection\TcpConnection  $client_connection, int  $cmd, mixed  $buffer) : \Workerman\Connection\TcpConnection

client_id 与 worker 绑定

Parameters

array $worker_connections
\Workerman\Connection\TcpConnection $client_connection
int $cmd
mixed $buffer

Returns

\Workerman\Connection\TcpConnection —

onClientClose()

onClientClose(\Workerman\Connection\TcpConnection  $connection) : mixed

当客户端关闭时

Parameters

\Workerman\Connection\TcpConnection $connection

Returns

mixed —

onWorkerStart()

onWorkerStart() : void

当 Gateway 启动的时候触发的回调函数

onWorkerConnect()

onWorkerConnect(\Workerman\Connection\TcpConnection  $connection) : mixed

当 worker 通过内部通讯端口连接到 gateway 时

Parameters

\Workerman\Connection\TcpConnection $connection

Returns

mixed —

onWorkerMessage()

onWorkerMessage(\Workerman\Connection\TcpConnection  $connection, mixed  $data) : void

当 worker 发来数据时

Parameters

\Workerman\Connection\TcpConnection $connection
mixed $data

Throws

\Exception

onWorkerClose()

onWorkerClose(\Workerman\Connection\TcpConnection  $connection) : mixed

当worker连接关闭时

Parameters

\Workerman\Connection\TcpConnection $connection

Returns

mixed —

registerAddress()

registerAddress() : bool

存储当前 Gateway 的内部通信地址

Returns

bool —

ping()

ping() : void

心跳逻辑

pingBusinessWorker()

pingBusinessWorker() : void

向 BusinessWorker 发送心跳数据,用于保持长连接

onWorkerStop()

onWorkerStop() : void

当 gateway 关闭时触发,清理数据

checkSapiEnv()

checkSapiEnv() : void

Check sapi.

init()

init() : void

Init.

lock()

lock() : void

Lock.

unlock()

unlock() : void

Unlock.

initWorkers()

initWorkers() : void

Init All worker instances.

initId()

initId() : mixed

Init idMap.

return void

Returns

mixed —

getCurrentUser()

getCurrentUser() : string

Get unix user of current porcess.

Returns

string —

displayUI()

displayUI() : void

Display staring UI.

parseCommand()

parseCommand() : void

Parse command.

formatStatusData()

formatStatusData( $statistics_file) : string

Format status data.

Parameters

$statistics_file

Returns

string —

installSignal()

installSignal() : void

Install signal handler.

reinstallSignal()

reinstallSignal() : void

Reinstall signal handler.

daemonize()

daemonize() : mixed

Run as deamon mode.

Throws

\Exception

Returns

mixed —

saveMasterPid()

saveMasterPid() : mixed

Save pid.

Throws

\Exception

Returns

mixed —

getEventLoopName()

getEventLoopName() : string

Get event loop name.

Returns

string —

getAllWorkerPids()

getAllWorkerPids() : array

Get all pids of worker processes.

Returns

array —

forkWorkers()

forkWorkers() : void

Fork some worker processes.

forkWorkersForLinux()

forkWorkersForLinux() : void

Fork some worker processes.

forkWorkersForWindows()

forkWorkersForWindows() : void

Fork some worker processes.

forkOneWorkerForLinux()

forkOneWorkerForLinux(self  $worker) : mixed

Fork one worker process.

Parameters

self $worker

Throws

\Exception

Returns

mixed —

getId()

getId(int  $worker_id, int  $pid) : int

Get worker id.

Parameters

int $worker_id
int $pid

Returns

int —

setProcessTitle()

setProcessTitle(string  $title) : void

Set process name.

Parameters

string $title

monitorWorkers()

monitorWorkers() : void

Monitor all child processes.

monitorWorkersForLinux()

monitorWorkersForLinux() : void

Monitor all child processes.

monitorWorkersForWindows()

monitorWorkersForWindows() : void

Monitor all child processes.

exitAndClearAll()

exitAndClearAll() : void

Exit current process.

reload()

reload() : void

Execute reload.

writeStatisticsToStatusFile()

writeStatisticsToStatusFile() : void

Write statistics data to disk.

writeConnectionsStatisticsToStatusFile()

writeConnectionsStatisticsToStatusFile() : void

Write statistics data to disk.

getErrorType()

getErrorType(int  $type) : string

Get error message by error code.

Parameters

int $type

Returns

string —

parseSocketAddress()

parseSocketAddress() : mixed

Parse local socket address.

Throws

\Exception

Returns

mixed —

checkMasterIsAlive()

checkMasterIsAlive(int  $master_pid) : bool

Check master process is alive

Parameters

int $master_pid

Returns

bool —

generateConnectionId()

generateConnectionId() : int

生成connection id

Returns

int —

sendToWorker()

sendToWorker(int  $cmd, \Workerman\Connection\TcpConnection  $connection, mixed  $body = '') : bool

发送数据给 worker 进程

Parameters

int $cmd
\Workerman\Connection\TcpConnection $connection
mixed $body

Returns

bool —

preEncodeForClient()

preEncodeForClient(mixed  $data) : string

Parameters

mixed $data

Returns

string —

outputStream()

outputStream(resource|null  $stream = null) : bool|resource

Parameters

resource|null $stream

Returns

bool|resource —