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 {
31 * IP/port number of bootstrapping node
33 private $bootIpPort = '';
36 * Query connector instance
38 private $queryInstance = null;
41 * Listener pool instance
43 private $listenerPoolInstance = null;
46 * Wether the hub is active (true/false)
48 private $hubIsActive = false;
51 * Protected constructor
53 * @param $className Name of the class
56 protected function __construct ($className) {
57 // Call parent constructor
58 parent::__construct($className);
64 * @param $nodeId Our new node id
67 private final function setNodeId ($nodeId) {
68 $this->nodeId = (string) $nodeId;
74 * @return $nodeId Our new node id
76 private final function getNodeId () {
81 * Setter for query instance
83 * @param $queryInstance Our new query instance
86 private final function setQueryInstance (Queryable $queryInstance) {
87 $this->queryInstance = $queryInstance;
91 * Getter for query instance
93 * @return $queryInstance Our new query instance
95 protected final function getQueryInstance () {
96 return $this->queryInstance;
100 * Checks wether the given IP address matches one of the bootstrapping nodes
102 * @param $remoteAddr IP address to checkout against our bootstrapping list
103 * @return $isFound Wether the IP is found
105 protected function ifAddressMatchesBootstrappingNodes ($remoteAddr) {
106 // By default nothing is found
109 // Run through all configured IPs
110 foreach (explode(',', $this->getConfigInstance()->getConfigEntry('hub_bootstrap_nodes')) as $ipPort) {
111 // Split it up in IP/port
112 $ipPortArray = explode(':', $ipPort);
115 if ($ipPortArray[0] == $remoteAddr) {
119 // Remember the port number
120 $this->bootIpPort = $ipPort;
123 $this->debugOutput('BOOTSTRAP: ' . __FUNCTION__ . '[' . __LINE__ . ']: IP matches remote address ' . $ipPort . '.');
125 // Stop further searching
127 } elseif ($ipPortArray[0] == $this->getConfigInstance()->getConfigEntry('node_listen_addr')) {
128 // IP matches listen address. At this point we really don't care
129 // if we can also listen on that address!
132 // Remember the port number
133 $this->bootIpPort = $ipPort;
136 $this->debugOutput('BOOTSTRAP: ' . __FUNCTION__ . '[' . __LINE__ . ']: IP matches listen address ' . $ipPort . '.');
138 // Stop further searching
148 * Outputs the console teaser. This should only be executed on startup or
149 * full restarts. This method generates some space around the teaser.
153 public function outputConsoleTeaser () {
154 // Get the app instance (for shortening our code)
155 $app = $this->getApplicationInstance();
158 $this->debugOutput(' ');
159 $this->debugOutput($app->getAppName() . ' v' . $app->getAppVersion() . ' - ' . $this->getRequestInstance()->getRequestElement('mode') . ' mode active');
160 $this->debugOutput('Copyright (c) 2007 - 2008 Roland Haeder, 2009 Hub Developer Team');
161 $this->debugOutput(' ');
162 $this->debugOutput('This program comes with ABSOLUTELY NO WARRANTY; for details see docs/COPYING.');
163 $this->debugOutput('This is free software, and you are welcome to redistribute it under certain');
164 $this->debugOutput('conditions; see docs/COPYING for details.');
165 $this->debugOutput(' ');
169 * Generic method to acquire a hub-id. On first run this generates a new one
170 * based on many pseudo-random data. On any later run, unless the id
171 * got not removed from database, it will be restored from the database.
175 public function bootstrapAcquireHubId () {
176 // Get a wrapper instance
177 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('node_info_db_wrapper_class');
179 // Now get a search criteria instance
180 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
182 // Search for the node number zero which is hard-coded the default
183 $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
184 $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_TYPE, $this->getRequestInstance()->getRequestElement('mode'));
185 $searchInstance->setLimit(1);
188 $resultInstance = $wrapperInstance->doSelectByCriteria($searchInstance);
191 if ($resultInstance->next()) {
192 // Save the result instance in this class
193 $this->setResultInstance($resultInstance);
195 // Get the node id from result and set it
196 $this->setNodeId($this->getField(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_ID));
199 $this->debugOutput('BOOTSTRAP: Re-using found node-id: ' . $this->getNodeId() . '');
201 // Get an RNG instance (Random Number Generator)
202 $rngInstance = ObjectFactory::createObjectByConfiguredName('rng_class');
204 // Generate a pseudo-random string
205 $randomString = $rngInstance->randomString(255) . ':' . $this->getRequestInstance()->getRequestElement('mode');
207 // Get a crypto instance
208 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
210 // Hash and encrypt the string so we become a "node id" aka Hub-Id
211 $this->setNodeId($cryptoInstance->hashString($cryptoInstance->encryptString($randomString)));
213 // Register the node id with our wrapper
214 $wrapperInstance->registerNodeId($this, $this->getRequestInstance());
217 $this->debugOutput('BOOTSTRAP: Created new node-id: ' . $this->getNodeId() . '');
222 * Getter for boot IP/port combination
224 * @return $bootIpPort The IP/port combination of the boot node
226 protected final function getBootIpPort () {
227 return $this->bootIpPort;
231 * Initializes queues which every node needs
235 protected function initGenericQueues () {
236 // Set the query connector instance
237 $this->setQueryInstance(ObjectFactory::createObjectByConfiguredName('query_connector_class', array($this)));
240 $this->getQueryInstance()->doTestQuery();
244 * Adds hub data elements to a given dataset instance
246 * @param $criteriaInstance An instance of a storeable criteria
247 * @param $requestInstance An instance of a Requestable class
250 public function addElementsToDataSet (StoreableCriteria $criteriaInstance, Requestable $requestInstance) {
251 // Add node number and type
252 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
253 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_TYPE, $requestInstance->getRequestElement('mode'));
256 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_ID, $this->getNodeId());
260 * Updates a given field with new value
262 * @param $fieldName Field to update
263 * @param $fieldValue New value to store
265 * @throws DatabaseUpdateSupportException If this class does not support database updates
266 * @todo Try to make this method more generic so we can move it in BaseFrameworkSystem
268 public function updateDatabaseField ($fieldName, $fieldValue) {
270 $this->partialStub('Unfinished!');
273 // Get a critieria instance
274 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
276 // Add search criteria
277 $searchInstance->addCriteria(UserDatabaseWrapper::DB_COLUMN_USERNAME, $this->getUserName());
278 $searchInstance->setLimit(1);
280 // Now get another criteria
281 $updateInstance = ObjectFactory::createObjectByConfiguredName('update_criteria_class');
283 // Add criteria entry which we shall update
284 $updateInstance->addCriteria($fieldName, $fieldValue);
286 // Add the search criteria for searching for the right entry
287 $updateInstance->setSearchInstance($searchInstance);
289 // Set wrapper class name
290 $updateInstance->setWrapperConfigEntry('user_db_wrapper_class');
292 // Remember the update in database result
293 $this->getResultInstance()->add2UpdateQueue($updateInstance);
297 * Getter for $hubIsActive attribute
299 * @return $hubIsActive Wether the hub is activer
301 public final function isHubActive () {
302 return $this->hubIsActive;
306 * Activates the hub by doing some final preparation and setting
307 * $hubIsActive to true
311 public function activateHub () {
312 // Checks wether a listener is still active and shuts it down if one
313 // is still listening
314 if (($this->determineIfListenerIsActive()) && ($this->isHubActive())) {
315 // Shutdown them down before they can hurt anything
316 $this->shutdownListenerPool();
319 // Initialize the TCP/UDP listener pool
320 $this->initializeListenerPool();
322 // @TODO Do some final preparation
323 $this->partialStub('Do some final preparation before the hub gots activated.');
325 // ----------------------- Last step from here ------------------------
326 // Activate the hub. This is ALWAYS the last step in this method
327 $this->hubIsActive = true;
328 // ---------------------- Last step until here ------------------------
332 * Initializes the listener pool (class)
336 private function initializeListenerPool () {
337 // Get a new pool instance
338 $this->listenerPoolInstance = ObjectFactory::createObjectByConfiguredName('listener_pool_class', array($this));
340 // Get an instance of the low-level listener
341 $listenerInstance = ObjectFactory::createObjectByConfiguredName('tcp_listener_class', array($this));
343 // Setup address and port
344 $listenerInstance->setListenAddressByConfiguration('node_listen_addr');
345 $listenerInstance->setListenPortByConfiguration('node_tcp_listen_port');
347 // Initialize the listener
348 $listenerInstance->initListener();
350 // Get a decorator class
351 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('hub_tcp_listener_class', array($listenerInstance));
353 // Add this listener to the pool
354 $this->listenerPoolInstance->addListener($decoratorInstance);
356 // Get a decorator class
357 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('client_tcp_listener_class', array($listenerInstance));
359 // Add this listener to the pool
360 $this->listenerPoolInstance->addListener($decoratorInstance);
362 // Get an instance of the low-level listener
363 $listenerInstance = ObjectFactory::createObjectByConfiguredName('udp_listener_class', array($this));
365 // Setup address and port
366 $listenerInstance->setListenAddressByConfiguration('node_listen_addr');
367 $listenerInstance->setListenPortByConfiguration('node_udp_listen_port');
369 // Initialize the listener
370 $listenerInstance->initListener();
372 // Get a decorator class
373 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('hub_udp_listener_class', array($listenerInstance));
375 // Add this listener to the pool
376 $this->listenerPoolInstance->addListener($decoratorInstance);
378 // Get a decorator class
379 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('client_udp_listener_class', array($listenerInstance));
381 // Add this listener to the pool
382 $this->listenerPoolInstance->addListener($decoratorInstance);