3 * A general hub node class
5 * @author Roland Haeder <webmaster@ship-simu.org>
7 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2012 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 * Whether this node is anncounced (KEEP ON false!)
55 private $hubIsAnnounced = false;
58 * Whether this hub is active (default: false)
60 private $isActive = false;
63 * Whether this node accepts announcements (default: false)
65 private $acceptAnnouncements = 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() {
88 * Get the state factory and create the initial state, we don't need
89 * the state instance here
91 NodeStateFactory::createNodeStateInstanceByName('init', $this);
95 * Generates a private key and hashes it (for speeding up things)
97 * @param $searchInstance An instance of a LocalSearchCriteria class
100 private function generatePrivateKeyAndHash (LocalSearchCriteria $searchInstance) {
101 // Get an RNG instance (Random Number Generator)
102 $rngInstance = ObjectFactory::createObjectByConfiguredName('rng_class');
104 // Generate a pseudo-random string
105 $randomString = $rngInstance->randomString(255) . ':' . $this->getBootIpPort() . ':' . $this->getRequestInstance()->getRequestElement('mode');
107 // Get a crypto instance
108 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
110 // Hash and encrypt the string so we become a node id (also documented as "hub id")
111 $this->setPrivateKey($cryptoInstance->encryptString($randomString));
112 $this->setPrivateKeyHash($cryptoInstance->hashString($this->getPrivateKey()));
114 // Get a wrapper instance
115 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('node_info_db_wrapper_class');
117 // Register the node id with our wrapper
118 $wrapperInstance->registerPrivateKey($this, $this->getRequestInstance(), $searchInstance);
121 $this->debugOutput('BOOTSTRAP: Created new private key with hash: ' . $this->getPrivateKeyHash() . '');
125 * Setter for query instance
127 * @param $connectorInstance Our new query instance
130 private final function setQueryConnectorInstance (Connectable $connectorInstance) {
131 $this->queryConnectorInstance = $connectorInstance;
135 * Getter for query instance
137 * @return $connectorInstance Our new query instance
139 public final function getQueryConnectorInstance () {
140 return $this->queryConnectorInstance;
144 * Setter for queue instance
146 * @param $connectorInstance Our new queue instance
149 private final function setQueueConnectorInstance (Connectable $connectorInstance) {
150 $this->queueConnectorInstance = $connectorInstance;
154 * Getter for queue instance
156 * @return $connectorInstance Our new queue instance
158 public final function getQueueConnectorInstance () {
159 return $this->queueConnectorInstance;
163 * Getter for boot IP/port combination
165 * @return $bootIpPort The IP/port combination of the boot node
167 protected final function getBootIpPort () {
168 return $this->bootIpPort;
172 * Checks whether the given IP address matches one of the bootstrapping nodes
174 * @param $remoteAddr IP address to checkout against our bootstrapping list
175 * @return $isFound Whether the IP is found
177 protected function ifAddressMatchesBootstrappingNodes ($remoteAddr) {
178 // By default nothing is found
181 // Run through all configured IPs
182 foreach (explode(BaseHubSystem::BOOTSTRAP_NODES_SEPARATOR, $this->getConfigInstance()->getConfigEntry('hub_bootstrap_nodes')) as $ipPort) {
183 // Split it up in IP/port
184 $ipPortArray = explode(':', $ipPort);
187 if ($ipPortArray[0] == $remoteAddr) {
191 // Remember the port number
192 $this->bootIpPort = $ipPort;
195 $this->debugOutput('BOOTSTRAP: ' . __FUNCTION__ . '[' . __LINE__ . ']: IP matches remote address ' . $ipPort . '.');
197 // Stop further searching
199 } elseif ($ipPortArray[0] == $this->getConfigInstance()->getConfigEntry('node_listen_addr')) {
200 // IP matches listen address. At this point we really don't care
201 // if we can really listen on that address
204 // Remember the port number
205 $this->bootIpPort = $ipPort;
208 $this->debugOutput('BOOTSTRAP: ' . __FUNCTION__ . '[' . __LINE__ . ']: IP matches listen address ' . $ipPort . '.');
210 // Stop further searching
220 * Outputs the console teaser. This should only be executed on startup or
221 * full restarts. This method generates some space around the teaser.
225 public function outputConsoleTeaser () {
226 // Get the app instance (for shortening our code)
227 $app = $this->getApplicationInstance();
230 $this->debugOutput(' ');
231 $this->debugOutput($app->getAppName() . ' v' . $app->getAppVersion() . ' - ' . $this->getRequestInstance()->getRequestElement('mode') . ' mode active');
232 $this->debugOutput('Copyright (c) 2007 - 2008 Roland Haeder, 2009 - 2012 Hub Developer Team');
233 $this->debugOutput(' ');
234 $this->debugOutput('This program comes with ABSOLUTELY NO WARRANTY; for details see docs/COPYING.');
235 $this->debugOutput('This is free software, and you are welcome to redistribute it under certain');
236 $this->debugOutput('conditions; see docs/COPYING for details.');
237 $this->debugOutput(' ');
241 * Generic method to acquire a hub-id. On first run this generates a new one
242 * based on many pseudo-random data. On any later run, unless the id
243 * got not removed from database, it will be restored from the database.
245 * @param $requestInstance A Requestable class
246 * @param $responseInstance A Responseable class
249 public function bootstrapAcquireNodeId (Requestable $requestInstance, Responseable $responseInstance) {
250 // Get a wrapper instance
251 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('node_info_db_wrapper_class');
253 // Now get a search criteria instance
254 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
256 // Search for the node number one which is hard-coded the default
257 $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
258 $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_TYPE, $this->getRequestInstance()->getRequestElement('mode'));
259 $searchInstance->setLimit(1);
262 $resultInstance = $wrapperInstance->doSelectByCriteria($searchInstance);
265 if ($resultInstance->next()) {
266 // Save the result instance in this class
267 $this->setResultInstance($resultInstance);
269 // Get the node id from result and set it
270 $this->setNodeId($this->getField(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_ID));
273 $this->debugOutput('BOOTSTRAP: Re-using found node-id: ' . $this->getNodeId() . '');
275 // Get an RNG instance (Random Number Generator)
276 $rngInstance = ObjectFactory::createObjectByConfiguredName('rng_class');
278 // Generate a pseudo-random string
279 $randomString = $rngInstance->randomString(255) . ':' . $this->getBootIpPort() . ':' . $this->getRequestInstance()->getRequestElement('mode');
281 // Get a crypto instance
282 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
284 // Hash and encrypt the string so we become a node id (also documented as "hub id")
285 $this->setNodeId($cryptoInstance->hashString($cryptoInstance->encryptString($randomString)));
287 // Register the node id with our wrapper
288 $wrapperInstance->registerNodeId($this, $this->getRequestInstance());
291 $this->debugOutput('BOOTSTRAP: Created new node-id: ' . $this->getNodeId() . '');
296 * Generates a session id which will be sent to the other hubs and peers
300 public function bootstrapGenerateSessionId () {
301 // Now get a search criteria instance
302 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
304 // Search for the node number one which is hard-coded the default
305 $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
306 $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_TYPE, $this->getRequestInstance()->getRequestElement('mode'));
307 $searchInstance->setLimit(1);
309 // Get an RNG instance
310 $rngInstance = ObjectFactory::createObjectByConfiguredName('rng_class');
312 // Generate a pseudo-random string
313 $randomString = $rngInstance->randomString(255) . ':' . $this->getBootIpPort() . ':' . $this->getRequestInstance()->getRequestElement('mode');
315 // Get a crypto instance
316 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
318 // Hash and encrypt the string so we become a "node id" aka Hub-Id
319 $this->setSessionId($cryptoInstance->hashString($cryptoInstance->encryptString($randomString)));
321 // Get a wrapper instance
322 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('node_info_db_wrapper_class');
324 // Register the node id with our wrapper
325 $wrapperInstance->registerSessionId($this, $this->getRequestInstance(), $searchInstance);
328 $this->debugOutput('BOOTSTRAP: Created new session-id: ' . $this->getSessionId() . '');
330 // Change the state because the node has auired a hub id
331 $this->getStateInstance()->nodeGeneratedSessionId();
335 * Generate a private key for en-/decryption
339 public function bootstrapGeneratePrivateKey () {
340 // Get a wrapper instance
341 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('node_info_db_wrapper_class');
343 // Now get a search criteria instance
344 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
346 // Search for the node number one which is hard-coded the default
347 $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
348 $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_TYPE, $this->getRequestInstance()->getRequestElement('mode'));
349 $searchInstance->setLimit(1);
352 $resultInstance = $wrapperInstance->doSelectByCriteria($searchInstance);
355 if ($resultInstance->next()) {
356 // Save the result instance in this class
357 $this->setResultInstance($resultInstance);
359 // Is the element set?
360 if (is_null($this->getField(NodeInformationDatabaseWrapper::DB_COLUMN_PRIVATE_KEY))) {
362 * Auto-generate the private key for e.g. out-dated database
363 * "tables". This allows a smooth update for the underlaying
366 $this->generatePrivateKeyAndHash($searchInstance);
368 // Get the node id from result and set it
369 $this->setPrivateKey($this->getField(NodeInformationDatabaseWrapper::DB_COLUMN_PRIVATE_KEY));
370 $this->setPrivateKeyHash($this->getField(NodeInformationDatabaseWrapper::DB_COLUMN_PRIVATE_KEY_HASH));
373 $this->debugOutput('BOOTSTRAP: Re-using found private key hash: ' . $this->getPrivateKeyHash() . '');
377 * Generate it in a private method (no confusion with 'private
378 * method access' and 'private key' here! ;-)).
380 $this->generatePrivateKeyAndHash($searchInstance);
385 * Initializes queues which every node needs
389 protected function initGenericQueues () {
391 $this->debugOutput('BOOTSTRAP: Initialize queues: START');
393 // Set the query connector instance
394 $this->setQueryConnectorInstance(ObjectFactory::createObjectByConfiguredName('query_connector_class', array($this)));
397 $this->getQueryConnectorInstance()->doTestQuery();
399 // Set the queue connector instance
400 $this->setQueueConnectorInstance(ObjectFactory::createObjectByConfiguredName('queue_connector_class', array($this)));
403 $this->getQueueConnectorInstance()->doTestQueue();
406 $this->debugOutput('BOOTSTRAP: Initialize queues: FINISHED');
410 * Adds hub data elements to a given dataset instance
412 * @param $criteriaInstance An instance of a storeable criteria
413 * @param $requestInstance An instance of a Requestable class
416 public function addElementsToDataSet (StoreableCriteria $criteriaInstance, Requestable $requestInstance) {
417 // Add node number and type
418 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
419 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_TYPE, $requestInstance->getRequestElement('mode'));
422 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_ID, $this->getNodeId());
424 // Add the session id if acquired
425 if ($this->getSessionId() != '') {
426 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_SESSION_ID, $this->getSessionId());
429 // Add the private key if acquired
430 if ($this->getPrivateKey() != '') {
431 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_PRIVATE_KEY, $this->getPrivateKey());
432 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_PRIVATE_KEY_HASH, $this->getPrivateKeyHash());
437 * Updates a given field with new value
439 * @param $fieldName Field to update
440 * @param $fieldValue New value to store
442 * @throws DatabaseUpdateSupportException If this class does not support database updates
443 * @todo Try to make this method more generic so we can move it in BaseFrameworkSystem
445 public function updateDatabaseField ($fieldName, $fieldValue) {
447 $this->partialStub('Unfinished!');
450 // Get a critieria instance
451 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
453 // Add search criteria
454 $searchInstance->addCriteria(UserDatabaseWrapper::DB_COLUMN_USERNAME, $this->getUserName());
455 $searchInstance->setLimit(1);
457 // Now get another criteria
458 $updateInstance = ObjectFactory::createObjectByConfiguredName('update_criteria_class');
460 // Add criteria entry which we shall update
461 $updateInstance->addCriteria($fieldName, $fieldValue);
463 // Add the search criteria for searching for the right entry
464 $updateInstance->setSearchInstance($searchInstance);
466 // Set wrapper class name
467 $updateInstance->setWrapperConfigEntry('user_db_wrapper_class');
469 // Remember the update in database result
470 $this->getResultInstance()->add2UpdateQueue($updateInstance);
474 * Announces this hub to the upper (bootstrap or list) hubs. After this is
475 * successfully done the given task is unregistered from the handler. This
476 * might look a bit overloaded here but the announcement phase isn't a
477 * simple "Hello there" message, it may later on also contain more
478 * informations like the object list.
480 * @param $taskInstance The task instance running this announcement
482 * @throws HubAlreadyAnnouncedException If this hub is already announced
483 * @todo Change the first if() block to check for a specific state
485 public function announceSelfToUpperNodes (Taskable $taskInstance) {
486 // Is this hub node announced?
487 if ($this->hubIsAnnounced === true) {
488 // Already announced!
489 throw new HubAlreadyAnnouncedException($this, self::EXCEPTION_HUB_ALREADY_ANNOUNCED);
493 $this->debugOutput('HUB-Announcement: START (taskInstance=' . $taskInstance->__toString(). ')');
495 // Get a helper instance
496 $helperInstance = ObjectFactory::createObjectByConfiguredName('hub_announcement_helper_class');
498 // Load the announcement descriptor
499 $helperInstance->loadDescriptorXml();
501 // Compile all variables
502 $helperInstance->getTemplateInstance()->compileConfigInVariables();
504 // "Publish" the descriptor by sending it to the bootstrap/list nodes
505 $helperInstance->sendPackage($this);
507 // Change the state, this should be the last line except debug output
508 $this->getStateInstance()->nodeAnnouncedToUpperHubs();
511 $this->debugOutput('HUB-Announcement: FINISHED');
515 * Does a self-connect attempt on the public IP address. This should make
516 * it sure, we are reachable from outside world. For this kind of package we
517 * don't need that overload we have in the announcement phase.
519 * @param $taskInstance The task instance running this announcement
522 public function doSelfConnection (Taskable $taskInstance) {
524 $this->debugOutput('HUB: Self Connection: START (taskInstance=' . $taskInstance->__toString(). ')');
526 // Get a helper instance
527 $helperInstance = ObjectFactory::createObjectByConfiguredName('hub_self_connect_helper_class', array($this));
529 // Load the descriptor (XML) file
530 $helperInstance->loadDescriptorXml();
532 // Compile all variables
533 $helperInstance->getTemplateInstance()->compileConfigInVariables();
535 // And send the package away
536 $helperInstance->sendPackage($this);
539 $this->debugOutput('HUB: Self Connection: FINISHED');
543 * Activates the hub by doing some final preparation and setting
544 * $hubIsActive to true
546 * @param $requestInstance A Requestable class
547 * @param $responseInstance A Responseable class
550 public function activateNode (Requestable $requestInstance, Responseable $responseInstance) {
551 // Checks whether a listener is still active and shuts it down if one
552 // is still listening.
553 if (($this->determineIfListenerIsActive()) && ($this->isNodeActive())) {
554 // Shutdown them down before they can hurt anything
555 $this->shutdownListenerPool();
558 // Get the controller here
559 $controllerInstance = Registry::getRegistry()->getInstance('controller');
561 // Run all filters for the hub activation
562 $controllerInstance->executeActivationFilters($requestInstance, $responseInstance);
564 // ----------------------- Last step from here ------------------------
565 // Activate the hub. This is ALWAYS the last step in this method
566 $this->getStateInstance()->nodeIsActivated();
567 // ---------------------- Last step until here ------------------------
571 * Initializes the listener pool (class)
575 public function initializeListenerPool () {
577 $this->debugOutput('HUB: Initialize listener: START');
579 // Get a new pool instance
580 $this->setListenerPoolInstance(ObjectFactory::createObjectByConfiguredName('listener_pool_class', array($this)));
582 // Get an instance of the low-level listener
583 $listenerInstance = ObjectFactory::createObjectByConfiguredName('tcp_listener_class', array($this));
585 // Setup address and port
586 $listenerInstance->setListenAddressByConfiguration('node_listen_addr');
589 * All nodes can now use the same configuration entry because it can be
590 * customized in config-local.php.
592 $listenerInstance->setListenPortByConfiguration('node_tcp_listen_port');
594 // Initialize the listener
595 $listenerInstance->initListener();
597 // Get a decorator class
598 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('hub_tcp_listener_class', array($listenerInstance));
600 // Add this listener to the pool
601 $this->getListenerPoolInstance()->addListener($decoratorInstance);
603 // Get a decorator class
604 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('client_tcp_listener_class', array($listenerInstance));
606 // Add this listener to the pool
607 $this->getListenerPoolInstance()->addListener($decoratorInstance);
609 // Get an instance of the low-level listener
610 $listenerInstance = ObjectFactory::createObjectByConfiguredName('udp_listener_class', array($this));
612 // Setup address and port
613 $listenerInstance->setListenAddressByConfiguration('node_listen_addr');
616 * All nodes can now use the same configuration entry because it can be
617 * customized in config-local.php.
619 $listenerInstance->setListenPortByConfiguration('node_udp_listen_port');
621 // Initialize the listener
622 $listenerInstance->initListener();
624 // Get a decorator class
625 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('hub_udp_listener_class', array($listenerInstance));
627 // Add this listener to the pool
628 $this->getListenerPoolInstance()->addListener($decoratorInstance);
630 // Get a decorator class
631 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('client_udp_listener_class', array($listenerInstance));
633 // Add this listener to the pool
634 $this->getListenerPoolInstance()->addListener($decoratorInstance);
637 $this->debugOutput('HUB: Initialize listener: FINISHED.');
641 * Restores a previously stored node list from database
645 public function bootstrapRestoreNodeList () {
647 $this->debugOutput('HUB: Restore node list: START');
649 // Get a wrapper instance
650 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('node_list_db_wrapper_class');
652 // Now get a search criteria instance
653 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
655 // Search for the node number zero which is hard-coded the default
656 // @TODO Add some criteria, e.g. if the node is active or so
657 //$searchInstance->addCriteria(NodeListDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
658 //$searchInstance->addCriteria(NodeListDatabaseWrapper::DB_COLUMN_NODE_TYPE, $this->getRequestInstance()->getRequestElement('mode'));
659 //$searchInstance->setLimit(1);
662 $resultInstance = $wrapperInstance->doSelectByCriteria($searchInstance);
665 if ($resultInstance->next()) {
666 $this->partialStub('Do something for restoring the list.');
668 //$this->debugOutput('HUB: ');
670 // No previously saved node list found!
671 $this->debugOutput('HUB: No previously saved node list found. This is fine.');
675 $this->debugOutput('HUB: Restore node list: FINISHED.');
679 * Getter for isActive attribute
681 * @return $isActive Whether the hub is active
683 public final function isNodeActive () {
684 return $this->isActive;
688 * Enables (default) or disables isActive flag
690 * @param $isActive Whether the hub is active
693 public final function enableIsActive ($isActive = true) {
694 $this->isActive = (bool) $isActive;
698 * Checks whether this node accepts announcements
700 * @return $acceptAnnouncements Whether this node accepts announcements
702 public final function isAcceptingAnnouncements () {
703 // Check it (this node must be active and not shutdown!)
704 $acceptAnnouncements = (($this->acceptAnnouncements === true) && ($this->isNodeActive()));
707 return $acceptAnnouncements;
711 * Enables whether this node accepts announcements
713 * @param $acceptAnnouncements Whether this node accepts announcements (default: true)
716 protected final function enableAcceptingAnnouncements ($acceptAnnouncements = true) {
717 $this->acceptAnnouncements = $acceptAnnouncements;
722 * "Getter for address:port combination
724 * @param $handlerInstance A valid Networkable instance
725 * @return $addressPort A address:port combination for this node
727 public final function getAddressPort (Networkable $handlerInstance) {
728 // Construct config entry
729 $configEntry = 'node_' . $handlerInstance->getHandlerName() . '_listen_port';
732 $addressPort = $this->getConfigInstance()->detectServerAddress() . ':' . $this->getConfigInstance()->getConfigEntry($configEntry);
739 * Updates/refreshes node data (e.g. state).
742 * @todo Find more to do here
744 public function updateNodeData () {
745 // Set some dummy configuration entries, e.g. node_status
746 $this->getConfigInstance()->setConfigEntry('node_status', $this->getStateInstance()->getStateName());