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() {
83 * Get the state factory and create the initial state, we don't need
84 * the state instance here
86 NodeStateFactory::createNodeStateInstanceByName('init', $this);
92 * @param $nodeId Our new node id
95 private final function setNodeId ($nodeId) {
97 $this->getConfigInstance()->setConfigEntry('node_id', (string) $nodeId);
103 * @return $nodeId Current node id
105 private final function getNodeId () {
106 // Get it from config
107 return $this->getConfigInstance()->getConfigEntry('node_id');
111 * Setter for session id
113 * @param $sessionId Our new session id
116 private final function setSessionId ($sessionId) {
117 $this->getConfigInstance()->setConfigEntry('session_id', (string) $sessionId);
121 * Getter for session id
123 * @return $sessionId Current session id
125 public final function getSessionId () {
126 return $this->getConfigInstance()->getConfigEntry('session_id');
130 * Setter for query instance
132 * @param $connectorInstance Our new query instance
135 private final function setQueryConnectorInstance (Connectable $connectorInstance) {
136 $this->queryConnectorInstance = $connectorInstance;
140 * Getter for query instance
142 * @return $connectorInstance Our new query instance
144 public final function getQueryConnectorInstance () {
145 return $this->queryConnectorInstance;
149 * Setter for queue instance
151 * @param $connectorInstance Our new queue instance
154 private final function setQueueConnectorInstance (Connectable $connectorInstance) {
155 $this->queueConnectorInstance = $connectorInstance;
159 * Getter for queue instance
161 * @return $connectorInstance Our new queue instance
163 public final function getQueueConnectorInstance () {
164 return $this->queueConnectorInstance;
168 * Getter for boot IP/port combination
170 * @return $bootIpPort The IP/port combination of the boot node
172 protected final function getBootIpPort () {
173 return $this->bootIpPort;
177 * Checks wether the given IP address matches one of the bootstrapping nodes
179 * @param $remoteAddr IP address to checkout against our bootstrapping list
180 * @return $isFound Wether the IP is found
182 protected function ifAddressMatchesBootstrappingNodes ($remoteAddr) {
183 // By default nothing is found
186 // Run through all configured IPs
187 foreach (explode(BaseHubSystem::BOOTSTRAP_NODES_SEPARATOR, $this->getConfigInstance()->getConfigEntry('hub_bootstrap_nodes')) as $ipPort) {
188 // Split it up in IP/port
189 $ipPortArray = explode(':', $ipPort);
192 if ($ipPortArray[0] == $remoteAddr) {
196 // Remember the port number
197 $this->bootIpPort = $ipPort;
200 $this->debugOutput('BOOTSTRAP: ' . __FUNCTION__ . '[' . __LINE__ . ']: IP matches remote address ' . $ipPort . '.');
202 // Stop further searching
204 } elseif ($ipPortArray[0] == $this->getConfigInstance()->getConfigEntry('node_listen_addr')) {
205 // IP matches listen address. At this point we really don't care
206 // if we can really listen on that address
209 // Remember the port number
210 $this->bootIpPort = $ipPort;
213 $this->debugOutput('BOOTSTRAP: ' . __FUNCTION__ . '[' . __LINE__ . ']: IP matches listen address ' . $ipPort . '.');
215 // Stop further searching
225 * Outputs the console teaser. This should only be executed on startup or
226 * full restarts. This method generates some space around the teaser.
230 public function outputConsoleTeaser () {
231 // Get the app instance (for shortening our code)
232 $app = $this->getApplicationInstance();
235 $this->debugOutput(' ');
236 $this->debugOutput($app->getAppName() . ' v' . $app->getAppVersion() . ' - ' . $this->getRequestInstance()->getRequestElement('mode') . ' mode active');
237 $this->debugOutput('Copyright (c) 2007 - 2008 Roland Haeder, 2009 - 2011 Hub Developer Team');
238 $this->debugOutput(' ');
239 $this->debugOutput('This program comes with ABSOLUTELY NO WARRANTY; for details see docs/COPYING.');
240 $this->debugOutput('This is free software, and you are welcome to redistribute it under certain');
241 $this->debugOutput('conditions; see docs/COPYING for details.');
242 $this->debugOutput(' ');
246 * Generic method to acquire a hub-id. On first run this generates a new one
247 * based on many pseudo-random data. On any later run, unless the id
248 * got not removed from database, it will be restored from the database.
250 * @param $requestInstance A Requestable class
251 * @param $responseInstance A Responseable class
254 public function bootstrapAcquireNodeId (Requestable $requestInstance, Responseable $responseInstance) {
255 // Get a wrapper instance
256 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('node_info_db_wrapper_class');
258 // Now get a search criteria instance
259 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
261 // Search for the node number zero which is hard-coded the default
262 $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
263 $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_TYPE, $this->getRequestInstance()->getRequestElement('mode'));
264 $searchInstance->setLimit(1);
267 $resultInstance = $wrapperInstance->doSelectByCriteria($searchInstance);
270 if ($resultInstance->next()) {
271 // Save the result instance in this class
272 $this->setResultInstance($resultInstance);
274 // Get the node id from result and set it
275 $this->setNodeId($this->getField(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_ID));
278 $this->debugOutput('BOOTSTRAP: Re-using found node-id: ' . $this->getNodeId() . '');
280 // Get an RNG instance (Random Number Generator)
281 $rngInstance = ObjectFactory::createObjectByConfiguredName('rng_class');
283 // Generate a pseudo-random string
284 $randomString = $rngInstance->randomString(255) . ':' . $this->getBootIpPort() . ':' . $this->getRequestInstance()->getRequestElement('mode');
286 // Get a crypto instance
287 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
289 // Hash and encrypt the string so we become a node id (also documented as "hub id")
290 $this->setNodeId($cryptoInstance->hashString($cryptoInstance->encryptString($randomString)));
292 // Register the node id with our wrapper
293 $wrapperInstance->registerNodeId($this, $this->getRequestInstance());
296 $this->debugOutput('BOOTSTRAP: Created new node-id: ' . $this->getNodeId() . '');
301 * Generates a session id which will be sent to the other hubs and peers
305 public function bootstrapGenerateSessionId () {
306 // Get an RNG instance
307 $rngInstance = ObjectFactory::createObjectByConfiguredName('rng_class');
309 // Generate a pseudo-random string
310 $randomString = $rngInstance->randomString(255) . ':' . $this->getBootIpPort() . ':' . $this->getRequestInstance()->getRequestElement('mode');
312 // Get a crypto instance
313 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
315 // Hash and encrypt the string so we become a "node id" aka Hub-Id
316 $this->setSessionId($cryptoInstance->hashString($cryptoInstance->encryptString($randomString)));
318 // Get a wrapper instance
319 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('node_info_db_wrapper_class');
321 // Register the node id with our wrapper
322 $wrapperInstance->registerSessionId($this, $this->getRequestInstance());
325 $this->debugOutput('BOOTSTRAP: Created new session-id: ' . $this->getSessionId() . '');
327 // Change the state because the node has auired a hub id
328 $this->getStateInstance()->nodeGeneratedSessionId();
332 * Initializes queues which every node needs
336 protected function initGenericQueues () {
338 $this->debugOutput('BOOTSTRAP: Initialize queues: START');
340 // Set the query connector instance
341 $this->setQueryConnectorInstance(ObjectFactory::createObjectByConfiguredName('query_connector_class', array($this)));
344 $this->getQueryConnectorInstance()->doTestQuery();
346 // Set the queue connector instance
347 $this->setQueueConnectorInstance(ObjectFactory::createObjectByConfiguredName('queue_connector_class', array($this)));
350 $this->getQueueConnectorInstance()->doTestQueue();
353 $this->debugOutput('BOOTSTRAP: Initialize queues: FINISHED');
357 * Adds hub data elements to a given dataset instance
359 * @param $criteriaInstance An instance of a storeable criteria
360 * @param $requestInstance An instance of a Requestable class
363 public function addElementsToDataSet (StoreableCriteria $criteriaInstance, Requestable $requestInstance) {
364 // Add node number and type
365 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
366 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_TYPE, $requestInstance->getRequestElement('mode'));
369 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_ID, $this->getNodeId());
371 // Add the session id if acquired
372 if ($this->getSessionId() != '') {
373 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_SESSION_ID, $this->getSessionId());
378 * Updates a given field with new value
380 * @param $fieldName Field to update
381 * @param $fieldValue New value to store
383 * @throws DatabaseUpdateSupportException If this class does not support database updates
384 * @todo Try to make this method more generic so we can move it in BaseFrameworkSystem
386 public function updateDatabaseField ($fieldName, $fieldValue) {
388 $this->partialStub('Unfinished!');
391 // Get a critieria instance
392 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
394 // Add search criteria
395 $searchInstance->addCriteria(UserDatabaseWrapper::DB_COLUMN_USERNAME, $this->getUserName());
396 $searchInstance->setLimit(1);
398 // Now get another criteria
399 $updateInstance = ObjectFactory::createObjectByConfiguredName('update_criteria_class');
401 // Add criteria entry which we shall update
402 $updateInstance->addCriteria($fieldName, $fieldValue);
404 // Add the search criteria for searching for the right entry
405 $updateInstance->setSearchInstance($searchInstance);
407 // Set wrapper class name
408 $updateInstance->setWrapperConfigEntry('user_db_wrapper_class');
410 // Remember the update in database result
411 $this->getResultInstance()->add2UpdateQueue($updateInstance);
415 * Announces this hub to the upper (bootstrap or list) hubs. After this is
416 * successfully done the given task is unregistered from the handler. This
417 * might look a bit overloaded here but the announcement phase isn't a
418 * simple "Hello there" message, it may later on also contain more
419 * informations like the object list.
421 * @param $taskInstance The task instance running this announcement
423 * @throws HubAlreadyAnnouncedException If this hub is already announced
424 * @todo Change the first if() block to check for a specific state
426 public function announceSelfToUpperNodes (Taskable $taskInstance) {
427 // Is this hub node announced?
428 if ($this->hubIsAnnounced === true) {
429 // Already announced!
430 throw new HubAlreadyAnnouncedException($this, self::EXCEPTION_HUB_ALREADY_ANNOUNCED);
434 $this->debugOutput('HUB-Announcement: START (taskInstance=' . $taskInstance->__toString(). ')');
436 // Get a helper instance
437 $helperInstance = ObjectFactory::createObjectByConfiguredName('hub_announcement_helper_class', array($this));
439 // Load the announcement descriptor
440 $helperInstance->loadDescriptorXml();
442 // Set some dummy configuration entries, e.g. node_status
443 $this->getConfigInstance()->setConfigEntry('node_status', $this->getStateInstance()->getStateName());
445 // Compile all variables
446 $helperInstance->getTemplateInstance()->compileConfigInVariables();
448 // "Publish" the descriptor by sending it to the bootstrap/list nodes
449 $helperInstance->sendPackage($this);
451 // Change the state, this should be the last line except debug output
452 $this->getStateInstance()->nodeAnnouncedToUpperHubs();
455 $this->debugOutput('HUB-Announcement: FINISHED');
459 * Does a self-connect attempt on the public IP address. This should make
460 * it sure, we are reachable from outside world. For this kind of package we
461 * don't need that overload we have in the announcement phase.
463 * @param $taskInstance The task instance running this announcement
466 public function doSelfConnection (Taskable $taskInstance) {
468 $this->debugOutput('HUB: Self Connection: START (taskInstance=' . $taskInstance->__toString(). ')');
470 // Get a helper instance
471 $helperInstance = ObjectFactory::createObjectByConfiguredName('hub_self_connect_helper_class', array($this));
473 // Load the descriptor (XML) file
474 $helperInstance->loadDescriptorXml();
476 // And send the package away
477 $helperInstance->sendPackage($this);
480 $this->debugOutput('HUB: Self Connection: FINISHED');
484 * Activates the hub by doing some final preparation and setting
485 * $hubIsActive to true
487 * @param $requestInstance A Requestable class
488 * @param $responseInstance A Responseable class
491 public function activateNode (Requestable $requestInstance, Responseable $responseInstance) {
492 // Checks wether a listener is still active and shuts it down if one
493 // is still listening.
494 if (($this->determineIfListenerIsActive()) && ($this->getIsActive())) {
495 // Shutdown them down before they can hurt anything
496 $this->shutdownListenerPool();
499 // Get the controller here
500 $controllerInstance = Registry::getRegistry()->getInstance('controller');
502 // Run all filters for the hub activation
503 $controllerInstance->executeActivationFilters($requestInstance, $responseInstance);
505 // ----------------------- Last step from here ------------------------
506 // Activate the hub. This is ALWAYS the last step in this method
507 $this->getStateInstance()->nodeIsActivated();
508 // ---------------------- Last step until here ------------------------
512 * Initializes the listener pool (class)
516 public function initializeListenerPool () {
518 $this->debugOutput('HUB: Initialize listener: START');
520 // Get a new pool instance
521 $this->setListenerPoolInstance(ObjectFactory::createObjectByConfiguredName('listener_pool_class', array($this)));
523 // Get an instance of the low-level listener
524 $listenerInstance = ObjectFactory::createObjectByConfiguredName('tcp_listener_class', array($this));
526 // Setup address and port
527 $listenerInstance->setListenAddressByConfiguration('node_listen_addr');
530 * All nodes can now use the same configuration entry because it can be
531 * customized in config-local.php.
533 $listenerInstance->setListenPortByConfiguration('node_tcp_listen_port');
535 // Initialize the listener
536 $listenerInstance->initListener();
538 // Get a decorator class
539 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('hub_tcp_listener_class', array($listenerInstance));
541 // Add this listener to the pool
542 $this->getListenerPoolInstance()->addListener($decoratorInstance);
544 // Get a decorator class
545 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('client_tcp_listener_class', array($listenerInstance));
547 // Add this listener to the pool
548 $this->getListenerPoolInstance()->addListener($decoratorInstance);
550 // Get an instance of the low-level listener
551 $listenerInstance = ObjectFactory::createObjectByConfiguredName('udp_listener_class', array($this));
553 // Setup address and port
554 $listenerInstance->setListenAddressByConfiguration('node_listen_addr');
557 * All nodes can now use the same configuration entry because it can be
558 * customized in config-local.php.
560 $listenerInstance->setListenPortByConfiguration('node_udp_listen_port');
562 // Initialize the listener
563 $listenerInstance->initListener();
565 // Get a decorator class
566 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('hub_udp_listener_class', array($listenerInstance));
568 // Add this listener to the pool
569 $this->getListenerPoolInstance()->addListener($decoratorInstance);
571 // Get a decorator class
572 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('client_udp_listener_class', array($listenerInstance));
574 // Add this listener to the pool
575 $this->getListenerPoolInstance()->addListener($decoratorInstance);
578 $this->debugOutput('HUB: Initialize listener: FINISHED.');
582 * Restores a previously stored node list from database
586 public function bootstrapRestoreNodeList () {
588 $this->debugOutput('HUB: Restore node list: START');
590 // Get a wrapper instance
591 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('node_list_db_wrapper_class');
593 // Now get a search criteria instance
594 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
596 // Search for the node number zero which is hard-coded the default
597 // @TODO Add some criteria, e.g. if the node is active or so
598 //$searchInstance->addCriteria(NodeListDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
599 //$searchInstance->addCriteria(NodeListDatabaseWrapper::DB_COLUMN_NODE_TYPE, $this->getRequestInstance()->getRequestElement('mode'));
600 //$searchInstance->setLimit(1);
603 $resultInstance = $wrapperInstance->doSelectByCriteria($searchInstance);
606 if ($resultInstance->next()) {
607 $this->partialStub('Do something for restoring the list.');
609 //$this->debugOutput('HUB: ');
611 // No previously saved node list found!
612 $this->debugOutput('HUB: No previously saved node list found. This is fine.');
616 $this->debugOutput('HUB: Restore node list: FINISHED.');
620 * Getter for isActive attribute
622 * @return $isActive Wether the hub is active
624 public final function getIsActive () {
625 return $this->isActive;
629 * Enables (default) or disables isActive flag
631 * @param $isActive Wether the hub is active
634 public final function enableIsActive ($isActive = true) {
635 $this->isActive = (bool) $isActive;
639 * "Getter for address:port combination
641 * @param $handlerInstance A valid Networkable instance
642 * @return $addressPort A address:port combination for this node
644 public final function getAddressPort (Networkable $handlerInstance) {
645 // Construct config entry
646 $configEntry = 'node_' . $handlerInstance->getHandlerName() . '_listen_port';
649 $addressPort = $this->getConfigInstance()->detectServerAddress() . ':' . $this->getConfigInstance()->getConfigEntry($configEntry);