apns-php
 All Data Structures Files Functions Variables Groups Pages
ApnsPHP_Push_Server Class Reference

The Push Notification Server Provider. More...

Inheritance diagram for ApnsPHP_Push_Server:
Inheritance graph
Collaboration diagram for ApnsPHP_Push_Server:
Collaboration graph

Public Member Functions

void __construct (integer $nEnvironment, string $sProviderCertificateFile)
 Constructor. More...
 
void add (ApnsPHP_Message $message)
 Adds a message to the inter-process message queue. More...
 
array getErrors (boolean $bEmpty=true)
 Returns messages not delivered to the end user because one (or more) error occurred. More...
 
array getQueue (boolean $bEmpty=true)
 Returns messages in the message queue. More...
 
void onChildExited ()
 Waits until a forked process has exited and decreases the current running process number. More...
 
void onShutdown ()
 When the parent process exits, cleans shared memory and semaphore. More...
 
void onSignal (integer $nSignal)
 When a child (not the parent) receive a signal of type TERM, QUIT or INT exits from the current process and decreases the current running process number. More...
 
boolean run ()
 Checks if the server is running and calls signal handlers for pending signals. More...
 
void setProcesses (integer $nProcesses)
 Set the total processes to start, default is 3. More...
 
void start ()
 Starts the server forking all processes and return immediately. More...
 
- Public Member Functions inherited from ApnsPHP_Push
void add (ApnsPHP_Message $message)
 Adds a message to the message queue. More...
 
array getErrors (boolean $bEmpty=true)
 Returns messages not delivered to the end user because one (or more) error occurred. More...
 
array getQueue (boolean $bEmpty=true)
 Returns messages in the message queue. More...
 
integer getSendRetryTimes ()
 Get the send retry time value. More...
 
void send ()
 Sends all messages in the message queue to Apple Push Notification Service. More...
 
void setSendRetryTimes (integer $nRetryTimes)
 Set the send retry times value. More...
 
- Public Member Functions inherited from ApnsPHP_Abstract
void __construct (integer $nEnvironment, string $sProviderCertificateFile)
 Constructor. More...
 
void connect ()
 Connects to Apple Push Notification service server. More...
 
boolean disconnect ()
 Disconnects from Apple Push Notifications service server. More...
 
string getCertificateAuthority ()
 Get the Root Certification Authority file path. More...
 
integer getConnectRetryInterval ()
 Get the connect retry interval. More...
 
integer getConnectRetryTimes ()
 Get the connect retry time value. More...
 
integer getConnectTimeout ()
 Get the connection timeout. More...
 
ApnsPHP_Log_Interface getLogger ()
 Get the Logger instance. More...
 
integer getSocketSelectTimeout ()
 Get the TCP socket select timeout. More...
 
integer getWriteInterval ()
 Get the write interval. More...
 
void setConnectRetryInterval (integer $nRetryInterval)
 Set the connect retry interval. More...
 
void setConnectRetryTimes (integer $nRetryTimes)
 Set the connect retry times value. More...
 
void setConnectTimeout (integer $nTimeout)
 Set the connection timeout. More...
 
void setLogger (ApnsPHP_Log_Interface $logger)
 Set the Logger instance to use for logging purpose. More...
 
void setProviderCertificatePassphrase (string $sProviderCertificatePassphrase)
 Set the Provider Certificate passphrase. More...
 
void setRootCertificationAuthority (string $sRootCertificationAuthorityFile)
 Set the Root Certification Authority file. More...
 
void setSocketSelectTimeout (integer $nSelectTimeout)
 Set the TCP socket select timeout. More...
 
void setWriteInterval (integer $nWriteInterval)
 Set the write interval. More...
 

Data Fields

const MAIN_LOOP_USLEEP = 200000
 integer Main loop sleep time in micro seconds. More...
 
const SHM_ERROR_MESSAGES_QUEUE_KEY = 999
 integer Message queue identifier for not delivered messages. More...
 
const SHM_MESSAGES_QUEUE_KEY_START = 1000
 integer Message queue start identifier for messages. More...
 
const SHM_SIZE = 524288
 integer Shared memory size in bytes useful to store message queues. More...
 
- Data Fields inherited from ApnsPHP_Push
const COMMAND_PUSH = 1
 integer Payload command. More...
 
const ERROR_RESPONSE_COMMAND = 8
 integer Error-response command code. More...
 
const ERROR_RESPONSE_SIZE = 6
 integer Error-response packet size. More...
 
const STATUS_CODE_INTERNAL_ERROR = 999
 integer Status code for internal error (not Apple). More...
 
- Data Fields inherited from ApnsPHP_Abstract
const CONNECT_RETRY_INTERVAL = 1000000
 integer Default connect retry interval in micro seconds. More...
 
const DEVICE_BINARY_SIZE = 32
 integer Device token length. More...
 
const ENVIRONMENT_PRODUCTION = 0
 integer Production environment. More...
 
const ENVIRONMENT_SANDBOX = 1
 integer Sandbox environment. More...
 
const SOCKET_SELECT_TIMEOUT = 1000000
 integer Default socket select timeout in micro seconds. More...
 
const WRITE_INTERVAL = 10000
 integer Default write interval in micro seconds. More...
 

Protected Member Functions

array _getQueue (integer $nQueueKey, integer $nProcess=0)
 Returns the queue from the shared memory. More...
 
void _mainLoop ()
 The process main loop. More...
 
boolean _setQueue (integer $nQueueKey, integer $nProcess=0, array $aQueue=array())
 Store the queue into the shared memory. More...
 
- Protected Member Functions inherited from ApnsPHP_Push
string _getBinaryNotification (string $sDeviceToken, string $sPayload, integer $nMessageID=0, integer $nExpire=604800)
 Generate a binary notification from a device token and a JSON-encoded payload. More...
 
array _parseErrorMessage (string $sErrorMessage)
 Parses the error message. More...
 
array null _readErrorMessage ()
 Reads an error message (if present) from the main stream. More...
 
void _removeMessageFromQueue (integer $nMessageID, boolean $bError=false)
 Remove a message from the message queue. More...
 
boolean _updateQueue (array $aErrorMessage=null)
 Checks for error message and deletes messages successfully sent from message queue. More...
 
- Protected Member Functions inherited from ApnsPHP_Abstract
boolean _connect ()
 Connects to Apple Push Notification service server. More...
 
void _log (string $sMessage)
 Logs a message through the Logger. More...
 

Protected Attributes

array $_aPids = array()
 Array of process PIDs. More...
 
resource $_hSem
 Semaphore. More...
 
resource $_hShm
 Shared memory. More...
 
integer $_nCurrentProcess
 Cardinal process number (0, 1, 2, ...). More...
 
integer $_nParentPid
 The parent process id. More...
 
integer $_nProcesses = 3
 The number of processes to start. More...
 
integer $_nRunningProcesses
 The number of running processes. More...
 
- Protected Attributes inherited from ApnsPHP_Push
 $_aErrorResponseMessages
 array Error-response messages. More...
 
array $_aErrors = array()
 Error container. More...
 
array $_aMessageQueue = array()
 Message queue. More...
 
 $_aServiceURLs
 array Service URLs environments. More...
 
integer $_nSendRetryTimes = 3
 Send retry times. More...
 
- Protected Attributes inherited from ApnsPHP_Abstract
array $_aServiceURLs = array()
 Container for service URLs environments. More...
 
resource $_hSocket
 SSL Socket. More...
 
ApnsPHP_Log_Interface $_logger
 Logger. More...
 
integer $_nConnectRetryInterval
 Connect retry interval in micro seconds. More...
 
integer $_nConnectRetryTimes = 3
 Connect retry times. More...
 
integer $_nConnectTimeout
 Connect timeout in seconds. More...
 
integer $_nEnvironment
 Active environment. More...
 
integer $_nSocketSelectTimeout
 Socket select timeout in micro seconds. More...
 
integer $_nWriteInterval
 Write interval in micro seconds. More...
 
string $_sProviderCertificateFile
 Provider certificate file with key (Bundled PEM). More...
 
string $_sProviderCertificatePassphrase
 Provider certificate passphrase. More...
 
string $_sRootCertificationAuthorityFile
 Root certification authority file. More...
 

Detailed Description

The Push Notification Server Provider.

The class manages multiple Push Notification Providers and an inter-process message queue. This class is useful to parallelize and speed-up send activities to Apple Push Notification service.

Definition at line 34 of file Server.php.

Member Function Documentation

void __construct ( integer  $nEnvironment,
string  $sProviderCertificateFile 
)

Constructor.

Parameters
$nEnvironmentEnvironment.
$sProviderCertificateFileProvider certificate file with key (Bundled PEM).
Exceptions
ApnsPHP_Push_Server_Exceptionif is unable to get Shared Memory Segment or Semaphore ID.

Definition at line 59 of file Server.php.

60  {
61  parent::__construct($nEnvironment, $sProviderCertificateFile);
62 
63  $this->_nParentPid = posix_getpid();
64  $this->_hShm = shm_attach(mt_rand(), self::SHM_SIZE);
65  if ($this->_hShm === false) {
67  'Unable to get shared memory segment'
68  );
69  }
70 
71  $this->_hSem = sem_get(mt_rand());
72  if ($this->_hSem === false) {
74  'Unable to get semaphore id'
75  );
76  }
77 
78  register_shutdown_function(array($this, 'onShutdown'));
79 
80  pcntl_signal(SIGCHLD, array($this, 'onChildExited'));
81  foreach(array(SIGTERM, SIGQUIT, SIGINT) as $nSignal) {
82  pcntl_signal($nSignal, array($this, 'onSignal'));
83  }
84  }
array _getQueue ( integer  $nQueueKey,
integer  $nProcess = 0 
)
protected

Returns the queue from the shared memory.

Parameters
$nQueueKeyThe key of the queue stored in the shared memory.
$nProcess[optional] The process cardinal number.
Returns
Array of messages from the queue.

Definition at line 313 of file Server.php.

Referenced by _mainLoop(), add(), getErrors(), and getQueue().

314  {
315  if (!shm_has_var($this->_hShm, $nQueueKey + $nProcess)) {
316  return array();
317  }
318  return shm_get_var($this->_hShm, $nQueueKey + $nProcess);
319  }

Here is the caller graph for this function:

void _mainLoop ( )
protected

The process main loop.

During the main loop: the per-process error queue is read and the common error message container is populated; the per-process message queue is spooled (message from this queue is added to ApnsPHP_Push queue and delivered).

Definition at line 273 of file Server.php.

References _getQueue(), ApnsPHP_Abstract::_log(), and _setQueue().

Referenced by start().

274  {
275  while (true) {
276  pcntl_signal_dispatch();
277 
278  if (posix_getppid() != $this->_nParentPid) {
279  $this->_log("INFO: Parent process {$this->_nParentPid} died unexpectedly, exiting...");
280  break;
281  }
282 
283  sem_acquire($this->_hSem);
284  $this->_setQueue(self::SHM_ERROR_MESSAGES_QUEUE_KEY, 0,
285  array_merge($this->_getQueue(self::SHM_ERROR_MESSAGES_QUEUE_KEY), parent::getErrors())
286  );
287 
288  $aQueue = $this->_getQueue(self::SHM_MESSAGES_QUEUE_KEY_START, $this->_nCurrentProcess);
289  foreach($aQueue as $message) {
290  parent::add($message);
291  }
292  $this->_setQueue(self::SHM_MESSAGES_QUEUE_KEY_START, $this->_nCurrentProcess);
293  sem_release($this->_hSem);
294 
295  $nMessages = count($aQueue);
296  if ($nMessages > 0) {
297  $this->_log('INFO: Process ' . ($this->_nCurrentProcess + 1) . " has {$nMessages} messages, sending...");
298  parent::send();
299  } else {
300  usleep(self::MAIN_LOOP_USLEEP);
301  }
302  }
303  }
array _getQueue(integer $nQueueKey, integer $nProcess=0)
Returns the queue from the shared memory.
Definition: Server.php:313
void _log(string $sMessage)
Logs a message through the Logger.
Definition: Abstract.php:414
boolean _setQueue(integer $nQueueKey, integer $nProcess=0, array $aQueue=array())
Store the queue into the shared memory.
Definition: Server.php:331

Here is the call graph for this function:

Here is the caller graph for this function:

boolean _setQueue ( integer  $nQueueKey,
integer  $nProcess = 0,
array  $aQueue = array() 
)
protected

Store the queue into the shared memory.

Parameters
$nQueueKeyThe key of the queue to store in the shared memory.
$nProcess[optional] The process cardinal number.
$aQueue[optional] The queue to store into shared memory. The default value is an empty array, useful to empty the queue.
Returns
True on success, false otherwise.

Definition at line 331 of file Server.php.

Referenced by _mainLoop(), add(), getErrors(), and getQueue().

332  {
333  if (!is_array($aQueue)) {
334  $aQueue = array();
335  }
336  return shm_put_var($this->_hShm, $nQueueKey + $nProcess, $aQueue);
337  }

Here is the caller graph for this function:

void add ( ApnsPHP_Message  $message)

Adds a message to the inter-process message queue.

Messages are added to the queues in a round-robin fashion starting from the first process to the last.

Parameters
$messageThe message.

Definition at line 209 of file Server.php.

References _getQueue(), and _setQueue().

210  {
211  static $n = 0;
212  if ($n >= $this->_nProcesses) {
213  $n = 0;
214  }
215  sem_acquire($this->_hSem);
216  $aQueue = $this->_getQueue(self::SHM_MESSAGES_QUEUE_KEY_START, $n);
217  $aQueue[] = $message;
218  $this->_setQueue(self::SHM_MESSAGES_QUEUE_KEY_START, $n, $aQueue);
219  sem_release($this->_hSem);
220  $n++;
221  }
array _getQueue(integer $nQueueKey, integer $nProcess=0)
Returns the queue from the shared memory.
Definition: Server.php:313
boolean _setQueue(integer $nQueueKey, integer $nProcess=0, array $aQueue=array())
Store the queue into the shared memory.
Definition: Server.php:331

Here is the call graph for this function:

array getErrors ( boolean  $bEmpty = true)

Returns messages not delivered to the end user because one (or more) error occurred.

Parameters
$bEmpty[optional] Empty message container.
Returns
Array of messages not delivered because one or more errors occurred.

Definition at line 255 of file Server.php.

References _getQueue(), and _setQueue().

256  {
257  sem_acquire($this->_hSem);
258  $aRet = $this->_getQueue(self::SHM_ERROR_MESSAGES_QUEUE_KEY);
259  if ($bEmpty) {
260  $this->_setQueue(self::SHM_ERROR_MESSAGES_QUEUE_KEY, 0, array());
261  }
262  sem_release($this->_hSem);
263  return $aRet;
264  }
array _getQueue(integer $nQueueKey, integer $nProcess=0)
Returns the queue from the shared memory.
Definition: Server.php:313
boolean _setQueue(integer $nQueueKey, integer $nProcess=0, array $aQueue=array())
Store the queue into the shared memory.
Definition: Server.php:331

Here is the call graph for this function:

array getQueue ( boolean  $bEmpty = true)

Returns messages in the message queue.

When a message is successful sent or reached the maximum retry time is removed from the message queue and inserted in the Errors container. Use the getErrors() method to retrive messages with delivery error(s).

Parameters
$bEmpty[optional] Empty message queue.
Returns
Array of messages left on the queue.

Definition at line 233 of file Server.php.

References $_nProcesses, _getQueue(), and _setQueue().

234  {
235  $aRet = array();
236  sem_acquire($this->_hSem);
237  for ($i = 0; $i < $this->_nProcesses; $i++) {
238  $aRet = array_merge($aRet, $this->_getQueue(self::SHM_MESSAGES_QUEUE_KEY_START, $i));
239  if ($bEmpty) {
240  $this->_setQueue(self::SHM_MESSAGES_QUEUE_KEY_START, $i);
241  }
242  }
243  sem_release($this->_hSem);
244  return $aRet;
245  }
integer $_nProcesses
The number of processes to start.
Definition: Server.php:41
array _getQueue(integer $nQueueKey, integer $nProcess=0)
Returns the queue from the shared memory.
Definition: Server.php:313
boolean _setQueue(integer $nQueueKey, integer $nProcess=0, array $aQueue=array())
Store the queue into the shared memory.
Definition: Server.php:331

Here is the call graph for this function:

void onChildExited ( )

Waits until a forked process has exited and decreases the current running process number.

Definition at line 109 of file Server.php.

110  {
111  while (pcntl_waitpid(-1, $nStatus, WNOHANG) > 0) {
112  $this->_nRunningProcesses--;
113  }
114  }
void onShutdown ( )

When the parent process exits, cleans shared memory and semaphore.

This is called using 'register_shutdown_function' pattern.

See Also
http://php.net/register_shutdown_function

Definition at line 146 of file Server.php.

References ApnsPHP_Abstract::_log().

147  {
148  if (posix_getpid() == $this->_nParentPid) {
149  $this->_log('INFO: Parent shutdown, cleaning memory...');
150  @shm_remove($this->_hShm) && @shm_detach($this->_hShm);
151  @sem_remove($this->_hSem);
152  }
153  }
void _log(string $sMessage)
Logs a message through the Logger.
Definition: Abstract.php:414

Here is the call graph for this function:

void onSignal ( integer  $nSignal)

When a child (not the parent) receive a signal of type TERM, QUIT or INT exits from the current process and decreases the current running process number.

Parameters
$nSignalSignal number.

Definition at line 122 of file Server.php.

References ApnsPHP_Abstract::_log().

123  {
124  switch ($nSignal) {
125  case SIGTERM:
126  case SIGQUIT:
127  case SIGINT:
128  if (($nPid = posix_getpid()) != $this->_nParentPid) {
129  $this->_log("INFO: Child $nPid received signal #{$nSignal}, shutdown...");
130  $this->_nRunningProcesses--;
131  exit(0);
132  }
133  break;
134  default:
135  $this->_log("INFO: Ignored signal #{$nSignal}.");
136  break;
137  }
138  }
void _log(string $sMessage)
Logs a message through the Logger.
Definition: Abstract.php:414

Here is the call graph for this function:

boolean run ( )

Checks if the server is running and calls signal handlers for pending signals.

Example:

while ($Server->run()) {
// do somethings...
usleep(200000);
}
Returns
True if the server is running.

Definition at line 99 of file Server.php.

100  {
101  pcntl_signal_dispatch();
102  return $this->_nRunningProcesses > 0;
103  }
void setProcesses ( integer  $nProcesses)

Set the total processes to start, default is 3.

Parameters
$nProcessesProcesses to start up.

Definition at line 160 of file Server.php.

161  {
162  $nProcesses = (int)$nProcesses;
163  if ($nProcesses <= 0) {
164  return;
165  }
166  $this->_nProcesses = $nProcesses;
167  }
void start ( )

Starts the server forking all processes and return immediately.

Every forked process is connected to Apple Push Notification Service on start and enter on the main loop.

Definition at line 175 of file Server.php.

References $_nProcesses, ApnsPHP_Abstract::_log(), and _mainLoop().

176  {
177  for ($i = 0; $i < $this->_nProcesses; $i++) {
178  $this->_nCurrentProcess = $i;
179  $this->_aPids[$i] = $nPid = pcntl_fork();
180  if ($nPid == -1) {
181  $this->_log('WARNING: Could not fork');
182  } else if ($nPid > 0) {
183  // Parent process
184  $this->_log("INFO: Forked process PID {$nPid}");
185  $this->_nRunningProcesses++;
186  } else {
187  // Child process
188  try {
189  parent::connect();
190  } catch (ApnsPHP_Exception $e) {
191  $this->_log('ERROR: ' . $e->getMessage() . ', exiting...');
192  exit(1);
193  }
194  $this->_mainLoop();
195  parent::disconnect();
196  exit(0);
197  }
198  }
199  }
integer $_nProcesses
The number of processes to start.
Definition: Server.php:41
Exception class.
Definition: Exception.php:25
void _log(string $sMessage)
Logs a message through the Logger.
Definition: Abstract.php:414
void _mainLoop()
The process main loop.
Definition: Server.php:273

Here is the call graph for this function:

Field Documentation

array $_aPids = array()
protected

Array of process PIDs.

Definition at line 42 of file Server.php.

resource $_hSem
protected

Semaphore.

Definition at line 48 of file Server.php.

resource $_hShm
protected

Shared memory.

Definition at line 47 of file Server.php.

integer $_nCurrentProcess
protected

Cardinal process number (0, 1, 2, ...).

Definition at line 44 of file Server.php.

integer $_nParentPid
protected

The parent process id.

Definition at line 43 of file Server.php.

integer $_nProcesses = 3
protected

The number of processes to start.

Definition at line 41 of file Server.php.

Referenced by getQueue(), and start().

integer $_nRunningProcesses
protected

The number of running processes.

Definition at line 45 of file Server.php.

const MAIN_LOOP_USLEEP = 200000

integer Main loop sleep time in micro seconds.

Definition at line 36 of file Server.php.

const SHM_ERROR_MESSAGES_QUEUE_KEY = 999

integer Message queue identifier for not delivered messages.

Definition at line 39 of file Server.php.

const SHM_MESSAGES_QUEUE_KEY_START = 1000

integer Message queue start identifier for messages.

For every process 1 is added to this number.

Definition at line 38 of file Server.php.

const SHM_SIZE = 524288

integer Shared memory size in bytes useful to store message queues.

Definition at line 37 of file Server.php.


The documentation for this class was generated from the following file: