3 * A general hub node 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 BaseHubNode extends BaseHubSystem implements Updateable {
25 // Exception constants
26 const EXCEPTION_HUB_ALREADY_ANNOUNCED = 0xe00;
29 * IP/port number of bootstrapping node
31 private $bootIpPort = '';
34 * Query connector instance
36 private $queryConnectorInstance = null;
39 * Queue connector instance
41 private $queueConnectorInstance = null;
44 * Listener pool instance
46 private $listenerPoolInstance = null;
49 * Wether this node is anncounced (KEEP ON false!)
52 private $hubIsAnnounced = false;
57 private $stateInstance = null;
60 * Wether this hub is active
62 private $isActive = false;
65 * Protected constructor
67 * @param $className Name of the class
70 protected function __construct ($className) {
71 // Call parent constructor
72 parent::__construct($className);
74 // Init state which sets the state to 'init'
79 * Initializes the node's state which sets it to 'init'
83 private function initState() {
84 // Get the state factory and create the initial state, we don't need
85 // the state instance here
86 StateFactory::createStateInstanceByName('init', $this);
92 * @param $nodeId Our new node id
95 private final function setNodeId ($nodeId) {
97 $this->getConfigInstance()->setConfigEntry('node_id', (string) $nodeId);
103 * @return $nodeId Current node id
105 private final function getNodeId () {
106 // Get it from config
107 return $this->getConfigInstance()->getConfigEntry('node_id');
111 * Setter for listener pool instance
113 * @param $listenerPoolInstance Our new listener pool instance
116 private final function setListenerPoolInstance (PoolableListener $listenerPoolInstance) {
117 $this->listenerPoolInstance = $listenerPoolInstance;
121 * Getter for listener pool instance
123 * @return $listenerPoolInstance Our current listener pool instance
125 public final function getListenerPoolInstance () {
126 return $this->listenerPoolInstance;
130 * Setter for state instance
132 * @param $stateInstance Node's current state instance
135 public final function setStateInstance (Stateable $stateInstance) {
136 $this->stateInstance = $stateInstance;
140 * Getter for state instance
142 * @return $stateInstance Node's current state instance
144 public final function getStateInstance () {
145 return $this->stateInstance;
149 * Setter for session id
151 * @param $sessionId Our new session id
154 private final function setSessionId ($sessionId) {
155 $this->getConfigInstance()->setConfigEntry('session_id', (string) $sessionId);
159 * Getter for session id
161 * @return $sessionId Current session id
163 public final function getSessionId () {
164 return $this->getConfigInstance()->getConfigEntry('session_id');
168 * Setter for query instance
170 * @param $connectorInstance Our new query instance
173 private final function setQueryConnectorInstance (Connectable $connectorInstance) {
174 $this->queryConnectorInstance = $connectorInstance;
178 * Getter for query instance
180 * @return $connectorInstance Our new query instance
182 public final function getQueryConnectorInstance () {
183 return $this->queryConnectorInstance;
187 * Setter for queue instance
189 * @param $connectorInstance Our new queue instance
192 private final function setQueueConnectorInstance (Connectable $connectorInstance) {
193 $this->queueConnectorInstance = $connectorInstance;
197 * Getter for queue instance
199 * @return $connectorInstance Our new queue instance
201 public final function getQueueConnectorInstance () {
202 return $this->queueConnectorInstance;
206 * Getter for boot IP/port combination
208 * @return $bootIpPort The IP/port combination of the boot node
210 protected final function getBootIpPort () {
211 return $this->bootIpPort;
215 * "Getter" for a printable state name
217 * @return $stateName Name of the node's state in a printable format
219 public final function getPrintableState () {
223 // Get the state instance
224 $stateInstance = $this->getStateInstance();
226 // Is it an instance of Stateable?
227 if ($stateInstance instanceof Stateable) {
228 // Then use that state name
229 $stateName = $stateInstance->getStateName();
237 * Checks wether the given IP address matches one of the bootstrapping nodes
239 * @param $remoteAddr IP address to checkout against our bootstrapping list
240 * @return $isFound Wether the IP is found
242 protected function ifAddressMatchesBootstrappingNodes ($remoteAddr) {
243 // By default nothing is found
246 // Run through all configured IPs
247 foreach (explode(',', $this->getConfigInstance()->getConfigEntry('hub_bootstrap_nodes')) as $ipPort) {
248 // Split it up in IP/port
249 $ipPortArray = explode(':', $ipPort);
252 if ($ipPortArray[0] == $remoteAddr) {
256 // Remember the port number
257 $this->bootIpPort = $ipPort;
260 $this->debugOutput('BOOTSTRAP: ' . __FUNCTION__ . '[' . __LINE__ . ']: IP matches remote address ' . $ipPort . '.');
262 // Stop further searching
264 } elseif ($ipPortArray[0] == $this->getConfigInstance()->getConfigEntry('node_listen_addr')) {
265 // IP matches listen address. At this point we really don't care
266 // if we can really listen on that address
269 // Remember the port number
270 $this->bootIpPort = $ipPort;
273 $this->debugOutput('BOOTSTRAP: ' . __FUNCTION__ . '[' . __LINE__ . ']: IP matches listen address ' . $ipPort . '.');
275 // Stop further searching
285 * Outputs the console teaser. This should only be executed on startup or
286 * full restarts. This method generates some space around the teaser.
290 public function outputConsoleTeaser () {
291 // Get the app instance (for shortening our code)
292 $app = $this->getApplicationInstance();
295 $this->debugOutput(' ');
296 $this->debugOutput($app->getAppName() . ' v' . $app->getAppVersion() . ' - ' . $this->getRequestInstance()->getRequestElement('mode') . ' mode active');
297 $this->debugOutput('Copyright (c) 2007 - 2008 Roland Haeder, 2009 - 2011 Hub Developer Team');
298 $this->debugOutput(' ');
299 $this->debugOutput('This program comes with ABSOLUTELY NO WARRANTY; for details see docs/COPYING.');
300 $this->debugOutput('This is free software, and you are welcome to redistribute it under certain');
301 $this->debugOutput('conditions; see docs/COPYING for details.');
302 $this->debugOutput(' ');
306 * Generic method to acquire a hub-id. On first run this generates a new one
307 * based on many pseudo-random data. On any later run, unless the id
308 * got not removed from database, it will be restored from the database.
310 * @param $requestInstance A Requestable class
311 * @param $responseInstance A Responseable class
314 public function bootstrapAcquireNodeId (Requestable $requestInstance, Responseable $responseInstance) {
315 // Get a wrapper instance
316 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('node_info_db_wrapper_class');
318 // Now get a search criteria instance
319 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
321 // Search for the node number zero which is hard-coded the default
322 $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
323 $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_TYPE, $this->getRequestInstance()->getRequestElement('mode'));
324 $searchInstance->setLimit(1);
327 $resultInstance = $wrapperInstance->doSelectByCriteria($searchInstance);
330 if ($resultInstance->next()) {
331 // Save the result instance in this class
332 $this->setResultInstance($resultInstance);
334 // Get the node id from result and set it
335 $this->setNodeId($this->getField(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_ID));
338 $this->debugOutput('BOOTSTRAP: Re-using found node-id: ' . $this->getNodeId() . '');
340 // Get an RNG instance (Random Number Generator)
341 $rngInstance = ObjectFactory::createObjectByConfiguredName('rng_class');
343 // Generate a pseudo-random string
344 $randomString = $rngInstance->randomString(255) . ':' . $this->getBootIpPort() . ':' . $this->getRequestInstance()->getRequestElement('mode');
346 // Get a crypto instance
347 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
349 // Hash and encrypt the string so we become a node id (also documented as "hub id")
350 $this->setNodeId($cryptoInstance->hashString($cryptoInstance->encryptString($randomString)));
352 // Register the node id with our wrapper
353 $wrapperInstance->registerNodeId($this, $this->getRequestInstance());
356 $this->debugOutput('BOOTSTRAP: Created new node-id: ' . $this->getNodeId() . '');
361 * Generates a session id which will be sent to the other hubs and peers
365 public function bootstrapGenerateSessionId () {
366 // Get an RNG instance
367 $rngInstance = ObjectFactory::createObjectByConfiguredName('rng_class');
369 // Generate a pseudo-random string
370 $randomString = $rngInstance->randomString(255) . ':' . $this->getBootIpPort() . ':' . $this->getRequestInstance()->getRequestElement('mode');
372 // Get a crypto instance
373 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
375 // Hash and encrypt the string so we become a "node id" aka Hub-Id
376 $this->setSessionId($cryptoInstance->hashString($cryptoInstance->encryptString($randomString)));
378 // Get a wrapper instance
379 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('node_info_db_wrapper_class');
381 // Register the node id with our wrapper
382 $wrapperInstance->registerSessionId($this, $this->getRequestInstance());
385 $this->debugOutput('BOOTSTRAP: Created new session-id: ' . $this->getSessionId() . '');
387 // Change the state because the node has auired a hub id
388 $this->getStateInstance()->nodeGeneratedSessionId();
392 * Initializes queues which every node needs
396 protected function initGenericQueues () {
398 $this->debugOutput('BOOTSTRAP: Initialize queues: START');
400 // Set the query connector instance
401 $this->setQueryConnectorInstance(ObjectFactory::createObjectByConfiguredName('query_connector_class', array($this)));
404 $this->getQueryConnectorInstance()->doTestQuery();
406 // Set the queue connector instance
407 $this->setQueueConnectorInstance(ObjectFactory::createObjectByConfiguredName('queue_connector_class', array($this)));
410 $this->getQueueConnectorInstance()->doTestQueue();
413 $this->debugOutput('BOOTSTRAP: Initialize queues: FINISHED');
417 * Adds hub data elements to a given dataset instance
419 * @param $criteriaInstance An instance of a storeable criteria
420 * @param $requestInstance An instance of a Requestable class
423 public function addElementsToDataSet (StoreableCriteria $criteriaInstance, Requestable $requestInstance) {
424 // Add node number and type
425 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
426 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_TYPE, $requestInstance->getRequestElement('mode'));
429 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_ID, $this->getNodeId());
431 // Add the session id if acquired
432 if ($this->getSessionId() != '') {
433 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_SESSION_ID, $this->getSessionId());
438 * Updates a given field with new value
440 * @param $fieldName Field to update
441 * @param $fieldValue New value to store
443 * @throws DatabaseUpdateSupportException If this class does not support database updates
444 * @todo Try to make this method more generic so we can move it in BaseFrameworkSystem
446 public function updateDatabaseField ($fieldName, $fieldValue) {
448 $this->partialStub('Unfinished!');
451 // Get a critieria instance
452 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
454 // Add search criteria
455 $searchInstance->addCriteria(UserDatabaseWrapper::DB_COLUMN_USERNAME, $this->getUserName());
456 $searchInstance->setLimit(1);
458 // Now get another criteria
459 $updateInstance = ObjectFactory::createObjectByConfiguredName('update_criteria_class');
461 // Add criteria entry which we shall update
462 $updateInstance->addCriteria($fieldName, $fieldValue);
464 // Add the search criteria for searching for the right entry
465 $updateInstance->setSearchInstance($searchInstance);
467 // Set wrapper class name
468 $updateInstance->setWrapperConfigEntry('user_db_wrapper_class');
470 // Remember the update in database result
471 $this->getResultInstance()->add2UpdateQueue($updateInstance);
475 * Announces this hub to the upper (bootstrap or list) hubs. After this is
476 * successfully done the given task is unregistered from the handler. This
477 * might look a bit overloaded here but the announcement phase isn't a
478 * simple "Hello there" message, it may later on also contain more
479 * informations like the object list.
481 * @param $taskInstance The task instance running this announcement
483 * @throws HubAlreadyAnnouncedException If this hub is already announced
484 * @todo Change the first if() block to check for a specific state
486 public function announceSelfToUpperNodes (Taskable $taskInstance) {
487 // Is this hub node announced?
488 if ($this->hubIsAnnounced === true) {
489 // Already announced!
490 throw new HubAlreadyAnnouncedException($this, self::EXCEPTION_HUB_ALREADY_ANNOUNCED);
494 $this->debugOutput('HUB: Announcement: START (taskInstance=' . $taskInstance->__toString(). ')');
496 // Get a helper instance
497 $helperInstance = ObjectFactory::createObjectByConfiguredName('hub_announcement_helper_class', array($this));
499 // Load the announcement descriptor
500 $helperInstance->loadDescriptorXml();
502 // Set some dummy configuration entries, e.g. node_status
503 $this->getConfigInstance()->setConfigEntry('node_status', $this->getStateInstance()->getStateName());
505 // Compile all variables
506 $helperInstance->getTemplateInstance()->compileConfigInVariables();
508 // "Publish" the descriptor by sending it to the bootstrap/list nodes
509 $helperInstance->sendPackage();
511 // Change the state, this should be the last line except debug output
512 $this->getStateInstance()->nodeAnnouncedToUpperHubs();
515 $this->debugOutput('HUB: Announcement: FINISHED');
519 * Does a self-connect attempt on the public IP address. This should make
520 * it sure, we are reachable from outside world. For this kind of package we
521 * don't need that overload we have in the announcement phase.
523 * @param $taskInstance The task instance running this announcement
526 public function doSelfConnection (Taskable $taskInstance) {
528 $this->debugOutput('HUB: Self Connection: START (taskInstance=' . $taskInstance->__toString(). ')');
530 // Get a helper instance
531 $helperInstance = ObjectFactory::createObjectByConfiguredName('hub_self_connect_helper_class', array($this));
533 // Load the descriptor (XML) file
534 $helperInstance->loadDescriptorXml();
536 // And send the package away
537 $helperInstance->sendPackage();
540 $this->debugOutput('HUB: Self Connection: FINISHED');
544 * Activates the hub by doing some final preparation and setting
545 * $hubIsActive to true
547 * @param $requestInstance A Requestable class
548 * @param $responseInstance A Responseable class
551 public function activateNode (Requestable $requestInstance, Responseable $responseInstance) {
552 // Checks wether a listener is still active and shuts it down if one
553 // is still listening.
554 if (($this->determineIfListenerIsActive()) && ($this->getIsActive())) {
555 // Shutdown them down before they can hurt anything
556 $this->shutdownListenerPool();
559 // Get the controller here
560 $controllerInstance = Registry::getRegistry()->getInstance('controller');
562 // Run all filters for the hub activation
563 $controllerInstance->executeActivationFilters($requestInstance, $responseInstance);
565 // ----------------------- Last step from here ------------------------
566 // Activate the hub. This is ALWAYS the last step in this method
567 $this->getStateInstance()->nodeIsActivated();
568 // ---------------------- Last step until here ------------------------
572 * Initializes the listener pool (class)
576 public function initializeListenerPool () {
578 $this->debugOutput('HUB: Initialize listener: START');
580 // Get a new pool instance
581 $this->setListenerPoolInstance(ObjectFactory::createObjectByConfiguredName('listener_pool_class', array($this)));
583 // Get an instance of the low-level listener
584 $listenerInstance = ObjectFactory::createObjectByConfiguredName('tcp_listener_class', array($this));
586 // Setup address and port
587 $listenerInstance->setListenAddressByConfiguration('node_listen_addr');
588 if ($this instanceof HubBootNode) {
589 // Bootstrap have different listening port
590 $listenerInstance->setListenPortByConfiguration('boot_node_tcp_listen_port');
592 // All other nodes use the default port
593 $listenerInstance->setListenPortByConfiguration('node_tcp_listen_port');
596 // Initialize the listener
597 $listenerInstance->initListener();
599 // Get a decorator class
600 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('hub_tcp_listener_class', array($listenerInstance));
602 // Add this listener to the pool
603 $this->getListenerPoolInstance()->addListener($decoratorInstance);
605 // Get a decorator class
606 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('peer_tcp_listener_class', array($listenerInstance));
608 // Add this listener to the pool
609 $this->getListenerPoolInstance()->addListener($decoratorInstance);
611 // Get an instance of the low-level listener
612 $listenerInstance = ObjectFactory::createObjectByConfiguredName('udp_listener_class', array($this));
614 // Setup address and port
615 $listenerInstance->setListenAddressByConfiguration('node_listen_addr');
616 if ($this instanceof HubBootNode) {
617 // Bootstrap have different listening port
618 $listenerInstance->setListenPortByConfiguration('boot_node_udp_listen_port');
620 // All other nodes use the default port
621 $listenerInstance->setListenPortByConfiguration('node_udp_listen_port');
624 // Initialize the listener
625 $listenerInstance->initListener();
627 // Get a decorator class
628 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('hub_udp_listener_class', array($listenerInstance));
630 // Add this listener to the pool
631 $this->getListenerPoolInstance()->addListener($decoratorInstance);
633 // Get a decorator class
634 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('peer_udp_listener_class', array($listenerInstance));
636 // Add this listener to the pool
637 $this->getListenerPoolInstance()->addListener($decoratorInstance);
640 $this->debugOutput('HUB: Initialize listener: FINISHED.');
644 * Restores a previously stored node list from database
648 public function bootstrapRestoreNodeList () {
650 $this->debugOutput('HUB: Restore node list: START');
652 // Get a wrapper instance
653 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('node_list_db_wrapper_class');
655 // Now get a search criteria instance
656 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
658 // Search for the node number zero which is hard-coded the default
659 // @TODO Add some criteria, e.g. if the node is active or so
660 //$searchInstance->addCriteria(NodeListDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
661 //$searchInstance->addCriteria(NodeListDatabaseWrapper::DB_COLUMN_NODE_TYPE, $this->getRequestInstance()->getRequestElement('mode'));
662 //$searchInstance->setLimit(1);
665 $resultInstance = $wrapperInstance->doSelectByCriteria($searchInstance);
668 if ($resultInstance->next()) {
669 $this->partialStub('Do something for restoring the list.');
671 //$this->debugOutput('HUB: ');
673 // No previously saved node list found!
674 $this->debugOutput('HUB: No previously saved node list found. This is fine.');
678 $this->debugOutput('HUB: Restore node list: FINISHED.');
682 * Getter for isActive attribute
684 * @return $isActive Wether the hub is active
686 public final function getIsActive () {
687 return $this->isActive;
691 * Enables (default) or disables isActive flag
693 * @param $isActive Wether the hub is active
696 public final function enableIsActive ($isActive = true) {
697 $this->isActive = (bool) $isActive;
701 * "Getter for address:port combination
703 * @param $handlerInstance A valid Networkable instance
704 * @return $addressPort A address:port combination for this node
706 public final function getAddressPort (Networkable $handlerInstance) {
707 // Construct config entry
708 $configEntry = 'node_' . $handlerInstance->getHandlerName() . '_listen_port';
711 $addressPort = $this->getConfigInstance()->detectServerAddress() . ':' . $this->getConfigInstance()->getConfigEntry($configEntry);