3 * A general hub node class
5 * @author Roland Haeder <webmaster@ship-simu.org>
7 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2012 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 (default: false)
60 private $isActive = false;
63 * Whether this node accepts announcements (default: false)
65 private $acceptAnnouncements = false;
68 * Protected constructor
70 * @param $className Name of the class
73 protected function __construct ($className) {
74 // Call parent constructor
75 parent::__construct($className);
77 // Init state which sets the state to 'init'
82 * Initializes the node's state which sets it to 'init'
86 private function initState() {
88 * Get the state factory and create the initial state, we don't need
89 * the state instance here
91 NodeStateFactory::createNodeStateInstanceByName('init', $this);
95 * Setter for query instance
97 * @param $connectorInstance Our new query instance
100 private final function setQueryConnectorInstance (Connectable $connectorInstance) {
101 $this->queryConnectorInstance = $connectorInstance;
105 * Getter for query instance
107 * @return $connectorInstance Our new query instance
109 public final function getQueryConnectorInstance () {
110 return $this->queryConnectorInstance;
114 * Setter for queue instance
116 * @param $connectorInstance Our new queue instance
119 private final function setQueueConnectorInstance (Connectable $connectorInstance) {
120 $this->queueConnectorInstance = $connectorInstance;
124 * Getter for queue instance
126 * @return $connectorInstance Our new queue instance
128 public final function getQueueConnectorInstance () {
129 return $this->queueConnectorInstance;
133 * Getter for boot IP/port combination
135 * @return $bootIpPort The IP/port combination of the boot node
137 protected final function getBootIpPort () {
138 return $this->bootIpPort;
142 * Checks whether the given IP address matches one of the bootstrapping nodes
144 * @param $remoteAddr IP address to checkout against our bootstrapping list
145 * @return $isFound Whether the IP is found
147 protected function ifAddressMatchesBootstrappingNodes ($remoteAddr) {
148 // By default nothing is found
151 // Run through all configured IPs
152 foreach (explode(BaseHubSystem::BOOTSTRAP_NODES_SEPARATOR, $this->getConfigInstance()->getConfigEntry('hub_bootstrap_nodes')) as $ipPort) {
153 // Split it up in IP/port
154 $ipPortArray = explode(':', $ipPort);
157 if ($ipPortArray[0] == $remoteAddr) {
161 // Remember the port number
162 $this->bootIpPort = $ipPort;
165 $this->debugOutput('BOOTSTRAP: ' . __FUNCTION__ . '[' . __LINE__ . ']: IP matches remote address ' . $ipPort . '.');
167 // Stop further searching
169 } elseif ($ipPortArray[0] == $this->getConfigInstance()->getConfigEntry('node_listen_addr')) {
170 // IP matches listen address. At this point we really don't care
171 // if we can really listen on that address
174 // Remember the port number
175 $this->bootIpPort = $ipPort;
178 $this->debugOutput('BOOTSTRAP: ' . __FUNCTION__ . '[' . __LINE__ . ']: IP matches listen address ' . $ipPort . '.');
180 // Stop further searching
190 * Outputs the console teaser. This should only be executed on startup or
191 * full restarts. This method generates some space around the teaser.
195 public function outputConsoleTeaser () {
196 // Get the app instance (for shortening our code)
197 $app = $this->getApplicationInstance();
200 $this->debugOutput(' ');
201 $this->debugOutput($app->getAppName() . ' v' . $app->getAppVersion() . ' - ' . $this->getRequestInstance()->getRequestElement('mode') . ' mode active');
202 $this->debugOutput('Copyright (c) 2007 - 2008 Roland Haeder, 2009 - 2012 Hub Developer Team');
203 $this->debugOutput(' ');
204 $this->debugOutput('This program comes with ABSOLUTELY NO WARRANTY; for details see docs/COPYING.');
205 $this->debugOutput('This is free software, and you are welcome to redistribute it under certain');
206 $this->debugOutput('conditions; see docs/COPYING for details.');
207 $this->debugOutput(' ');
211 * Generic method to acquire a hub-id. On first run this generates a new one
212 * based on many pseudo-random data. On any later run, unless the id
213 * got not removed from database, it will be restored from the database.
215 * @param $requestInstance A Requestable class
216 * @param $responseInstance A Responseable class
219 public function bootstrapAcquireNodeId (Requestable $requestInstance, Responseable $responseInstance) {
220 // Get a wrapper instance
221 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('node_info_db_wrapper_class');
223 // Now get a search criteria instance
224 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
226 // Search for the node number zero which is hard-coded the default
227 $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
228 $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_TYPE, $this->getRequestInstance()->getRequestElement('mode'));
229 $searchInstance->setLimit(1);
232 $resultInstance = $wrapperInstance->doSelectByCriteria($searchInstance);
235 if ($resultInstance->next()) {
236 // Save the result instance in this class
237 $this->setResultInstance($resultInstance);
239 // Get the node id from result and set it
240 $this->setNodeId($this->getField(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_ID));
243 $this->debugOutput('BOOTSTRAP: Re-using found node-id: ' . $this->getNodeId() . '');
245 // Get an RNG instance (Random Number Generator)
246 $rngInstance = ObjectFactory::createObjectByConfiguredName('rng_class');
248 // Generate a pseudo-random string
249 $randomString = $rngInstance->randomString(255) . ':' . $this->getBootIpPort() . ':' . $this->getRequestInstance()->getRequestElement('mode');
251 // Get a crypto instance
252 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
254 // Hash and encrypt the string so we become a node id (also documented as "hub id")
255 $this->setNodeId($cryptoInstance->hashString($cryptoInstance->encryptString($randomString)));
257 // Register the node id with our wrapper
258 $wrapperInstance->registerNodeId($this, $this->getRequestInstance());
261 $this->debugOutput('BOOTSTRAP: Created new node-id: ' . $this->getNodeId() . '');
266 * Generates a session id which will be sent to the other hubs and peers
270 public function bootstrapGenerateSessionId () {
271 // Get an RNG instance
272 $rngInstance = ObjectFactory::createObjectByConfiguredName('rng_class');
274 // Generate a pseudo-random string
275 $randomString = $rngInstance->randomString(255) . ':' . $this->getBootIpPort() . ':' . $this->getRequestInstance()->getRequestElement('mode');
277 // Get a crypto instance
278 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
280 // Hash and encrypt the string so we become a "node id" aka Hub-Id
281 $this->setSessionId($cryptoInstance->hashString($cryptoInstance->encryptString($randomString)));
283 // Get a wrapper instance
284 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('node_info_db_wrapper_class');
286 // Register the node id with our wrapper
287 $wrapperInstance->registerSessionId($this, $this->getRequestInstance());
290 $this->debugOutput('BOOTSTRAP: Created new session-id: ' . $this->getSessionId() . '');
292 // Change the state because the node has auired a hub id
293 $this->getStateInstance()->nodeGeneratedSessionId();
297 * Initializes queues which every node needs
301 protected function initGenericQueues () {
303 $this->debugOutput('BOOTSTRAP: Initialize queues: START');
305 // Set the query connector instance
306 $this->setQueryConnectorInstance(ObjectFactory::createObjectByConfiguredName('query_connector_class', array($this)));
309 $this->getQueryConnectorInstance()->doTestQuery();
311 // Set the queue connector instance
312 $this->setQueueConnectorInstance(ObjectFactory::createObjectByConfiguredName('queue_connector_class', array($this)));
315 $this->getQueueConnectorInstance()->doTestQueue();
318 $this->debugOutput('BOOTSTRAP: Initialize queues: FINISHED');
322 * Adds hub data elements to a given dataset instance
324 * @param $criteriaInstance An instance of a storeable criteria
325 * @param $requestInstance An instance of a Requestable class
328 public function addElementsToDataSet (StoreableCriteria $criteriaInstance, Requestable $requestInstance) {
329 // Add node number and type
330 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
331 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_TYPE, $requestInstance->getRequestElement('mode'));
334 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_ID, $this->getNodeId());
336 // Add the session id if acquired
337 if ($this->getSessionId() != '') {
338 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_SESSION_ID, $this->getSessionId());
343 * Updates a given field with new value
345 * @param $fieldName Field to update
346 * @param $fieldValue New value to store
348 * @throws DatabaseUpdateSupportException If this class does not support database updates
349 * @todo Try to make this method more generic so we can move it in BaseFrameworkSystem
351 public function updateDatabaseField ($fieldName, $fieldValue) {
353 $this->partialStub('Unfinished!');
356 // Get a critieria instance
357 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
359 // Add search criteria
360 $searchInstance->addCriteria(UserDatabaseWrapper::DB_COLUMN_USERNAME, $this->getUserName());
361 $searchInstance->setLimit(1);
363 // Now get another criteria
364 $updateInstance = ObjectFactory::createObjectByConfiguredName('update_criteria_class');
366 // Add criteria entry which we shall update
367 $updateInstance->addCriteria($fieldName, $fieldValue);
369 // Add the search criteria for searching for the right entry
370 $updateInstance->setSearchInstance($searchInstance);
372 // Set wrapper class name
373 $updateInstance->setWrapperConfigEntry('user_db_wrapper_class');
375 // Remember the update in database result
376 $this->getResultInstance()->add2UpdateQueue($updateInstance);
380 * Announces this hub to the upper (bootstrap or list) hubs. After this is
381 * successfully done the given task is unregistered from the handler. This
382 * might look a bit overloaded here but the announcement phase isn't a
383 * simple "Hello there" message, it may later on also contain more
384 * informations like the object list.
386 * @param $taskInstance The task instance running this announcement
388 * @throws HubAlreadyAnnouncedException If this hub is already announced
389 * @todo Change the first if() block to check for a specific state
391 public function announceSelfToUpperNodes (Taskable $taskInstance) {
392 // Is this hub node announced?
393 if ($this->hubIsAnnounced === true) {
394 // Already announced!
395 throw new HubAlreadyAnnouncedException($this, self::EXCEPTION_HUB_ALREADY_ANNOUNCED);
398 // Set some dummy configuration entries, e.g. node_status
399 $this->getConfigInstance()->setConfigEntry('node_status', $this->getStateInstance()->getStateName());
402 $this->debugOutput('HUB-Announcement: START (taskInstance=' . $taskInstance->__toString(). ')');
404 // Get a helper instance
405 $helperInstance = ObjectFactory::createObjectByConfiguredName('hub_announcement_helper_class');
407 // Load the announcement descriptor
408 $helperInstance->loadDescriptorXml();
410 // Compile all variables
411 $helperInstance->getTemplateInstance()->compileConfigInVariables();
413 // "Publish" the descriptor by sending it to the bootstrap/list nodes
414 $helperInstance->sendPackage($this);
416 // Change the state, this should be the last line except debug output
417 $this->getStateInstance()->nodeAnnouncedToUpperHubs();
420 $this->debugOutput('HUB-Announcement: FINISHED');
424 * Does a self-connect attempt on the public IP address. This should make
425 * it sure, we are reachable from outside world. For this kind of package we
426 * don't need that overload we have in the announcement phase.
428 * @param $taskInstance The task instance running this announcement
431 public function doSelfConnection (Taskable $taskInstance) {
433 $this->debugOutput('HUB: Self Connection: START (taskInstance=' . $taskInstance->__toString(). ')');
435 // Get a helper instance
436 $helperInstance = ObjectFactory::createObjectByConfiguredName('hub_self_connect_helper_class', array($this));
438 // Load the descriptor (XML) file
439 $helperInstance->loadDescriptorXml();
441 // Compile all variables
442 $helperInstance->getTemplateInstance()->compileConfigInVariables();
444 // And send the package away
445 $helperInstance->sendPackage($this);
448 $this->debugOutput('HUB: Self Connection: FINISHED');
452 * Activates the hub by doing some final preparation and setting
453 * $hubIsActive to true
455 * @param $requestInstance A Requestable class
456 * @param $responseInstance A Responseable class
459 public function activateNode (Requestable $requestInstance, Responseable $responseInstance) {
460 // Checks whether a listener is still active and shuts it down if one
461 // is still listening.
462 if (($this->determineIfListenerIsActive()) && ($this->isNodeActive())) {
463 // Shutdown them down before they can hurt anything
464 $this->shutdownListenerPool();
467 // Get the controller here
468 $controllerInstance = Registry::getRegistry()->getInstance('controller');
470 // Run all filters for the hub activation
471 $controllerInstance->executeActivationFilters($requestInstance, $responseInstance);
473 // ----------------------- Last step from here ------------------------
474 // Activate the hub. This is ALWAYS the last step in this method
475 $this->getStateInstance()->nodeIsActivated();
476 // ---------------------- Last step until here ------------------------
480 * Initializes the listener pool (class)
484 public function initializeListenerPool () {
486 $this->debugOutput('HUB: Initialize listener: START');
488 // Get a new pool instance
489 $this->setListenerPoolInstance(ObjectFactory::createObjectByConfiguredName('listener_pool_class', array($this)));
491 // Get an instance of the low-level listener
492 $listenerInstance = ObjectFactory::createObjectByConfiguredName('tcp_listener_class', array($this));
494 // Setup address and port
495 $listenerInstance->setListenAddressByConfiguration('node_listen_addr');
498 * All nodes can now use the same configuration entry because it can be
499 * customized in config-local.php.
501 $listenerInstance->setListenPortByConfiguration('node_tcp_listen_port');
503 // Initialize the listener
504 $listenerInstance->initListener();
506 // Get a decorator class
507 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('hub_tcp_listener_class', array($listenerInstance));
509 // Add this listener to the pool
510 $this->getListenerPoolInstance()->addListener($decoratorInstance);
512 // Get a decorator class
513 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('client_tcp_listener_class', array($listenerInstance));
515 // Add this listener to the pool
516 $this->getListenerPoolInstance()->addListener($decoratorInstance);
518 // Get an instance of the low-level listener
519 $listenerInstance = ObjectFactory::createObjectByConfiguredName('udp_listener_class', array($this));
521 // Setup address and port
522 $listenerInstance->setListenAddressByConfiguration('node_listen_addr');
525 * All nodes can now use the same configuration entry because it can be
526 * customized in config-local.php.
528 $listenerInstance->setListenPortByConfiguration('node_udp_listen_port');
530 // Initialize the listener
531 $listenerInstance->initListener();
533 // Get a decorator class
534 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('hub_udp_listener_class', array($listenerInstance));
536 // Add this listener to the pool
537 $this->getListenerPoolInstance()->addListener($decoratorInstance);
539 // Get a decorator class
540 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('client_udp_listener_class', array($listenerInstance));
542 // Add this listener to the pool
543 $this->getListenerPoolInstance()->addListener($decoratorInstance);
546 $this->debugOutput('HUB: Initialize listener: FINISHED.');
550 * Restores a previously stored node list from database
554 public function bootstrapRestoreNodeList () {
556 $this->debugOutput('HUB: Restore node list: START');
558 // Get a wrapper instance
559 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('node_list_db_wrapper_class');
561 // Now get a search criteria instance
562 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
564 // Search for the node number zero which is hard-coded the default
565 // @TODO Add some criteria, e.g. if the node is active or so
566 //$searchInstance->addCriteria(NodeListDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
567 //$searchInstance->addCriteria(NodeListDatabaseWrapper::DB_COLUMN_NODE_TYPE, $this->getRequestInstance()->getRequestElement('mode'));
568 //$searchInstance->setLimit(1);
571 $resultInstance = $wrapperInstance->doSelectByCriteria($searchInstance);
574 if ($resultInstance->next()) {
575 $this->partialStub('Do something for restoring the list.');
577 //$this->debugOutput('HUB: ');
579 // No previously saved node list found!
580 $this->debugOutput('HUB: No previously saved node list found. This is fine.');
584 $this->debugOutput('HUB: Restore node list: FINISHED.');
588 * Getter for isActive attribute
590 * @return $isActive Whether the hub is active
592 public final function isNodeActive () {
593 return $this->isActive;
597 * Enables (default) or disables isActive flag
599 * @param $isActive Whether the hub is active
602 public final function enableIsActive ($isActive = true) {
603 $this->isActive = (bool) $isActive;
607 * Checks whether this node accepts announcements
609 * @return $acceptsAnnouncements Whether this node accepts announcements
611 public final function isAcceptingAnnouncements () {
612 // Check it (this node must be active and not shutdown!)
613 $acceptsAnnouncements = (($this->acceptsAnnouncements === true) && ($this->isNodeActive());
616 return $acceptsAnnouncements;
620 * Enables whether this node accepts announcements
622 * @param $acceptsAnnouncements Whether this node accepts announcements (default: true)
625 protected final function enableAcceptingAnnouncements ($acceptsAnnouncements = true) {
626 $this->acceptAnnouncements = $acceptsAnnouncements;
631 * "Getter for address:port combination
633 * @param $handlerInstance A valid Networkable instance
634 * @return $addressPort A address:port combination for this node
636 public final function getAddressPort (Networkable $handlerInstance) {
637 // Construct config entry
638 $configEntry = 'node_' . $handlerInstance->getHandlerName() . '_listen_port';
641 $addressPort = $this->getConfigInstance()->detectServerAddress() . ':' . $this->getConfigInstance()->getConfigEntry($configEntry);