3 * A general hub system class
5 * @author Roland Haeder <webmaster@ship-simu.org>
7 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2011 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;
30 * Separator for all bootstrap node entries
32 const BOOTSTRAP_NODES_SEPARATOR = ';';
35 * An instance of a node
37 private $nodeInstance = NULL;
40 * An instance of a cruncher
42 private $cruncherInstance = NULL;
47 private $listenerInstance = NULL;
50 * A network package handler instance
52 private $packageInstance = NULL;
55 * A Receivable instance
57 private $receiverInstance = NULL;
62 private $stateInstance = NULL;
65 * Listener pool instance
67 private $listenerPoolInstance = NULL;
72 private $fragmenterInstance = NULL;
77 private $decoderInstance = NULL;
82 private $assemblerInstance = NULL;
85 * Protected constructor
87 * @param $className Name of the class
90 protected function __construct ($className) {
91 // Call parent constructor
92 parent::__construct($className);
96 * Getter for node instance
98 * @return $nodeInstance An instance of a node node
100 public final function getNodeInstance () {
101 return $this->nodeInstance;
105 * Setter for node instance
107 * @param $nodeInstance An instance of a node node
110 protected final function setNodeInstance (NodeHelper $nodeInstance) {
111 $this->nodeInstance = $nodeInstance;
115 * Getter for cruncher instance
117 * @return $cruncherInstance An instance of a cruncher cruncher
119 public final function getCruncherInstance () {
120 return $this->cruncherInstance;
124 * Setter for cruncher instance
126 * @param $cruncherInstance An instance of a cruncher cruncher
129 protected final function setCruncherInstance (CruncherHelper $cruncherInstance) {
130 $this->cruncherInstance = $cruncherInstance;
134 * Setter for listener instance
136 * @param $listenerInstance A Listenable instance
139 protected final function setListenerInstance (Listenable $listenerInstance) {
140 $this->listenerInstance = $listenerInstance;
144 * Getter for listener instance
146 * @return $listenerInstance A Listenable instance
148 protected final function getListenerInstance () {
149 return $this->listenerInstance;
153 * Setter for network package handler instance
155 * @param $packageInstance The network package instance we shall set
158 protected final function setPackageInstance (Deliverable $packageInstance) {
159 $this->packageInstance = $packageInstance;
163 * Getter for network package handler instance
165 * @return $packageInstance The network package handler instance we shall set
167 protected final function getPackageInstance () {
168 return $this->packageInstance;
172 * Setter for receiver instance
174 * @param $receiverInstance A Receivable instance we shall set
177 protected final function setReceiverInstance (Receivable $receiverInstance) {
178 $this->receiverInstance = $receiverInstance;
182 * Getter for receiver instance
184 * @return $receiverInstance A Receivable instance we shall get
186 protected final function getReceiverInstance () {
187 return $this->receiverInstance;
191 * Setter for state instance
193 * @param $stateInstance A Stateable instance
196 public final function setStateInstance (Stateable $stateInstance) {
197 $this->stateInstance = $stateInstance;
201 * Getter for state instance
203 * @return $stateInstance A Stateable instance
205 public final function getStateInstance () {
206 return $this->stateInstance;
210 * Setter for listener pool instance
212 * @param $listenerPoolInstance Our new listener pool instance
215 protected final function setListenerPoolInstance (PoolableListener $listenerPoolInstance) {
216 $this->listenerPoolInstance = $listenerPoolInstance;
220 * Getter for listener pool instance
222 * @return $listenerPoolInstance Our current listener pool instance
224 public final function getListenerPoolInstance () {
225 return $this->listenerPoolInstance;
229 * Setter for fragmenter instance
231 * @param $fragmenterInstance A Fragmentable instance
234 protected final function setFragmenterInstance (Fragmentable $fragmenterInstance) {
235 $this->fragmenterInstance = $fragmenterInstance;
239 * Getter for fragmenter instance
241 * @return $fragmenterInstance A Fragmentable instance
243 protected final function getFragmenterInstance () {
244 return $this->fragmenterInstance;
248 * Setter for decoder instance
250 * @param $decoderInstance A Decodeable instance
253 protected final function setDecoderInstance (Decodeable $decoderInstance) {
254 $this->decoderInstance = $decoderInstance;
258 * Getter for decoder instance
260 * @return $decoderInstance A Decodeable instance
262 protected final function getDecoderInstance () {
263 return $this->decoderInstance;
267 * Setter for assembler instance
269 * @param $assemblerInstance A Decodeable instance
272 protected final function setAssemblerInstance (Assembler $assemblerInstance) {
273 $this->assemblerInstance = $assemblerInstance;
277 * Getter for assembler instance
279 * @return $assemblerInstance A Decodeable instance
281 protected final function getAssemblerInstance () {
282 return $this->assemblerInstance;
288 * @param $nodeId Our new node id
291 protected final function setNodeId ($nodeId) {
293 $this->getConfigInstance()->setConfigEntry('node_id', (string) $nodeId);
299 * @return $nodeId Current node id
301 public final function getNodeId () {
302 // Get it from config
303 return $this->getConfigInstance()->getConfigEntry('node_id');
307 * Setter for session id
309 * @param $sessionId Our new session id
312 protected final function setSessionId ($sessionId) {
313 $this->getConfigInstance()->setConfigEntry('session_id', (string) $sessionId);
317 * Getter for session id
319 * @return $sessionId Current session id
321 public final function getSessionId () {
322 return $this->getConfigInstance()->getConfigEntry('session_id');
326 * Constructs a callable method name from given socket error code. If the
327 * method is not found, a generic one is used.
329 * @param $errorCode Error code from socket_last_error()
330 * @return $handlerName Call-back method name for the error handler
331 * @throws UnsupportedSocketErrorHandlerException If the error handler is not implemented
333 protected function getSocketErrorHandlerFromCode ($errorCode) {
334 // Create a name from translated error code
335 $handlerName = 'socketError' . $this->convertToClassName($this->translateSocketErrorCodeToName($errorCode)) . 'Handler';
337 // Is the call-back method there?
338 if (!method_exists($this, $handlerName)) {
339 // Please implement this
340 throw new UnsupportedSocketErrorHandlerException(array($this, $handlerName, $errorCode), self::EXCEPTION_UNSUPPORTED_ERROR_HANDLER);
348 * Handles socket error for given socket resource and peer data. This method
349 * validates $socketResource if it is a valid resource (see is_resource())
350 * but assumes valid data in array $recipientData, except that
351 * count($recipientData) is always 2.
353 * @param $socketResource A valid socket resource
354 * @param $recipientData An array with two elements: 0=IP number, 1=port number
356 * @throws InvalidSocketException If $socketResource is no socket resource
357 * @throws NoSocketErrorDetectedException If socket_last_error() gives zero back
359 protected final function handleSocketError ($socketResource, array $recipientData) {
360 // This method handles only socket resources
361 if (!is_resource($socketResource)) {
362 // No resource, abort here
363 throw new InvalidSocketException(array($this, $socketResource), BaseListener::EXCEPTION_INVALID_SOCKET);
366 // Check count of array, should be two
367 assert(count($recipientData) == 2);
369 // Get error code for first validation (0 is not an error)
370 $errorCode = socket_last_error($socketResource);
372 // If the error code is zero, someone called this method without an error
373 if ($errorCode == 0) {
374 // No error detected (or previously cleared outside this method)
375 throw new NoSocketErrorDetectedException(array($this, $socketResource), BaseListener::EXCEPTION_NO_SOCKET_ERROR);
378 // Get handler (method) name
379 $handlerName = $this->getSocketErrorHandlerFromCode($errorCode);
381 // Call-back the error handler method
382 call_user_func(array($this, $handlerName), $socketResource);
384 // Finally clear the error because it has been handled
385 socket_clear_error($socketResource);
389 * Checks whether the final (last) chunk is valid
391 * @param $chunks An array with chunks and (hopefully) a valid final chunk
392 * @return $isValid Whether the final (last) chunk is valid
394 protected function isValidFinalChunk (array $chunks) {
395 // Default is all fine
398 // Split the (possible) EOP chunk
399 $chunkSplits = explode(PackageFragmenter::CHUNK_DATA_HASH_SEPARATOR, $chunks[count($chunks) - 1]);
401 // Make sure chunks with only 3 elements are parsed (for details see ChunkHandler)
402 //* NOISY-DEBUG: */ $this->debugOutput('eopChunk=' . $chunks[count($chunks) - 1] . ',chunkSplits=' . print_r($chunkSplits,true));
403 assert(count($chunkSplits) == 3);
405 // Validate final chunk
406 if (substr($chunkSplits[ChunkHandler::CHUNK_SPLITS_INDEX_RAW_DATA], 0, strlen(PackageFragmenter::END_OF_PACKAGE_IDENTIFIER)) != PackageFragmenter::END_OF_PACKAGE_IDENTIFIER) {
409 } elseif (substr_count($chunkSplits[ChunkHandler::CHUNK_SPLITS_INDEX_RAW_DATA], PackageFragmenter::CHUNK_HASH_SEPARATOR) != 1) {
410 // CHUNK_HASH_SEPARATOR shall only be found once
419 * Translates socket error codes into our own internal names which can be
420 * used for call-backs.
422 * @param $errorCode The error code from socket_last_error() to be translated
423 * @return $errorName The translated name (all lower-case, with underlines)
425 public function translateSocketErrorCodeToName ($errorCode) {
426 // Nothing bad happened by default
427 $errorName = BaseRawDataHandler::SOCKET_CONNECTED;
429 // Is the code a number, then we have to change it
430 switch ($errorCode) {
431 case 0: // Silently ignored, the socket is connected
434 case 11: // "Resource temporary unavailable"
435 $errorName = BaseRawDataHandler::SOCKET_ERROR_RESOURCE_UNAVAILABLE;
438 case 107: // "Transport end-point not connected"
439 case 134: // On some (?) systems for 'transport end-point not connected'
440 // @TODO On some systems it is 134, on some 107?
441 $errorName = BaseRawDataHandler::SOCKET_ERROR_TRANSPORT_ENDPOINT;
444 case 110: // "Connection timed out"
445 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_TIMED_OUT;
448 case 111: // "Connection refused"
449 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_REFUSED;
452 case 113: // "No route to host"
453 $errorName = BaseRawDataHandler::SOCKET_ERROR_NO_ROUTE_TO_HOST;
456 case 114: // "Operation already in progress"
457 $errorName = BaseRawDataHandler::SOCKET_ERROR_OPERATION_ALREADY_PROGRESS;
460 case 115: // "Operation now in progress"
461 $errorName = BaseRawDataHandler::SOCKET_ERROR_OPERATION_IN_PROGRESS;
464 default: // Everything else <> 0
465 // Unhandled error code detected, so first debug it because we may want to handle it like the others
466 $this->debugOutput('[' . __METHOD__ . ':' . __LINE__ . '] UNKNOWN ERROR CODE = ' . $errorCode . ', MESSAGE = ' . socket_strerror($errorCode));
468 // Change it only in this class
469 $errorName = BaseRawDataHandler::SOCKET_ERROR_UNKNOWN;
473 // Return translated name
478 * Shuts down a given socket resource. This method does only ease calling
481 * @param $socketResource A valid socket resource
484 public function shutdownSocket ($socketResource) {
486 $this->debugOutput('HUB-SYSTEM: Shutting down socket resource ' . $socketResource . ' with state ' . $this->getPrintableState() . ' ...');
488 // Set socket resource
489 $this->setSocketResource($socketResource);
491 // Get a visitor instance
492 $visitorInstance = ObjectFactory::createObjectByConfiguredName('shutdown_socket_visitor_class');
495 $this->debugOutput('HUB-SYSTEM:' . $this->__toString() . ': visitorInstance=' . $visitorInstance->__toString());
498 $this->accept($visitorInstance);
502 * Half-shuts down a given socket resource. This method does only ease calling
503 * an other visitor than shutdownSocket() does.
505 * @param $socketResource A valid socket resource
508 public function halfShutdownSocket ($socketResource) {
510 $this->debugOutput('HUB-SYSTEM: Half-shutting down socket resource ' . $socketResource . ' with state ' . $this->getPrintableState() . ' ...');
512 // Set socket resource
513 $this->setSocketResource($socketResource);
515 // Get a visitor instance
516 $visitorInstance = ObjectFactory::createObjectByConfiguredName('half_shutdown_socket_visitor_class');
519 $this->debugOutput('HUB-SYSTEM:' . $this->__toString() . ': visitorInstance=' . $visitorInstance->__toString());
522 $this->accept($visitorInstance);
526 * "Getter" for a printable state name
528 * @return $stateName Name of the node's state in a printable format
530 public final function getPrintableState () {
534 // Get the state instance
535 $stateInstance = $this->getStateInstance();
537 // Is it an instance of Stateable?
538 if ($stateInstance instanceof Stateable) {
539 // Then use that state name
540 $stateName = $stateInstance->getStateName();