]> git.mxchange.org Git - hub.git/blobdiff - application/hub/main/helper/connection/class_BaseConnectionHelper.php
Continued on development of 'hub' project with many refactorings/addings:
[hub.git] / application / hub / main / helper / connection / class_BaseConnectionHelper.php
index c88e89e53d49d298ac1acf3e3a053c424034cece..27ced2e4224bea69087ff3a90d53af7b89159c1f 100644 (file)
@@ -22,6 +22,9 @@
  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  */
 class BaseConnectionHelper extends BaseHubHelper implements Registerable, ProtocolHandler {
+       // Exception codes
+       const EXCEPTION_UNSUPPORTED_ERROR_HANDLER = 0x900;
+
        /**
         * Protocol used
         */
@@ -48,9 +51,9 @@ class BaseConnectionHelper extends BaseHubHelper implements Registerable, Protoc
        private $diff = 0;
 
        /**
-        * Connect retries for this connection
+        * Whether this connection is initialized
         */
-       private $retryCount = 0;
+       private $isInitialized = false;
 
        /**
         * Wether this connection is shutted down
@@ -77,10 +80,32 @@ class BaseConnectionHelper extends BaseHubHelper implements Registerable, Protoc
                // Call parent constructor
                parent::__construct($className);
 
+               // Initialize output stream
+               $streamInstance = ObjectFactory::createObjectByConfiguredName('node_raw_data_output_stream_class');
+
+               // And add it to this connection helper
+               $this->setOutputStreamInstance($streamInstance);
+
+               // Init state which sets the state to 'init'
+               $this->initState();
+
                // Register this connection helper
                Registry::getRegistry()->addInstance('connection', $this);
        }
 
+       /**
+        * Getter for real class name, overwrites generic method and is final
+        *
+        * @return      $class  Name of this class
+        */
+       public final function __toString () {
+               // Class name representation
+               $class = self::getConnectionClassName($this->getAddress(), $this->getPort(), parent::__toString());
+
+               // Return it
+               return $class;
+       }
+
        /**
         * Getter for port number to satify ProtocolHandler
         *
@@ -138,6 +163,119 @@ class BaseConnectionHelper extends BaseHubHelper implements Registerable, Protoc
                $this->address = $address;
        }
 
+       /**
+        * Initializes the current connection
+        *
+        * @return      void
+        * @throws      SocketOptionException   If setting any socket option fails
+        */
+       protected function initConnection () {
+               // Get socket resource
+               $socketResource = $this->getSocketResource();
+
+               // Set the option to reuse the port
+               if (!socket_set_option($socketResource, SOL_SOCKET, SO_REUSEADDR, 1)) {
+                       // Handle this socket error with a faked recipientData array
+                       $this->handleSocketError($socketResource, array('0.0.0.0', '0'));
+
+                       // And throw again
+                       // @TODO Move this to the socket error handler
+                       throw new SocketOptionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
+               } // END - if
+
+               /*
+                * Set socket to non-blocking mode before trying to establish a link to
+                * it. This is now the default behaviour for all connection helpers who
+                * call initConnection(); .
+                */
+               if (!socket_set_nonblock($socketResource)) {
+                       // Handle this socket error with a faked recipientData array
+                       $helperInstance->handleSocketError($socketResource, array('0.0.0.0', '0'));
+
+                       // And throw again
+                       throw new SocketOptionException(array($helperInstance, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
+               } // END - if
+
+               // Last step: mark connection as initialized
+               $this->isInitialized = true;
+       }
+
+       /**
+        * Attempts to connect to a peer by given IP number and port from a valid
+        * recipientData array with currently configured timeout.
+        *
+        * @param       $recipientData  A valid recipient data array, 0=IP; 1=PORT
+        * @return      $isConnected    Wether the connection went fine
+        * @see         Please see http://de.php.net/manual/en/function.socket-connect.php#84465 for original code
+        * @todo        Rewrite the while() loop to a iterator to not let the software stay very long here
+        */
+       protected function connectToPeerByRecipientDataArray (array $recipientData) {
+               // Only call this if the connection is initialized by initConnection()
+               assert($this->isInitialized === true);
+
+               // Get current time
+               $time = time();
+
+               // "Cache" socket resource and timeout config
+               $socketResource = $this->getSocketResource();
+               $timeout = $this->getConfigInstance()->getConfigEntry('socket_timeout_seconds');
+
+               // Try to connect until it is connected
+               while ($isConnected = !@socket_connect($socketResource, $recipientData[0], $recipientData[1])) {
+                       // Get last socket error
+                       $socketError = socket_last_error($socketResource);
+
+                       // Skip any errors which may happen on non-blocking connections
+                       if (($socketError == SOCKET_EINPROGRESS) || ($socketError == SOCKET_EALREADY)) {
+                               // Now, is that attempt within parameters?
+                               if ((time() - $time) >= $timeout) {
+                                       // Didn't work within timeout
+                                       $isConnected = false;
+                                       break;
+                               } // END - if
+
+                               // Sleep about one second
+                               $this->idle(1000);
+                       } elseif ($socketError != 0) {
+                               // Stop on everything else pronto
+                               $isConnected = false;
+                               break;
+                       }
+               } // END - while
+
+               // Return status
+               return $isConnected;
+       }
+
+       /**
+        * Static "getter" for this connection class' name
+        *
+        * @param       $address        IP address
+        * @param       $port           Port number
+        * @param       $className      Original class name
+        * @return      $class          Expanded class name
+        */
+       public static function getConnectionClassName ($address, $port, $className) {
+               // Construct it
+               $class = $address . ':' . $port . ':' . $className;
+
+               // ... and return it
+               return $class;
+       }
+
+       /**
+        * Initializes the peer's state which sets it to 'init'
+        *
+        * @return      void
+        */
+       private function initState() {
+               /*
+                * Get the state factory and create the initial state, we don't need
+                * the state instance here
+                */
+               PeerStateFactory::createPeerStateInstanceByName('init', $this);
+       }
+
        /**
         * "Getter" for raw data from a package array. A fragmenter is used which
         * will returns us only so many raw data which fits into the back buffer.
@@ -154,17 +292,8 @@ class BaseConnectionHelper extends BaseHubHelper implements Registerable, Protoc
         * @return      $chunkData              Raw data chunk
         */
        private function getRawDataFromPackageArray (array $packageData) {
-               // If there is no fragmenter?
-               if (!Registry::getRegistry()->instanceExists('package_fragmenter')) {
-                       // Get the fragmenter instance
-                       $fragmenterInstance = ObjectFactory::createObjectByConfiguredName('package_fragmenter_class');
-
-                       // Add it to the registry
-                       Registry::getRegistry()->addInstance('package_fragmenter', $fragmenterInstance);
-               } else {
-                       // Get fragmenter from registry
-                       $fragmenterInstance = Registry::getRegistry()->getInstance('package_fragmenter');
-               }
+               // Get the fragmenter instance
+               $fragmenterInstance = FragmenterFactory::createFragmenterInstance('package');
 
                // Implode the package data array and fragement the resulting string, returns the final hash
                $finalHash = $fragmenterInstance->fragmentPackageArray($packageData, $this);
@@ -215,12 +344,15 @@ class BaseConnectionHelper extends BaseHubHelper implements Registerable, Protoc
         * @throws      InvalidSocketException  If we got a problem with this socket
         */
        public function sendRawPackageData (array $packageData) {
+               // The helper's state must be 'connected'
+               $this->getStateInstance()->validatePeerStateConnected();
+
                // Cache buffer length
                $bufferSize = $this->getConfigInstance()->getConfigEntry($this->getProtocol() . '_buffer_length');
 
                // Init variables
-               $rawData = '';
-               $dataStream = ' ';
+               $rawData        = '';
+               $dataStream     = ' ';
                $totalSentBytes = 0;
 
                // Fill sending buffer with data
@@ -231,11 +363,14 @@ class BaseConnectionHelper extends BaseHubHelper implements Registerable, Protoc
                        $rawData .= $dataStream;
                } // END - while
 
-               // Nothing to sent is bad news!
+               // Nothing to sent is bad news, so assert on it
                assert(strlen($rawData) > 0);
 
+               // Encode the raw data with our output-stream
+               $encodedData = $this->getOutputStreamInstance()->streamData($rawData);
+
                // Calculate difference
-               $this->diff = $bufferSize - strlen($rawData);
+               $this->diff = $bufferSize - strlen($encodedData);
 
                // Get socket resource
                $socketResource = $this->getSocketResource();
@@ -246,43 +381,37 @@ class BaseConnectionHelper extends BaseHubHelper implements Registerable, Protoc
                // Deliver all data
                while ($sentBytes !== false) {
                        // And deliver it
-                       //* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: Sending out ' . strlen($rawData) . ' bytes,bufferSize=' . $bufferSize . ',diff=' . $this->diff);
-                       $sentBytes = @socket_write($socketResource, $rawData, ($bufferSize - $this->diff));
+                       //* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: Sending out ' . strlen($encodedData) . ' bytes,bufferSize=' . $bufferSize . ',diff=' . $this->diff);
+                       $sentBytes = @socket_write($socketResource, $encodedData, ($bufferSize - $this->diff));
 
                        // If there was an error, we don't continue here
                        if ($sentBytes === false) {
-                               // Get socket error code for verification
-                               $socketError = socket_last_error($socketResource);
-
-                               // Get error message
-                               $errorMessage = socket_strerror($socketError);
-
-                               // Shutdown this socket
-                               $this->shutdownSocket($socketResource);
+                               // Handle the error with a faked recipientData array
+                               $this->handleSocketError($socketResource, array('0.0.0.0', '0'));
 
                                // And throw it
-                               throw new InvalidSocketException(array($this, gettype($socketResource), $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
-                       } elseif (($sentBytes == 0) && (strlen($rawData) > 0)) {
+                               throw new InvalidSocketException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
+                       } elseif (($sentBytes == 0) && (strlen($encodedData) > 0)) {
                                // Nothing sent means we are done
                                //* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: All sent! (' . __LINE__ . ')');
                                break;
                        }
 
-                       // The difference between sent bytes and length of raw data should not be below zero
-                       assert((strlen($rawData) - $sentBytes) >= 0);
+                       // The difference between sent bytes and length of raw data should not go below zero
+                       assert((strlen($encodedData) - $sentBytes) >= 0);
 
                        // Add total sent bytes
                        $totalSentBytes += $sentBytes;
 
                        // Cut out the last unsent bytes
-                       //* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: Sent out ' . $sentBytes . ' of ' . strlen($rawData) . ' bytes ...');
-                       $rawData = substr($rawData, $sentBytes);
+                       //* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: Sent out ' . $sentBytes . ' of ' . strlen($encodedData) . ' bytes ...');
+                       $encodedData = substr($encodedData, $sentBytes);
 
                        // Calculate difference again
-                       $this->diff = $bufferSize - strlen($rawData);
+                       $this->diff = $bufferSize - strlen($encodedData);
 
                        // Can we abort?
-                       if (strlen($rawData) <= 0) {
+                       if (strlen($encodedData) <= 0) {
                                // Abort here, all sent!
                                //* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: All sent! (' . __LINE__ . ')');
                                break;
@@ -295,59 +424,152 @@ class BaseConnectionHelper extends BaseHubHelper implements Registerable, Protoc
        }
 
        /**
-        * Getter for real class name
+        * Marks this connection as shutted down
         *
-        * @return      $class  Name of this class
+        * @return      void
         */
-       public function __toString () {
-               // Class name representation
-               $class = $this->getAddress() . ':' . $this->getPort() . ':' . parent::__toString();
+       protected final function markConnectionShuttedDown () {
+               /* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: ' . $this->__toString() . ' has been marked as shutted down');
+               $this->shuttedDown = true;
 
-               // Return it
-               return $class;
+               // And remove the (now invalid) socket
+               $this->setSocketResource(false);
+       }
+
+       /**
+        * Getter for shuttedDown
+        *
+        * @return      $shuttedDown    Wether this connection is shutted down
+        */
+       public final function isShuttedDown () {
+               /* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: ' . $this->__toString() . ',shuttedDown=' . intval($this->shuttedDown));
+               return $this->shuttedDown;
        }
 
+       // ************************************************************************
+       //                 Socket error handler call-back methods
+       // ************************************************************************
+
        /**
-        * Checks wether the connect retry is exhausted
+        * Handles socket error 'connection timed out', but does not clear it for
+        * later debugging purposes.
         *
-        * @return      $isExhaused             Wether connect retry is exchausted
+        * @param       $socketResource         A valid socket resource
+        * @return      void
+        * @throws      SocketConnectionException       The connection attempts fails with a time-out
         */
-       public final function isConnectRetryExhausted () {
-               // Construct config entry
-               $configEntry = $this->getProtocol() . '_connect_retry_max';
+       protected function socketErrorConnectionTimedOutHandler ($socketResource) {
+               // Get socket error code for verification
+               $socketError = socket_last_error($socketResource);
 
-               // Check it out
-               $isExhausted = ($this->retryCount >=  $this->getConfigInstance()->getConfigEntry($configEntry));
+               // Get error message
+               $errorMessage = socket_strerror($socketError);
 
-               // Return it
-               return $isExhausted;
+               // Shutdown this socket
+               $this->shutdownSocket($socketResource);
+
+               // Throw it again
+               throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
        }
 
        /**
-        * Increases the connect retry count
+        * Handles socket error 'resource temporary unavailable', but does not
+        * clear it for later debugging purposes.
         *
+        * @param       $socketResource         A valid socket resource
         * @return      void
+        * @throws      SocketConnectionException       The connection attempts fails with a time-out
         */
-       public final function increaseConnectRetry () {
-               $this->retryCount++;
+       protected function socketErrorResourceUnavailableHandler ($socketResource) {
+               // Get socket error code for verification
+               $socketError = socket_last_error($socketResource);
+
+               // Get error message
+               $errorMessage = socket_strerror($socketError);
+
+               // Shutdown this socket
+               $this->shutdownSocket($socketResource);
+
+               // Throw it again
+               throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
        }
 
        /**
-        * Marks this connection as shutted down
+        * Handles socket error 'connection refused', but does not clear it for
+        * later debugging purposes.
         *
+        * @param       $socketResource         A valid socket resource
         * @return      void
+        * @throws      SocketConnectionException       The connection attempts fails with a time-out
         */
-       protected final function markConnectionShutdown () {
-               $this->shuttedDown = true;
+       protected function socketErrorConnectionRefusedHandler ($socketResource) {
+               // Get socket error code for verification
+               $socketError = socket_last_error($socketResource);
+
+               // Get error message
+               $errorMessage = socket_strerror($socketError);
+
+               // Shutdown this socket
+               $this->shutdownSocket($socketResource);
+
+               // Throw it again
+               throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
        }
 
        /**
-        * Getter for shuttedDown
+        * Handles socket error 'no route to host', but does not clear it for later
+        * debugging purposes.
         *
-        * @return      $shuttedDown    Wether this connection is shutted down
+        * @param       $socketResource         A valid socket resource
+        * @return      void
+        * @throws      SocketConnectionException       The connection attempts fails with a time-out
         */
-       public final function isShuttedDown () {
-               return $this->shuttedDown;
+       protected function socketErrorNoRouteToHostHandler ($socketResource) {
+               // Get socket error code for verification
+               $socketError = socket_last_error($socketResource);
+
+               // Get error message
+               $errorMessage = socket_strerror($socketError);
+
+               // Shutdown this socket
+               $this->shutdownSocket($socketResource);
+
+               // Throw it again
+               throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
+       }
+
+       /**
+        * Handles socket error 'operation already in progress' which happens in
+        * method connectToPeerByRecipientDataArray() on timed out connection
+        * attempts.
+        *
+        * @param       $socketResource         A valid socket resource
+        * @return      void
+        * @throws      SocketConnectionException       The connection attempts fails with a time-out
+        */
+       protected function socketErrorOperationAlreadyProgressHandler ($socketResource) {
+               // Get socket error code for verification
+               $socketError = socket_last_error($socketResource);
+
+               // Get error message
+               $errorMessage = socket_strerror($socketError);
+
+               // Half-shutdown this socket (see there for difference to shutdownSocket())
+               $this->halfShutdownSocket($socketResource);
+
+               // Throw it again
+               throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
+       }
+
+       /**
+        * Handles socket "error" 'operation now in progress' which can be safely
+        * passed on with non-blocking connections.
+        *
+        * @param       $socketResource         A valid socket resource
+        * @return      void
+        */
+       protected function socketErrorOperationInProgressHandler ($socketResource) {
+               $this->debugOutput('CONNECTION: Operation is now in progress, this is usual for non-blocking connections and no bug.');
        }
 }