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 * Whether this node is anncounced (KEEP ON false!)
55 private $hubIsAnnounced = false;
58 * Whether 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);
90 * Setter for query instance
92 * @param $connectorInstance Our new query instance
95 private final function setQueryConnectorInstance (Connectable $connectorInstance) {
96 $this->queryConnectorInstance = $connectorInstance;
100 * Getter for query instance
102 * @return $connectorInstance Our new query instance
104 public final function getQueryConnectorInstance () {
105 return $this->queryConnectorInstance;
109 * Setter for queue instance
111 * @param $connectorInstance Our new queue instance
114 private final function setQueueConnectorInstance (Connectable $connectorInstance) {
115 $this->queueConnectorInstance = $connectorInstance;
119 * Getter for queue instance
121 * @return $connectorInstance Our new queue instance
123 public final function getQueueConnectorInstance () {
124 return $this->queueConnectorInstance;
128 * Getter for boot IP/port combination
130 * @return $bootIpPort The IP/port combination of the boot node
132 protected final function getBootIpPort () {
133 return $this->bootIpPort;
137 * Checks whether the given IP address matches one of the bootstrapping nodes
139 * @param $remoteAddr IP address to checkout against our bootstrapping list
140 * @return $isFound Whether the IP is found
142 protected function ifAddressMatchesBootstrappingNodes ($remoteAddr) {
143 // By default nothing is found
146 // Run through all configured IPs
147 foreach (explode(BaseHubSystem::BOOTSTRAP_NODES_SEPARATOR, $this->getConfigInstance()->getConfigEntry('hub_bootstrap_nodes')) as $ipPort) {
148 // Split it up in IP/port
149 $ipPortArray = explode(':', $ipPort);
152 if ($ipPortArray[0] == $remoteAddr) {
156 // Remember the port number
157 $this->bootIpPort = $ipPort;
160 $this->debugOutput('BOOTSTRAP: ' . __FUNCTION__ . '[' . __LINE__ . ']: IP matches remote address ' . $ipPort . '.');
162 // Stop further searching
164 } elseif ($ipPortArray[0] == $this->getConfigInstance()->getConfigEntry('node_listen_addr')) {
165 // IP matches listen address. At this point we really don't care
166 // if we can really listen on that address
169 // Remember the port number
170 $this->bootIpPort = $ipPort;
173 $this->debugOutput('BOOTSTRAP: ' . __FUNCTION__ . '[' . __LINE__ . ']: IP matches listen address ' . $ipPort . '.');
175 // Stop further searching
185 * Outputs the console teaser. This should only be executed on startup or
186 * full restarts. This method generates some space around the teaser.
190 public function outputConsoleTeaser () {
191 // Get the app instance (for shortening our code)
192 $app = $this->getApplicationInstance();
195 $this->debugOutput(' ');
196 $this->debugOutput($app->getAppName() . ' v' . $app->getAppVersion() . ' - ' . $this->getRequestInstance()->getRequestElement('mode') . ' mode active');
197 $this->debugOutput('Copyright (c) 2007 - 2008 Roland Haeder, 2009 - 2011 Hub Developer Team');
198 $this->debugOutput(' ');
199 $this->debugOutput('This program comes with ABSOLUTELY NO WARRANTY; for details see docs/COPYING.');
200 $this->debugOutput('This is free software, and you are welcome to redistribute it under certain');
201 $this->debugOutput('conditions; see docs/COPYING for details.');
202 $this->debugOutput(' ');
206 * Generic method to acquire a hub-id. On first run this generates a new one
207 * based on many pseudo-random data. On any later run, unless the id
208 * got not removed from database, it will be restored from the database.
210 * @param $requestInstance A Requestable class
211 * @param $responseInstance A Responseable class
214 public function bootstrapAcquireNodeId (Requestable $requestInstance, Responseable $responseInstance) {
215 // Get a wrapper instance
216 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('node_info_db_wrapper_class');
218 // Now get a search criteria instance
219 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
221 // Search for the node number zero which is hard-coded the default
222 $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
223 $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_TYPE, $this->getRequestInstance()->getRequestElement('mode'));
224 $searchInstance->setLimit(1);
227 $resultInstance = $wrapperInstance->doSelectByCriteria($searchInstance);
230 if ($resultInstance->next()) {
231 // Save the result instance in this class
232 $this->setResultInstance($resultInstance);
234 // Get the node id from result and set it
235 $this->setNodeId($this->getField(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_ID));
238 $this->debugOutput('BOOTSTRAP: Re-using found node-id: ' . $this->getNodeId() . '');
240 // Get an RNG instance (Random Number Generator)
241 $rngInstance = ObjectFactory::createObjectByConfiguredName('rng_class');
243 // Generate a pseudo-random string
244 $randomString = $rngInstance->randomString(255) . ':' . $this->getBootIpPort() . ':' . $this->getRequestInstance()->getRequestElement('mode');
246 // Get a crypto instance
247 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
249 // Hash and encrypt the string so we become a node id (also documented as "hub id")
250 $this->setNodeId($cryptoInstance->hashString($cryptoInstance->encryptString($randomString)));
252 // Register the node id with our wrapper
253 $wrapperInstance->registerNodeId($this, $this->getRequestInstance());
256 $this->debugOutput('BOOTSTRAP: Created new node-id: ' . $this->getNodeId() . '');
261 * Generates a session id which will be sent to the other hubs and peers
265 public function bootstrapGenerateSessionId () {
266 // Get an RNG instance
267 $rngInstance = ObjectFactory::createObjectByConfiguredName('rng_class');
269 // Generate a pseudo-random string
270 $randomString = $rngInstance->randomString(255) . ':' . $this->getBootIpPort() . ':' . $this->getRequestInstance()->getRequestElement('mode');
272 // Get a crypto instance
273 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
275 // Hash and encrypt the string so we become a "node id" aka Hub-Id
276 $this->setSessionId($cryptoInstance->hashString($cryptoInstance->encryptString($randomString)));
278 // Get a wrapper instance
279 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('node_info_db_wrapper_class');
281 // Register the node id with our wrapper
282 $wrapperInstance->registerSessionId($this, $this->getRequestInstance());
285 $this->debugOutput('BOOTSTRAP: Created new session-id: ' . $this->getSessionId() . '');
287 // Change the state because the node has auired a hub id
288 $this->getStateInstance()->nodeGeneratedSessionId();
292 * Initializes queues which every node needs
296 protected function initGenericQueues () {
298 $this->debugOutput('BOOTSTRAP: Initialize queues: START');
300 // Set the query connector instance
301 $this->setQueryConnectorInstance(ObjectFactory::createObjectByConfiguredName('query_connector_class', array($this)));
304 $this->getQueryConnectorInstance()->doTestQuery();
306 // Set the queue connector instance
307 $this->setQueueConnectorInstance(ObjectFactory::createObjectByConfiguredName('queue_connector_class', array($this)));
310 $this->getQueueConnectorInstance()->doTestQueue();
313 $this->debugOutput('BOOTSTRAP: Initialize queues: FINISHED');
317 * Adds hub data elements to a given dataset instance
319 * @param $criteriaInstance An instance of a storeable criteria
320 * @param $requestInstance An instance of a Requestable class
323 public function addElementsToDataSet (StoreableCriteria $criteriaInstance, Requestable $requestInstance) {
324 // Add node number and type
325 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
326 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_TYPE, $requestInstance->getRequestElement('mode'));
329 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_ID, $this->getNodeId());
331 // Add the session id if acquired
332 if ($this->getSessionId() != '') {
333 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_SESSION_ID, $this->getSessionId());
338 * Updates a given field with new value
340 * @param $fieldName Field to update
341 * @param $fieldValue New value to store
343 * @throws DatabaseUpdateSupportException If this class does not support database updates
344 * @todo Try to make this method more generic so we can move it in BaseFrameworkSystem
346 public function updateDatabaseField ($fieldName, $fieldValue) {
348 $this->partialStub('Unfinished!');
351 // Get a critieria instance
352 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
354 // Add search criteria
355 $searchInstance->addCriteria(UserDatabaseWrapper::DB_COLUMN_USERNAME, $this->getUserName());
356 $searchInstance->setLimit(1);
358 // Now get another criteria
359 $updateInstance = ObjectFactory::createObjectByConfiguredName('update_criteria_class');
361 // Add criteria entry which we shall update
362 $updateInstance->addCriteria($fieldName, $fieldValue);
364 // Add the search criteria for searching for the right entry
365 $updateInstance->setSearchInstance($searchInstance);
367 // Set wrapper class name
368 $updateInstance->setWrapperConfigEntry('user_db_wrapper_class');
370 // Remember the update in database result
371 $this->getResultInstance()->add2UpdateQueue($updateInstance);
375 * Announces this hub to the upper (bootstrap or list) hubs. After this is
376 * successfully done the given task is unregistered from the handler. This
377 * might look a bit overloaded here but the announcement phase isn't a
378 * simple "Hello there" message, it may later on also contain more
379 * informations like the object list.
381 * @param $taskInstance The task instance running this announcement
383 * @throws HubAlreadyAnnouncedException If this hub is already announced
384 * @todo Change the first if() block to check for a specific state
386 public function announceSelfToUpperNodes (Taskable $taskInstance) {
387 // Is this hub node announced?
388 if ($this->hubIsAnnounced === true) {
389 // Already announced!
390 throw new HubAlreadyAnnouncedException($this, self::EXCEPTION_HUB_ALREADY_ANNOUNCED);
393 // Set some dummy configuration entries, e.g. node_status
394 $this->getConfigInstance()->setConfigEntry('node_status', $this->getStateInstance()->getStateName());
397 $this->debugOutput('HUB-Announcement: START (taskInstance=' . $taskInstance->__toString(). ')');
399 // Get a helper instance
400 $helperInstance = ObjectFactory::createObjectByConfiguredName('hub_announcement_helper_class');
402 // Load the announcement descriptor
403 $helperInstance->loadDescriptorXml();
405 // Compile all variables
406 $helperInstance->getTemplateInstance()->compileConfigInVariables();
408 // "Publish" the descriptor by sending it to the bootstrap/list nodes
409 $helperInstance->sendPackage($this);
411 // Change the state, this should be the last line except debug output
412 $this->getStateInstance()->nodeAnnouncedToUpperHubs();
415 $this->debugOutput('HUB-Announcement: FINISHED');
419 * Does a self-connect attempt on the public IP address. This should make
420 * it sure, we are reachable from outside world. For this kind of package we
421 * don't need that overload we have in the announcement phase.
423 * @param $taskInstance The task instance running this announcement
426 public function doSelfConnection (Taskable $taskInstance) {
428 $this->debugOutput('HUB: Self Connection: START (taskInstance=' . $taskInstance->__toString(). ')');
430 // Get a helper instance
431 $helperInstance = ObjectFactory::createObjectByConfiguredName('hub_self_connect_helper_class', array($this));
433 // Load the descriptor (XML) file
434 $helperInstance->loadDescriptorXml();
436 // And send the package away
437 $helperInstance->sendPackage($this);
440 $this->debugOutput('HUB: Self Connection: FINISHED');
444 * Activates the hub by doing some final preparation and setting
445 * $hubIsActive to true
447 * @param $requestInstance A Requestable class
448 * @param $responseInstance A Responseable class
451 public function activateNode (Requestable $requestInstance, Responseable $responseInstance) {
452 // Checks whether a listener is still active and shuts it down if one
453 // is still listening.
454 if (($this->determineIfListenerIsActive()) && ($this->getIsActive())) {
455 // Shutdown them down before they can hurt anything
456 $this->shutdownListenerPool();
459 // Get the controller here
460 $controllerInstance = Registry::getRegistry()->getInstance('controller');
462 // Run all filters for the hub activation
463 $controllerInstance->executeActivationFilters($requestInstance, $responseInstance);
465 // ----------------------- Last step from here ------------------------
466 // Activate the hub. This is ALWAYS the last step in this method
467 $this->getStateInstance()->nodeIsActivated();
468 // ---------------------- Last step until here ------------------------
472 * Initializes the listener pool (class)
476 public function initializeListenerPool () {
478 $this->debugOutput('HUB: Initialize listener: START');
480 // Get a new pool instance
481 $this->setListenerPoolInstance(ObjectFactory::createObjectByConfiguredName('listener_pool_class', array($this)));
483 // Get an instance of the low-level listener
484 $listenerInstance = ObjectFactory::createObjectByConfiguredName('tcp_listener_class', array($this));
486 // Setup address and port
487 $listenerInstance->setListenAddressByConfiguration('node_listen_addr');
490 * All nodes can now use the same configuration entry because it can be
491 * customized in config-local.php.
493 $listenerInstance->setListenPortByConfiguration('node_tcp_listen_port');
495 // Initialize the listener
496 $listenerInstance->initListener();
498 // Get a decorator class
499 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('hub_tcp_listener_class', array($listenerInstance));
501 // Add this listener to the pool
502 $this->getListenerPoolInstance()->addListener($decoratorInstance);
504 // Get a decorator class
505 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('client_tcp_listener_class', array($listenerInstance));
507 // Add this listener to the pool
508 $this->getListenerPoolInstance()->addListener($decoratorInstance);
510 // Get an instance of the low-level listener
511 $listenerInstance = ObjectFactory::createObjectByConfiguredName('udp_listener_class', array($this));
513 // Setup address and port
514 $listenerInstance->setListenAddressByConfiguration('node_listen_addr');
517 * All nodes can now use the same configuration entry because it can be
518 * customized in config-local.php.
520 $listenerInstance->setListenPortByConfiguration('node_udp_listen_port');
522 // Initialize the listener
523 $listenerInstance->initListener();
525 // Get a decorator class
526 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('hub_udp_listener_class', array($listenerInstance));
528 // Add this listener to the pool
529 $this->getListenerPoolInstance()->addListener($decoratorInstance);
531 // Get a decorator class
532 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('client_udp_listener_class', array($listenerInstance));
534 // Add this listener to the pool
535 $this->getListenerPoolInstance()->addListener($decoratorInstance);
538 $this->debugOutput('HUB: Initialize listener: FINISHED.');
542 * Restores a previously stored node list from database
546 public function bootstrapRestoreNodeList () {
548 $this->debugOutput('HUB: Restore node list: START');
550 // Get a wrapper instance
551 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('node_list_db_wrapper_class');
553 // Now get a search criteria instance
554 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
556 // Search for the node number zero which is hard-coded the default
557 // @TODO Add some criteria, e.g. if the node is active or so
558 //$searchInstance->addCriteria(NodeListDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
559 //$searchInstance->addCriteria(NodeListDatabaseWrapper::DB_COLUMN_NODE_TYPE, $this->getRequestInstance()->getRequestElement('mode'));
560 //$searchInstance->setLimit(1);
563 $resultInstance = $wrapperInstance->doSelectByCriteria($searchInstance);
566 if ($resultInstance->next()) {
567 $this->partialStub('Do something for restoring the list.');
569 //$this->debugOutput('HUB: ');
571 // No previously saved node list found!
572 $this->debugOutput('HUB: No previously saved node list found. This is fine.');
576 $this->debugOutput('HUB: Restore node list: FINISHED.');
580 * Getter for isActive attribute
582 * @return $isActive Whether the hub is active
584 public final function getIsActive () {
585 return $this->isActive;
589 * Enables (default) or disables isActive flag
591 * @param $isActive Whether the hub is active
594 public final function enableIsActive ($isActive = true) {
595 $this->isActive = (bool) $isActive;
599 * "Getter for address:port combination
601 * @param $handlerInstance A valid Networkable instance
602 * @return $addressPort A address:port combination for this node
604 public final function getAddressPort (Networkable $handlerInstance) {
605 // Construct config entry
606 $configEntry = 'node_' . $handlerInstance->getHandlerName() . '_listen_port';
609 $addressPort = $this->getConfigInstance()->detectServerAddress() . ':' . $this->getConfigInstance()->getConfigEntry($configEntry);