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;
30 // Message status codes
31 const MESSAGE_STATUS_CODE_OKAY = 'OKAY';
34 * Separator for all bootstrap node entries
36 const BOOTSTRAP_NODES_SEPARATOR = ';';
39 * An instance of a node
41 private $nodeInstance = NULL;
44 * An instance of a cruncher
46 private $cruncherInstance = NULL;
51 private $listenerInstance = NULL;
54 * A network package handler instance
56 private $packageInstance = NULL;
59 * A Receivable instance
61 private $receiverInstance = NULL;
66 private $stateInstance = NULL;
69 * Listener pool instance
71 private $listenerPoolInstance = NULL;
76 private $fragmenterInstance = NULL;
81 private $decoderInstance = NULL;
86 private $assemblerInstance = NULL;
89 * Protected constructor
91 * @param $className Name of the class
94 protected function __construct ($className) {
95 // Call parent constructor
96 parent::__construct($className);
100 * Getter for node instance
102 * @return $nodeInstance An instance of a node node
104 public final function getNodeInstance () {
105 return $this->nodeInstance;
109 * Setter for node instance
111 * @param $nodeInstance An instance of a node node
114 protected final function setNodeInstance (NodeHelper $nodeInstance) {
115 $this->nodeInstance = $nodeInstance;
119 * Getter for cruncher instance
121 * @return $cruncherInstance An instance of a cruncher cruncher
123 public final function getCruncherInstance () {
124 return $this->cruncherInstance;
128 * Setter for cruncher instance
130 * @param $cruncherInstance An instance of a cruncher cruncher
133 protected final function setCruncherInstance (CruncherHelper $cruncherInstance) {
134 $this->cruncherInstance = $cruncherInstance;
138 * Setter for listener instance
140 * @param $listenerInstance A Listenable instance
143 protected final function setListenerInstance (Listenable $listenerInstance) {
144 $this->listenerInstance = $listenerInstance;
148 * Getter for listener instance
150 * @return $listenerInstance A Listenable instance
152 protected final function getListenerInstance () {
153 return $this->listenerInstance;
157 * Setter for network package handler instance
159 * @param $packageInstance The network package instance we shall set
162 protected final function setPackageInstance (Deliverable $packageInstance) {
163 $this->packageInstance = $packageInstance;
167 * Getter for network package handler instance
169 * @return $packageInstance The network package handler instance we shall set
171 protected final function getPackageInstance () {
172 return $this->packageInstance;
176 * Setter for receiver instance
178 * @param $receiverInstance A Receivable instance we shall set
181 protected final function setReceiverInstance (Receivable $receiverInstance) {
182 $this->receiverInstance = $receiverInstance;
186 * Getter for receiver instance
188 * @return $receiverInstance A Receivable instance we shall get
190 protected final function getReceiverInstance () {
191 return $this->receiverInstance;
195 * Setter for state instance
197 * @param $stateInstance A Stateable instance
200 public final function setStateInstance (Stateable $stateInstance) {
201 $this->stateInstance = $stateInstance;
205 * Getter for state instance
207 * @return $stateInstance A Stateable instance
209 public final function getStateInstance () {
210 return $this->stateInstance;
214 * Setter for listener pool instance
216 * @param $listenerPoolInstance Our new listener pool instance
219 protected final function setListenerPoolInstance (PoolableListener $listenerPoolInstance) {
220 $this->listenerPoolInstance = $listenerPoolInstance;
224 * Getter for listener pool instance
226 * @return $listenerPoolInstance Our current listener pool instance
228 public final function getListenerPoolInstance () {
229 return $this->listenerPoolInstance;
233 * Setter for fragmenter instance
235 * @param $fragmenterInstance A Fragmentable instance
238 protected final function setFragmenterInstance (Fragmentable $fragmenterInstance) {
239 $this->fragmenterInstance = $fragmenterInstance;
243 * Getter for fragmenter instance
245 * @return $fragmenterInstance A Fragmentable instance
247 protected final function getFragmenterInstance () {
248 return $this->fragmenterInstance;
252 * Setter for decoder instance
254 * @param $decoderInstance A Decodeable instance
257 protected final function setDecoderInstance (Decodeable $decoderInstance) {
258 $this->decoderInstance = $decoderInstance;
262 * Getter for decoder instance
264 * @return $decoderInstance A Decodeable instance
266 protected final function getDecoderInstance () {
267 return $this->decoderInstance;
271 * Setter for assembler instance
273 * @param $assemblerInstance A Decodeable instance
276 protected final function setAssemblerInstance (Assembler $assemblerInstance) {
277 $this->assemblerInstance = $assemblerInstance;
281 * Getter for assembler instance
283 * @return $assemblerInstance A Decodeable instance
285 protected final function getAssemblerInstance () {
286 return $this->assemblerInstance;
292 * @param $nodeId Our new node id
295 protected final function setNodeId ($nodeId) {
297 $this->getConfigInstance()->setConfigEntry('node_id', (string) $nodeId);
303 * @return $nodeId Current node id
305 public final function getNodeId () {
306 // Get it from config
307 return $this->getConfigInstance()->getConfigEntry('node_id');
311 * Setter for session id
313 * @param $sessionId Our new session id
316 protected final function setSessionId ($sessionId) {
317 $this->getConfigInstance()->setConfigEntry('session_id', (string) $sessionId);
321 * Getter for session id
323 * @return $sessionId Current session id
325 public final function getSessionId () {
326 return $this->getConfigInstance()->getConfigEntry('session_id');
330 * Constructs a callable method name from given socket error code. If the
331 * method is not found, a generic one is used.
333 * @param $errorCode Error code from socket_last_error()
334 * @return $handlerName Call-back method name for the error handler
335 * @throws UnsupportedSocketErrorHandlerException If the error handler is not implemented
337 protected function getSocketErrorHandlerFromCode ($errorCode) {
338 // Create a name from translated error code
339 $handlerName = 'socketError' . $this->convertToClassName($this->translateSocketErrorCodeToName($errorCode)) . 'Handler';
341 // Is the call-back method there?
342 if (!method_exists($this, $handlerName)) {
343 // Please implement this
344 throw new UnsupportedSocketErrorHandlerException(array($this, $handlerName, $errorCode), self::EXCEPTION_UNSUPPORTED_ERROR_HANDLER);
352 * Handles socket error for given socket resource and peer data. This method
353 * validates $socketResource if it is a valid resource (see is_resource())
354 * but assumes valid data in array $recipientData, except that
355 * count($recipientData) is always 2.
357 * @param $socketResource A valid socket resource
358 * @param $recipientData An array with two elements: 0=IP number, 1=port number
360 * @throws InvalidSocketException If $socketResource is no socket resource
361 * @throws NoSocketErrorDetectedException If socket_last_error() gives zero back
363 protected final function handleSocketError ($socketResource, array $recipientData) {
364 // This method handles only socket resources
365 if (!is_resource($socketResource)) {
366 // No resource, abort here
367 throw new InvalidSocketException(array($this, $socketResource), BaseListener::EXCEPTION_INVALID_SOCKET);
370 // Check count of array, should be two
371 assert(count($recipientData) == 2);
373 // Get error code for first validation (0 is not an error)
374 $errorCode = socket_last_error($socketResource);
376 // If the error code is zero, someone called this method without an error
377 if ($errorCode == 0) {
378 // No error detected (or previously cleared outside this method)
379 throw new NoSocketErrorDetectedException(array($this, $socketResource), BaseListener::EXCEPTION_NO_SOCKET_ERROR);
382 // Get handler (method) name
383 $handlerName = $this->getSocketErrorHandlerFromCode($errorCode);
385 // Call-back the error handler method
386 call_user_func(array($this, $handlerName), $socketResource);
388 // Finally clear the error because it has been handled
389 socket_clear_error($socketResource);
393 * Checks whether the final (last) chunk is valid
395 * @param $chunks An array with chunks and (hopefully) a valid final chunk
396 * @return $isValid Whether the final (last) chunk is valid
398 protected function isValidFinalChunk (array $chunks) {
399 // Default is all fine
402 // Split the (possible) EOP chunk
403 $chunkSplits = explode(PackageFragmenter::CHUNK_DATA_HASH_SEPARATOR, $chunks[count($chunks) - 1]);
405 // Make sure chunks with only 3 elements are parsed (for details see ChunkHandler)
406 //* NOISY-DEBUG: */ $this->debugOutput('eopChunk=' . $chunks[count($chunks) - 1] . ',chunkSplits=' . print_r($chunkSplits,true));
407 assert(count($chunkSplits) == 3);
409 // Validate final chunk
410 if (substr($chunkSplits[ChunkHandler::CHUNK_SPLITS_INDEX_RAW_DATA], 0, strlen(PackageFragmenter::END_OF_PACKAGE_IDENTIFIER)) != PackageFragmenter::END_OF_PACKAGE_IDENTIFIER) {
413 } elseif (substr_count($chunkSplits[ChunkHandler::CHUNK_SPLITS_INDEX_RAW_DATA], PackageFragmenter::CHUNK_HASH_SEPARATOR) != 1) {
414 // CHUNK_HASH_SEPARATOR shall only be found once
423 * Translates socket error codes into our own internal names which can be
424 * used for call-backs.
426 * @param $errorCode The error code from socket_last_error() to be translated
427 * @return $errorName The translated name (all lower-case, with underlines)
429 public function translateSocketErrorCodeToName ($errorCode) {
430 // Nothing bad happened by default
431 $errorName = BaseRawDataHandler::SOCKET_CONNECTED;
433 // Is the code a number, then we have to change it
434 switch ($errorCode) {
435 case 0: // Silently ignored, the socket is connected
438 case 11: // "Resource temporary unavailable"
439 $errorName = BaseRawDataHandler::SOCKET_ERROR_RESOURCE_UNAVAILABLE;
442 case 107: // "Transport end-point not connected"
443 case 134: // On some (?) systems for 'transport end-point not connected'
444 // @TODO On some systems it is 134, on some 107?
445 $errorName = BaseRawDataHandler::SOCKET_ERROR_TRANSPORT_ENDPOINT;
448 case 110: // "Connection timed out"
449 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_TIMED_OUT;
452 case 111: // "Connection refused"
453 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_REFUSED;
456 case 113: // "No route to host"
457 $errorName = BaseRawDataHandler::SOCKET_ERROR_NO_ROUTE_TO_HOST;
460 case 114: // "Operation already in progress"
461 $errorName = BaseRawDataHandler::SOCKET_ERROR_OPERATION_ALREADY_PROGRESS;
464 case 115: // "Operation now in progress"
465 $errorName = BaseRawDataHandler::SOCKET_ERROR_OPERATION_IN_PROGRESS;
468 default: // Everything else <> 0
469 // Unhandled error code detected, so first debug it because we may want to handle it like the others
470 $this->debugOutput('[' . __METHOD__ . ':' . __LINE__ . '] UNKNOWN ERROR CODE = ' . $errorCode . ', MESSAGE = ' . socket_strerror($errorCode));
472 // Change it only in this class
473 $errorName = BaseRawDataHandler::SOCKET_ERROR_UNKNOWN;
477 // Return translated name
482 * Shuts down a given socket resource. This method does only ease calling
485 * @param $socketResource A valid socket resource
488 public function shutdownSocket ($socketResource) {
490 $this->debugOutput('HUB-SYSTEM: Shutting down socket resource ' . $socketResource . ' with state ' . $this->getPrintableState() . ' ...');
492 // Set socket resource
493 $this->setSocketResource($socketResource);
495 // Get a visitor instance
496 $visitorInstance = ObjectFactory::createObjectByConfiguredName('shutdown_socket_visitor_class');
499 $this->debugOutput('HUB-SYSTEM:' . $this->__toString() . ': visitorInstance=' . $visitorInstance->__toString());
502 $this->accept($visitorInstance);
506 * Half-shuts down a given socket resource. This method does only ease calling
507 * an other visitor than shutdownSocket() does.
509 * @param $socketResource A valid socket resource
512 public function halfShutdownSocket ($socketResource) {
514 $this->debugOutput('HUB-SYSTEM: Half-shutting down socket resource ' . $socketResource . ' with state ' . $this->getPrintableState() . ' ...');
516 // Set socket resource
517 $this->setSocketResource($socketResource);
519 // Get a visitor instance
520 $visitorInstance = ObjectFactory::createObjectByConfiguredName('half_shutdown_socket_visitor_class');
523 $this->debugOutput('HUB-SYSTEM:' . $this->__toString() . ': visitorInstance=' . $visitorInstance->__toString());
526 $this->accept($visitorInstance);
530 * "Getter" for a printable state name
532 * @return $stateName Name of the node's state in a printable format
534 public final function getPrintableState () {
538 // Get the state instance
539 $stateInstance = $this->getStateInstance();
541 // Is it an instance of Stateable?
542 if ($stateInstance instanceof Stateable) {
543 // Then use that state name
544 $stateName = $stateInstance->getStateName();