3 * A general hub node class
5 * @author Roland Haeder <webmaster@ship-simu.org>
7 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009, 2010 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 $connectorInstance = null;
39 * Listener pool instance
41 private $listenerPoolInstance = null;
44 * Wether this node is anncounced (KEEP ON false!)
47 private $hubIsAnnounced = false;
52 private $stateInstance = null;
55 * Wether this hub is active
57 private $isActive = false;
60 * List instance of all hubs
62 private $hubsInstance = 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 list for connected hubs
75 $this->hubsInstance = ObjectFactory::createObjectByConfiguredName('hub_list_class');
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 StateFactory::createStateInstanceByName('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 state instance
135 * @param $stateInstance Node's current state instance
138 public final function setStateInstance (Stateable $stateInstance) {
139 $this->stateInstance = $stateInstance;
143 * Getter for state instance
145 * @return $stateInstance Node's current state instance
147 public final function getStateInstance () {
148 return $this->stateInstance;
152 * Setter for session id
154 * @param $sessionId Our new session id
157 private final function setSessionId ($sessionId) {
158 $this->getConfigInstance()->setConfigEntry('session_id', (string) $sessionId);
162 * Getter for session id
164 * @return $sessionId Current session id
166 public final function getSessionId () {
167 return $this->getConfigInstance()->getConfigEntry('session_id');
171 * Setter for query instance
173 * @param $connectorInstance Our new query instance
176 private final function setQueryConnectorInstance (Connectable $connectorInstance) {
177 $this->connectorInstance = $connectorInstance;
181 * Getter for query instance
183 * @return $connectorInstance Our new query instance
185 public final function getQueryConnectorInstance () {
186 return $this->connectorInstance;
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 public final function getPrintableState () {
205 // Get the state instance
206 $stateInstance = $this->getStateInstance();
208 // Is it an instance of Stateable?
209 if ($stateInstance instanceof Stateable) {
210 // Then use that state name
211 $stateName = $stateInstance->getStateName();
219 * Checks wether the given IP address matches one of the bootstrapping nodes
221 * @param $remoteAddr IP address to checkout against our bootstrapping list
222 * @return $isFound Wether the IP is found
224 protected function ifAddressMatchesBootstrappingNodes ($remoteAddr) {
225 // By default nothing is found
228 // Run through all configured IPs
229 foreach (explode(',', $this->getConfigInstance()->getConfigEntry('hub_bootstrap_nodes')) as $ipPort) {
230 // Split it up in IP/port
231 $ipPortArray = explode(':', $ipPort);
234 if ($ipPortArray[0] == $remoteAddr) {
238 // Remember the port number
239 $this->bootIpPort = $ipPort;
242 $this->debugOutput('BOOTSTRAP: ' . __FUNCTION__ . '[' . __LINE__ . ']: IP matches remote address ' . $ipPort . '.');
244 // Stop further searching
246 } elseif ($ipPortArray[0] == $this->getConfigInstance()->getConfigEntry('node_listen_addr')) {
247 // IP matches listen address. At this point we really don't care
248 // if we can also listen on that address!
251 // Remember the port number
252 $this->bootIpPort = $ipPort;
255 $this->debugOutput('BOOTSTRAP: ' . __FUNCTION__ . '[' . __LINE__ . ']: IP matches listen address ' . $ipPort . '.');
257 // Stop further searching
267 * Outputs the console teaser. This should only be executed on startup or
268 * full restarts. This method generates some space around the teaser.
272 public function outputConsoleTeaser () {
273 // Get the app instance (for shortening our code)
274 $app = $this->getApplicationInstance();
277 $this->debugOutput(' ');
278 $this->debugOutput($app->getAppName() . ' v' . $app->getAppVersion() . ' - ' . $this->getRequestInstance()->getRequestElement('mode') . ' mode active');
279 $this->debugOutput('Copyright (c) 2007 - 2008 Roland Haeder, 2009, 2010 Hub Developer Team');
280 $this->debugOutput(' ');
281 $this->debugOutput('This program comes with ABSOLUTELY NO WARRANTY; for details see docs/COPYING.');
282 $this->debugOutput('This is free software, and you are welcome to redistribute it under certain');
283 $this->debugOutput('conditions; see docs/COPYING for details.');
284 $this->debugOutput(' ');
288 * Generic method to acquire a hub-id. On first run this generates a new one
289 * based on many pseudo-random data. On any later run, unless the id
290 * got not removed from database, it will be restored from the database.
292 * @param $requestInstance A Requestable class
293 * @param $responseInstance A Responseable class
296 public function bootstrapAcquireHubId (Requestable $requestInstance, Responseable $responseInstance) {
297 // Get a wrapper instance
298 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('node_info_db_wrapper_class');
300 // Now get a search criteria instance
301 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
303 // Search for the node number zero which is hard-coded the default
304 $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
305 $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_TYPE, $this->getRequestInstance()->getRequestElement('mode'));
306 $searchInstance->setLimit(1);
309 $resultInstance = $wrapperInstance->doSelectByCriteria($searchInstance);
312 if ($resultInstance->next()) {
313 // Save the result instance in this class
314 $this->setResultInstance($resultInstance);
316 // Get the node id from result and set it
317 $this->setNodeId($this->getField(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_ID));
320 $this->debugOutput('BOOTSTRAP: Re-using found node-id: ' . $this->getNodeId() . '');
322 // Get an RNG instance (Random Number Generator)
323 $rngInstance = ObjectFactory::createObjectByConfiguredName('rng_class');
325 // Generate a pseudo-random string
326 $randomString = $rngInstance->randomString(255) . ':' . $this->getBootIpPort() . ':' . $this->getRequestInstance()->getRequestElement('mode');
328 // Get a crypto instance
329 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
331 // Hash and encrypt the string so we become a "node id" aka Hub-Id
332 $this->setNodeId($cryptoInstance->hashString($cryptoInstance->encryptString($randomString)));
334 // Register the node id with our wrapper
335 $wrapperInstance->registerNodeId($this, $this->getRequestInstance());
338 $this->debugOutput('BOOTSTRAP: Created new node-id: ' . $this->getNodeId() . '');
343 * Generates a session id which will be sent to the other hubs and clients
347 public function bootstrapGenerateSessionId () {
348 // Get an RNG instance
349 $rngInstance = ObjectFactory::createObjectByConfiguredName('rng_class');
351 // Generate a pseudo-random string
352 $randomString = $rngInstance->randomString(255) . ':' . $this->getBootIpPort() . ':' . $this->getRequestInstance()->getRequestElement('mode');
354 // Get a crypto instance
355 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
357 // Hash and encrypt the string so we become a "node id" aka Hub-Id
358 $this->setSessionId($cryptoInstance->hashString($cryptoInstance->encryptString($randomString)));
360 // Get a wrapper instance
361 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('node_info_db_wrapper_class');
363 // Register the node id with our wrapper
364 $wrapperInstance->registerSessionId($this, $this->getRequestInstance());
367 $this->debugOutput('BOOTSTRAP: Created new session-id: ' . $this->getSessionId() . '');
369 // Change the state because the node has auired a hub id
370 $this->getStateInstance()->nodeGeneratedSessionId();
374 * Initializes queues which every node needs
378 protected function initGenericQueues () {
380 $this->debugOutput('BOOTSTRAP: Initialize queues: START');
382 // Set the query connector instance
383 $this->setQueryConnectorInstance(ObjectFactory::createObjectByConfiguredName('query_connector_class', array($this)));
386 $this->getQueryConnectorInstance()->doTestQuery();
389 $this->debugOutput('BOOTSTRAP: Initialize queues: FINISHED');
393 * Adds hub data elements to a given dataset instance
395 * @param $criteriaInstance An instance of a storeable criteria
396 * @param $requestInstance An instance of a Requestable class
399 public function addElementsToDataSet (StoreableCriteria $criteriaInstance, Requestable $requestInstance) {
400 // Add node number and type
401 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
402 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_TYPE, $requestInstance->getRequestElement('mode'));
405 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_ID, $this->getNodeId());
407 // Add the session id if acquired
408 if ($this->getSessionId() != '') {
409 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_SESSION_ID, $this->getSessionId());
414 * Updates a given field with new value
416 * @param $fieldName Field to update
417 * @param $fieldValue New value to store
419 * @throws DatabaseUpdateSupportException If this class does not support database updates
420 * @todo Try to make this method more generic so we can move it in BaseFrameworkSystem
422 public function updateDatabaseField ($fieldName, $fieldValue) {
424 $this->partialStub('Unfinished!');
427 // Get a critieria instance
428 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
430 // Add search criteria
431 $searchInstance->addCriteria(UserDatabaseWrapper::DB_COLUMN_USERNAME, $this->getUserName());
432 $searchInstance->setLimit(1);
434 // Now get another criteria
435 $updateInstance = ObjectFactory::createObjectByConfiguredName('update_criteria_class');
437 // Add criteria entry which we shall update
438 $updateInstance->addCriteria($fieldName, $fieldValue);
440 // Add the search criteria for searching for the right entry
441 $updateInstance->setSearchInstance($searchInstance);
443 // Set wrapper class name
444 $updateInstance->setWrapperConfigEntry('user_db_wrapper_class');
446 // Remember the update in database result
447 $this->getResultInstance()->add2UpdateQueue($updateInstance);
451 * Announces this hub to the upper (bootstrap or list) hubs. After this is
452 * successfully done the given task is unregistered from the handler.
454 * @param $taskInstance The task instance running this announcement
456 * @throws HubAlreadyAnnouncedException If this hub is already announced
457 * @todo Change the first if() block to check for a specific state
459 public function announceSelfToUpperNodes (Taskable $taskInstance) {
460 // Is this hub node announced?
461 if ($this->hubIsAnnounced === true) {
462 // Already announced!
463 throw new HubAlreadyAnnouncedException($this, self::EXCEPTION_HUB_ALREADY_ANNOUNCED);
467 $this->debugOutput('HUB: Self-announcement: START (taskInstance=' . $taskInstance->__toString(). ')');
469 // Get a helper instance
470 $helperInstance = ObjectFactory::createObjectByConfiguredName('hub_announcement_helper_class', array($this));
472 // Load the announcement descriptor
473 $helperInstance->loadAnnouncementDescriptor();
475 // Set some dummy configuration entries, e.g. node_status
476 $this->getConfigInstance()->setConfigEntry('node_status', $this->getStateInstance()->getStateName());
478 // Compile all variables
479 $helperInstance->getTemplateInstance()->compileConfigInVariables();
481 // "Publish" the descriptor by sending it to the bootstrap/list nodes
482 $helperInstance->publishAnnouncementDescriptor();
484 // Change the state, this should be the last line except debug output
485 $this->getStateInstance()->nodeAnnouncedToUpperHubs();
488 $this->debugOutput('HUB: Self-announcement: FINISHED');
492 * Activates the hub by doing some final preparation and setting
493 * $hubIsActive to true
495 * @param $requestInstance A Requestable class
496 * @param $responseInstance A Responseable class
499 public function activateHub (Requestable $requestInstance, Responseable $responseInstance) {
500 // Checks wether a listener is still active and shuts it down if one
501 // is still listening.
502 if (($this->determineIfListenerIsActive()) && ($this->getIsActive())) {
503 // Shutdown them down before they can hurt anything
504 $this->shutdownListenerPool();
507 // Get the controller here
508 $controllerInstance = Registry::getRegistry()->getInstance('controller');
510 // Run all filters for the hub activation
511 $controllerInstance->executeActivationFilters($requestInstance, $responseInstance);
513 // ----------------------- Last step from here ------------------------
514 // Activate the hub. This is ALWAYS the last step in this method
515 $this->getStateInstance()->nodeIsActivated();
516 // ---------------------- Last step until here ------------------------
520 * Initializes the listener pool (class)
524 public function initializeListenerPool () {
526 $this->debugOutput('HUB: Initialize listener: START');
528 // Get a new pool instance
529 $this->setListenerPoolInstance(ObjectFactory::createObjectByConfiguredName('listener_pool_class', array($this)));
531 // Get an instance of the low-level listener
532 $listenerInstance = ObjectFactory::createObjectByConfiguredName('tcp_listener_class', array($this));
534 // Setup address and port
535 $listenerInstance->setListenAddressByConfiguration('node_listen_addr');
536 $listenerInstance->setListenPortByConfiguration('node_tcp_listen_port');
538 // Initialize the listener
539 $listenerInstance->initListener();
541 // Get a decorator class
542 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('hub_tcp_listener_class', array($listenerInstance));
544 // Add this listener to the pool
545 $this->getListenerPoolInstance()->addListener($decoratorInstance);
547 // Get a decorator class
548 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('client_tcp_listener_class', array($listenerInstance));
550 // Add this listener to the pool
551 $this->getListenerPoolInstance()->addListener($decoratorInstance);
553 // Get an instance of the low-level listener
554 $listenerInstance = ObjectFactory::createObjectByConfiguredName('udp_listener_class', array($this));
556 // Setup address and port
557 $listenerInstance->setListenAddressByConfiguration('node_listen_addr');
558 $listenerInstance->setListenPortByConfiguration('node_udp_listen_port');
560 // Initialize the listener
561 $listenerInstance->initListener();
563 // Get a decorator class
564 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('hub_udp_listener_class', array($listenerInstance));
566 // Add this listener to the pool
567 $this->getListenerPoolInstance()->addListener($decoratorInstance);
569 // Get a decorator class
570 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('client_udp_listener_class', array($listenerInstance));
572 // Add this listener to the pool
573 $this->getListenerPoolInstance()->addListener($decoratorInstance);
576 $this->debugOutput('HUB: Initialize listener: FINISHED.');
580 * Restores a previously stored node list from database
584 public function bootstrapRestoreNodeList () {
586 $this->debugOutput('HUB: Restore node list: START');
588 // Get a wrapper instance
589 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('node_list_db_wrapper_class');
591 // Now get a search criteria instance
592 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
594 // Search for the node number zero which is hard-coded the default
595 // @TODO Add some criteria, e.g. if the node is active or so
596 //$searchInstance->addCriteria(NodeListDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
597 //$searchInstance->addCriteria(NodeListDatabaseWrapper::DB_COLUMN_NODE_TYPE, $this->getRequestInstance()->getRequestElement('mode'));
598 //$searchInstance->setLimit(1);
601 $resultInstance = $wrapperInstance->doSelectByCriteria($searchInstance);
604 if ($resultInstance->next()) {
605 $this->partialStub('Do something for restoring the list.');
607 //$this->debugOutput('HUB: ');
609 // No previously saved node list found!
610 $this->debugOutput('HUB: No previously saved node list found. This is fine.');
614 $this->debugOutput('HUB: Restore node list: FINISHED.');
618 * Getter for isActive attribute
620 * @return $isActive Wether the hub is active
622 public final function getIsActive () {
623 return $this->isActive;
627 * Enables (default) or disables isActive flag
629 * @param $isActive Wether the hub is active
632 public final function enableIsActive ($isActive = true) {
633 $this->isActive = (bool) $isActive;