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 * "Getter" for a printable state name
201 * @return $stateName Name of the node's state in a printable format
203 public final function getPrintableState () {
207 // Get the state instance
208 $stateInstance = $this->getStateInstance();
210 // Is it an instance of Stateable?
211 if ($stateInstance instanceof Stateable) {
212 // Then use that state name
213 $stateName = $stateInstance->getStateName();
221 * Checks wether the given IP address matches one of the bootstrapping nodes
223 * @param $remoteAddr IP address to checkout against our bootstrapping list
224 * @return $isFound Wether the IP is found
226 protected function ifAddressMatchesBootstrappingNodes ($remoteAddr) {
227 // By default nothing is found
230 // Run through all configured IPs
231 foreach (explode(',', $this->getConfigInstance()->getConfigEntry('hub_bootstrap_nodes')) as $ipPort) {
232 // Split it up in IP/port
233 $ipPortArray = explode(':', $ipPort);
236 if ($ipPortArray[0] == $remoteAddr) {
240 // Remember the port number
241 $this->bootIpPort = $ipPort;
244 $this->debugOutput('BOOTSTRAP: ' . __FUNCTION__ . '[' . __LINE__ . ']: IP matches remote address ' . $ipPort . '.');
246 // Stop further searching
248 } elseif ($ipPortArray[0] == $this->getConfigInstance()->getConfigEntry('node_listen_addr')) {
249 // IP matches listen address. At this point we really don't care
250 // if we can really listen on that address
253 // Remember the port number
254 $this->bootIpPort = $ipPort;
257 $this->debugOutput('BOOTSTRAP: ' . __FUNCTION__ . '[' . __LINE__ . ']: IP matches listen address ' . $ipPort . '.');
259 // Stop further searching
269 * Outputs the console teaser. This should only be executed on startup or
270 * full restarts. This method generates some space around the teaser.
274 public function outputConsoleTeaser () {
275 // Get the app instance (for shortening our code)
276 $app = $this->getApplicationInstance();
279 $this->debugOutput(' ');
280 $this->debugOutput($app->getAppName() . ' v' . $app->getAppVersion() . ' - ' . $this->getRequestInstance()->getRequestElement('mode') . ' mode active');
281 $this->debugOutput('Copyright (c) 2007 - 2008 Roland Haeder, 2009 - 2011 Hub Developer Team');
282 $this->debugOutput(' ');
283 $this->debugOutput('This program comes with ABSOLUTELY NO WARRANTY; for details see docs/COPYING.');
284 $this->debugOutput('This is free software, and you are welcome to redistribute it under certain');
285 $this->debugOutput('conditions; see docs/COPYING for details.');
286 $this->debugOutput(' ');
290 * Generic method to acquire a hub-id. On first run this generates a new one
291 * based on many pseudo-random data. On any later run, unless the id
292 * got not removed from database, it will be restored from the database.
294 * @param $requestInstance A Requestable class
295 * @param $responseInstance A Responseable class
298 public function bootstrapAcquireNodeId (Requestable $requestInstance, Responseable $responseInstance) {
299 // Get a wrapper instance
300 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('node_info_db_wrapper_class');
302 // Now get a search criteria instance
303 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
305 // Search for the node number zero which is hard-coded the default
306 $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
307 $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_TYPE, $this->getRequestInstance()->getRequestElement('mode'));
308 $searchInstance->setLimit(1);
311 $resultInstance = $wrapperInstance->doSelectByCriteria($searchInstance);
314 if ($resultInstance->next()) {
315 // Save the result instance in this class
316 $this->setResultInstance($resultInstance);
318 // Get the node id from result and set it
319 $this->setNodeId($this->getField(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_ID));
322 $this->debugOutput('BOOTSTRAP: Re-using found node-id: ' . $this->getNodeId() . '');
324 // Get an RNG instance (Random Number Generator)
325 $rngInstance = ObjectFactory::createObjectByConfiguredName('rng_class');
327 // Generate a pseudo-random string
328 $randomString = $rngInstance->randomString(255) . ':' . $this->getBootIpPort() . ':' . $this->getRequestInstance()->getRequestElement('mode');
330 // Get a crypto instance
331 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
333 // Hash and encrypt the string so we become a node id (also documented as "hub id")
334 $this->setNodeId($cryptoInstance->hashString($cryptoInstance->encryptString($randomString)));
336 // Register the node id with our wrapper
337 $wrapperInstance->registerNodeId($this, $this->getRequestInstance());
340 $this->debugOutput('BOOTSTRAP: Created new node-id: ' . $this->getNodeId() . '');
345 * Generates a session id which will be sent to the other hubs and peers
349 public function bootstrapGenerateSessionId () {
350 // Get an RNG instance
351 $rngInstance = ObjectFactory::createObjectByConfiguredName('rng_class');
353 // Generate a pseudo-random string
354 $randomString = $rngInstance->randomString(255) . ':' . $this->getBootIpPort() . ':' . $this->getRequestInstance()->getRequestElement('mode');
356 // Get a crypto instance
357 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
359 // Hash and encrypt the string so we become a "node id" aka Hub-Id
360 $this->setSessionId($cryptoInstance->hashString($cryptoInstance->encryptString($randomString)));
362 // Get a wrapper instance
363 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('node_info_db_wrapper_class');
365 // Register the node id with our wrapper
366 $wrapperInstance->registerSessionId($this, $this->getRequestInstance());
369 $this->debugOutput('BOOTSTRAP: Created new session-id: ' . $this->getSessionId() . '');
371 // Change the state because the node has auired a hub id
372 $this->getStateInstance()->nodeGeneratedSessionId();
376 * Initializes queues which every node needs
380 protected function initGenericQueues () {
382 $this->debugOutput('BOOTSTRAP: Initialize queues: START');
384 // Set the query connector instance
385 $this->setQueryConnectorInstance(ObjectFactory::createObjectByConfiguredName('query_connector_class', array($this)));
388 $this->getQueryConnectorInstance()->doTestQuery();
390 // Set the queue connector instance
391 $this->setQueueConnectorInstance(ObjectFactory::createObjectByConfiguredName('queue_connector_class', array($this)));
394 $this->getQueueConnectorInstance()->doTestQueue();
397 $this->debugOutput('BOOTSTRAP: Initialize queues: FINISHED');
401 * Adds hub data elements to a given dataset instance
403 * @param $criteriaInstance An instance of a storeable criteria
404 * @param $requestInstance An instance of a Requestable class
407 public function addElementsToDataSet (StoreableCriteria $criteriaInstance, Requestable $requestInstance) {
408 // Add node number and type
409 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
410 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_TYPE, $requestInstance->getRequestElement('mode'));
413 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_ID, $this->getNodeId());
415 // Add the session id if acquired
416 if ($this->getSessionId() != '') {
417 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_SESSION_ID, $this->getSessionId());
422 * Updates a given field with new value
424 * @param $fieldName Field to update
425 * @param $fieldValue New value to store
427 * @throws DatabaseUpdateSupportException If this class does not support database updates
428 * @todo Try to make this method more generic so we can move it in BaseFrameworkSystem
430 public function updateDatabaseField ($fieldName, $fieldValue) {
432 $this->partialStub('Unfinished!');
435 // Get a critieria instance
436 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
438 // Add search criteria
439 $searchInstance->addCriteria(UserDatabaseWrapper::DB_COLUMN_USERNAME, $this->getUserName());
440 $searchInstance->setLimit(1);
442 // Now get another criteria
443 $updateInstance = ObjectFactory::createObjectByConfiguredName('update_criteria_class');
445 // Add criteria entry which we shall update
446 $updateInstance->addCriteria($fieldName, $fieldValue);
448 // Add the search criteria for searching for the right entry
449 $updateInstance->setSearchInstance($searchInstance);
451 // Set wrapper class name
452 $updateInstance->setWrapperConfigEntry('user_db_wrapper_class');
454 // Remember the update in database result
455 $this->getResultInstance()->add2UpdateQueue($updateInstance);
459 * Announces this hub to the upper (bootstrap or list) hubs. After this is
460 * successfully done the given task is unregistered from the handler. This
461 * might look a bit overloaded here but the announcement phase isn't a
462 * simple "Hello there" message, it may later on also contain more
463 * informations like the object list.
465 * @param $taskInstance The task instance running this announcement
467 * @throws HubAlreadyAnnouncedException If this hub is already announced
468 * @todo Change the first if() block to check for a specific state
470 public function announceSelfToUpperNodes (Taskable $taskInstance) {
471 // Is this hub node announced?
472 if ($this->hubIsAnnounced === true) {
473 // Already announced!
474 throw new HubAlreadyAnnouncedException($this, self::EXCEPTION_HUB_ALREADY_ANNOUNCED);
478 $this->debugOutput('HUB: Announcement: START (taskInstance=' . $taskInstance->__toString(). ')');
480 // Get a helper instance
481 $helperInstance = ObjectFactory::createObjectByConfiguredName('hub_announcement_helper_class', array($this));
483 // Load the announcement descriptor
484 $helperInstance->loadDescriptorXml();
486 // Set some dummy configuration entries, e.g. node_status
487 $this->getConfigInstance()->setConfigEntry('node_status', $this->getStateInstance()->getStateName());
489 // Compile all variables
490 $helperInstance->getTemplateInstance()->compileConfigInVariables();
492 // "Publish" the descriptor by sending it to the bootstrap/list nodes
493 $helperInstance->sendPackage();
495 // Change the state, this should be the last line except debug output
496 $this->getStateInstance()->nodeAnnouncedToUpperHubs();
499 $this->debugOutput('HUB: Announcement: FINISHED');
503 * Does a self-connect attempt on the public IP address. This should make
504 * it sure, we are reachable from outside world. For this kind of package we
505 * don't need that overload we have in the announcement phase.
507 * @param $taskInstance The task instance running this announcement
510 public function doSelfConnection (Taskable $taskInstance) {
512 $this->debugOutput('HUB: Self Connection: START (taskInstance=' . $taskInstance->__toString(). ')');
514 // Get a helper instance
515 $helperInstance = ObjectFactory::createObjectByConfiguredName('hub_self_connect_helper_class', array($this));
517 // Load the descriptor (XML) file
518 $helperInstance->loadDescriptorXml();
520 // And send the package away
521 $helperInstance->sendPackage();
524 $this->debugOutput('HUB: Self Connection: FINISHED');
528 * Activates the hub by doing some final preparation and setting
529 * $hubIsActive to true
531 * @param $requestInstance A Requestable class
532 * @param $responseInstance A Responseable class
535 public function activateNode (Requestable $requestInstance, Responseable $responseInstance) {
536 // Checks wether a listener is still active and shuts it down if one
537 // is still listening.
538 if (($this->determineIfListenerIsActive()) && ($this->getIsActive())) {
539 // Shutdown them down before they can hurt anything
540 $this->shutdownListenerPool();
543 // Get the controller here
544 $controllerInstance = Registry::getRegistry()->getInstance('controller');
546 // Run all filters for the hub activation
547 $controllerInstance->executeActivationFilters($requestInstance, $responseInstance);
549 // ----------------------- Last step from here ------------------------
550 // Activate the hub. This is ALWAYS the last step in this method
551 $this->getStateInstance()->nodeIsActivated();
552 // ---------------------- Last step until here ------------------------
556 * Initializes the listener pool (class)
560 public function initializeListenerPool () {
562 $this->debugOutput('HUB: Initialize listener: START');
564 // Get a new pool instance
565 $this->setListenerPoolInstance(ObjectFactory::createObjectByConfiguredName('listener_pool_class', array($this)));
567 // Get an instance of the low-level listener
568 $listenerInstance = ObjectFactory::createObjectByConfiguredName('tcp_listener_class', array($this));
570 // Setup address and port
571 $listenerInstance->setListenAddressByConfiguration('node_listen_addr');
572 if ($this instanceof HubBootNode) {
573 // Bootstrap have different listening port
574 $listenerInstance->setListenPortByConfiguration('boot_node_tcp_listen_port');
576 // All other nodes use the default port
577 $listenerInstance->setListenPortByConfiguration('node_tcp_listen_port');
580 // Initialize the listener
581 $listenerInstance->initListener();
583 // Get a decorator class
584 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('hub_tcp_listener_class', array($listenerInstance));
586 // Add this listener to the pool
587 $this->getListenerPoolInstance()->addListener($decoratorInstance);
589 // Get a decorator class
590 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('peer_tcp_listener_class', array($listenerInstance));
592 // Add this listener to the pool
593 $this->getListenerPoolInstance()->addListener($decoratorInstance);
595 // Get an instance of the low-level listener
596 $listenerInstance = ObjectFactory::createObjectByConfiguredName('udp_listener_class', array($this));
598 // Setup address and port
599 $listenerInstance->setListenAddressByConfiguration('node_listen_addr');
600 if ($this instanceof HubBootNode) {
601 // Bootstrap have different listening port
602 $listenerInstance->setListenPortByConfiguration('boot_node_udp_listen_port');
604 // All other nodes use the default port
605 $listenerInstance->setListenPortByConfiguration('node_udp_listen_port');
608 // Initialize the listener
609 $listenerInstance->initListener();
611 // Get a decorator class
612 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('hub_udp_listener_class', array($listenerInstance));
614 // Add this listener to the pool
615 $this->getListenerPoolInstance()->addListener($decoratorInstance);
617 // Get a decorator class
618 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('peer_udp_listener_class', array($listenerInstance));
620 // Add this listener to the pool
621 $this->getListenerPoolInstance()->addListener($decoratorInstance);
624 $this->debugOutput('HUB: Initialize listener: FINISHED.');
628 * Restores a previously stored node list from database
632 public function bootstrapRestoreNodeList () {
634 $this->debugOutput('HUB: Restore node list: START');
636 // Get a wrapper instance
637 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('node_list_db_wrapper_class');
639 // Now get a search criteria instance
640 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
642 // Search for the node number zero which is hard-coded the default
643 // @TODO Add some criteria, e.g. if the node is active or so
644 //$searchInstance->addCriteria(NodeListDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
645 //$searchInstance->addCriteria(NodeListDatabaseWrapper::DB_COLUMN_NODE_TYPE, $this->getRequestInstance()->getRequestElement('mode'));
646 //$searchInstance->setLimit(1);
649 $resultInstance = $wrapperInstance->doSelectByCriteria($searchInstance);
652 if ($resultInstance->next()) {
653 $this->partialStub('Do something for restoring the list.');
655 //$this->debugOutput('HUB: ');
657 // No previously saved node list found!
658 $this->debugOutput('HUB: No previously saved node list found. This is fine.');
662 $this->debugOutput('HUB: Restore node list: FINISHED.');
666 * Getter for isActive attribute
668 * @return $isActive Wether the hub is active
670 public final function getIsActive () {
671 return $this->isActive;
675 * Enables (default) or disables isActive flag
677 * @param $isActive Wether the hub is active
680 public final function enableIsActive ($isActive = true) {
681 $this->isActive = (bool) $isActive;
685 * "Getter for address:port combination
687 * @param $handlerInstance A valid Networkable instance
688 * @return $addressPort A address:port combination for this node
690 public final function getAddressPort (Networkable $handlerInstance) {
691 // Construct config entry
692 $configEntry = 'node_' . $handlerInstance->getHandlerName() . '_listen_port';
695 $addressPort = $this->getConfigInstance()->detectServerAddress() . ':' . $this->getConfigInstance()->getConfigEntry($configEntry);