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 * Wether this node is anncounced (KEEP ON false!)
55 private $hubIsAnnounced = false;
58 * Wether this hub is active
60 private $isActive = false;
63 * Protected constructor
65 * @param $className Name of the class
68 protected function __construct ($className) {
69 // Call parent constructor
70 parent::__construct($className);
72 // Init state which sets the state to 'init'
77 * Initializes the node's state which sets it to 'init'
81 private function initState() {
82 // Get the state factory and create the initial state, we don't need
83 // the state instance here
84 NodeStateFactory::createNodeStateInstanceByName('init', $this);
90 * @param $nodeId Our new node id
93 private final function setNodeId ($nodeId) {
95 $this->getConfigInstance()->setConfigEntry('node_id', (string) $nodeId);
101 * @return $nodeId Current node id
103 private final function getNodeId () {
104 // Get it from config
105 return $this->getConfigInstance()->getConfigEntry('node_id');
109 * Setter for session id
111 * @param $sessionId Our new session id
114 private final function setSessionId ($sessionId) {
115 $this->getConfigInstance()->setConfigEntry('session_id', (string) $sessionId);
119 * Getter for session id
121 * @return $sessionId Current session id
123 public final function getSessionId () {
124 return $this->getConfigInstance()->getConfigEntry('session_id');
128 * Setter for query instance
130 * @param $connectorInstance Our new query instance
133 private final function setQueryConnectorInstance (Connectable $connectorInstance) {
134 $this->queryConnectorInstance = $connectorInstance;
138 * Getter for query instance
140 * @return $connectorInstance Our new query instance
142 public final function getQueryConnectorInstance () {
143 return $this->queryConnectorInstance;
147 * Setter for queue instance
149 * @param $connectorInstance Our new queue instance
152 private final function setQueueConnectorInstance (Connectable $connectorInstance) {
153 $this->queueConnectorInstance = $connectorInstance;
157 * Getter for queue instance
159 * @return $connectorInstance Our new queue instance
161 public final function getQueueConnectorInstance () {
162 return $this->queueConnectorInstance;
166 * Getter for boot IP/port combination
168 * @return $bootIpPort The IP/port combination of the boot node
170 protected final function getBootIpPort () {
171 return $this->bootIpPort;
175 * Checks wether the given IP address matches one of the bootstrapping nodes
177 * @param $remoteAddr IP address to checkout against our bootstrapping list
178 * @return $isFound Wether the IP is found
180 protected function ifAddressMatchesBootstrappingNodes ($remoteAddr) {
181 // By default nothing is found
184 // Run through all configured IPs
185 foreach (explode(BaseHubSystem::BOOTSTRAP_NODES_SEPERATOR, $this->getConfigInstance()->getConfigEntry('hub_bootstrap_nodes')) as $ipPort) {
186 // Split it up in IP/port
187 $ipPortArray = explode(':', $ipPort);
190 if ($ipPortArray[0] == $remoteAddr) {
194 // Remember the port number
195 $this->bootIpPort = $ipPort;
198 $this->debugOutput('BOOTSTRAP: ' . __FUNCTION__ . '[' . __LINE__ . ']: IP matches remote address ' . $ipPort . '.');
200 // Stop further searching
202 } elseif ($ipPortArray[0] == $this->getConfigInstance()->getConfigEntry('node_listen_addr')) {
203 // IP matches listen address. At this point we really don't care
204 // if we can really listen on that address
207 // Remember the port number
208 $this->bootIpPort = $ipPort;
211 $this->debugOutput('BOOTSTRAP: ' . __FUNCTION__ . '[' . __LINE__ . ']: IP matches listen address ' . $ipPort . '.');
213 // Stop further searching
223 * Outputs the console teaser. This should only be executed on startup or
224 * full restarts. This method generates some space around the teaser.
228 public function outputConsoleTeaser () {
229 // Get the app instance (for shortening our code)
230 $app = $this->getApplicationInstance();
233 $this->debugOutput(' ');
234 $this->debugOutput($app->getAppName() . ' v' . $app->getAppVersion() . ' - ' . $this->getRequestInstance()->getRequestElement('mode') . ' mode active');
235 $this->debugOutput('Copyright (c) 2007 - 2008 Roland Haeder, 2009 - 2011 Hub Developer Team');
236 $this->debugOutput(' ');
237 $this->debugOutput('This program comes with ABSOLUTELY NO WARRANTY; for details see docs/COPYING.');
238 $this->debugOutput('This is free software, and you are welcome to redistribute it under certain');
239 $this->debugOutput('conditions; see docs/COPYING for details.');
240 $this->debugOutput(' ');
244 * Generic method to acquire a hub-id. On first run this generates a new one
245 * based on many pseudo-random data. On any later run, unless the id
246 * got not removed from database, it will be restored from the database.
248 * @param $requestInstance A Requestable class
249 * @param $responseInstance A Responseable class
252 public function bootstrapAcquireNodeId (Requestable $requestInstance, Responseable $responseInstance) {
253 // Get a wrapper instance
254 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('node_info_db_wrapper_class');
256 // Now get a search criteria instance
257 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
259 // Search for the node number zero which is hard-coded the default
260 $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
261 $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_TYPE, $this->getRequestInstance()->getRequestElement('mode'));
262 $searchInstance->setLimit(1);
265 $resultInstance = $wrapperInstance->doSelectByCriteria($searchInstance);
268 if ($resultInstance->next()) {
269 // Save the result instance in this class
270 $this->setResultInstance($resultInstance);
272 // Get the node id from result and set it
273 $this->setNodeId($this->getField(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_ID));
276 $this->debugOutput('BOOTSTRAP: Re-using found node-id: ' . $this->getNodeId() . '');
278 // Get an RNG instance (Random Number Generator)
279 $rngInstance = ObjectFactory::createObjectByConfiguredName('rng_class');
281 // Generate a pseudo-random string
282 $randomString = $rngInstance->randomString(255) . ':' . $this->getBootIpPort() . ':' . $this->getRequestInstance()->getRequestElement('mode');
284 // Get a crypto instance
285 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
287 // Hash and encrypt the string so we become a node id (also documented as "hub id")
288 $this->setNodeId($cryptoInstance->hashString($cryptoInstance->encryptString($randomString)));
290 // Register the node id with our wrapper
291 $wrapperInstance->registerNodeId($this, $this->getRequestInstance());
294 $this->debugOutput('BOOTSTRAP: Created new node-id: ' . $this->getNodeId() . '');
299 * Generates a session id which will be sent to the other hubs and peers
303 public function bootstrapGenerateSessionId () {
304 // Get an RNG instance
305 $rngInstance = ObjectFactory::createObjectByConfiguredName('rng_class');
307 // Generate a pseudo-random string
308 $randomString = $rngInstance->randomString(255) . ':' . $this->getBootIpPort() . ':' . $this->getRequestInstance()->getRequestElement('mode');
310 // Get a crypto instance
311 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
313 // Hash and encrypt the string so we become a "node id" aka Hub-Id
314 $this->setSessionId($cryptoInstance->hashString($cryptoInstance->encryptString($randomString)));
316 // Get a wrapper instance
317 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('node_info_db_wrapper_class');
319 // Register the node id with our wrapper
320 $wrapperInstance->registerSessionId($this, $this->getRequestInstance());
323 $this->debugOutput('BOOTSTRAP: Created new session-id: ' . $this->getSessionId() . '');
325 // Change the state because the node has auired a hub id
326 $this->getStateInstance()->nodeGeneratedSessionId();
330 * Initializes queues which every node needs
334 protected function initGenericQueues () {
336 $this->debugOutput('BOOTSTRAP: Initialize queues: START');
338 // Set the query connector instance
339 $this->setQueryConnectorInstance(ObjectFactory::createObjectByConfiguredName('query_connector_class', array($this)));
342 $this->getQueryConnectorInstance()->doTestQuery();
344 // Set the queue connector instance
345 $this->setQueueConnectorInstance(ObjectFactory::createObjectByConfiguredName('queue_connector_class', array($this)));
348 $this->getQueueConnectorInstance()->doTestQueue();
351 $this->debugOutput('BOOTSTRAP: Initialize queues: FINISHED');
355 * Adds hub data elements to a given dataset instance
357 * @param $criteriaInstance An instance of a storeable criteria
358 * @param $requestInstance An instance of a Requestable class
361 public function addElementsToDataSet (StoreableCriteria $criteriaInstance, Requestable $requestInstance) {
362 // Add node number and type
363 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
364 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_TYPE, $requestInstance->getRequestElement('mode'));
367 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_ID, $this->getNodeId());
369 // Add the session id if acquired
370 if ($this->getSessionId() != '') {
371 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_SESSION_ID, $this->getSessionId());
376 * Updates a given field with new value
378 * @param $fieldName Field to update
379 * @param $fieldValue New value to store
381 * @throws DatabaseUpdateSupportException If this class does not support database updates
382 * @todo Try to make this method more generic so we can move it in BaseFrameworkSystem
384 public function updateDatabaseField ($fieldName, $fieldValue) {
386 $this->partialStub('Unfinished!');
389 // Get a critieria instance
390 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
392 // Add search criteria
393 $searchInstance->addCriteria(UserDatabaseWrapper::DB_COLUMN_USERNAME, $this->getUserName());
394 $searchInstance->setLimit(1);
396 // Now get another criteria
397 $updateInstance = ObjectFactory::createObjectByConfiguredName('update_criteria_class');
399 // Add criteria entry which we shall update
400 $updateInstance->addCriteria($fieldName, $fieldValue);
402 // Add the search criteria for searching for the right entry
403 $updateInstance->setSearchInstance($searchInstance);
405 // Set wrapper class name
406 $updateInstance->setWrapperConfigEntry('user_db_wrapper_class');
408 // Remember the update in database result
409 $this->getResultInstance()->add2UpdateQueue($updateInstance);
413 * Announces this hub to the upper (bootstrap or list) hubs. After this is
414 * successfully done the given task is unregistered from the handler. This
415 * might look a bit overloaded here but the announcement phase isn't a
416 * simple "Hello there" message, it may later on also contain more
417 * informations like the object list.
419 * @param $taskInstance The task instance running this announcement
421 * @throws HubAlreadyAnnouncedException If this hub is already announced
422 * @todo Change the first if() block to check for a specific state
424 public function announceSelfToUpperNodes (Taskable $taskInstance) {
425 // Is this hub node announced?
426 if ($this->hubIsAnnounced === true) {
427 // Already announced!
428 throw new HubAlreadyAnnouncedException($this, self::EXCEPTION_HUB_ALREADY_ANNOUNCED);
432 $this->debugOutput('HUB-Announcement: START (taskInstance=' . $taskInstance->__toString(). ')');
434 // Get a helper instance
435 $helperInstance = ObjectFactory::createObjectByConfiguredName('hub_announcement_helper_class', array($this));
437 // Load the announcement descriptor
438 $helperInstance->loadDescriptorXml();
440 // Set some dummy configuration entries, e.g. node_status
441 $this->getConfigInstance()->setConfigEntry('node_status', $this->getStateInstance()->getStateName());
443 // Compile all variables
444 $helperInstance->getTemplateInstance()->compileConfigInVariables();
446 // "Publish" the descriptor by sending it to the bootstrap/list nodes
447 $helperInstance->sendPackage($this);
449 // Change the state, this should be the last line except debug output
450 $this->getStateInstance()->nodeAnnouncedToUpperHubs();
453 $this->debugOutput('HUB-Announcement: FINISHED');
457 * Does a self-connect attempt on the public IP address. This should make
458 * it sure, we are reachable from outside world. For this kind of package we
459 * don't need that overload we have in the announcement phase.
461 * @param $taskInstance The task instance running this announcement
464 public function doSelfConnection (Taskable $taskInstance) {
466 $this->debugOutput('HUB: Self Connection: START (taskInstance=' . $taskInstance->__toString(). ')');
468 // Get a helper instance
469 $helperInstance = ObjectFactory::createObjectByConfiguredName('hub_self_connect_helper_class', array($this));
471 // Load the descriptor (XML) file
472 $helperInstance->loadDescriptorXml();
474 // And send the package away
475 $helperInstance->sendPackage($this);
478 $this->debugOutput('HUB: Self Connection: FINISHED');
482 * Activates the hub by doing some final preparation and setting
483 * $hubIsActive to true
485 * @param $requestInstance A Requestable class
486 * @param $responseInstance A Responseable class
489 public function activateNode (Requestable $requestInstance, Responseable $responseInstance) {
490 // Checks wether a listener is still active and shuts it down if one
491 // is still listening.
492 if (($this->determineIfListenerIsActive()) && ($this->getIsActive())) {
493 // Shutdown them down before they can hurt anything
494 $this->shutdownListenerPool();
497 // Get the controller here
498 $controllerInstance = Registry::getRegistry()->getInstance('controller');
500 // Run all filters for the hub activation
501 $controllerInstance->executeActivationFilters($requestInstance, $responseInstance);
503 // ----------------------- Last step from here ------------------------
504 // Activate the hub. This is ALWAYS the last step in this method
505 $this->getStateInstance()->nodeIsActivated();
506 // ---------------------- Last step until here ------------------------
510 * Initializes the listener pool (class)
514 public function initializeListenerPool () {
516 $this->debugOutput('HUB: Initialize listener: START');
518 // Get a new pool instance
519 $this->setListenerPoolInstance(ObjectFactory::createObjectByConfiguredName('listener_pool_class', array($this)));
521 // Get an instance of the low-level listener
522 $listenerInstance = ObjectFactory::createObjectByConfiguredName('tcp_listener_class', array($this));
524 // Setup address and port
525 $listenerInstance->setListenAddressByConfiguration('node_listen_addr');
528 * All nodes can now use the same configuration entry because it can be
529 * customized in config-local.php.
531 $listenerInstance->setListenPortByConfiguration('node_tcp_listen_port');
533 // Initialize the listener
534 $listenerInstance->initListener();
536 // Get a decorator class
537 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('hub_tcp_listener_class', array($listenerInstance));
539 // Add this listener to the pool
540 $this->getListenerPoolInstance()->addListener($decoratorInstance);
542 // Get a decorator class
543 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('client_tcp_listener_class', array($listenerInstance));
545 // Add this listener to the pool
546 $this->getListenerPoolInstance()->addListener($decoratorInstance);
548 // Get an instance of the low-level listener
549 $listenerInstance = ObjectFactory::createObjectByConfiguredName('udp_listener_class', array($this));
551 // Setup address and port
552 $listenerInstance->setListenAddressByConfiguration('node_listen_addr');
555 * All nodes can now use the same configuration entry because it can be
556 * customized in config-local.php.
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;
637 * "Getter for address:port combination
639 * @param $handlerInstance A valid Networkable instance
640 * @return $addressPort A address:port combination for this node
642 public final function getAddressPort (Networkable $handlerInstance) {
643 // Construct config entry
644 $configEntry = 'node_' . $handlerInstance->getHandlerName() . '_listen_port';
647 $addressPort = $this->getConfigInstance()->detectServerAddress() . ':' . $this->getConfigInstance()->getConfigEntry($configEntry);