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 * Protected constructor
62 * @param $className Name of the class
65 protected function __construct ($className) {
66 // Call parent constructor
67 parent::__construct($className);
69 // Init state which sets the state to 'init'
74 * Initializes the node's state which sets it to 'init'
78 private function initState() {
79 // Get the state factory and create the initial state, we don't need
80 // the state instance here
81 StateFactory::createStateInstanceByName('init', $this);
87 * @param $nodeId Our new node id
90 private final function setNodeId ($nodeId) {
92 $this->getConfigInstance()->setConfigEntry('node_id', (string) $nodeId);
98 * @return $nodeId Current node id
100 private final function getNodeId () {
101 // Get it from config
102 return $this->getConfigInstance()->getConfigEntry('node_id');
106 * Setter for listener pool instance
108 * @param $listenerPoolInstance Our new listener pool instance
111 private final function setListenerPoolInstance (PoolableListener $listenerPoolInstance) {
112 $this->listenerPoolInstance = $listenerPoolInstance;
116 * Getter for listener pool instance
118 * @return $listenerPoolInstance Our current listener pool instance
120 public final function getListenerPoolInstance () {
121 return $this->listenerPoolInstance;
125 * Setter for state instance
127 * @param $stateInstance Node's current state instance
130 public final function setStateInstance (Stateable $stateInstance) {
131 $this->stateInstance = $stateInstance;
135 * Getter for state instance
137 * @return $stateInstance Node's current state instance
139 public final function getStateInstance () {
140 return $this->stateInstance;
144 * Setter for session id
146 * @param $sessionId Our new session id
149 private final function setSessionId ($sessionId) {
150 $this->getConfigInstance()->setConfigEntry('session_id', (string) $sessionId);
154 * Getter for session id
156 * @return $sessionId Current session id
158 public final function getSessionId () {
159 return $this->getConfigInstance()->getConfigEntry('session_id');
163 * Setter for query instance
165 * @param $connectorInstance Our new query instance
168 private final function setQueryConnectorInstance (Connectable $connectorInstance) {
169 $this->connectorInstance = $connectorInstance;
173 * Getter for query instance
175 * @return $connectorInstance Our new query instance
177 public final function getQueryConnectorInstance () {
178 return $this->connectorInstance;
182 * Getter for boot IP/port combination
184 * @return $bootIpPort The IP/port combination of the boot node
186 protected final function getBootIpPort () {
187 return $this->bootIpPort;
191 * "Getter" for a printable state name
193 public final function getPrintableState () {
197 // Get the state instance
198 $stateInstance = $this->getStateInstance();
200 // Is it an instance of Stateable?
201 if ($stateInstance instanceof Stateable) {
202 // Then use that state name
203 $stateName = $stateInstance->getStateName();
211 * Checks wether the given IP address matches one of the bootstrapping nodes
213 * @param $remoteAddr IP address to checkout against our bootstrapping list
214 * @return $isFound Wether the IP is found
216 protected function ifAddressMatchesBootstrappingNodes ($remoteAddr) {
217 // By default nothing is found
220 // Run through all configured IPs
221 foreach (explode(',', $this->getConfigInstance()->getConfigEntry('hub_bootstrap_nodes')) as $ipPort) {
222 // Split it up in IP/port
223 $ipPortArray = explode(':', $ipPort);
226 if ($ipPortArray[0] == $remoteAddr) {
230 // Remember the port number
231 $this->bootIpPort = $ipPort;
234 $this->debugOutput('BOOTSTRAP: ' . __FUNCTION__ . '[' . __LINE__ . ']: IP matches remote address ' . $ipPort . '.');
236 // Stop further searching
238 } elseif ($ipPortArray[0] == $this->getConfigInstance()->getConfigEntry('node_listen_addr')) {
239 // IP matches listen address. At this point we really don't care
240 // if we can also listen on that address!
243 // Remember the port number
244 $this->bootIpPort = $ipPort;
247 $this->debugOutput('BOOTSTRAP: ' . __FUNCTION__ . '[' . __LINE__ . ']: IP matches listen address ' . $ipPort . '.');
249 // Stop further searching
259 * Outputs the console teaser. This should only be executed on startup or
260 * full restarts. This method generates some space around the teaser.
264 public function outputConsoleTeaser () {
265 // Get the app instance (for shortening our code)
266 $app = $this->getApplicationInstance();
269 $this->debugOutput(' ');
270 $this->debugOutput($app->getAppName() . ' v' . $app->getAppVersion() . ' - ' . $this->getRequestInstance()->getRequestElement('mode') . ' mode active');
271 $this->debugOutput('Copyright (c) 2007 - 2008 Roland Haeder, 2009, 2010 Hub Developer Team');
272 $this->debugOutput(' ');
273 $this->debugOutput('This program comes with ABSOLUTELY NO WARRANTY; for details see docs/COPYING.');
274 $this->debugOutput('This is free software, and you are welcome to redistribute it under certain');
275 $this->debugOutput('conditions; see docs/COPYING for details.');
276 $this->debugOutput(' ');
280 * Generic method to acquire a hub-id. On first run this generates a new one
281 * based on many pseudo-random data. On any later run, unless the id
282 * got not removed from database, it will be restored from the database.
284 * @param $requestInstance A Requestable class
285 * @param $responseInstance A Responseable class
288 public function bootstrapAcquireHubId (Requestable $requestInstance, Responseable $responseInstance) {
289 // Get a wrapper instance
290 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('node_info_db_wrapper_class');
292 // Now get a search criteria instance
293 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
295 // Search for the node number zero which is hard-coded the default
296 $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
297 $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_TYPE, $this->getRequestInstance()->getRequestElement('mode'));
298 $searchInstance->setLimit(1);
301 $resultInstance = $wrapperInstance->doSelectByCriteria($searchInstance);
304 if ($resultInstance->next()) {
305 // Save the result instance in this class
306 $this->setResultInstance($resultInstance);
308 // Get the node id from result and set it
309 $this->setNodeId($this->getField(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_ID));
312 $this->debugOutput('BOOTSTRAP: Re-using found node-id: ' . $this->getNodeId() . '');
314 // Get an RNG instance (Random Number Generator)
315 $rngInstance = ObjectFactory::createObjectByConfiguredName('rng_class');
317 // Generate a pseudo-random string
318 $randomString = $rngInstance->randomString(255) . ':' . $this->getBootIpPort() . ':' . $this->getRequestInstance()->getRequestElement('mode');
320 // Get a crypto instance
321 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
323 // Hash and encrypt the string so we become a "node id" aka Hub-Id
324 $this->setNodeId($cryptoInstance->hashString($cryptoInstance->encryptString($randomString)));
326 // Register the node id with our wrapper
327 $wrapperInstance->registerNodeId($this, $this->getRequestInstance());
330 $this->debugOutput('BOOTSTRAP: Created new node-id: ' . $this->getNodeId() . '');
335 * Generates a session id which will be sent to the other hubs and peers
339 public function bootstrapGenerateSessionId () {
340 // Get an RNG instance
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" aka Hub-Id
350 $this->setSessionId($cryptoInstance->hashString($cryptoInstance->encryptString($randomString)));
352 // Get a wrapper instance
353 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('node_info_db_wrapper_class');
355 // Register the node id with our wrapper
356 $wrapperInstance->registerSessionId($this, $this->getRequestInstance());
359 $this->debugOutput('BOOTSTRAP: Created new session-id: ' . $this->getSessionId() . '');
361 // Change the state because the node has auired a hub id
362 $this->getStateInstance()->nodeGeneratedSessionId();
366 * Initializes queues which every node needs
370 protected function initGenericQueues () {
372 $this->debugOutput('BOOTSTRAP: Initialize queues: START');
374 // Set the query connector instance
375 $this->setQueryConnectorInstance(ObjectFactory::createObjectByConfiguredName('query_connector_class', array($this)));
378 $this->getQueryConnectorInstance()->doTestQuery();
381 $this->debugOutput('BOOTSTRAP: Initialize queues: FINISHED');
385 * Adds hub data elements to a given dataset instance
387 * @param $criteriaInstance An instance of a storeable criteria
388 * @param $requestInstance An instance of a Requestable class
391 public function addElementsToDataSet (StoreableCriteria $criteriaInstance, Requestable $requestInstance) {
392 // Add node number and type
393 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
394 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_TYPE, $requestInstance->getRequestElement('mode'));
397 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_ID, $this->getNodeId());
399 // Add the session id if acquired
400 if ($this->getSessionId() != '') {
401 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_SESSION_ID, $this->getSessionId());
406 * Updates a given field with new value
408 * @param $fieldName Field to update
409 * @param $fieldValue New value to store
411 * @throws DatabaseUpdateSupportException If this class does not support database updates
412 * @todo Try to make this method more generic so we can move it in BaseFrameworkSystem
414 public function updateDatabaseField ($fieldName, $fieldValue) {
416 $this->partialStub('Unfinished!');
419 // Get a critieria instance
420 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
422 // Add search criteria
423 $searchInstance->addCriteria(UserDatabaseWrapper::DB_COLUMN_USERNAME, $this->getUserName());
424 $searchInstance->setLimit(1);
426 // Now get another criteria
427 $updateInstance = ObjectFactory::createObjectByConfiguredName('update_criteria_class');
429 // Add criteria entry which we shall update
430 $updateInstance->addCriteria($fieldName, $fieldValue);
432 // Add the search criteria for searching for the right entry
433 $updateInstance->setSearchInstance($searchInstance);
435 // Set wrapper class name
436 $updateInstance->setWrapperConfigEntry('user_db_wrapper_class');
438 // Remember the update in database result
439 $this->getResultInstance()->add2UpdateQueue($updateInstance);
443 * Announces this hub to the upper (bootstrap or list) hubs. After this is
444 * successfully done the given task is unregistered from the handler. This
445 * might look a bit overloaded here but the announcement phase isn't a
446 * simple "Hello there" message, it may later on also contain more
447 * informations like the object list.
449 * @param $taskInstance The task instance running this announcement
451 * @throws HubAlreadyAnnouncedException If this hub is already announced
452 * @todo Change the first if() block to check for a specific state
454 public function announceSelfToUpperNodes (Taskable $taskInstance) {
455 // Is this hub node announced?
456 if ($this->hubIsAnnounced === true) {
457 // Already announced!
458 throw new HubAlreadyAnnouncedException($this, self::EXCEPTION_HUB_ALREADY_ANNOUNCED);
462 $this->debugOutput('HUB: Self Announcement: START (taskInstance=' . $taskInstance->__toString(). ')');
464 // Get a helper instance
465 $helperInstance = ObjectFactory::createObjectByConfiguredName('hub_announcement_helper_class', array($this));
467 // Load the announcement descriptor
468 $helperInstance->loadAnnouncementDescriptor();
470 // Set some dummy configuration entries, e.g. node_status
471 $this->getConfigInstance()->setConfigEntry('node_status', $this->getStateInstance()->getStateName());
473 // Compile all variables
474 $helperInstance->getTemplateInstance()->compileConfigInVariables();
476 // "Publish" the descriptor by sending it to the bootstrap/list nodes
477 $helperInstance->publishAnnouncementDescriptor();
479 // Change the state, this should be the last line except debug output
480 $this->getStateInstance()->nodeAnnouncedToUpperHubs();
483 $this->debugOutput('HUB: Self Announcement: FINISHED');
487 * Does a self-connect attempt on the public IP address. This should make
488 * it sure, we are reachable from outside world. For this kind of package we
489 * don't need that overload we have in the announcement phase.
491 * @param $taskInstance The task instance running this announcement
494 public function doSelfConnection (Taskable $taskInstance) {
496 $this->debugOutput('HUB: Self Connection: START (taskInstance=' . $taskInstance->__toString(). ')');
498 // Get a helper instance
499 $helperInstance = ObjectFactory::createObjectByConfiguredName('hub_self_connect_helper_class', array($this));
501 // And send the package away
502 $helperInstance->doSelfConnect();
505 $this->debugOutput('HUB: Self Connection: FINISHED');
509 * Activates the hub by doing some final preparation and setting
510 * $hubIsActive to true
512 * @param $requestInstance A Requestable class
513 * @param $responseInstance A Responseable class
516 public function activateHub (Requestable $requestInstance, Responseable $responseInstance) {
517 // Checks wether a listener is still active and shuts it down if one
518 // is still listening.
519 if (($this->determineIfListenerIsActive()) && ($this->getIsActive())) {
520 // Shutdown them down before they can hurt anything
521 $this->shutdownListenerPool();
524 // Get the controller here
525 $controllerInstance = Registry::getRegistry()->getInstance('controller');
527 // Run all filters for the hub activation
528 $controllerInstance->executeActivationFilters($requestInstance, $responseInstance);
530 // ----------------------- Last step from here ------------------------
531 // Activate the hub. This is ALWAYS the last step in this method
532 $this->getStateInstance()->nodeIsActivated();
533 // ---------------------- Last step until here ------------------------
537 * Initializes the listener pool (class)
541 public function initializeListenerPool () {
543 $this->debugOutput('HUB: Initialize listener: START');
545 // Get a new pool instance
546 $this->setListenerPoolInstance(ObjectFactory::createObjectByConfiguredName('listener_pool_class', array($this)));
548 // Get an instance of the low-level listener
549 $listenerInstance = ObjectFactory::createObjectByConfiguredName('tcp_listener_class', array($this));
551 // Setup address and port
552 $listenerInstance->setListenAddressByConfiguration('node_listen_addr');
553 $listenerInstance->setListenPortByConfiguration('node_tcp_listen_port');
555 // Initialize the listener
556 $listenerInstance->initListener();
558 // Get a decorator class
559 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('hub_tcp_listener_class', array($listenerInstance));
561 // Add this listener to the pool
562 $this->getListenerPoolInstance()->addListener($decoratorInstance);
564 // Get a decorator class
565 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('peer_tcp_listener_class', array($listenerInstance));
567 // Add this listener to the pool
568 $this->getListenerPoolInstance()->addListener($decoratorInstance);
570 // Get an instance of the low-level listener
571 $listenerInstance = ObjectFactory::createObjectByConfiguredName('udp_listener_class', array($this));
573 // Setup address and port
574 $listenerInstance->setListenAddressByConfiguration('node_listen_addr');
575 $listenerInstance->setListenPortByConfiguration('node_udp_listen_port');
577 // Initialize the listener
578 $listenerInstance->initListener();
580 // Get a decorator class
581 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('hub_udp_listener_class', array($listenerInstance));
583 // Add this listener to the pool
584 $this->getListenerPoolInstance()->addListener($decoratorInstance);
586 // Get a decorator class
587 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('peer_udp_listener_class', array($listenerInstance));
589 // Add this listener to the pool
590 $this->getListenerPoolInstance()->addListener($decoratorInstance);
593 $this->debugOutput('HUB: Initialize listener: FINISHED.');
597 * Restores a previously stored node list from database
601 public function bootstrapRestoreNodeList () {
603 $this->debugOutput('HUB: Restore node list: START');
605 // Get a wrapper instance
606 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('node_list_db_wrapper_class');
608 // Now get a search criteria instance
609 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
611 // Search for the node number zero which is hard-coded the default
612 // @TODO Add some criteria, e.g. if the node is active or so
613 //$searchInstance->addCriteria(NodeListDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
614 //$searchInstance->addCriteria(NodeListDatabaseWrapper::DB_COLUMN_NODE_TYPE, $this->getRequestInstance()->getRequestElement('mode'));
615 //$searchInstance->setLimit(1);
618 $resultInstance = $wrapperInstance->doSelectByCriteria($searchInstance);
621 if ($resultInstance->next()) {
622 $this->partialStub('Do something for restoring the list.');
624 //$this->debugOutput('HUB: ');
626 // No previously saved node list found!
627 $this->debugOutput('HUB: No previously saved node list found. This is fine.');
631 $this->debugOutput('HUB: Restore node list: FINISHED.');
635 * Getter for isActive attribute
637 * @return $isActive Wether the hub is active
639 public final function getIsActive () {
640 return $this->isActive;
644 * Enables (default) or disables isActive flag
646 * @param $isActive Wether the hub is active
649 public final function enableIsActive ($isActive = true) {
650 $this->isActive = (bool) $isActive;