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 {
28 const NODE_TYPE_BOOT = 'boot';
29 const NODE_TYPE_MASTER = 'master';
30 const NODE_TYPE_LIST = 'list';
31 const NODE_TYPE_REGULAR = 'regular';
33 // Exception constants
34 const EXCEPTION_HUB_ALREADY_ANNOUNCED = 0xe00;
37 * IP/port number of bootstrapping node
39 private $bootIpPort = '';
42 * Query connector instance
44 private $queryConnectorInstance = null;
47 * Queue connector instance
49 private $queueConnectorInstance = null;
52 * Listener pool instance
54 private $listenerPoolInstance = null;
57 * Wether this node is anncounced (KEEP ON false!)
60 private $hubIsAnnounced = false;
63 * Wether this hub is active
65 private $isActive = false;
68 * Protected constructor
70 * @param $className Name of the class
73 protected function __construct ($className) {
74 // Call parent constructor
75 parent::__construct($className);
77 // Init state which sets the state to 'init'
82 * Initializes the node's state which sets it to 'init'
86 private function initState() {
87 // Get the state factory and create the initial state, we don't need
88 // the state instance here
89 NodeStateFactory::createNodeStateInstanceByName('init', $this);
95 * @param $nodeId Our new node id
98 private final function setNodeId ($nodeId) {
100 $this->getConfigInstance()->setConfigEntry('node_id', (string) $nodeId);
106 * @return $nodeId Current node id
108 private final function getNodeId () {
109 // Get it from config
110 return $this->getConfigInstance()->getConfigEntry('node_id');
114 * Setter for listener pool instance
116 * @param $listenerPoolInstance Our new listener pool instance
119 private final function setListenerPoolInstance (PoolableListener $listenerPoolInstance) {
120 $this->listenerPoolInstance = $listenerPoolInstance;
124 * Getter for listener pool instance
126 * @return $listenerPoolInstance Our current listener pool instance
128 public final function getListenerPoolInstance () {
129 return $this->listenerPoolInstance;
133 * Setter for session id
135 * @param $sessionId Our new session id
138 private final function setSessionId ($sessionId) {
139 $this->getConfigInstance()->setConfigEntry('session_id', (string) $sessionId);
143 * Getter for session id
145 * @return $sessionId Current session id
147 public final function getSessionId () {
148 return $this->getConfigInstance()->getConfigEntry('session_id');
152 * Setter for query instance
154 * @param $connectorInstance Our new query instance
157 private final function setQueryConnectorInstance (Connectable $connectorInstance) {
158 $this->queryConnectorInstance = $connectorInstance;
162 * Getter for query instance
164 * @return $connectorInstance Our new query instance
166 public final function getQueryConnectorInstance () {
167 return $this->queryConnectorInstance;
171 * Setter for queue instance
173 * @param $connectorInstance Our new queue instance
176 private final function setQueueConnectorInstance (Connectable $connectorInstance) {
177 $this->queueConnectorInstance = $connectorInstance;
181 * Getter for queue instance
183 * @return $connectorInstance Our new queue instance
185 public final function getQueueConnectorInstance () {
186 return $this->queueConnectorInstance;
190 * Getter for boot IP/port combination
192 * @return $bootIpPort The IP/port combination of the boot node
194 protected final function getBootIpPort () {
195 return $this->bootIpPort;
199 * Checks wether the given IP address matches one of the bootstrapping nodes
201 * @param $remoteAddr IP address to checkout against our bootstrapping list
202 * @return $isFound Wether the IP is found
204 protected function ifAddressMatchesBootstrappingNodes ($remoteAddr) {
205 // By default nothing is found
208 // Run through all configured IPs
209 foreach (explode(BaseHubSystem::BOOTSTRAP_NODES_SEPERATOR, $this->getConfigInstance()->getConfigEntry('hub_bootstrap_nodes')) as $ipPort) {
210 // Split it up in IP/port
211 $ipPortArray = explode(':', $ipPort);
214 if ($ipPortArray[0] == $remoteAddr) {
218 // Remember the port number
219 $this->bootIpPort = $ipPort;
222 $this->debugOutput('BOOTSTRAP: ' . __FUNCTION__ . '[' . __LINE__ . ']: IP matches remote address ' . $ipPort . '.');
224 // Stop further searching
226 } elseif ($ipPortArray[0] == $this->getConfigInstance()->getConfigEntry('node_listen_addr')) {
227 // IP matches listen address. At this point we really don't care
228 // if we can really listen on that address
231 // Remember the port number
232 $this->bootIpPort = $ipPort;
235 $this->debugOutput('BOOTSTRAP: ' . __FUNCTION__ . '[' . __LINE__ . ']: IP matches listen address ' . $ipPort . '.');
237 // Stop further searching
247 * Outputs the console teaser. This should only be executed on startup or
248 * full restarts. This method generates some space around the teaser.
252 public function outputConsoleTeaser () {
253 // Get the app instance (for shortening our code)
254 $app = $this->getApplicationInstance();
257 $this->debugOutput(' ');
258 $this->debugOutput($app->getAppName() . ' v' . $app->getAppVersion() . ' - ' . $this->getRequestInstance()->getRequestElement('mode') . ' mode active');
259 $this->debugOutput('Copyright (c) 2007 - 2008 Roland Haeder, 2009 - 2011 Hub Developer Team');
260 $this->debugOutput(' ');
261 $this->debugOutput('This program comes with ABSOLUTELY NO WARRANTY; for details see docs/COPYING.');
262 $this->debugOutput('This is free software, and you are welcome to redistribute it under certain');
263 $this->debugOutput('conditions; see docs/COPYING for details.');
264 $this->debugOutput(' ');
268 * Generic method to acquire a hub-id. On first run this generates a new one
269 * based on many pseudo-random data. On any later run, unless the id
270 * got not removed from database, it will be restored from the database.
272 * @param $requestInstance A Requestable class
273 * @param $responseInstance A Responseable class
276 public function bootstrapAcquireNodeId (Requestable $requestInstance, Responseable $responseInstance) {
277 // Get a wrapper instance
278 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('node_info_db_wrapper_class');
280 // Now get a search criteria instance
281 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
283 // Search for the node number zero which is hard-coded the default
284 $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
285 $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_TYPE, $this->getRequestInstance()->getRequestElement('mode'));
286 $searchInstance->setLimit(1);
289 $resultInstance = $wrapperInstance->doSelectByCriteria($searchInstance);
292 if ($resultInstance->next()) {
293 // Save the result instance in this class
294 $this->setResultInstance($resultInstance);
296 // Get the node id from result and set it
297 $this->setNodeId($this->getField(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_ID));
300 $this->debugOutput('BOOTSTRAP: Re-using found node-id: ' . $this->getNodeId() . '');
302 // Get an RNG instance (Random Number Generator)
303 $rngInstance = ObjectFactory::createObjectByConfiguredName('rng_class');
305 // Generate a pseudo-random string
306 $randomString = $rngInstance->randomString(255) . ':' . $this->getBootIpPort() . ':' . $this->getRequestInstance()->getRequestElement('mode');
308 // Get a crypto instance
309 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
311 // Hash and encrypt the string so we become a node id (also documented as "hub id")
312 $this->setNodeId($cryptoInstance->hashString($cryptoInstance->encryptString($randomString)));
314 // Register the node id with our wrapper
315 $wrapperInstance->registerNodeId($this, $this->getRequestInstance());
318 $this->debugOutput('BOOTSTRAP: Created new node-id: ' . $this->getNodeId() . '');
323 * Generates a session id which will be sent to the other hubs and peers
327 public function bootstrapGenerateSessionId () {
328 // Get an RNG instance
329 $rngInstance = ObjectFactory::createObjectByConfiguredName('rng_class');
331 // Generate a pseudo-random string
332 $randomString = $rngInstance->randomString(255) . ':' . $this->getBootIpPort() . ':' . $this->getRequestInstance()->getRequestElement('mode');
334 // Get a crypto instance
335 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
337 // Hash and encrypt the string so we become a "node id" aka Hub-Id
338 $this->setSessionId($cryptoInstance->hashString($cryptoInstance->encryptString($randomString)));
340 // Get a wrapper instance
341 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('node_info_db_wrapper_class');
343 // Register the node id with our wrapper
344 $wrapperInstance->registerSessionId($this, $this->getRequestInstance());
347 $this->debugOutput('BOOTSTRAP: Created new session-id: ' . $this->getSessionId() . '');
349 // Change the state because the node has auired a hub id
350 $this->getStateInstance()->nodeGeneratedSessionId();
354 * Initializes queues which every node needs
358 protected function initGenericQueues () {
360 $this->debugOutput('BOOTSTRAP: Initialize queues: START');
362 // Set the query connector instance
363 $this->setQueryConnectorInstance(ObjectFactory::createObjectByConfiguredName('query_connector_class', array($this)));
366 $this->getQueryConnectorInstance()->doTestQuery();
368 // Set the queue connector instance
369 $this->setQueueConnectorInstance(ObjectFactory::createObjectByConfiguredName('queue_connector_class', array($this)));
372 $this->getQueueConnectorInstance()->doTestQueue();
375 $this->debugOutput('BOOTSTRAP: Initialize queues: FINISHED');
379 * Adds hub data elements to a given dataset instance
381 * @param $criteriaInstance An instance of a storeable criteria
382 * @param $requestInstance An instance of a Requestable class
385 public function addElementsToDataSet (StoreableCriteria $criteriaInstance, Requestable $requestInstance) {
386 // Add node number and type
387 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
388 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_TYPE, $requestInstance->getRequestElement('mode'));
391 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_ID, $this->getNodeId());
393 // Add the session id if acquired
394 if ($this->getSessionId() != '') {
395 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_SESSION_ID, $this->getSessionId());
400 * Updates a given field with new value
402 * @param $fieldName Field to update
403 * @param $fieldValue New value to store
405 * @throws DatabaseUpdateSupportException If this class does not support database updates
406 * @todo Try to make this method more generic so we can move it in BaseFrameworkSystem
408 public function updateDatabaseField ($fieldName, $fieldValue) {
410 $this->partialStub('Unfinished!');
413 // Get a critieria instance
414 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
416 // Add search criteria
417 $searchInstance->addCriteria(UserDatabaseWrapper::DB_COLUMN_USERNAME, $this->getUserName());
418 $searchInstance->setLimit(1);
420 // Now get another criteria
421 $updateInstance = ObjectFactory::createObjectByConfiguredName('update_criteria_class');
423 // Add criteria entry which we shall update
424 $updateInstance->addCriteria($fieldName, $fieldValue);
426 // Add the search criteria for searching for the right entry
427 $updateInstance->setSearchInstance($searchInstance);
429 // Set wrapper class name
430 $updateInstance->setWrapperConfigEntry('user_db_wrapper_class');
432 // Remember the update in database result
433 $this->getResultInstance()->add2UpdateQueue($updateInstance);
437 * Announces this hub to the upper (bootstrap or list) hubs. After this is
438 * successfully done the given task is unregistered from the handler. This
439 * might look a bit overloaded here but the announcement phase isn't a
440 * simple "Hello there" message, it may later on also contain more
441 * informations like the object list.
443 * @param $taskInstance The task instance running this announcement
445 * @throws HubAlreadyAnnouncedException If this hub is already announced
446 * @todo Change the first if() block to check for a specific state
448 public function announceSelfToUpperNodes (Taskable $taskInstance) {
449 // Is this hub node announced?
450 if ($this->hubIsAnnounced === true) {
451 // Already announced!
452 throw new HubAlreadyAnnouncedException($this, self::EXCEPTION_HUB_ALREADY_ANNOUNCED);
456 $this->debugOutput('HUB-Announcement: START (taskInstance=' . $taskInstance->__toString(). ')');
458 // Get a helper instance
459 $helperInstance = ObjectFactory::createObjectByConfiguredName('hub_announcement_helper_class', array($this));
461 // Load the announcement descriptor
462 $helperInstance->loadDescriptorXml();
464 // Set some dummy configuration entries, e.g. node_status
465 $this->getConfigInstance()->setConfigEntry('node_status', $this->getStateInstance()->getStateName());
467 // Compile all variables
468 $helperInstance->getTemplateInstance()->compileConfigInVariables();
470 // "Publish" the descriptor by sending it to the bootstrap/list nodes
471 $helperInstance->sendPackage($this);
473 // Change the state, this should be the last line except debug output
474 $this->getStateInstance()->nodeAnnouncedToUpperHubs();
477 $this->debugOutput('HUB-Announcement: FINISHED');
481 * Does a self-connect attempt on the public IP address. This should make
482 * it sure, we are reachable from outside world. For this kind of package we
483 * don't need that overload we have in the announcement phase.
485 * @param $taskInstance The task instance running this announcement
488 public function doSelfConnection (Taskable $taskInstance) {
490 $this->debugOutput('HUB: Self Connection: START (taskInstance=' . $taskInstance->__toString(). ')');
492 // Get a helper instance
493 $helperInstance = ObjectFactory::createObjectByConfiguredName('hub_self_connect_helper_class', array($this));
495 // Load the descriptor (XML) file
496 $helperInstance->loadDescriptorXml();
498 // And send the package away
499 $helperInstance->sendPackage($this);
502 $this->debugOutput('HUB: Self Connection: FINISHED');
506 * Activates the hub by doing some final preparation and setting
507 * $hubIsActive to true
509 * @param $requestInstance A Requestable class
510 * @param $responseInstance A Responseable class
513 public function activateNode (Requestable $requestInstance, Responseable $responseInstance) {
514 // Checks wether a listener is still active and shuts it down if one
515 // is still listening.
516 if (($this->determineIfListenerIsActive()) && ($this->getIsActive())) {
517 // Shutdown them down before they can hurt anything
518 $this->shutdownListenerPool();
521 // Get the controller here
522 $controllerInstance = Registry::getRegistry()->getInstance('controller');
524 // Run all filters for the hub activation
525 $controllerInstance->executeActivationFilters($requestInstance, $responseInstance);
527 // ----------------------- Last step from here ------------------------
528 // Activate the hub. This is ALWAYS the last step in this method
529 $this->getStateInstance()->nodeIsActivated();
530 // ---------------------- Last step until here ------------------------
534 * Initializes the listener pool (class)
538 public function initializeListenerPool () {
540 $this->debugOutput('HUB: Initialize listener: START');
542 // Get a new pool instance
543 $this->setListenerPoolInstance(ObjectFactory::createObjectByConfiguredName('listener_pool_class', array($this)));
545 // Get an instance of the low-level listener
546 $listenerInstance = ObjectFactory::createObjectByConfiguredName('tcp_listener_class', array($this));
548 // Setup address and port
549 $listenerInstance->setListenAddressByConfiguration('node_listen_addr');
550 if ($this instanceof HubBootNode) {
551 // Bootstrap have different listening port
552 $listenerInstance->setListenPortByConfiguration('boot_node_tcp_listen_port');
554 // All other nodes use the default port
555 $listenerInstance->setListenPortByConfiguration('node_tcp_listen_port');
558 // Initialize the listener
559 $listenerInstance->initListener();
561 // Get a decorator class
562 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('hub_tcp_listener_class', array($listenerInstance));
564 // Add this listener to the pool
565 $this->getListenerPoolInstance()->addListener($decoratorInstance);
567 // Get a decorator class
568 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('peer_tcp_listener_class', array($listenerInstance));
570 // Add this listener to the pool
571 $this->getListenerPoolInstance()->addListener($decoratorInstance);
573 // Get an instance of the low-level listener
574 $listenerInstance = ObjectFactory::createObjectByConfiguredName('udp_listener_class', array($this));
576 // Setup address and port
577 $listenerInstance->setListenAddressByConfiguration('node_listen_addr');
578 if ($this instanceof HubBootNode) {
579 // Bootstrap have different listening port
580 $listenerInstance->setListenPortByConfiguration('boot_node_udp_listen_port');
582 // All other nodes use the default port
583 $listenerInstance->setListenPortByConfiguration('node_udp_listen_port');
586 // Initialize the listener
587 $listenerInstance->initListener();
589 // Get a decorator class
590 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('hub_udp_listener_class', array($listenerInstance));
592 // Add this listener to the pool
593 $this->getListenerPoolInstance()->addListener($decoratorInstance);
595 // Get a decorator class
596 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('peer_udp_listener_class', array($listenerInstance));
598 // Add this listener to the pool
599 $this->getListenerPoolInstance()->addListener($decoratorInstance);
602 $this->debugOutput('HUB: Initialize listener: FINISHED.');
606 * Restores a previously stored node list from database
610 public function bootstrapRestoreNodeList () {
612 $this->debugOutput('HUB: Restore node list: START');
614 // Get a wrapper instance
615 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('node_list_db_wrapper_class');
617 // Now get a search criteria instance
618 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
620 // Search for the node number zero which is hard-coded the default
621 // @TODO Add some criteria, e.g. if the node is active or so
622 //$searchInstance->addCriteria(NodeListDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
623 //$searchInstance->addCriteria(NodeListDatabaseWrapper::DB_COLUMN_NODE_TYPE, $this->getRequestInstance()->getRequestElement('mode'));
624 //$searchInstance->setLimit(1);
627 $resultInstance = $wrapperInstance->doSelectByCriteria($searchInstance);
630 if ($resultInstance->next()) {
631 $this->partialStub('Do something for restoring the list.');
633 //$this->debugOutput('HUB: ');
635 // No previously saved node list found!
636 $this->debugOutput('HUB: No previously saved node list found. This is fine.');
640 $this->debugOutput('HUB: Restore node list: FINISHED.');
644 * Getter for isActive attribute
646 * @return $isActive Wether the hub is active
648 public final function getIsActive () {
649 return $this->isActive;
653 * Enables (default) or disables isActive flag
655 * @param $isActive Wether the hub is active
658 public final function enableIsActive ($isActive = true) {
659 $this->isActive = (bool) $isActive;
663 * "Getter for address:port combination
665 * @param $handlerInstance A valid Networkable instance
666 * @return $addressPort A address:port combination for this node
668 public final function getAddressPort (Networkable $handlerInstance) {
669 // Construct config entry
670 $configEntry = 'node_' . $handlerInstance->getHandlerName() . '_listen_port';
673 $addressPort = $this->getConfigInstance()->detectServerAddress() . ':' . $this->getConfigInstance()->getConfigEntry($configEntry);