]> git.mxchange.org Git - hub.git/commitdiff
Code cleanups and project continued:
authorRoland Häder <roland@mxchange.org>
Thu, 1 Sep 2011 07:43:54 +0000 (07:43 +0000)
committerRoland Häder <roland@mxchange.org>
Thu, 1 Sep 2011 07:43:54 +0000 (07:43 +0000)
- Some 'abstract' removed
- Some code moved to HubTools::determineOwnExternalIp() to encapsulate it
- Peer state lookup now working partly (still one part is left)
- Other cleanups

13 files changed:
.gitattributes
application/hub/exceptions/peer/class_PeerAlreadyRegisteredException.php
application/hub/main/database/wrapper/node/class_NodeInformationDatabaseWrapper.php
application/hub/main/database/wrapper/node/class_NodeListDatabaseWrapper.php
application/hub/main/database/wrapper/states/class_PeerStateLookupDatabaseWrapper.php
application/hub/main/discovery/package/class_PackageRecipientDiscovery.php
application/hub/main/factories/states/peer/class_PeerStateFactory.php
application/hub/main/helper/messages/class_BaseMessageHelper.php
application/hub/main/producer/class_BaseProducer.php
application/hub/main/producer/cruncher/class_BaseKeyProducer.php
application/hub/main/producer/cruncher/class_BaseUnitProducer.php
application/hub/main/resolver/controller/http/class_HubHttpControllerResolver.php [new file with mode: 0644]
application/hub/main/tools/class_HubTools.php

index 6c28d77d0f18318815b0fb69425966b1685d64a0..544de4bea5ea4d86856f879ff89e90376a32531a 100644 (file)
@@ -435,6 +435,7 @@ application/hub/main/resolver/controller/.htaccess -text svneol=unset#text/plain
 application/hub/main/resolver/controller/console/.htaccess -text svneol=unset#text/plain
 application/hub/main/resolver/controller/console/class_HubConsoleControllerResolver.php svneol=native#text/plain
 application/hub/main/resolver/controller/http/.htaccess -text svneol=unset#text/plain
+application/hub/main/resolver/controller/http/class_HubHttpControllerResolver.php svneol=native#text/plain
 application/hub/main/resolver/state/.htaccess -text svneol=unset#text/plain
 application/hub/main/resolver/state/class_BaseStateResolver.php svneol=native#text/plain
 application/hub/main/resolver/state/network/.htaccess -text svneol=unset#text/plain
index d2501012b958c773e7e55a65fa1db661b833c93e..863180d4d375c62e167e45bfe69cf60d614af854 100644 (file)
@@ -34,7 +34,7 @@ class PeerAlreadyRegisteredException extends FrameworkException {
                $message = sprintf("[%s:%d] Sender %s is already registered.",
                        $messageArray[0]->__toString(),
                        $this->getLine(),
-                       $messageArray[NetworkPackage::PACKAGE_DATA_SENDER]
+                       $messageArray[1][NetworkPackage::PACKAGE_DATA_SENDER]
                );
 
                // Call parent exception constructor
index 52dc0ff1361cd6447fd5d57e4089e528ea03307a..629844a8e03c03163c9062f249e837d13079cf4e 100644 (file)
@@ -84,8 +84,8 @@ class NodeInformationDatabaseWrapper extends BaseDatabaseWrapper {
                // Add registration elements to the dataset
                $nodeInstance->addElementsToDataSet($dataSetInstance, $requestInstance);
 
-               // "Insert" this request instance completely into the database
-               $this->getDatabaseInstance()->queryInsertDataSet($dataSetInstance);
+               // "Insert" this dataset instance completely into the database
+               $this->queryInsertDataSet($dataSetInstance);
        }
 
        /**
@@ -106,8 +106,8 @@ class NodeInformationDatabaseWrapper extends BaseDatabaseWrapper {
                // Add registration elements to the dataset
                $nodeInstance->addElementsToDataSet($dataSetInstance, $requestInstance);
 
-               // "Insert" this request instance completely into the database
-               $this->getDatabaseInstance()->queryInsertDataSet($dataSetInstance);
+               // "Insert" this dataset instance completely into the database
+               $this->queryInsertDataSet($dataSetInstance);
        }
 }
 
index e008420d2156f7f447f1d48a6fe1bc7f647b4261..2279037cd25902519213f08fef915f879a21508e 100644 (file)
@@ -80,8 +80,8 @@ class NodeListDatabaseWrapper extends BaseDatabaseWrapper implements Registerabl
                // Now get a search criteria instance
                $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
 
-               // Search for the node number zero which is hard-coded the default
-               $searchInstance->addCriteria(NodeListDatabaseWrapper::DB_COLUMN_NODE_SESSION_ID, 1);
+               // Search for the node session id
+               $searchInstance->addCriteria(NodeListDatabaseWrapper::DB_COLUMN_NODE_SESSION_ID, $sessionId);
                $searchInstance->setLimit(1);
 
                // Get a result back
index 450609e1ed24a29f6350a5eacb175024669e662c..330a3b3cb769199c741ec9545861d935ec92a837 100644 (file)
@@ -32,6 +32,7 @@ class PeerStateLookupDatabaseWrapper extends BaseDatabaseWrapper implements Look
        const DB_COLUMN_PEER_IP           = 'peer_ip';
        const DB_COLUMN_PEER_PORT         = 'peer_port';
        const DB_COLUMN_PEER_SESSION_ID   = 'peer_session_id';
+       const DB_COLUMN_PEER_STATE        = 'peer_state';
        const DB_COLUMN_SOCKET_ERROR_CODE = 'socket_error_code';
        const DB_COLUMN_SOCKET_ERROR_MSG  = 'socket_error_msg';
 
@@ -73,10 +74,11 @@ class PeerStateLookupDatabaseWrapper extends BaseDatabaseWrapper implements Look
        /**
         * Checks wether given 'sender' is a new peer
         *
-        * @param       $packageData    Raw package data
-        * @return      $isNewPeer              Wether 'sender' is a new peer to this peer
+        * @param       $packageData            Raw package data
+        * @param       $dataSetInstance        An optional instance of a StoreableCriteria class
+        * @return      $isNewPeer                      Wether 'sender' is a new peer to this peer
         */
-       public function isSenderNewPeer (array $packageData) {
+       public function isSenderNewPeer (array $packageData, StoreableCriteria $dataSetInstance = NULL) {
                //* DEBUG: */ $this->debugOutput('DATABASE-WRAPPER: ' . __FUNCTION__ . ' called with packageData()=' . count($packageData) . ' - ENTERED!');
                // Is always new peer by default
                $isNewPeer = true;
@@ -87,27 +89,26 @@ class PeerStateLookupDatabaseWrapper extends BaseDatabaseWrapper implements Look
                        die(__METHOD__ . ': packageData=' . print_r($packageData, true));
                } // END - if
 
-               // Resolve session id > IP:port
-               //* DEBUG: */ $this->debugOutput('DATABASE-WRAPPER: sender=' . $packageData[NetworkPackage::PACKAGE_DATA_SENDER] . ' - resolving ...');
-               $ipPort = HubTools::resolveSessionId($packageData[NetworkPackage::PACKAGE_DATA_SENDER]);
-               //* DEBUG: */ $this->debugOutput('DATABASE-WRAPPER: ipPort=' . $ipPort);
+               // Get a search criteria instance
+               //* DEBUG: */ $this->debugOutput('DATABASE-WRAPPER: Searching for sender ' . $packageData[NetworkPackage::PACKAGE_DATA_SENDER]);
+               $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
 
-               // Is it not invalid:invalid?
-               if ($ipPort != NodeListDatabaseWrapper::INVALID_IP_PORT) {
-                       // Get a search criteria instance
-                       $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
+               // Add 'sender' as the peer's IP address
+               $searchInstance->addCriteria(self::DB_COLUMN_PEER_SESSION_ID, $packageData[NetworkPackage::PACKAGE_DATA_SENDER]);
+               $searchInstance->setLimit(1);
 
-                       // Add 'sender' as the peer's IP address
-                       $searchInstance->addCriteria(self::DB_COLUMN_PEER_IP, $ipPort);
-                       $searchInstance->setLimit(1);
+               // Is the dataset instance set?
+               if ($dataSetInstance instanceof StoreableCriteria) {
+                       // Then remember the search instance in it
+                       $dataSetInstance->setSearchInstance($searchInstance);
+               } // END - if
 
-                       // Count the query
-                       $entries = $this->doSelectCountByCriteria($searchInstance);
+               // Count the query
+               $entries = $this->doSelectCountByCriteria($searchInstance, array(self::DB_COLUMN_PEER_SESSION_ID => true));
 
-                       // Is it there?
-                       //* DEBUG: */ $this->debugOutput('DATABASE-WRAPPER: entries=' . $entries);
-                       $isNewPeer = ($entries === 0);
-               } // END - if
+               // Is it there?
+               //* DEBUG: */ $this->debugOutput('DATABASE-WRAPPER: entries=' . $entries);
+               $isNewPeer = ($entries != 1);
 
                // Return the result
                //* DEBUG: */ $this->debugOutput('DATABASE-WRAPPER: isNewPeer=' . intval($isNewPeer) . ' - EXIT!');
@@ -153,7 +154,10 @@ class PeerStateLookupDatabaseWrapper extends BaseDatabaseWrapper implements Look
                $dataSetInstance->addCriteria(self::DB_COLUMN_PEER_PORT, $peerPort);
 
                // "Insert" the data set
-               $this->getDatabaseInstance()->queryInsertDataSet($dataSetInstance);
+               $this->queryInsertDataSet($dataSetInstance, array(self::DB_COLUMN_PEER_SESSION_ID => true));
+
+               // Debug message
+               /* DEBUG: */ $this->debugOutput('DATABASE-WRAPPER: Peer ' . $packageData[NetworkPackage::PACKAGE_DATA_SENDER] . ' has been registered.');
        }
 
        /**
@@ -162,10 +166,41 @@ class PeerStateLookupDatabaseWrapper extends BaseDatabaseWrapper implements Look
         * @param       $stateInstance  A PeerStateable class instance
         * @param       $packageData    Valid package data array
         * @return      void
+        * @throws      PeerAlreadyRegisteredException  If a peer is already registered
         * @todo        Unfinished area
         */
        public function registerPeerState (PeerStateable $stateInstance, array $packageData) {
-               $this->debugBackTrace('stateInstance=' . $stateInstance->__toString() . ' - UNFINISHED AREA!');
+               // Generate a dataset instance
+               $dataSetInstance = ObjectFactory::createObjectByConfiguredName('dataset_criteria_class', array(self::DB_TABLE_PEER_LOOKUP));
+
+               // Session ids must be unique
+               $dataSetInstance->setUniqueKey(self::DB_COLUMN_PEER_SESSION_ID);
+
+               // Add session id
+               $dataSetInstance->addCriteria(self::DB_COLUMN_PEER_SESSION_ID, $packageData[NetworkPackage::PACKAGE_DATA_SENDER]);
+               $dataSetInstance->addCriteria(self::DB_COLUMN_PEER_STATE, $stateInstance->getStateName());
+
+               // Try to resolve sender's session id
+               $senderData = explode(':', HubTools::resolveSessionId($packageData[NetworkPackage::PACKAGE_DATA_SENDER]));
+
+               // Just make sure that 'invalid:invalid' is not being processed
+               assert(($senderData[0] != 'invalid') && ($senderData[1] != 'invalid'));
+
+               // Add ip address and port
+               $dataSetInstance->addCriteria(self::DB_COLUMN_PEER_IP  , $senderData[0]);
+               $dataSetInstance->addCriteria(self::DB_COLUMN_PEER_PORT, $senderData[1]);
+
+               // Is this a new peer?
+               if ($this->isSenderNewPeer($packageData, $dataSetInstance)) {
+                       // "Insert" the data set
+                       $this->queryInsertDataSet($dataSetInstance, array(self::DB_COLUMN_PEER_SESSION_ID => true));
+               } else {
+                       // Update the data set
+                       $this->queryUpdateDataSet($dataSetInstance, array(self::DB_COLUMN_PEER_SESSION_ID => true));
+               }
+
+               // Debug message
+               /* DEBUG: */ $this->debugOutput('DATABASE-WRAPPER: Peer ' . $packageData[NetworkPackage::PACKAGE_DATA_SENDER] . ' has been registered with state ' . $stateInstance->getStateName());
        }
 
        /**
@@ -174,6 +209,7 @@ class PeerStateLookupDatabaseWrapper extends BaseDatabaseWrapper implements Look
         * @param       $socketResource         A valid socket resource
         * @return      void
         * @throws      InvalidSocketException  If the socket resource was invalid
+        * @todo        Unfinished area
         */
        public function purgeOldEntriesBySocketResource ($socketResource) {
                // Get peer name
@@ -184,6 +220,8 @@ class PeerStateLookupDatabaseWrapper extends BaseDatabaseWrapper implements Look
                        // Doesn't work!
                        throw new InvalidSocketException(array($this, gettype($socketResource), $lastError, socket_strerror($lastError)), BaseListener::EXCEPTION_INVALID_SOCKET);
                } // END - if
+
+               $this->debugBackTrace('peerName=' . $peerName . ',peerPort=' . $peerPort . ' - UNFINISHED!');
        }
 }
 
index d7a5c0e4c760e155aab02c1f47fe17b08545d438..7ddff1fb664129fa0b9588dbb93d09e332f414a6 100644 (file)
@@ -71,14 +71,8 @@ class PackageRecipientDiscovery extends BaseHubDiscovery implements Discoverable
 
                        // The target 'self' is always the external IP address!
                        case NetworkPackage::NETWORK_TARGET_SELF:
-                               // Is the external_ip config entry set?
-                               if ($this->getConfigInstance()->getConfigEntry('external_ip') != '') {
-                                       // Use it as external ip
-                                       $ip = $this->getConfigInstance()->getConfigEntry('external_ip');
-                               } else {
-                                       // Determine own external ip by connecting to my (coder) server at 188.138.90.169
-                                       $ip = ConsoleTools::determineExternalIp();
-                               }
+                               // Determine IP or 'external_ip' if set
+                               $ip = HubTools::determineOwnExternalIp();
 
                                // Get port and add it
                                $ipPort = $ip . ':' . $this->getConfigInstance()->getConfigEntry('node_' . $this->determineProtocolByPackageData($packageData) . '_listen_port');
index 847bfdef4358a8e8ddb339af35ad3a1eb97c4f01..181fc970000b0a2e6a79ed605a99a24f68185766 100644 (file)
@@ -95,7 +95,7 @@ class PeerStateFactory extends ObjectFactory {
                        $tableInstance->registerPeerState($stateInstance, $packageData);
                } else {
                        // It is a known peer, so we need to check if the state has changed
-                       $this->debugBackTrace(__METHOD__ . ': Lookup!' . "\n");
+                       $tableInstance->debugBackTrace(__METHOD__ . ': Lookup!' . "\n");
                }
 
                // Debug message
index 8d1b57921bf5e1eab5cdda8787711117354d7de1..ea2eb33de0deff1b503f0c87882cf508198f23e6 100644 (file)
@@ -21,7 +21,7 @@
  * You should have received a copy of the GNU General Public License
  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  */
-abstract class BaseMessageHelper extends BaseFrameworkSystem {
+class BaseMessageHelper extends BaseFrameworkSystem {
        /**
         * Protected constructor
         *
index e69b83f7fe86c641f85938db29d3bff0ed774527..ee5976cbf74bc37c180f65ae6d492aedf1a031f5 100644 (file)
@@ -21,7 +21,7 @@
  * You should have received a copy of the GNU General Public License
  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  */
-abstract class BaseProducer extends BaseFrameworkSystem {
+class BaseProducer extends BaseFrameworkSystem {
        /**
         * Outgoing work-queue
         */
index c89fa57789d736418eabd2714a91b96f2ad8386d..599412aa68890731ec9fb79a488b91ff44dc275b 100644 (file)
@@ -21,7 +21,7 @@
  * You should have received a copy of the GNU General Public License
  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  */
-abstract class BaseKeyProducer extends BaseProducer {
+class BaseKeyProducer extends BaseProducer {
        /**
         * Protected constructor
         *
index 6c1c4bc2053e3f8015728867286b03ca434fe8d1..46ffd6f119d6ded8c218ee26a3cc9a8408cb2148 100644 (file)
@@ -21,7 +21,7 @@
  * You should have received a copy of the GNU General Public License
  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  */
-abstract class BaseUnitProducer extends BaseProducer {
+class BaseUnitProducer extends BaseProducer {
        /**
         * Work/test unit status
         */
diff --git a/application/hub/main/resolver/controller/http/class_HubHttpControllerResolver.php b/application/hub/main/resolver/controller/http/class_HubHttpControllerResolver.php
new file mode 100644 (file)
index 0000000..414efb7
--- /dev/null
@@ -0,0 +1,114 @@
+<?php
+/**
+ * A resolver for resolving controllers locally
+ *
+ * @author             Roland Haeder <webmaster@ship-simu.org>
+ * @version            0.0.0
+ * @copyright  Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2011 Core Developer Team
+ * @license            GNU GPL 3.0 or any newer version
+ * @link               http://www.ship-simu.org
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+class HubHttpControllerResolver extends BaseControllerResolver implements ControllerResolver {
+       /**
+        * Last successfull resolved controller (name)
+        */
+       private $lastControllerName = '';
+
+       /**
+        * Last successfull resolved controller (instance)
+        */
+       private $lastControllerInstance = NULL;
+
+       /**
+        * Protected constructor
+        *
+        * @return      void
+        */
+       protected function __construct () {
+               // Call parent constructor
+               parent::__construct(__CLASS__);
+
+               // Set prefix to 'Web'
+               $this->setClassPrefix('Web');
+       }
+
+       /**
+        * Creates an instance of a resolver class with a given command
+        *
+        * @param       $controllerName                         The controller we shall resolve
+        * @param       $applicationInstance            An instance of a manageable application helper class
+        * @return      $resolverInstance                       The prepared controller resolver instance
+        * @throws      EmptyVariableException          Thrown if default command is not set
+        * @throws      InvalidControllerException      Thrown if default controller is invalid
+        */
+       public static final function createHubHttpControllerResolver ($controllerName, ManageableApplication $applicationInstance) {
+               // Create the new instance
+               $resolverInstance = new HubHttpControllerResolver();
+
+               // Is the variable $controllerName set and the command is valid?
+               if (empty($controllerName)) {
+                       // Then thrown an exception here
+                       throw new EmptyVariableException(array($resolverInstance, 'commandName'), self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
+               } elseif ($resolverInstance->isControllerValid($controllerName) === false) {
+                       // Invalid command found
+                       throw new InvalidControllerException(array($resolverInstance, $controllerName), self::EXCEPTION_INVALID_CONTROLLER);
+               }
+
+               // Set the application instance
+               $resolverInstance->setApplicationInstance($applicationInstance);
+
+               // Set command name
+               $resolverInstance->setControllerName($controllerName);
+
+               // Return the prepared instance
+               return $resolverInstance;
+       }
+
+       /**
+        * Resolves the default controller of the given command
+        *
+        * @return      $controllerInstance             A controller instance for the default
+        *                                                                      command
+        * @throws      InvalidControllerInstanceException      Thrown if $controllerInstance
+        *                                                                                              is invalid
+        */
+       public function resolveController () {
+               // Init variables
+               $controllerName = '';
+               $controllerInstance = NULL;
+
+               // Get the command name 
+               $controllerName = $this->getControllerName();
+
+               // Get the command
+               $controllerInstance = $this->loadController($controllerName);
+
+               // And validate it
+               if ((!is_object($controllerInstance)) || (!$controllerInstance instanceof Controller)) {
+                       // This command has an invalid instance!
+                       throw new InvalidControllerInstanceException(array($this, $controllerName), self::EXCEPTION_INVALID_CONTROLLER);
+               } // END - if
+
+               // Set last controller
+               $this->setResolvedInstance($controllerInstance);
+
+               // Return the maybe resolved instance
+               return $controllerInstance;
+       }
+}
+
+// [EOF]
+?>
index 4d8227f2f80799908c20fcda9da453cf1936d780..231078411ce8e6f3fc2b5482044acb6a09f2e94b 100644 (file)
@@ -92,6 +92,18 @@ class HubTools extends BaseFrameworkSystem {
                // And ask it for the session id
                $recipient = $wrapperInstance->resolveIpPortBySessionId($sessionId);
 
+               // Is the recipient invalid?
+               if ($recipient == 'invalid:invalid') {
+                       // Get the instance, this might throw a NPE
+                       $nodeInstance = Registry::getRegistry()->getInstance('node');
+
+                       // Is the session id the same?
+                       if ($nodeInstance->getSessionId() == $sessionId) {
+                               // Then get the ip:port from it, assume TCP by default
+                               $recipient = self::determineOwnExternalIp() . ':' . $nodeInstance->getConfigInstance()->getConfigEntry('node_tcp_listen_port');
+                       } // END - if
+               } // END - if
+
                // Return result
                return $recipient;
        }
@@ -151,6 +163,25 @@ class HubTools extends BaseFrameworkSystem {
                // Return it
                return $recipient;
        }
+
+       /**
+        * Determine IP or 'external_ip' if set
+        *
+        * @return      $ip             The determined external ip of this node
+        */
+       public static function determineOwnExternalIp () {
+               // Is the external_ip config entry set?
+               if (FrameworkConfiguration::getInstance()->getConfigEntry('external_ip') != '') {
+                       // Use it as external ip
+                       $ip = FrameworkConfiguration::getInstance()->getConfigEntry('external_ip');
+               } else {
+                       // Determine own external ip by connecting to my (coder) server at 188.138.90.169
+                       $ip = ConsoleTools::determineExternalIp();
+               }
+
+               // Return it
+               return $ip;
+       }
 }
 
 // [EOF]