3 * A general hub system class
5 * @author Roland Haeder <webmaster@ship-simu.org>
7 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2012 Hub Developer Team
8 * @license GNU GPL 3.0 or any newer version
9 * @link http://www.ship-simu.org
11 * This program is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program. If not, see <http://www.gnu.org/licenses/>.
24 class BaseHubSystem extends BaseFrameworkSystem {
26 const EXCEPTION_UNSUPPORTED_ERROR_HANDLER = 0x900;
27 const EXCEPTION_CHUNK_ALREADY_ASSEMBLED = 0x901;
28 const EXCEPTION_ANNOUNCEMENT_NOT_ACCEPTED = 0x902;
29 const EXCEPTION_INVALID_CONNECTION_TYPE = 0x903;
31 // Message status codes
32 const MESSAGE_STATUS_CODE_OKAY = 'OKAY';
35 * Separator for all bootstrap node entries
37 const BOOTSTRAP_NODES_SEPARATOR = ';';
40 * An instance of a node
42 private $nodeInstance = NULL;
45 * An instance of a cruncher
47 private $cruncherInstance = NULL;
52 private $listenerInstance = NULL;
55 * A network package handler instance
57 private $packageInstance = NULL;
60 * A Receivable instance
62 private $receiverInstance = NULL;
67 private $stateInstance = NULL;
70 * Listener pool instance
72 private $listenerPoolInstance = NULL;
77 private $fragmenterInstance = NULL;
82 private $decoderInstance = NULL;
87 private $assemblerInstance = NULL;
90 * Protected constructor
92 * @param $className Name of the class
95 protected function __construct ($className) {
96 // Call parent constructor
97 parent::__construct($className);
101 * Getter for node instance
103 * @return $nodeInstance An instance of a node node
105 public final function getNodeInstance () {
106 return $this->nodeInstance;
110 * Setter for node instance
112 * @param $nodeInstance An instance of a node node
115 protected final function setNodeInstance (NodeHelper $nodeInstance) {
116 $this->nodeInstance = $nodeInstance;
120 * Getter for cruncher instance
122 * @return $cruncherInstance An instance of a cruncher cruncher
124 public final function getCruncherInstance () {
125 return $this->cruncherInstance;
129 * Setter for cruncher instance
131 * @param $cruncherInstance An instance of a cruncher cruncher
134 protected final function setCruncherInstance (CruncherHelper $cruncherInstance) {
135 $this->cruncherInstance = $cruncherInstance;
139 * Setter for listener instance
141 * @param $listenerInstance A Listenable instance
144 protected final function setListenerInstance (Listenable $listenerInstance) {
145 $this->listenerInstance = $listenerInstance;
149 * Getter for listener instance
151 * @return $listenerInstance A Listenable instance
153 protected final function getListenerInstance () {
154 return $this->listenerInstance;
158 * Setter for network package handler instance
160 * @param $packageInstance The network package instance we shall set
163 protected final function setPackageInstance (Deliverable $packageInstance) {
164 $this->packageInstance = $packageInstance;
168 * Getter for network package handler instance
170 * @return $packageInstance The network package handler instance we shall set
172 protected final function getPackageInstance () {
173 return $this->packageInstance;
177 * Setter for receiver instance
179 * @param $receiverInstance A Receivable instance we shall set
182 protected final function setReceiverInstance (Receivable $receiverInstance) {
183 $this->receiverInstance = $receiverInstance;
187 * Getter for receiver instance
189 * @return $receiverInstance A Receivable instance we shall get
191 protected final function getReceiverInstance () {
192 return $this->receiverInstance;
196 * Setter for state instance
198 * @param $stateInstance A Stateable instance
201 public final function setStateInstance (Stateable $stateInstance) {
202 $this->stateInstance = $stateInstance;
206 * Getter for state instance
208 * @return $stateInstance A Stateable instance
210 public final function getStateInstance () {
211 return $this->stateInstance;
215 * Setter for listener pool instance
217 * @param $listenerPoolInstance The new listener pool instance
220 protected final function setListenerPoolInstance (PoolableListener $listenerPoolInstance) {
221 $this->listenerPoolInstance = $listenerPoolInstance;
225 * Getter for listener pool instance
227 * @return $listenerPoolInstance Our current listener pool instance
229 public final function getListenerPoolInstance () {
230 return $this->listenerPoolInstance;
234 * Setter for fragmenter instance
236 * @param $fragmenterInstance A Fragmentable instance
239 protected final function setFragmenterInstance (Fragmentable $fragmenterInstance) {
240 $this->fragmenterInstance = $fragmenterInstance;
244 * Getter for fragmenter instance
246 * @return $fragmenterInstance A Fragmentable instance
248 protected final function getFragmenterInstance () {
249 return $this->fragmenterInstance;
253 * Setter for decoder instance
255 * @param $decoderInstance A Decodeable instance
258 protected final function setDecoderInstance (Decodeable $decoderInstance) {
259 $this->decoderInstance = $decoderInstance;
263 * Getter for decoder instance
265 * @return $decoderInstance A Decodeable instance
267 protected final function getDecoderInstance () {
268 return $this->decoderInstance;
272 * Setter for assembler instance
274 * @param $assemblerInstance A Decodeable instance
277 protected final function setAssemblerInstance (Assembler $assemblerInstance) {
278 $this->assemblerInstance = $assemblerInstance;
282 * Getter for assembler instance
284 * @return $assemblerInstance A Decodeable instance
286 protected final function getAssemblerInstance () {
287 return $this->assemblerInstance;
293 * @param $nodeId The new node id
296 protected final function setNodeId ($nodeId) {
298 $this->getConfigInstance()->setConfigEntry('node_id', (string) $nodeId);
304 * @return $nodeId Current node id
306 public final function getNodeId () {
307 // Get it from config
308 return $this->getConfigInstance()->getConfigEntry('node_id');
312 * Setter for private key
314 * @param $privateKey The new private key
317 protected final function setPrivateKey ($privateKey) {
319 $this->getConfigInstance()->setConfigEntry('private_key', (string) $privateKey);
323 * Getter for private key
325 * @return $privateKey Current private key
327 public final function getPrivateKey () {
328 // Get it from config
329 return $this->getConfigInstance()->getConfigEntry('private_key');
333 * Setter for private key hash
335 * @param $privateKeyHash The new private key hash
338 protected final function setPrivateKeyHash ($privateKeyHash) {
340 $this->getConfigInstance()->setConfigEntry('private_key_hash', (string) $privateKeyHash);
344 * Getter for private key hash
346 * @return $privateKeyHash Current private key hash
348 public final function getPrivateKeyHash () {
349 // Get it from config
350 return $this->getConfigInstance()->getConfigEntry('private_key_hash');
354 * Setter for session id
356 * @param $sessionId The new session id
359 protected final function setSessionId ($sessionId) {
360 $this->getConfigInstance()->setConfigEntry('session_id', (string) $sessionId);
364 * Getter for session id
366 * @return $sessionId Current session id
368 public final function getSessionId () {
369 return $this->getConfigInstance()->getConfigEntry('session_id');
373 * Constructs a callable method name from given socket error code. If the
374 * method is not found, a generic one is used.
376 * @param $errorCode Error code from socket_last_error()
377 * @return $handlerName Call-back method name for the error handler
378 * @throws UnsupportedSocketErrorHandlerException If the error handler is not implemented
380 protected function getSocketErrorHandlerFromCode ($errorCode) {
381 // Create a name from translated error code
382 $handlerName = 'socketError' . $this->convertToClassName($this->translateSocketErrorCodeToName($errorCode)) . 'Handler';
384 // Is the call-back method there?
385 if (!method_exists($this, $handlerName)) {
386 // Please implement this
387 throw new UnsupportedSocketErrorHandlerException(array($this, $handlerName, $errorCode), self::EXCEPTION_UNSUPPORTED_ERROR_HANDLER);
395 * Handles socket error for given socket resource and peer data. This method
396 * validates $socketResource if it is a valid resource (see is_resource())
397 * but assumes valid data in array $recipientData, except that
398 * count($recipientData) is always 2.
400 * @param $method Value of __METHOD__ from calling method
401 * @param $line Source code line where this method was called
402 * @param $socketResource A valid socket resource
403 * @param $recipientData An array with two elements: 0=IP number, 1=port number
405 * @throws InvalidSocketException If $socketResource is no socket resource
406 * @throws NoSocketErrorDetectedException If socket_last_error() gives zero back
408 protected final function handleSocketError ($method, $line, $socketResource, array $recipientData) {
409 // This method handles only socket resources
410 if (!is_resource($socketResource)) {
411 // No resource, abort here
412 throw new InvalidSocketException(array($this, $socketResource), BaseListener::EXCEPTION_INVALID_SOCKET);
415 // Check count of array, should be two
416 assert(count($recipientData) == 2);
418 // Get error code for first validation (0 is not an error)
419 $errorCode = socket_last_error($socketResource);
421 // If the error code is zero, someone called this method without an error
422 if ($errorCode == 0) {
423 // No error detected (or previously cleared outside this method)
424 throw new NoSocketErrorDetectedException(array($this, $socketResource), BaseListener::EXCEPTION_NO_SOCKET_ERROR);
427 // Get handler (method) name
428 $handlerName = $this->getSocketErrorHandlerFromCode($errorCode);
430 // Call-back the error handler method
431 call_user_func(array($this, $handlerName), $socketResource);
433 // Finally clear the error because it has been handled
434 socket_clear_error($socketResource);
438 * Checks whether the final (last) chunk is valid
440 * @param $chunks An array with chunks and (hopefully) a valid final chunk
441 * @return $isValid Whether the final (last) chunk is valid
443 protected function isValidFinalChunk (array $chunks) {
444 // Default is all fine
447 // Split the (possible) EOP chunk
448 $chunkSplits = explode(PackageFragmenter::CHUNK_DATA_HASH_SEPARATOR, $chunks[count($chunks) - 1]);
450 // Make sure chunks with only 3 elements are parsed (for details see ChunkHandler)
451 //* NOISY-DEBUG: */ $this->debugOutput('eopChunk=' . $chunks[count($chunks) - 1] . ',chunkSplits=' . print_r($chunkSplits,true));
452 assert(count($chunkSplits) == 3);
454 // Validate final chunk
455 if (substr($chunkSplits[ChunkHandler::CHUNK_SPLITS_INDEX_RAW_DATA], 0, strlen(PackageFragmenter::END_OF_PACKAGE_IDENTIFIER)) != PackageFragmenter::END_OF_PACKAGE_IDENTIFIER) {
458 } elseif (substr_count($chunkSplits[ChunkHandler::CHUNK_SPLITS_INDEX_RAW_DATA], PackageFragmenter::CHUNK_HASH_SEPARATOR) != 1) {
459 // CHUNK_HASH_SEPARATOR shall only be found once
468 * Translates socket error codes into our own internal names which can be
469 * used for call-backs.
471 * @param $errorCode The error code from socket_last_error() to be translated
472 * @return $errorName The translated name (all lower-case, with underlines)
474 public function translateSocketErrorCodeToName ($errorCode) {
475 // Nothing bad happened by default
476 $errorName = BaseRawDataHandler::SOCKET_CONNECTED;
478 // Is the code a number, then we have to change it
479 switch ($errorCode) {
480 case 0: // Silently ignored, the socket is connected
483 case 11: // "Resource temporary unavailable"
484 $errorName = BaseRawDataHandler::SOCKET_ERROR_RESOURCE_UNAVAILABLE;
487 case 107: // "Transport end-point not connected"
488 case 134: // On some (?) systems for 'transport end-point not connected'
489 // @TODO On some systems it is 134, on some 107?
490 $errorName = BaseRawDataHandler::SOCKET_ERROR_TRANSPORT_ENDPOINT;
493 case 110: // "Connection timed out"
494 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_TIMED_OUT;
497 case 111: // "Connection refused"
498 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_REFUSED;
501 case 113: // "No route to host"
502 $errorName = BaseRawDataHandler::SOCKET_ERROR_NO_ROUTE_TO_HOST;
505 case 114: // "Operation already in progress"
506 $errorName = BaseRawDataHandler::SOCKET_ERROR_OPERATION_ALREADY_PROGRESS;
509 case 115: // "Operation now in progress"
510 $errorName = BaseRawDataHandler::SOCKET_ERROR_OPERATION_IN_PROGRESS;
513 default: // Everything else <> 0
514 // Unhandled error code detected, so first debug it because we may want to handle it like the others
515 $this->debugOutput('[' . __METHOD__ . ':' . __LINE__ . '] UNKNOWN ERROR CODE = ' . $errorCode . ', MESSAGE = ' . socket_strerror($errorCode));
517 // Change it only in this class
518 $errorName = BaseRawDataHandler::SOCKET_ERROR_UNKNOWN;
522 // Return translated name
527 * Shuts down a given socket resource. This method does only ease calling
530 * @param $socketResource A valid socket resource
533 public function shutdownSocket ($socketResource) {
535 $this->debugOutput('HUB-SYSTEM: Shutting down socket resource ' . $socketResource . ' with state ' . $this->getPrintableState() . ' ...');
537 // Set socket resource
538 $this->setSocketResource($socketResource);
540 // Get a visitor instance
541 $visitorInstance = ObjectFactory::createObjectByConfiguredName('shutdown_socket_visitor_class');
544 $this->debugOutput('HUB-SYSTEM:' . $this->__toString() . ': visitorInstance=' . $visitorInstance->__toString());
547 $this->accept($visitorInstance);
551 * Half-shuts down a given socket resource. This method does only ease calling
552 * an other visitor than shutdownSocket() does.
554 * @param $socketResource A valid socket resource
557 public function halfShutdownSocket ($socketResource) {
559 $this->debugOutput('HUB-SYSTEM: Half-shutting down socket resource ' . $socketResource . ' with state ' . $this->getPrintableState() . ' ...');
561 // Set socket resource
562 $this->setSocketResource($socketResource);
564 // Get a visitor instance
565 $visitorInstance = ObjectFactory::createObjectByConfiguredName('half_shutdown_socket_visitor_class');
568 $this->debugOutput('HUB-SYSTEM:' . $this->__toString() . ': visitorInstance=' . $visitorInstance->__toString());
571 $this->accept($visitorInstance);
575 * "Getter" for a printable state name
577 * @return $stateName Name of the node's state in a printable format
579 public final function getPrintableState () {
583 // Get the state instance
584 $stateInstance = $this->getStateInstance();
586 // Is it an instance of Stateable?
587 if ($stateInstance instanceof Stateable) {
588 // Then use that state name
589 $stateName = $stateInstance->getStateName();