3 * A general hub node class
5 * @author Roland Haeder <webmaster@ship-simu.org>
7 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 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;
36 private $sessionId = '';
39 * IP/port number of bootstrapping node
41 private $bootIpPort = '';
44 * Query connector instance
46 private $connectorInstance = null;
49 * Listener pool instance
51 private $listenerPoolInstance = null;
54 * Wether the hub is active (true/false)
56 private $hubIsActive = false;
59 * Wether this node is anncounced (KEEP ON false!)
61 private $hubIsAnnounced = false;
64 * Protected constructor
66 * @param $className Name of the class
69 protected function __construct ($className) {
70 // Call parent constructor
71 parent::__construct($className);
77 * @param $nodeId Our new node id
80 private final function setNodeId ($nodeId) {
81 $this->nodeId = (string) $nodeId;
87 * @return $nodeId Our new node id
89 private final function getNodeId () {
94 * Setter for listener pool instance
96 * @param $listenerPoolInstance Our new listener pool instance
99 private final function setListenerPoolInstance (PoolableListener $listenerPoolInstance) {
100 $this->listenerPoolInstance = $listenerPoolInstance;
104 * Getter for listener pool instance
106 * @return $listenerPoolInstance Our current listener pool instance
108 public final function getListenerPoolInstance () {
109 return $this->listenerPoolInstance;
113 * Setter for session id
115 * @param $sessionId Our new session id
118 private final function setSessionId ($sessionId) {
119 $this->sessionId = (string) $sessionId;
123 * Getter for session id
125 * @return $sessionId Our new session id
127 public final function getSessionId () {
128 return $this->sessionId;
132 * Setter for query instance
134 * @param $connectorInstance Our new query instance
137 private final function setQueryConnectorInstance (Connectable $connectorInstance) {
138 $this->connectorInstance = $connectorInstance;
142 * Getter for query instance
144 * @return $connectorInstance Our new query instance
146 public final function getQueryConnectorInstance () {
147 return $this->connectorInstance;
151 * Getter for boot IP/port combination
153 * @return $bootIpPort The IP/port combination of the boot node
155 protected final function getBootIpPort () {
156 return $this->bootIpPort;
160 * Checks wether the given IP address matches one of the bootstrapping nodes
162 * @param $remoteAddr IP address to checkout against our bootstrapping list
163 * @return $isFound Wether the IP is found
165 protected function ifAddressMatchesBootstrappingNodes ($remoteAddr) {
166 // By default nothing is found
169 // Run through all configured IPs
170 foreach (explode(',', $this->getConfigInstance()->getConfigEntry('hub_bootstrap_nodes')) as $ipPort) {
171 // Split it up in IP/port
172 $ipPortArray = explode(':', $ipPort);
175 if ($ipPortArray[0] == $remoteAddr) {
179 // Remember the port number
180 $this->bootIpPort = $ipPort;
183 $this->debugOutput('BOOTSTRAP: ' . __FUNCTION__ . '[' . __LINE__ . ']: IP matches remote address ' . $ipPort . '.');
185 // Stop further searching
187 } elseif ($ipPortArray[0] == $this->getConfigInstance()->getConfigEntry('node_listen_addr')) {
188 // IP matches listen address. At this point we really don't care
189 // if we can also listen on that address!
192 // Remember the port number
193 $this->bootIpPort = $ipPort;
196 $this->debugOutput('BOOTSTRAP: ' . __FUNCTION__ . '[' . __LINE__ . ']: IP matches listen address ' . $ipPort . '.');
198 // Stop further searching
208 * Outputs the console teaser. This should only be executed on startup or
209 * full restarts. This method generates some space around the teaser.
213 public function outputConsoleTeaser () {
214 // Get the app instance (for shortening our code)
215 $app = $this->getApplicationInstance();
218 $this->debugOutput(' ');
219 $this->debugOutput($app->getAppName() . ' v' . $app->getAppVersion() . ' - ' . $this->getRequestInstance()->getRequestElement('mode') . ' mode active');
220 $this->debugOutput('Copyright (c) 2007 - 2008 Roland Haeder, 2009 Hub Developer Team');
221 $this->debugOutput(' ');
222 $this->debugOutput('This program comes with ABSOLUTELY NO WARRANTY; for details see docs/COPYING.');
223 $this->debugOutput('This is free software, and you are welcome to redistribute it under certain');
224 $this->debugOutput('conditions; see docs/COPYING for details.');
225 $this->debugOutput(' ');
229 * Generic method to acquire a hub-id. On first run this generates a new one
230 * based on many pseudo-random data. On any later run, unless the id
231 * got not removed from database, it will be restored from the database.
235 public function bootstrapAcquireHubId () {
236 // Get a wrapper instance
237 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('node_info_db_wrapper_class');
239 // Now get a search criteria instance
240 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
242 // Search for the node number zero which is hard-coded the default
243 $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
244 $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_TYPE, $this->getRequestInstance()->getRequestElement('mode'));
245 $searchInstance->setLimit(1);
248 $resultInstance = $wrapperInstance->doSelectByCriteria($searchInstance);
251 if ($resultInstance->next()) {
252 // Save the result instance in this class
253 $this->setResultInstance($resultInstance);
255 // Get the node id from result and set it
256 $this->setNodeId($this->getField(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_ID));
259 $this->debugOutput('BOOTSTRAP: Re-using found node-id: ' . $this->getNodeId() . '');
261 // Get an RNG instance (Random Number Generator)
262 $rngInstance = ObjectFactory::createObjectByConfiguredName('rng_class');
264 // Generate a pseudo-random string
265 $randomString = $rngInstance->randomString(255) . ':' . $this->getBootIpPort() . ':' . $this->getRequestInstance()->getRequestElement('mode');
267 // Get a crypto instance
268 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
270 // Hash and encrypt the string so we become a "node id" aka Hub-Id
271 $this->setNodeId($cryptoInstance->hashString($cryptoInstance->encryptString($randomString)));
273 // Register the node id with our wrapper
274 $wrapperInstance->registerNodeId($this, $this->getRequestInstance());
277 $this->debugOutput('BOOTSTRAP: Created new node-id: ' . $this->getNodeId() . '');
282 * Generates a session id which will be sent to the other hubs and clients
286 public function bootstrapGenerateSessionId () {
287 // Get an RNG instance
288 $rngInstance = ObjectFactory::createObjectByConfiguredName('rng_class');
290 // Generate a pseudo-random string
291 $randomString = $rngInstance->randomString(255) . ':' . $this->getBootIpPort() . ':' . $this->getRequestInstance()->getRequestElement('mode');
293 // Get a crypto instance
294 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
296 // Hash and encrypt the string so we become a "node id" aka Hub-Id
297 $this->setSessionId($cryptoInstance->hashString($cryptoInstance->encryptString($randomString)));
299 // Get a wrapper instance
300 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('node_info_db_wrapper_class');
302 // Register the node id with our wrapper
303 $wrapperInstance->registerSessionId($this, $this->getRequestInstance());
306 $this->debugOutput('BOOTSTRAP: Created new session-id: ' . $this->getSessionId() . '');
310 * Initializes queues which every node needs
314 protected function initGenericQueues () {
316 $this->debugOutput('BOOTSTRAP: Initialize queues: START');
318 // Set the query connector instance
319 $this->setQueryConnectorInstance(ObjectFactory::createObjectByConfiguredName('query_connector_class', array($this)));
322 $this->getQueryConnectorInstance()->doTestQuery();
325 $this->debugOutput('BOOTSTRAP: Initialize queues: FINISHED');
329 * Adds hub data elements to a given dataset instance
331 * @param $criteriaInstance An instance of a storeable criteria
332 * @param $requestInstance An instance of a Requestable class
335 public function addElementsToDataSet (StoreableCriteria $criteriaInstance, Requestable $requestInstance) {
336 // Add node number and type
337 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
338 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_TYPE, $requestInstance->getRequestElement('mode'));
341 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_ID, $this->getNodeId());
343 // Add the session id if acquired
344 if ($this->getSessionId() != '') {
345 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_SESSION_ID, $this->getSessionId());
350 * Updates a given field with new value
352 * @param $fieldName Field to update
353 * @param $fieldValue New value to store
355 * @throws DatabaseUpdateSupportException If this class does not support database updates
356 * @todo Try to make this method more generic so we can move it in BaseFrameworkSystem
358 public function updateDatabaseField ($fieldName, $fieldValue) {
360 $this->partialStub('Unfinished!');
363 // Get a critieria instance
364 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
366 // Add search criteria
367 $searchInstance->addCriteria(UserDatabaseWrapper::DB_COLUMN_USERNAME, $this->getUserName());
368 $searchInstance->setLimit(1);
370 // Now get another criteria
371 $updateInstance = ObjectFactory::createObjectByConfiguredName('update_criteria_class');
373 // Add criteria entry which we shall update
374 $updateInstance->addCriteria($fieldName, $fieldValue);
376 // Add the search criteria for searching for the right entry
377 $updateInstance->setSearchInstance($searchInstance);
379 // Set wrapper class name
380 $updateInstance->setWrapperConfigEntry('user_db_wrapper_class');
382 // Remember the update in database result
383 $this->getResultInstance()->add2UpdateQueue($updateInstance);
387 * Getter for $hubIsActive attribute
389 * @return $hubIsActive Wether the hub is activer
391 public final function isHubActive () {
392 return $this->hubIsActive;
396 * Setter for $hubIsActive attribute
398 * @param $hubIsActive Wether the hub is activer
400 public final function enableHubIsActive ($hubIsActive = true) {
401 $this->hubIsActive = $hubIsActive;
405 * Announces this hub to the upper (bootstrap or list) hubs. After this is
406 * successfully done the given task is unregistered from the handler.
408 * @param $taskInstance The task instance running this announcement
410 * @throws HubAlreadyAnnouncedException If this hub is already announced
412 public function announceSelfToUpperNodes (Taskable $taskInstance) {
413 // Is this hub node announced?
414 if ($this->hubIsAnnounced === true) {
415 // Already announced!
416 throw new HubAlreadyAnnouncedException($this, self::EXCEPTION_HUB_ALREADY_ANNOUNCED);
419 // Get a helper instance
420 $helperInstance = ObjectFactory::createObjectByConfiguredName('hub_descriptor_class', array($this));
422 // Load the announcement descriptor
423 $helperInstance->loadAnnouncementDescriptor();
428 * Activates the hub by doing some final preparation and setting
429 * $hubIsActive to true
431 * @param $requestInstance A Requestable class
432 * @param $responseInstance A Responseable class
435 public function activateHub (Requestable $requestInstance, Responseable $responseInstance) {
436 // Checks wether a listener is still active and shuts it down if one
437 // is still listening
438 if (($this->determineIfListenerIsActive()) && ($this->isHubActive())) {
439 // Shutdown them down before they can hurt anything
440 $this->shutdownListenerPool();
443 // Get the controller here
444 $controllerInstance = Registry::getRegistry()->getInstance('controller');
446 // Run all filters for the hub activation
447 $controllerInstance->executeActivationFilters($requestInstance, $responseInstance);
449 // ----------------------- Last step from here ------------------------
450 // Activate the hub. This is ALWAYS the last step in this method
451 $this->enableHubIsActive();
452 // ---------------------- Last step until here ------------------------
456 * Initializes the listener pool (class)
460 public function initializeListenerPool () {
462 $this->debugOutput('HUB: Initialize listener: START');
464 // Get a new pool instance
465 $this->setListenerPoolInstance(ObjectFactory::createObjectByConfiguredName('listener_pool_class', array($this)));
467 // Get an instance of the low-level listener
468 $listenerInstance = ObjectFactory::createObjectByConfiguredName('tcp_listener_class', array($this));
470 // Setup address and port
471 $listenerInstance->setListenAddressByConfiguration('node_listen_addr');
472 $listenerInstance->setListenPortByConfiguration('node_tcp_listen_port');
474 // Initialize the listener
475 $listenerInstance->initListener();
477 // Get a decorator class
478 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('hub_tcp_listener_class', array($listenerInstance));
480 // Add this listener to the pool
481 $this->getListenerPoolInstance()->addListener($decoratorInstance);
483 // Get a decorator class
484 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('client_tcp_listener_class', array($listenerInstance));
486 // Add this listener to the pool
487 $this->getListenerPoolInstance()->addListener($decoratorInstance);
489 // Get an instance of the low-level listener
490 $listenerInstance = ObjectFactory::createObjectByConfiguredName('udp_listener_class', array($this));
492 // Setup address and port
493 $listenerInstance->setListenAddressByConfiguration('node_listen_addr');
494 $listenerInstance->setListenPortByConfiguration('node_udp_listen_port');
496 // Initialize the listener
497 $listenerInstance->initListener();
499 // Get a decorator class
500 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('hub_udp_listener_class', array($listenerInstance));
502 // Add this listener to the pool
503 $this->getListenerPoolInstance()->addListener($decoratorInstance);
505 // Get a decorator class
506 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('client_udp_listener_class', array($listenerInstance));
508 // Add this listener to the pool
509 $this->getListenerPoolInstance()->addListener($decoratorInstance);
512 $this->debugOutput('HUB: Initialize listener: FINISHED.');
516 * Restores a previously stored node list from database
520 public function bootstrapRestoreNodeList () {
522 $this->debugOutput('HUB: Restore node list: START');
524 // Get a wrapper instance
525 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('node_list_db_wrapper_class');
527 // Now get a search criteria instance
528 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
530 // Search for the node number zero which is hard-coded the default
531 // @TODO Add some criteria, e.g. if the node is active or so
532 //$searchInstance->addCriteria(NodeListDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
533 //$searchInstance->addCriteria(NodeListDatabaseWrapper::DB_COLUMN_NODE_TYPE, $this->getRequestInstance()->getRequestElement('mode'));
534 //$searchInstance->setLimit(1);
537 $resultInstance = $wrapperInstance->doSelectByCriteria($searchInstance);
540 if ($resultInstance->next()) {
541 $this->partialStub('Do something for restoring the list.');
543 //$this->debugOutput('HUB: ');
545 // No previously saved node list found!
546 $this->debugOutput('HUB: No previously saved node list found. This is fine.');
550 $this->debugOutput('HUB: Restore node list: FINISHED.');