3 * A general hub node class
5 * @author Roland Haeder <webmaster@ship-simu.org>
7 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009, 2010 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 {
25 // Exception constants
26 const EXCEPTION_HUB_ALREADY_ANNOUNCED = 0xe00;
29 * IP/port number of bootstrapping node
31 private $bootIpPort = '';
34 * Query connector instance
36 private $connectorInstance = null;
39 * Listener pool instance
41 private $listenerPoolInstance = null;
44 * Wether this node is anncounced (KEEP ON false!)
47 private $hubIsAnnounced = false;
52 private $stateInstance = null;
55 * Protected constructor
57 * @param $className Name of the class
60 protected function __construct ($className) {
61 // Call parent constructor
62 parent::__construct($className);
64 // Init state which sets the state to 'init'
69 * Initializes the node's state which sets it to 'init'
73 private function initState() {
74 // Get the state factory and create the initial state, we don't need
75 // the state instance here
76 StateFactory::createStateInstanceByName('init', $this);
82 * @param $nodeId Our new node id
85 private final function setNodeId ($nodeId) {
87 $this->getConfigInstance()->setConfigEntry('node_id', (string) $nodeId);
93 * @return $nodeId Current node id
95 private final function getNodeId () {
97 return $this->getConfigInstance()->getConfigEntry('node_id');
101 * Setter for listener pool instance
103 * @param $listenerPoolInstance Our new listener pool instance
106 private final function setListenerPoolInstance (PoolableListener $listenerPoolInstance) {
107 $this->listenerPoolInstance = $listenerPoolInstance;
111 * Getter for listener pool instance
113 * @return $listenerPoolInstance Our current listener pool instance
115 public final function getListenerPoolInstance () {
116 return $this->listenerPoolInstance;
120 * Setter for state instance
122 * @param $stateInstance Node's current state instance
125 public final function setStateInstance (Stateable $stateInstance) {
126 $this->stateInstance = $stateInstance;
130 * Getter for state instance
132 * @return $stateInstance Node's current state instance
134 public final function getStateInstance () {
135 return $this->stateInstance;
139 * Setter for session id
141 * @param $sessionId Our new session id
144 private final function setSessionId ($sessionId) {
145 $this->getConfigInstance()->setConfigEntry('session_id', (string) $sessionId);
149 * Getter for session id
151 * @return $sessionId Current session id
153 public final function getSessionId () {
154 return $this->getConfigInstance()->getConfigEntry('session_id');
158 * Setter for query instance
160 * @param $connectorInstance Our new query instance
163 private final function setQueryConnectorInstance (Connectable $connectorInstance) {
164 $this->connectorInstance = $connectorInstance;
168 * Getter for query instance
170 * @return $connectorInstance Our new query instance
172 public final function getQueryConnectorInstance () {
173 return $this->connectorInstance;
177 * Getter for boot IP/port combination
179 * @return $bootIpPort The IP/port combination of the boot node
181 protected final function getBootIpPort () {
182 return $this->bootIpPort;
186 * "Getter" for a printable state name
188 public final function getPrintableState () {
192 // Get the state instance
193 $stateInstance = $this->getStateInstance();
195 // Is it an instance of Stateable?
196 if ($stateInstance instanceof Stateable) {
197 // Then use that state name
198 $stateName = $stateInstance->getStateName();
206 * Checks wether the given IP address matches one of the bootstrapping nodes
208 * @param $remoteAddr IP address to checkout against our bootstrapping list
209 * @return $isFound Wether the IP is found
211 protected function ifAddressMatchesBootstrappingNodes ($remoteAddr) {
212 // By default nothing is found
215 // Run through all configured IPs
216 foreach (explode(',', $this->getConfigInstance()->getConfigEntry('hub_bootstrap_nodes')) as $ipPort) {
217 // Split it up in IP/port
218 $ipPortArray = explode(':', $ipPort);
221 if ($ipPortArray[0] == $remoteAddr) {
225 // Remember the port number
226 $this->bootIpPort = $ipPort;
229 $this->debugOutput('BOOTSTRAP: ' . __FUNCTION__ . '[' . __LINE__ . ']: IP matches remote address ' . $ipPort . '.');
231 // Stop further searching
233 } elseif ($ipPortArray[0] == $this->getConfigInstance()->getConfigEntry('node_listen_addr')) {
234 // IP matches listen address. At this point we really don't care
235 // if we can also listen on that address!
238 // Remember the port number
239 $this->bootIpPort = $ipPort;
242 $this->debugOutput('BOOTSTRAP: ' . __FUNCTION__ . '[' . __LINE__ . ']: IP matches listen address ' . $ipPort . '.');
244 // Stop further searching
254 * Outputs the console teaser. This should only be executed on startup or
255 * full restarts. This method generates some space around the teaser.
259 public function outputConsoleTeaser () {
260 // Get the app instance (for shortening our code)
261 $app = $this->getApplicationInstance();
264 $this->debugOutput(' ');
265 $this->debugOutput($app->getAppName() . ' v' . $app->getAppVersion() . ' - ' . $this->getRequestInstance()->getRequestElement('mode') . ' mode active');
266 $this->debugOutput('Copyright (c) 2007 - 2008 Roland Haeder, 2009, 2010 Hub Developer Team');
267 $this->debugOutput(' ');
268 $this->debugOutput('This program comes with ABSOLUTELY NO WARRANTY; for details see docs/COPYING.');
269 $this->debugOutput('This is free software, and you are welcome to redistribute it under certain');
270 $this->debugOutput('conditions; see docs/COPYING for details.');
271 $this->debugOutput(' ');
275 * Generic method to acquire a hub-id. On first run this generates a new one
276 * based on many pseudo-random data. On any later run, unless the id
277 * got not removed from database, it will be restored from the database.
279 * @param $requestInstance A Requestable class
280 * @param $responseInstance A Responseable class
283 public function bootstrapAcquireHubId (Requestable $requestInstance, Responseable $responseInstance) {
284 // Get a wrapper instance
285 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('node_info_db_wrapper_class');
287 // Now get a search criteria instance
288 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
290 // Search for the node number zero which is hard-coded the default
291 $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
292 $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_TYPE, $this->getRequestInstance()->getRequestElement('mode'));
293 $searchInstance->setLimit(1);
296 $resultInstance = $wrapperInstance->doSelectByCriteria($searchInstance);
299 if ($resultInstance->next()) {
300 // Save the result instance in this class
301 $this->setResultInstance($resultInstance);
303 // Get the node id from result and set it
304 $this->setNodeId($this->getField(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_ID));
307 $this->debugOutput('BOOTSTRAP: Re-using found node-id: ' . $this->getNodeId() . '');
309 // Get an RNG instance (Random Number Generator)
310 $rngInstance = ObjectFactory::createObjectByConfiguredName('rng_class');
312 // Generate a pseudo-random string
313 $randomString = $rngInstance->randomString(255) . ':' . $this->getBootIpPort() . ':' . $this->getRequestInstance()->getRequestElement('mode');
315 // Get a crypto instance
316 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
318 // Hash and encrypt the string so we become a "node id" aka Hub-Id
319 $this->setNodeId($cryptoInstance->hashString($cryptoInstance->encryptString($randomString)));
321 // Register the node id with our wrapper
322 $wrapperInstance->registerNodeId($this, $this->getRequestInstance());
325 $this->debugOutput('BOOTSTRAP: Created new node-id: ' . $this->getNodeId() . '');
330 * Generates a session id which will be sent to the other hubs and clients
334 public function bootstrapGenerateSessionId () {
335 // Get an RNG instance
336 $rngInstance = ObjectFactory::createObjectByConfiguredName('rng_class');
338 // Generate a pseudo-random string
339 $randomString = $rngInstance->randomString(255) . ':' . $this->getBootIpPort() . ':' . $this->getRequestInstance()->getRequestElement('mode');
341 // Get a crypto instance
342 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
344 // Hash and encrypt the string so we become a "node id" aka Hub-Id
345 $this->setSessionId($cryptoInstance->hashString($cryptoInstance->encryptString($randomString)));
347 // Get a wrapper instance
348 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('node_info_db_wrapper_class');
350 // Register the node id with our wrapper
351 $wrapperInstance->registerSessionId($this, $this->getRequestInstance());
354 $this->debugOutput('BOOTSTRAP: Created new session-id: ' . $this->getSessionId() . '');
356 // Change the state because the node has auired a hub id
357 $this->getStateInstance()->nodeGeneratedSessionId();
361 * Initializes queues which every node needs
365 protected function initGenericQueues () {
367 $this->debugOutput('BOOTSTRAP: Initialize queues: START');
369 // Set the query connector instance
370 $this->setQueryConnectorInstance(ObjectFactory::createObjectByConfiguredName('query_connector_class', array($this)));
373 $this->getQueryConnectorInstance()->doTestQuery();
376 $this->debugOutput('BOOTSTRAP: Initialize queues: FINISHED');
380 * Adds hub data elements to a given dataset instance
382 * @param $criteriaInstance An instance of a storeable criteria
383 * @param $requestInstance An instance of a Requestable class
386 public function addElementsToDataSet (StoreableCriteria $criteriaInstance, Requestable $requestInstance) {
387 // Add node number and type
388 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
389 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_TYPE, $requestInstance->getRequestElement('mode'));
392 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_ID, $this->getNodeId());
394 // Add the session id if acquired
395 if ($this->getSessionId() != '') {
396 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_SESSION_ID, $this->getSessionId());
401 * Updates a given field with new value
403 * @param $fieldName Field to update
404 * @param $fieldValue New value to store
406 * @throws DatabaseUpdateSupportException If this class does not support database updates
407 * @todo Try to make this method more generic so we can move it in BaseFrameworkSystem
409 public function updateDatabaseField ($fieldName, $fieldValue) {
411 $this->partialStub('Unfinished!');
414 // Get a critieria instance
415 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
417 // Add search criteria
418 $searchInstance->addCriteria(UserDatabaseWrapper::DB_COLUMN_USERNAME, $this->getUserName());
419 $searchInstance->setLimit(1);
421 // Now get another criteria
422 $updateInstance = ObjectFactory::createObjectByConfiguredName('update_criteria_class');
424 // Add criteria entry which we shall update
425 $updateInstance->addCriteria($fieldName, $fieldValue);
427 // Add the search criteria for searching for the right entry
428 $updateInstance->setSearchInstance($searchInstance);
430 // Set wrapper class name
431 $updateInstance->setWrapperConfigEntry('user_db_wrapper_class');
433 // Remember the update in database result
434 $this->getResultInstance()->add2UpdateQueue($updateInstance);
438 * Announces this hub to the upper (bootstrap or list) hubs. After this is
439 * successfully done the given task is unregistered from the handler.
441 * @param $taskInstance The task instance running this announcement
443 * @throws HubAlreadyAnnouncedException If this hub is already announced
444 * @todo Change the first if() block to check for a specific state
446 public function announceSelfToUpperNodes (Taskable $taskInstance) {
447 // Is this hub node announced?
448 if ($this->hubIsAnnounced === true) {
449 // Already announced!
450 throw new HubAlreadyAnnouncedException($this, self::EXCEPTION_HUB_ALREADY_ANNOUNCED);
454 $this->debugOutput('HUB: Self-announcement: START (taskInstance=' . $taskInstance->__toString(). ')');
456 // Get a helper instance
457 $helperInstance = ObjectFactory::createObjectByConfiguredName('hub_announcement_helper_class', array($this));
459 // Load the announcement descriptor
460 $helperInstance->loadAnnouncementDescriptor();
462 // Set some dummy configuration entries, e.g. node_status
463 $this->getConfigInstance()->setConfigEntry('node_status', $this->getStateInstance()->getStateName());
465 // Compile all variables
466 $helperInstance->getTemplateInstance()->compileConfigInVariables();
468 // "Publish" the descriptor by sending it to the bootstrap/list nodes
469 $helperInstance->publishAnnouncementDescriptor();
471 // Change the state, this should be the last line except debug output
472 $this->getStateInstance()->nodeAnnouncedToUpperHubs();
475 $this->debugOutput('HUB: Self-announcement: FINISHED');
479 * Activates the hub by doing some final preparation and setting
480 * $hubIsActive to true
482 * @param $requestInstance A Requestable class
483 * @param $responseInstance A Responseable class
486 public function activateHub (Requestable $requestInstance, Responseable $responseInstance) {
487 // Checks wether a listener is still active and shuts it down if one
488 // is still listening.
489 if (($this->determineIfListenerIsActive()) && ($this->determineIfHubIsActive())) {
490 // Shutdown them down before they can hurt anything
491 $this->shutdownListenerPool();
494 // Get the controller here
495 $controllerInstance = Registry::getRegistry()->getInstance('controller');
497 // Run all filters for the hub activation
498 $controllerInstance->executeActivationFilters($requestInstance, $responseInstance);
500 // ----------------------- Last step from here ------------------------
501 // Activate the hub. This is ALWAYS the last step in this method
502 $this->getStateInstance()->nodeIsActivated();
503 // ---------------------- Last step until here ------------------------
507 * Initializes the listener pool (class)
511 public function initializeListenerPool () {
513 $this->debugOutput('HUB: Initialize listener: START');
515 // Get a new pool instance
516 $this->setListenerPoolInstance(ObjectFactory::createObjectByConfiguredName('listener_pool_class', array($this)));
518 // Get an instance of the low-level listener
519 $listenerInstance = ObjectFactory::createObjectByConfiguredName('tcp_listener_class', array($this));
521 // Setup address and port
522 $listenerInstance->setListenAddressByConfiguration('node_listen_addr');
523 $listenerInstance->setListenPortByConfiguration('node_tcp_listen_port');
525 // Initialize the listener
526 $listenerInstance->initListener();
528 // Get a decorator class
529 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('hub_tcp_listener_class', array($listenerInstance));
531 // Add this listener to the pool
532 $this->getListenerPoolInstance()->addListener($decoratorInstance);
534 // Get a decorator class
535 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('client_tcp_listener_class', array($listenerInstance));
537 // Add this listener to the pool
538 $this->getListenerPoolInstance()->addListener($decoratorInstance);
540 // Get an instance of the low-level listener
541 $listenerInstance = ObjectFactory::createObjectByConfiguredName('udp_listener_class', array($this));
543 // Setup address and port
544 $listenerInstance->setListenAddressByConfiguration('node_listen_addr');
545 $listenerInstance->setListenPortByConfiguration('node_udp_listen_port');
547 // Initialize the listener
548 $listenerInstance->initListener();
550 // Get a decorator class
551 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('hub_udp_listener_class', array($listenerInstance));
553 // Add this listener to the pool
554 $this->getListenerPoolInstance()->addListener($decoratorInstance);
556 // Get a decorator class
557 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('client_udp_listener_class', array($listenerInstance));
559 // Add this listener to the pool
560 $this->getListenerPoolInstance()->addListener($decoratorInstance);
563 $this->debugOutput('HUB: Initialize listener: FINISHED.');
567 * Restores a previously stored node list from database
571 public function bootstrapRestoreNodeList () {
573 $this->debugOutput('HUB: Restore node list: START');
575 // Get a wrapper instance
576 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('node_list_db_wrapper_class');
578 // Now get a search criteria instance
579 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
581 // Search for the node number zero which is hard-coded the default
582 // @TODO Add some criteria, e.g. if the node is active or so
583 //$searchInstance->addCriteria(NodeListDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
584 //$searchInstance->addCriteria(NodeListDatabaseWrapper::DB_COLUMN_NODE_TYPE, $this->getRequestInstance()->getRequestElement('mode'));
585 //$searchInstance->setLimit(1);
588 $resultInstance = $wrapperInstance->doSelectByCriteria($searchInstance);
591 if ($resultInstance->next()) {
592 $this->partialStub('Do something for restoring the list.');
594 //$this->debugOutput('HUB: ');
596 // No previously saved node list found!
597 $this->debugOutput('HUB: No previously saved node list found. This is fine.');
601 $this->debugOutput('HUB: Restore node list: FINISHED.');
605 * Determines wether the hub is active by checking its current state
607 * @return $isActive Wether the hub is active
609 public function determineIfHubIsActive () {
611 // @TODO Add more states e.g. 'firewalled', 'senior'
612 $isActive = ($this->getStateInstance() instanceof NodeActiveState);
619 * Returns a singleton network package instance. If an instance is found in
620 * the registry it will be returned, else a new instance is created and
621 * stored in the same registry entry.
623 * @param $compressorInstance A Compressor instance
624 * @return $packageInstance A network package instance
626 public function createPackageInstance (Compressor $compressorInstance) {
627 // Do we have an instance in the registry?
628 if (Registry::getRegistry()->instanceExists('network_package')) {
629 // Then use this instance
630 $packageInstance = Registry::getRegistry()->getInstance('network_package');
633 * Prepare the compressor for our package, GZIP should be fine but we
634 * keep it open here so you can experiment with the settings and don't
635 * need to touch any code.
637 $compressorInstance = ObjectFactory::createObjectByConfiguredName('raw_package_compressor_class');
639 // Prepare the decorator compressor (for later flawless and easy updates)
640 $compressorInstance = ObjectFactory::createObjectByConfiguredName('deco_package_compressor_class', array($compressorInstance));
642 // Now prepare the network package for delivery so only need to do this
643 // once just before the "big announcement loop".
644 $packageInstance = ObjectFactory::createObjectByConfiguredName('network_package_class', array($compressorInstance));
646 // Set the instance in registry for further use
647 Registry::getRegistry()->addInstance('network_package', $packageInstance);
650 // Return the instance
651 return $packageInstance;