]> git.mxchange.org Git - hub.git/blobdiff - application/hub/main/class_BaseHubSystem.php
Copyright notice updated
[hub.git] / application / hub / main / class_BaseHubSystem.php
index 14ec46a9d9ba5dfdbecb783d1b4bb668ca828545..a147db4370dac946fd666aeda250e394e49b84a8 100644 (file)
@@ -4,7 +4,7 @@
  *
  * @author             Roland Haeder <webmaster@ship-simu.org>
  * @version            0.0.0
- * @copyright  Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2011 Hub Developer Team
+ * @copyright  Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2012 Hub Developer Team
  * @license            GNU GPL 3.0 or any newer version
  * @link               http://www.ship-simu.org
  *
  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  */
 class BaseHubSystem extends BaseFrameworkSystem {
+       // Exception codes
+       const EXCEPTION_UNSUPPORTED_ERROR_HANDLER = 0x900;
+       const EXCEPTION_CHUNK_ALREADY_ASSEMBLED   = 0x901;
+
        /**
-        * Seperator for all bootstrap node entries
+        * Separator for all bootstrap node entries
         */
-       const BOOTSTRAP_NODES_SEPERATOR = ';';
+       const BOOTSTRAP_NODES_SEPARATOR = ';';
 
        /**
         * An instance of a node
@@ -62,6 +66,21 @@ class BaseHubSystem extends BaseFrameworkSystem {
         */
        private $listenerPoolInstance = NULL;
 
+       /**
+        * Fragmenter instance
+        */
+       private $fragmenterInstance = NULL;
+
+       /**
+        * Decoder instance
+        */
+       private $decoderInstance = NULL;
+
+       /**
+        * Assembler instance
+        */
+       private $assemblerInstance = NULL;
+
        /**
         * Protected constructor
         *
@@ -133,10 +152,10 @@ class BaseHubSystem extends BaseFrameworkSystem {
        /**
         * Setter for network package handler instance
         *
-        * @param       $packageInstance        The network package handler instance we shall set
+        * @param       $packageInstance        The network package instance we shall set
         * @return      void
         */
-       protected final function setPackageInstance (Networkable $packageInstance) {
+       protected final function setPackageInstance (Deliverable $packageInstance) {
                $this->packageInstance = $packageInstance;
        }
 
@@ -206,6 +225,255 @@ class BaseHubSystem extends BaseFrameworkSystem {
                return $this->listenerPoolInstance;
        }
 
+       /**
+        * Setter for fragmenter instance
+        *
+        * @param       $fragmenterInstance             A Fragmentable instance
+        * @return      void
+        */
+       protected final function setFragmenterInstance (Fragmentable $fragmenterInstance) {
+               $this->fragmenterInstance = $fragmenterInstance;
+       }
+
+       /**
+        * Getter for fragmenter instance
+        *
+        * @return      $fragmenterInstance             A Fragmentable instance
+        */
+       protected final function getFragmenterInstance () {
+               return $this->fragmenterInstance;
+       }
+
+       /**
+        * Setter for decoder instance
+        *
+        * @param       $decoderInstance        A Decodeable instance
+        * @return      void
+        */
+       protected final function setDecoderInstance (Decodeable $decoderInstance) {
+               $this->decoderInstance = $decoderInstance;
+       }
+
+       /**
+        * Getter for decoder instance
+        *
+        * @return      $decoderInstance        A Decodeable instance
+        */
+       protected final function getDecoderInstance () {
+               return $this->decoderInstance;
+       }
+
+       /**
+        * Setter for assembler instance
+        *
+        * @param       $assemblerInstance      A Decodeable instance
+        * @return      void
+        */
+       protected final function setAssemblerInstance (Assembler $assemblerInstance) {
+               $this->assemblerInstance = $assemblerInstance;
+       }
+
+       /**
+        * Getter for assembler instance
+        *
+        * @return      $assemblerInstance      A Decodeable instance
+        */
+       protected final function getAssemblerInstance () {
+               return $this->assemblerInstance;
+       }
+
+       /**
+        * Setter for node id
+        *
+        * @param       $nodeId         Our new node id
+        * @return      void
+        */
+       protected final function setNodeId ($nodeId) {
+               // Set it config now
+               $this->getConfigInstance()->setConfigEntry('node_id', (string) $nodeId);
+       }
+
+       /**
+        * Getter for node id
+        *
+        * @return      $nodeId         Current node id
+        */
+       public final function getNodeId () {
+               // Get it from config
+               return $this->getConfigInstance()->getConfigEntry('node_id');
+       }
+
+       /**
+        * Setter for session id
+        *
+        * @param       $sessionId              Our new session id
+        * @return      void
+        */
+       protected final function setSessionId ($sessionId) {
+               $this->getConfigInstance()->setConfigEntry('session_id', (string) $sessionId);
+       }
+
+       /**
+        * Getter for session id
+        *
+        * @return      $sessionId              Current session id
+        */
+       public final function getSessionId () {
+               return $this->getConfigInstance()->getConfigEntry('session_id');
+       }
+
+       /**
+        * Constructs a callable method name from given socket error code. If the
+        * method is not found, a generic one is used.
+        *
+        * @param       $errorCode              Error code from socket_last_error()
+        * @return      $handlerName    Call-back method name for the error handler
+        * @throws      UnsupportedSocketErrorHandlerException If the error handler is not implemented
+        */
+       protected function getSocketErrorHandlerFromCode ($errorCode) {
+               // Create a name from translated error code
+               $handlerName = 'socketError' . $this->convertToClassName($this->translateSocketErrorCodeToName($errorCode)) . 'Handler';
+
+               // Is the call-back method there?
+               if (!method_exists($this, $handlerName)) {
+                       // Please implement this
+                       throw new UnsupportedSocketErrorHandlerException(array($this, $handlerName, $errorCode), self::EXCEPTION_UNSUPPORTED_ERROR_HANDLER);
+               } // END - if
+
+               // Return it
+               return $handlerName;
+       }
+
+       /**
+        * Handles socket error for given socket resource and peer data. This method
+        * validates $socketResource if it is a valid resource (see is_resource())
+        * but assumes valid data in array $recipientData, except that
+        * count($recipientData) is always 2.
+        *
+        * @param       $socketResource         A valid socket resource
+        * @param       $recipientData          An array with two elements: 0=IP number, 1=port number
+        * @return      void
+        * @throws      InvalidSocketException  If $socketResource is no socket resource
+        * @throws      NoSocketErrorDetectedException  If socket_last_error() gives zero back
+        */
+       protected final function handleSocketError ($socketResource, array $recipientData) {
+               // This method handles only socket resources
+               if (!is_resource($socketResource)) {
+                       // No resource, abort here
+                       throw new InvalidSocketException(array($this, $socketResource), BaseListener::EXCEPTION_INVALID_SOCKET);
+               } // END - if
+
+               // Check count of array, should be two
+               assert(count($recipientData) == 2);
+
+               // Get error code for first validation (0 is not an error)
+               $errorCode = socket_last_error($socketResource);
+
+               // If the error code is zero, someone called this method without an error
+               if ($errorCode == 0) {
+                       // No error detected (or previously cleared outside this method)
+                       throw new NoSocketErrorDetectedException(array($this, $socketResource), BaseListener::EXCEPTION_NO_SOCKET_ERROR);
+               } // END - if
+
+               // Get handler (method) name
+               $handlerName = $this->getSocketErrorHandlerFromCode($errorCode);
+
+               // Call-back the error handler method
+               call_user_func(array($this, $handlerName), $socketResource);
+
+               // Finally clear the error because it has been handled
+               socket_clear_error($socketResource);
+       }
+
+       /**
+        * Checks whether the final (last) chunk is valid
+        *
+        * @param       $chunks         An array with chunks and (hopefully) a valid final chunk
+        * @return      $isValid        Whether the final (last) chunk is valid
+        */
+       protected function isValidFinalChunk (array $chunks) {
+               // Default is all fine
+               $isValid = true;
+
+               // Split the (possible) EOP chunk
+               $chunkSplits = explode(PackageFragmenter::CHUNK_DATA_HASH_SEPARATOR, $chunks[count($chunks) - 1]);
+
+               // Make sure chunks with only 3 elements are parsed (for details see ChunkHandler)
+               //* NOISY-DEBUG: */ $this->debugOutput('eopChunk=' . $chunks[count($chunks) - 1] . ',chunkSplits=' . print_r($chunkSplits,true));
+               assert(count($chunkSplits) == 3);
+
+               // Validate final chunk
+               if (substr($chunkSplits[ChunkHandler::CHUNK_SPLITS_INDEX_RAW_DATA], 0, strlen(PackageFragmenter::END_OF_PACKAGE_IDENTIFIER)) != PackageFragmenter::END_OF_PACKAGE_IDENTIFIER) {
+                       // Not fine
+                       $isValid = false;
+               } elseif (substr_count($chunkSplits[ChunkHandler::CHUNK_SPLITS_INDEX_RAW_DATA], PackageFragmenter::CHUNK_HASH_SEPARATOR) != 1) {
+                       // CHUNK_HASH_SEPARATOR shall only be found once
+                       $isValid = false;
+               }
+
+               // Return status
+               return $isValid;
+       }
+
+       /**
+        * Translates socket error codes into our own internal names which can be
+        * used for call-backs.
+        *
+        * @param       $errorCode      The error code from socket_last_error() to be translated
+        * @return      $errorName      The translated name (all lower-case, with underlines)
+        */
+       public function translateSocketErrorCodeToName ($errorCode) {
+               // Nothing bad happened by default
+               $errorName = BaseRawDataHandler::SOCKET_CONNECTED;
+
+               // Is the code a number, then we have to change it
+               switch ($errorCode) {
+                       case 0: // Silently ignored, the socket is connected
+                               break;
+
+                       case 11:  // "Resource temporary unavailable"
+                               $errorName = BaseRawDataHandler::SOCKET_ERROR_RESOURCE_UNAVAILABLE;
+                               break;
+
+                       case 107: // "Transport end-point not connected"
+                       case 134: // On some (?) systems for 'transport end-point not connected'
+                               // @TODO On some systems it is 134, on some 107?
+                               $errorName = BaseRawDataHandler::SOCKET_ERROR_TRANSPORT_ENDPOINT;
+                               break;
+
+                       case 110: // "Connection timed out"
+                               $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_TIMED_OUT;
+                               break;
+
+                       case 111: // "Connection refused"
+                               $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_REFUSED;
+                               break;
+
+                       case 113: // "No route to host"
+                               $errorName = BaseRawDataHandler::SOCKET_ERROR_NO_ROUTE_TO_HOST;
+                               break;
+
+                       case 114: // "Operation already in progress"
+                               $errorName = BaseRawDataHandler::SOCKET_ERROR_OPERATION_ALREADY_PROGRESS;
+                               break;
+
+                       case 115: // "Operation now in progress"
+                               $errorName = BaseRawDataHandler::SOCKET_ERROR_OPERATION_IN_PROGRESS;
+                               break;
+
+                       default: // Everything else <> 0
+                               // Unhandled error code detected, so first debug it because we may want to handle it like the others
+                               $this->debugOutput('[' . __METHOD__ . ':' . __LINE__ . '] UNKNOWN ERROR CODE = ' . $errorCode . ', MESSAGE = ' . socket_strerror($errorCode));
+
+                               // Change it only in this class
+                               $errorName = BaseRawDataHandler::SOCKET_ERROR_UNKNOWN;
+                               break;
+               }
+
+               // Return translated name
+               return $errorName;
+       }
+
        /**
         * Shuts down a given socket resource. This method does only ease calling
         * the right visitor.
@@ -223,6 +491,33 @@ class BaseHubSystem extends BaseFrameworkSystem {
                // Get a visitor instance
                $visitorInstance = ObjectFactory::createObjectByConfiguredName('shutdown_socket_visitor_class');
 
+               // Debug output
+               $this->debugOutput('HUB-SYSTEM:' . $this->__toString() . ': visitorInstance=' . $visitorInstance->__toString());
+
+               // Call the visitor
+               $this->accept($visitorInstance);
+       }
+
+       /**
+        * Half-shuts down a given socket resource. This method does only ease calling
+        * an other visitor than shutdownSocket() does.
+        *
+        * @param       $socketResource         A valid socket resource
+        * @return      void
+        */
+       public function halfShutdownSocket ($socketResource) {
+               // Debug message
+               $this->debugOutput('HUB-SYSTEM: Half-shutting down socket resource ' . $socketResource . ' with state ' . $this->getPrintableState() . ' ...');
+
+               // Set socket resource
+               $this->setSocketResource($socketResource);
+
+               // Get a visitor instance
+               $visitorInstance = ObjectFactory::createObjectByConfiguredName('half_shutdown_socket_visitor_class');
+
+               // Debug output
+               $this->debugOutput('HUB-SYSTEM:' . $this->__toString() . ': visitorInstance=' . $visitorInstance->__toString());
+
                // Call the visitor
                $this->accept($visitorInstance);
        }