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);
399 $this->debugOutput('HUB-Announcement: START (taskInstance=' . $taskInstance->__toString(). ')');
401 // Get a helper instance
402 $helperInstance = ObjectFactory::createObjectByConfiguredName('hub_announcement_helper_class');
404 // Load the announcement descriptor
405 $helperInstance->loadDescriptorXml();
407 // Compile all variables
408 $helperInstance->getTemplateInstance()->compileConfigInVariables();
410 // "Publish" the descriptor by sending it to the bootstrap/list nodes
411 $helperInstance->sendPackage($this);
413 // Change the state, this should be the last line except debug output
414 $this->getStateInstance()->nodeAnnouncedToUpperHubs();
417 $this->debugOutput('HUB-Announcement: FINISHED');
421 * Does a self-connect attempt on the public IP address. This should make
422 * it sure, we are reachable from outside world. For this kind of package we
423 * don't need that overload we have in the announcement phase.
425 * @param $taskInstance The task instance running this announcement
428 public function doSelfConnection (Taskable $taskInstance) {
430 $this->debugOutput('HUB: Self Connection: START (taskInstance=' . $taskInstance->__toString(). ')');
432 // Get a helper instance
433 $helperInstance = ObjectFactory::createObjectByConfiguredName('hub_self_connect_helper_class', array($this));
435 // Load the descriptor (XML) file
436 $helperInstance->loadDescriptorXml();
438 // Compile all variables
439 $helperInstance->getTemplateInstance()->compileConfigInVariables();
441 // And send the package away
442 $helperInstance->sendPackage($this);
445 $this->debugOutput('HUB: Self Connection: FINISHED');
449 * Activates the hub by doing some final preparation and setting
450 * $hubIsActive to true
452 * @param $requestInstance A Requestable class
453 * @param $responseInstance A Responseable class
456 public function activateNode (Requestable $requestInstance, Responseable $responseInstance) {
457 // Checks whether a listener is still active and shuts it down if one
458 // is still listening.
459 if (($this->determineIfListenerIsActive()) && ($this->isNodeActive())) {
460 // Shutdown them down before they can hurt anything
461 $this->shutdownListenerPool();
464 // Get the controller here
465 $controllerInstance = Registry::getRegistry()->getInstance('controller');
467 // Run all filters for the hub activation
468 $controllerInstance->executeActivationFilters($requestInstance, $responseInstance);
470 // ----------------------- Last step from here ------------------------
471 // Activate the hub. This is ALWAYS the last step in this method
472 $this->getStateInstance()->nodeIsActivated();
473 // ---------------------- Last step until here ------------------------
477 * Initializes the listener pool (class)
481 public function initializeListenerPool () {
483 $this->debugOutput('HUB: Initialize listener: START');
485 // Get a new pool instance
486 $this->setListenerPoolInstance(ObjectFactory::createObjectByConfiguredName('listener_pool_class', array($this)));
488 // Get an instance of the low-level listener
489 $listenerInstance = ObjectFactory::createObjectByConfiguredName('tcp_listener_class', array($this));
491 // Setup address and port
492 $listenerInstance->setListenAddressByConfiguration('node_listen_addr');
495 * All nodes can now use the same configuration entry because it can be
496 * customized in config-local.php.
498 $listenerInstance->setListenPortByConfiguration('node_tcp_listen_port');
500 // Initialize the listener
501 $listenerInstance->initListener();
503 // Get a decorator class
504 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('hub_tcp_listener_class', array($listenerInstance));
506 // Add this listener to the pool
507 $this->getListenerPoolInstance()->addListener($decoratorInstance);
509 // Get a decorator class
510 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('client_tcp_listener_class', array($listenerInstance));
512 // Add this listener to the pool
513 $this->getListenerPoolInstance()->addListener($decoratorInstance);
515 // Get an instance of the low-level listener
516 $listenerInstance = ObjectFactory::createObjectByConfiguredName('udp_listener_class', array($this));
518 // Setup address and port
519 $listenerInstance->setListenAddressByConfiguration('node_listen_addr');
522 * All nodes can now use the same configuration entry because it can be
523 * customized in config-local.php.
525 $listenerInstance->setListenPortByConfiguration('node_udp_listen_port');
527 // Initialize the listener
528 $listenerInstance->initListener();
530 // Get a decorator class
531 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('hub_udp_listener_class', array($listenerInstance));
533 // Add this listener to the pool
534 $this->getListenerPoolInstance()->addListener($decoratorInstance);
536 // Get a decorator class
537 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('client_udp_listener_class', array($listenerInstance));
539 // Add this listener to the pool
540 $this->getListenerPoolInstance()->addListener($decoratorInstance);
543 $this->debugOutput('HUB: Initialize listener: FINISHED.');
547 * Restores a previously stored node list from database
551 public function bootstrapRestoreNodeList () {
553 $this->debugOutput('HUB: Restore node list: START');
555 // Get a wrapper instance
556 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('node_list_db_wrapper_class');
558 // Now get a search criteria instance
559 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
561 // Search for the node number zero which is hard-coded the default
562 // @TODO Add some criteria, e.g. if the node is active or so
563 //$searchInstance->addCriteria(NodeListDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
564 //$searchInstance->addCriteria(NodeListDatabaseWrapper::DB_COLUMN_NODE_TYPE, $this->getRequestInstance()->getRequestElement('mode'));
565 //$searchInstance->setLimit(1);
568 $resultInstance = $wrapperInstance->doSelectByCriteria($searchInstance);
571 if ($resultInstance->next()) {
572 $this->partialStub('Do something for restoring the list.');
574 //$this->debugOutput('HUB: ');
576 // No previously saved node list found!
577 $this->debugOutput('HUB: No previously saved node list found. This is fine.');
581 $this->debugOutput('HUB: Restore node list: FINISHED.');
585 * Getter for isActive attribute
587 * @return $isActive Whether the hub is active
589 public final function isNodeActive () {
590 return $this->isActive;
594 * Enables (default) or disables isActive flag
596 * @param $isActive Whether the hub is active
599 public final function enableIsActive ($isActive = true) {
600 $this->isActive = (bool) $isActive;
604 * Checks whether this node accepts announcements
606 * @return $acceptAnnouncements Whether this node accepts announcements
608 public final function isAcceptingAnnouncements () {
609 // Check it (this node must be active and not shutdown!)
610 $acceptAnnouncements = (($this->acceptAnnouncements === true) && ($this->isNodeActive()));
613 return $acceptAnnouncements;
617 * Enables whether this node accepts announcements
619 * @param $acceptAnnouncements Whether this node accepts announcements (default: true)
622 protected final function enableAcceptingAnnouncements ($acceptAnnouncements = true) {
623 $this->acceptAnnouncements = $acceptAnnouncements;
628 * "Getter for address:port combination
630 * @param $handlerInstance A valid Networkable instance
631 * @return $addressPort A address:port combination for this node
633 public final function getAddressPort (Networkable $handlerInstance) {
634 // Construct config entry
635 $configEntry = 'node_' . $handlerInstance->getHandlerName() . '_listen_port';
638 $addressPort = $this->getConfigInstance()->detectServerAddress() . ':' . $this->getConfigInstance()->getConfigEntry($configEntry);
645 * Updates/refreshes node data (e.g. state).
648 * @todo Find more to do here
650 public function updateNodeData () {
651 // Set some dummy configuration entries, e.g. node_status
652 $this->getConfigInstance()->setConfigEntry('node_status', $this->getStateInstance()->getStateName());