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 {
33 private $sessionId = '';
36 * IP/port number of bootstrapping node
38 private $bootIpPort = '';
41 * Query connector instance
43 private $queryInstance = null;
46 * Listener pool instance
48 private $listenerPoolInstance = null;
51 * Wether the hub is active (true/false)
53 private $hubIsActive = false;
56 * Protected constructor
58 * @param $className Name of the class
61 protected function __construct ($className) {
62 // Call parent constructor
63 parent::__construct($className);
69 * @param $nodeId Our new node id
72 private final function setNodeId ($nodeId) {
73 $this->nodeId = (string) $nodeId;
79 * @return $nodeId Our new node id
81 private final function getNodeId () {
86 * Setter for session id
88 * @param $sessionId Our new session id
91 private final function setSessionId ($sessionId) {
92 $this->sessionId = (string) $sessionId;
96 * Getter for session id
98 * @return $sessionId Our new session id
100 private final function getSessionId () {
101 return $this->sessionId;
105 * Setter for query instance
107 * @param $queryInstance Our new query instance
110 private final function setQueryInstance (Queryable $queryInstance) {
111 $this->queryInstance = $queryInstance;
115 * Getter for query instance
117 * @return $queryInstance Our new query instance
119 protected final function getQueryInstance () {
120 return $this->queryInstance;
124 * Checks wether the given IP address matches one of the bootstrapping nodes
126 * @param $remoteAddr IP address to checkout against our bootstrapping list
127 * @return $isFound Wether the IP is found
129 protected function ifAddressMatchesBootstrappingNodes ($remoteAddr) {
130 // By default nothing is found
133 // Run through all configured IPs
134 foreach (explode(',', $this->getConfigInstance()->getConfigEntry('hub_bootstrap_nodes')) as $ipPort) {
135 // Split it up in IP/port
136 $ipPortArray = explode(':', $ipPort);
139 if ($ipPortArray[0] == $remoteAddr) {
143 // Remember the port number
144 $this->bootIpPort = $ipPort;
147 $this->debugOutput('BOOTSTRAP: ' . __FUNCTION__ . '[' . __LINE__ . ']: IP matches remote address ' . $ipPort . '.');
149 // Stop further searching
151 } elseif ($ipPortArray[0] == $this->getConfigInstance()->getConfigEntry('node_listen_addr')) {
152 // IP matches listen address. At this point we really don't care
153 // if we can also listen on that address!
156 // Remember the port number
157 $this->bootIpPort = $ipPort;
160 $this->debugOutput('BOOTSTRAP: ' . __FUNCTION__ . '[' . __LINE__ . ']: IP matches listen address ' . $ipPort . '.');
162 // Stop further searching
172 * Outputs the console teaser. This should only be executed on startup or
173 * full restarts. This method generates some space around the teaser.
177 public function outputConsoleTeaser () {
178 // Get the app instance (for shortening our code)
179 $app = $this->getApplicationInstance();
182 $this->debugOutput(' ');
183 $this->debugOutput($app->getAppName() . ' v' . $app->getAppVersion() . ' - ' . $this->getRequestInstance()->getRequestElement('mode') . ' mode active');
184 $this->debugOutput('Copyright (c) 2007 - 2008 Roland Haeder, 2009 Hub Developer Team');
185 $this->debugOutput(' ');
186 $this->debugOutput('This program comes with ABSOLUTELY NO WARRANTY; for details see docs/COPYING.');
187 $this->debugOutput('This is free software, and you are welcome to redistribute it under certain');
188 $this->debugOutput('conditions; see docs/COPYING for details.');
189 $this->debugOutput(' ');
193 * Generic method to acquire a hub-id. On first run this generates a new one
194 * based on many pseudo-random data. On any later run, unless the id
195 * got not removed from database, it will be restored from the database.
199 public function bootstrapAcquireHubId () {
200 // Get a wrapper instance
201 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('node_info_db_wrapper_class');
203 // Now get a search criteria instance
204 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
206 // Search for the node number zero which is hard-coded the default
207 $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
208 $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_TYPE, $this->getRequestInstance()->getRequestElement('mode'));
209 $searchInstance->setLimit(1);
212 $resultInstance = $wrapperInstance->doSelectByCriteria($searchInstance);
215 if ($resultInstance->next()) {
216 // Save the result instance in this class
217 $this->setResultInstance($resultInstance);
219 // Get the node id from result and set it
220 $this->setNodeId($this->getField(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_ID));
223 $this->debugOutput('BOOTSTRAP: Re-using found node-id: ' . $this->getNodeId() . '');
225 // Get an RNG instance (Random Number Generator)
226 $rngInstance = ObjectFactory::createObjectByConfiguredName('rng_class');
228 // Generate a pseudo-random string
229 $randomString = $rngInstance->randomString(255) . ':' . $this->getBootIpPort() . ':' . $this->getRequestInstance()->getRequestElement('mode');
231 // Get a crypto instance
232 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
234 // Hash and encrypt the string so we become a "node id" aka Hub-Id
235 $this->setNodeId($cryptoInstance->hashString($cryptoInstance->encryptString($randomString)));
237 // Register the node id with our wrapper
238 $wrapperInstance->registerNodeId($this, $this->getRequestInstance());
241 $this->debugOutput('BOOTSTRAP: Created new node-id: ' . $this->getNodeId() . '');
246 * Generates a session id which will be sent to the other hubs and clients
250 public function bootstrapGenerateSessionId () {
251 // Get an RNG instance
252 $rngInstance = ObjectFactory::createObjectByConfiguredName('rng_class');
254 // Generate a pseudo-random string
255 $randomString = $rngInstance->randomString(255) . ':' . $this->getBootIpPort() . ':' . $this->getRequestInstance()->getRequestElement('mode');
257 // Get a crypto instance
258 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
260 // Hash and encrypt the string so we become a "node id" aka Hub-Id
261 $this->setSessionId($cryptoInstance->hashString($cryptoInstance->encryptString($randomString)));
263 // Get a wrapper instance
264 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('node_info_db_wrapper_class');
266 // Register the node id with our wrapper
267 $wrapperInstance->registerNodeId($this, $this->getRequestInstance());
270 $this->debugOutput('BOOTSTRAP: Created new session-id: ' . $this->getSessionId() . '');
274 * Getter for boot IP/port combination
276 * @return $bootIpPort The IP/port combination of the boot node
278 protected final function getBootIpPort () {
279 return $this->bootIpPort;
283 * Initializes queues which every node needs
287 protected function initGenericQueues () {
288 // Set the query connector instance
289 $this->setQueryInstance(ObjectFactory::createObjectByConfiguredName('query_connector_class', array($this)));
292 $this->getQueryInstance()->doTestQuery();
294 // Query queue initialized
295 $this->debugOutput('BOOTSTRAP: Query queue initialized.');
299 * Adds hub data elements to a given dataset instance
301 * @param $criteriaInstance An instance of a storeable criteria
302 * @param $requestInstance An instance of a Requestable class
305 public function addElementsToDataSet (StoreableCriteria $criteriaInstance, Requestable $requestInstance) {
306 // Add node number and type
307 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
308 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_TYPE, $requestInstance->getRequestElement('mode'));
311 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_ID, $this->getNodeId());
315 * Updates a given field with new value
317 * @param $fieldName Field to update
318 * @param $fieldValue New value to store
320 * @throws DatabaseUpdateSupportException If this class does not support database updates
321 * @todo Try to make this method more generic so we can move it in BaseFrameworkSystem
323 public function updateDatabaseField ($fieldName, $fieldValue) {
325 $this->partialStub('Unfinished!');
328 // Get a critieria instance
329 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
331 // Add search criteria
332 $searchInstance->addCriteria(UserDatabaseWrapper::DB_COLUMN_USERNAME, $this->getUserName());
333 $searchInstance->setLimit(1);
335 // Now get another criteria
336 $updateInstance = ObjectFactory::createObjectByConfiguredName('update_criteria_class');
338 // Add criteria entry which we shall update
339 $updateInstance->addCriteria($fieldName, $fieldValue);
341 // Add the search criteria for searching for the right entry
342 $updateInstance->setSearchInstance($searchInstance);
344 // Set wrapper class name
345 $updateInstance->setWrapperConfigEntry('user_db_wrapper_class');
347 // Remember the update in database result
348 $this->getResultInstance()->add2UpdateQueue($updateInstance);
352 * Getter for $hubIsActive attribute
354 * @return $hubIsActive Wether the hub is activer
356 public final function isHubActive () {
357 return $this->hubIsActive;
361 * Activates the hub by doing some final preparation and setting
362 * $hubIsActive to true
366 public function activateHub () {
367 // Checks wether a listener is still active and shuts it down if one
368 // is still listening
369 if (($this->determineIfListenerIsActive()) && ($this->isHubActive())) {
370 // Shutdown them down before they can hurt anything
371 $this->shutdownListenerPool();
374 // Initialize the TCP/UDP listener pool
375 $this->initializeListenerPool();
377 // @TODO Do some final preparation
378 $this->partialStub('Do some final preparation before the hub gots activated.');
380 // ----------------------- Last step from here ------------------------
381 // Activate the hub. This is ALWAYS the last step in this method
382 $this->hubIsActive = true;
383 // ---------------------- Last step until here ------------------------
387 * Initializes the listener pool (class)
391 private function initializeListenerPool () {
392 // Get a new pool instance
393 $this->listenerPoolInstance = ObjectFactory::createObjectByConfiguredName('listener_pool_class', array($this));
395 // Get an instance of the low-level listener
396 $listenerInstance = ObjectFactory::createObjectByConfiguredName('tcp_listener_class', array($this));
398 // Setup address and port
399 $listenerInstance->setListenAddressByConfiguration('node_listen_addr');
400 $listenerInstance->setListenPortByConfiguration('node_tcp_listen_port');
402 // Initialize the listener
403 $listenerInstance->initListener();
405 // Get a decorator class
406 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('hub_tcp_listener_class', array($listenerInstance));
408 // Add this listener to the pool
409 $this->listenerPoolInstance->addListener($decoratorInstance);
411 // Get a decorator class
412 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('client_tcp_listener_class', array($listenerInstance));
414 // Add this listener to the pool
415 $this->listenerPoolInstance->addListener($decoratorInstance);
417 // Get an instance of the low-level listener
418 $listenerInstance = ObjectFactory::createObjectByConfiguredName('udp_listener_class', array($this));
420 // Setup address and port
421 $listenerInstance->setListenAddressByConfiguration('node_listen_addr');
422 $listenerInstance->setListenPortByConfiguration('node_udp_listen_port');
424 // Initialize the listener
425 $listenerInstance->initListener();
427 // Get a decorator class
428 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('hub_udp_listener_class', array($listenerInstance));
430 // Add this listener to the pool
431 $this->listenerPoolInstance->addListener($decoratorInstance);
433 // Get a decorator class
434 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('client_udp_listener_class', array($listenerInstance));
436 // Add this listener to the pool
437 $this->listenerPoolInstance->addListener($decoratorInstance);