]> git.mxchange.org Git - hub.git/blobdiff - application/hub/main/nodes/class_BaseHubNode.php
State pattern added, hub continued (sorry, I let it lay around uncommitted for long...
[hub.git] / application / hub / main / nodes / class_BaseHubNode.php
index 03f8f5052393fed1020b9200240cf14442966035..784c9a15c944f81ce1a0bc0269f7026e13e25590 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 Hub Developer Team
+ * @copyright  Copyright (c) 2007, 2008 Roland Haeder, 2009, 2010 Hub Developer Team
  * @license            GNU GPL 3.0 or any newer version
  * @link               http://www.ship-simu.org
  *
  * 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 BaseHubNode extends BaseFrameworkSystem implements Updateable {
-       /**
-        * Node id
-        */
-       private $nodeId = '';
+class BaseHubNode extends BaseHubSystem implements Updateable {
+       // Exception constants
+       const EXCEPTION_HUB_ALREADY_ANNOUNCED = 0xe00;
 
        /**
         * IP/port number of bootstrapping node
         */
        private $bootIpPort = '';
 
+       /**
+        * Query connector instance
+        */
+       private $connectorInstance = null;
+
+       /**
+        * Listener pool instance
+        */
+       private $listenerPoolInstance = null;
+
+       /**
+        * Wether this node is anncounced (KEEP ON false!)
+        * @deprecated
+        */
+       private $hubIsAnnounced = false;
+
+       /**
+        * State instance
+        */
+       private $stateInstance = null;
+
        /**
         * Protected constructor
         *
@@ -42,9 +61,19 @@ class BaseHubNode extends BaseFrameworkSystem implements Updateable {
                // Call parent constructor
                parent::__construct($className);
 
-               // Clean up a little
-               $this->removeNumberFormaters();
-               $this->removeSystemArray();
+               // Init state which sets the state to 'init'
+               $this->initState();
+       }
+
+       /**
+        * Initializes the node'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
+               StateFactory::createStateInstanceByName('init', $this);
        }
 
        /**
@@ -54,16 +83,123 @@ class BaseHubNode extends BaseFrameworkSystem implements Updateable {
         * @return      void
         */
        private final function setNodeId ($nodeId) {
-               $this->nodeId = (string) $nodeId;
+               // Set it config now
+               $this->getConfigInstance()->setConfigEntry('node_id', (string) $nodeId);
        }
 
        /**
         * Getter for node id
         *
-        * @return      $nodeId         Our new node id
+        * @return      $nodeId         Current node id
         */
        private final function getNodeId () {
-               return $this->nodeId;
+               // Get it from config
+               return $this->getConfigInstance()->getConfigEntry('node_id');
+       }
+
+       /**
+        * Setter for listener pool instance
+        *
+        * @param       $listenerPoolInstance   Our new listener pool instance
+        * @return      void
+        */
+       private final function setListenerPoolInstance (PoolableListener $listenerPoolInstance) {
+               $this->listenerPoolInstance = $listenerPoolInstance;
+       }
+
+       /**
+        * Getter for listener pool instance
+        *
+        * @return      $listenerPoolInstance   Our current listener pool instance
+        */
+       public final function getListenerPoolInstance () {
+               return $this->listenerPoolInstance;
+       }
+
+       /**
+        * Setter for state instance
+        *
+        * @param       $stateInstance  Node's current state instance
+        * @return      void
+        */
+       public final function setStateInstance (Stateable $stateInstance) {
+               $this->stateInstance = $stateInstance;
+       }
+
+       /**
+        * Getter for state instance
+        *
+        * @return      $stateInstance  Node's current state instance
+        */
+       public final function getStateInstance () {
+               return $this->stateInstance;
+       }
+
+       /**
+        * Setter for session id
+        *
+        * @param       $sessionId              Our new session id
+        * @return      void
+        */
+       private 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');
+       }
+
+       /**
+        * Setter for query instance
+        *
+        * @param       $connectorInstance              Our new query instance
+        * @return      void
+        */
+       private final function setQueryConnectorInstance (Connectable $connectorInstance) {
+               $this->connectorInstance = $connectorInstance;
+       }
+
+       /**
+        * Getter for query instance
+        *
+        * @return      $connectorInstance              Our new query instance
+        */
+       public final function getQueryConnectorInstance () {
+               return $this->connectorInstance;
+       }
+
+       /**
+        * Getter for boot IP/port combination
+        *
+        * @return      $bootIpPort             The IP/port combination of the boot node
+        */
+       protected final function getBootIpPort () {
+               return $this->bootIpPort;
+       }
+
+       /**
+        * "Getter" for a printable state name
+        */
+       public final function getPrintableState () {
+               // Default is 'null'
+               $stateName = 'null';
+
+               // Get the state instance
+               $stateInstance = $this->getStateInstance();
+
+               // Is it an instance of Stateable?
+               if ($stateInstance instanceof Stateable) {
+                       // Then use that state name
+                       $stateName = $stateInstance->getStateName();
+               } // END - if
+
+               // Return result
+               return $stateName;
        }
 
        /**
@@ -77,7 +213,7 @@ class BaseHubNode extends BaseFrameworkSystem implements Updateable {
                $isFound = false;
 
                // Run through all configured IPs
-               foreach (explode(',', $this->getConfigInstance()->readConfig('hub_bootstrap_nodes')) as $ipPort) {
+               foreach (explode(',', $this->getConfigInstance()->getConfigEntry('hub_bootstrap_nodes')) as $ipPort) {
                        // Split it up in IP/port
                        $ipPortArray = explode(':', $ipPort);
 
@@ -90,11 +226,11 @@ class BaseHubNode extends BaseFrameworkSystem implements Updateable {
                                $this->bootIpPort = $ipPort;
 
                                // Output message
-                               $this->getDebugInstance()->output(__FUNCTION__.'['.__LINE__.']: IP matches remote address ' . $ipPort . '.');
+                               $this->debugOutput('BOOTSTRAP: ' . __FUNCTION__ . '[' . __LINE__ . ']: IP matches remote address ' . $ipPort . '.');
 
                                // Stop further searching
                                break;
-                       } elseif ($ipPortArray[0] == $this->getConfigInstance()->readConfig('node_listen_addr')) {
+                       } elseif ($ipPortArray[0] == $this->getConfigInstance()->getConfigEntry('node_listen_addr')) {
                                // IP matches listen address. At this point we really don't care
                                // if we can also listen on that address!
                                $isFound = true;
@@ -103,7 +239,7 @@ class BaseHubNode extends BaseFrameworkSystem implements Updateable {
                                $this->bootIpPort = $ipPort;
 
                                // Output message
-                               $this->getDebugInstance()->output(__FUNCTION__.'['.__LINE__.']: IP matches listen address ' . $ipPort . '.');
+                               $this->debugOutput('BOOTSTRAP: ' . __FUNCTION__ . '[' . __LINE__ . ']: IP matches listen address ' . $ipPort . '.');
 
                                // Stop further searching
                                break;
@@ -120,31 +256,19 @@ class BaseHubNode extends BaseFrameworkSystem implements Updateable {
         *
         * @return      void
         */
-       private function outputConsoleTeaser () {
+       public function outputConsoleTeaser () {
                // Get the app instance (for shortening our code)
                $app = $this->getApplicationInstance();
 
                // Output all lines
-               $this->getDebugInstance()->output(' ');
-               $this->getDebugInstance()->output($app->getAppName() . ' v' . $app->getAppVersion() . ' - ' . $this->getRequestInstance()->getRequestElement('mode') . ' mode active');
-               $this->getDebugInstance()->output('Copyright (c) 2007 - 2008 Roland Haeder, 2009 Hub Developer Team');
-               $this->getDebugInstance()->output(' ');
-               $this->getDebugInstance()->output('This program comes with ABSOLUTELY NO WARRANTY; for details see docs/COPYING.');
-               $this->getDebugInstance()->output('This is free software, and you are welcome to redistribute it under certain');
-               $this->getDebugInstance()->output('conditions; see docs/COPYING for details.');
-               $this->getDebugInstance()->output(' ');
-       }
-
-       /**
-        * Do generic things for bootup phase. This can be e.g. checking if the
-        * right node mode is selected for this hub's IP number.
-        *
-        * @todo        This method is maybe not yet finished.
-        * @return      void
-        */
-       protected function doGenericBootstrapping () {
-               // Finally output our teaser. This should be the last line!
-               $this->outputConsoleTeaser();
+               $this->debugOutput(' ');
+               $this->debugOutput($app->getAppName() . ' v' . $app->getAppVersion() . ' - ' . $this->getRequestInstance()->getRequestElement('mode') . ' mode active');
+               $this->debugOutput('Copyright (c) 2007 - 2008 Roland Haeder, 2009, 2010 Hub Developer Team');
+               $this->debugOutput(' ');
+               $this->debugOutput('This program comes with ABSOLUTELY NO WARRANTY; for details see docs/COPYING.');
+               $this->debugOutput('This is free software, and you are welcome to redistribute it under certain');
+               $this->debugOutput('conditions; see docs/COPYING for details.');
+               $this->debugOutput(' ');
        }
 
        /**
@@ -152,10 +276,11 @@ class BaseHubNode extends BaseFrameworkSystem implements Updateable {
         * based on many pseudo-random data. On any later run, unless the id
         * got not removed from database, it will be restored from the database.
         *
-        * @param       $requestInstance        An instance of a Requestable class
+        * @param       $requestInstance        A Requestable class
+        * @param       $responseInstance       A Responseable class
         * @return      void
         */
-       public function acquireHubId (Requestable $requestInstance) {
+       public function bootstrapAcquireHubId (Requestable $requestInstance, Responseable $responseInstance) {
                // Get a wrapper instance
                $wrapperInstance = ObjectFactory::createObjectByConfiguredName('node_info_db_wrapper_class');
 
@@ -164,7 +289,7 @@ class BaseHubNode extends BaseFrameworkSystem implements Updateable {
 
                // Search for the node number zero which is hard-coded the default
                $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
-               $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_TYPE, $requestInstance->getRequestElement('mode'));
+               $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_TYPE, $this->getRequestInstance()->getRequestElement('mode'));
                $searchInstance->setLimit(1);
 
                // Get a result back
@@ -179,13 +304,13 @@ class BaseHubNode extends BaseFrameworkSystem implements Updateable {
                        $this->setNodeId($this->getField(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_ID));
 
                        // Output message
-                       $this->getDebugInstance()->output('Re-using found node-id: ' . $this->getNodeId() . '');
+                       $this->debugOutput('BOOTSTRAP: Re-using found node-id: ' . $this->getNodeId() . '');
                } else {
                        // Get an RNG instance (Random Number Generator)
                        $rngInstance = ObjectFactory::createObjectByConfiguredName('rng_class');
 
                        // Generate a pseudo-random string
-                       $randomString = $rngInstance->randomString(255) . ':' . $requestInstance->getRequestElement('mode');
+                       $randomString = $rngInstance->randomString(255) . ':' . $this->getBootIpPort()  . ':' . $this->getRequestInstance()->getRequestElement('mode');
 
                        // Get a crypto instance
                        $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
@@ -194,13 +319,63 @@ class BaseHubNode extends BaseFrameworkSystem implements Updateable {
                        $this->setNodeId($cryptoInstance->hashString($cryptoInstance->encryptString($randomString)));
 
                        // Register the node id with our wrapper
-                       $wrapperInstance->registerNodeId($this, $requestInstance);
+                       $wrapperInstance->registerNodeId($this, $this->getRequestInstance());
 
                        // Output message
-                       $this->getDebugInstance()->output('Created new node-id: ' . $this->getNodeId() . '');
+                       $this->debugOutput('BOOTSTRAP: Created new node-id: ' . $this->getNodeId() . '');
                }
        }
 
+       /**
+        * Generates a session id which will be sent to the other hubs and clients
+        *
+        * @return      void
+        */
+       public function bootstrapGenerateSessionId () {
+               // Get an RNG instance
+               $rngInstance = ObjectFactory::createObjectByConfiguredName('rng_class');
+
+               // Generate a pseudo-random string
+               $randomString = $rngInstance->randomString(255) . ':' . $this->getBootIpPort() . ':' . $this->getRequestInstance()->getRequestElement('mode');
+
+               // Get a crypto instance
+               $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
+
+               // Hash and encrypt the string so we become a "node id" aka Hub-Id
+               $this->setSessionId($cryptoInstance->hashString($cryptoInstance->encryptString($randomString)));
+
+               // Get a wrapper instance
+               $wrapperInstance = ObjectFactory::createObjectByConfiguredName('node_info_db_wrapper_class');
+
+               // Register the node id with our wrapper
+               $wrapperInstance->registerSessionId($this, $this->getRequestInstance());
+
+               // Output message
+               $this->debugOutput('BOOTSTRAP: Created new session-id: ' . $this->getSessionId() . '');
+
+               // Change the state because the node has auired a hub id
+               $this->getStateInstance()->nodeGeneratedSessionId();
+       }
+
+       /**
+        * Initializes queues which every node needs
+        *
+        * @return      void
+        */
+       protected function initGenericQueues () {
+               // Debug message
+               $this->debugOutput('BOOTSTRAP: Initialize queues: START');
+
+               // Set the query connector instance
+               $this->setQueryConnectorInstance(ObjectFactory::createObjectByConfiguredName('query_connector_class', array($this)));
+
+               // Run a test query
+               $this->getQueryConnectorInstance()->doTestQuery();
+
+               // Debug message
+               $this->debugOutput('BOOTSTRAP: Initialize queues: FINISHED');
+       }
+
        /**
         * Adds hub data elements to a given dataset instance
         *
@@ -215,6 +390,11 @@ class BaseHubNode extends BaseFrameworkSystem implements Updateable {
 
                // Add the node id
                $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_ID, $this->getNodeId());
+
+               // Add the session id if acquired
+               if ($this->getSessionId() != '') {
+                       $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_SESSION_ID, $this->getSessionId());
+               } // END - if
        }
 
        /**
@@ -228,7 +408,7 @@ class BaseHubNode extends BaseFrameworkSystem implements Updateable {
         */
        public function updateDatabaseField ($fieldName, $fieldValue) {
                // Unfinished
-               $this->partialStub("Unfinished!");
+               $this->partialStub('Unfinished!');
                return;
 
                // Get a critieria instance
@@ -253,6 +433,188 @@ class BaseHubNode extends BaseFrameworkSystem implements Updateable {
                // Remember the update in database result
                $this->getResultInstance()->add2UpdateQueue($updateInstance);
        }
+
+       /**
+        * Announces this hub to the upper (bootstrap or list) hubs. After this is
+        * successfully done the given task is unregistered from the handler.
+        *
+        * @param       $taskInstance   The task instance running this announcement
+        * @return      void
+        * @throws      HubAlreadyAnnouncedException    If this hub is already announced
+        * @todo        Change the first if() block to check for a specific state
+        */
+       public function announceSelfToUpperNodes (Taskable $taskInstance) {
+               // Is this hub node announced?
+               if ($this->hubIsAnnounced === true) {
+                       // Already announced!
+                       throw new HubAlreadyAnnouncedException($this, self::EXCEPTION_HUB_ALREADY_ANNOUNCED);
+               } // END - if
+
+               // Debug output
+               $this->debugOutput('HUB: Self-announcement: START (taskInstance=' . $taskInstance->__toString(). ')');
+
+               // Get a helper instance
+               $helperInstance = ObjectFactory::createObjectByConfiguredName('hub_announcement_helper_class', array($this));
+
+               // Load the announcement descriptor
+               $helperInstance->loadAnnouncementDescriptor();
+
+               // Set some dummy configuration entries, e.g. node_status
+               $this->getConfigInstance()->setConfigEntry('node_status', $this->getStateInstance()->getStateName());
+
+               // Compile all variables
+               $helperInstance->getTemplateInstance()->compileConfigInVariables();
+
+               // "Publish" the descriptor by sending it to the bootstrap/list nodes
+               $helperInstance->publishAnnouncementDescriptor();
+
+               // Change the state, this should be the last line except debug output
+               $this->getStateInstance()->nodeAnnouncedToUpperHubs();
+               die("OK!\n");
+
+               // Debug output
+               $this->debugOutput('HUB: Self-announcement: FINISHED');
+       }
+
+       /**
+        * Activates the hub by doing some final preparation and setting
+        * $hubIsActive to true
+        *
+        * @param       $requestInstance        A Requestable class
+        * @param       $responseInstance       A Responseable class
+        * @return      void
+        */
+       public function activateHub (Requestable $requestInstance, Responseable $responseInstance) {
+               // Checks wether a listener is still active and shuts it down if one
+               // is still listening.
+               if (($this->determineIfListenerIsActive()) && ($this->determineIfHubIsActive())) {
+                       // Shutdown them down before they can hurt anything
+                       $this->shutdownListenerPool();
+               } // END - if
+
+               // Get the controller here
+               $controllerInstance = Registry::getRegistry()->getInstance('controller');
+
+               // Run all filters for the hub activation
+               $controllerInstance->executeActivationFilters($requestInstance, $responseInstance);
+
+               // ----------------------- Last step from here ------------------------
+               // Activate the hub. This is ALWAYS the last step in this method
+               $this->getStateInstance()->nodeIsActivated();
+               // ---------------------- Last step until here ------------------------
+       }
+
+       /**
+        * Initializes the listener pool (class)
+        *
+        * @return      void
+        */
+       public function initializeListenerPool () {
+               // Debug output
+               $this->debugOutput('HUB: Initialize listener: START');
+
+               // Get a new pool instance
+               $this->setListenerPoolInstance(ObjectFactory::createObjectByConfiguredName('listener_pool_class', array($this)));
+
+               // Get an instance of the low-level listener
+               $listenerInstance = ObjectFactory::createObjectByConfiguredName('tcp_listener_class', array($this));
+
+               // Setup address and port
+               $listenerInstance->setListenAddressByConfiguration('node_listen_addr');
+               $listenerInstance->setListenPortByConfiguration('node_tcp_listen_port');
+
+               // Initialize the listener
+               $listenerInstance->initListener();
+
+               // Get a decorator class
+               $decoratorInstance = ObjectFactory::createObjectByConfiguredName('hub_tcp_listener_class', array($listenerInstance));
+
+               // Add this listener to the pool
+               $this->getListenerPoolInstance()->addListener($decoratorInstance);
+
+               // Get a decorator class
+               $decoratorInstance = ObjectFactory::createObjectByConfiguredName('client_tcp_listener_class', array($listenerInstance));
+
+               // Add this listener to the pool
+               $this->getListenerPoolInstance()->addListener($decoratorInstance);
+
+               // Get an instance of the low-level listener
+               $listenerInstance = ObjectFactory::createObjectByConfiguredName('udp_listener_class', array($this));
+
+               // Setup address and port
+               $listenerInstance->setListenAddressByConfiguration('node_listen_addr');
+               $listenerInstance->setListenPortByConfiguration('node_udp_listen_port');
+
+               // Initialize the listener
+               $listenerInstance->initListener();
+
+               // Get a decorator class
+               $decoratorInstance = ObjectFactory::createObjectByConfiguredName('hub_udp_listener_class', array($listenerInstance));
+
+               // Add this listener to the pool
+               $this->getListenerPoolInstance()->addListener($decoratorInstance);
+
+               // Get a decorator class
+               $decoratorInstance = ObjectFactory::createObjectByConfiguredName('client_udp_listener_class', array($listenerInstance));
+
+               // Add this listener to the pool
+               $this->getListenerPoolInstance()->addListener($decoratorInstance);
+
+               // Debug output
+               $this->debugOutput('HUB: Initialize listener: FINISHED.');
+       }
+
+       /**
+        * Restores a previously stored node list from database
+        *
+        * @return      void
+        */
+       public function bootstrapRestoreNodeList () {
+               // Debug output
+               $this->debugOutput('HUB: Restore node list: START');
+
+               // Get a wrapper instance
+               $wrapperInstance = ObjectFactory::createObjectByConfiguredName('node_list_db_wrapper_class');
+
+               // Now get a search criteria instance
+               $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
+
+               // Search for the node number zero which is hard-coded the default
+               // @TODO Add some criteria, e.g. if the node is active or so
+               //$searchInstance->addCriteria(NodeListDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
+               //$searchInstance->addCriteria(NodeListDatabaseWrapper::DB_COLUMN_NODE_TYPE, $this->getRequestInstance()->getRequestElement('mode'));
+               //$searchInstance->setLimit(1);
+
+               // Get a result back
+               $resultInstance = $wrapperInstance->doSelectByCriteria($searchInstance);
+
+               // Is it valid?
+               if ($resultInstance->next()) {
+                       $this->partialStub('Do something for restoring the list.');
+                       // Output message
+                       //$this->debugOutput('HUB: ');
+               } else {
+                       // No previously saved node list found!
+                       $this->debugOutput('HUB: No previously saved node list found. This is fine.');
+               }
+
+               // Debug output
+               $this->debugOutput('HUB: Restore node list: FINISHED.');
+       }
+
+       /**
+        * Determines wether the hub is active by checking its current state
+        *
+        * @return      $isActive       Wether the hub is active
+        */
+       public function determineIfHubIsActive () {
+               // Check the state
+               // @TODO Add more states e.g. 'firewalled', 'senior'
+               $isActive = ($this->getStateInstance() instanceof NodeActiveState);
+
+               // Return value
+               return $isActive;
+       }
 }
 
 // [EOF]