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 * Checks wether the given IP address matches one of the bootstrapping nodes
83 * @param $remoteAddr IP address to checkout against our bootstrapping list
84 * @return $isFound Wether the IP is found
86 protected function ifAddressMatchesBootstrappingNodes ($remoteAddr) {
87 // By default nothing is found
90 // Run through all configured IPs
91 foreach (explode(',', $this->getConfigInstance()->readConfig('hub_bootstrap_nodes')) as $ipPort) {
92 // Split it up in IP/port
93 $ipPortArray = explode(':', $ipPort);
96 if ($ipPortArray[0] == $remoteAddr) {
100 // Remember the port number
101 $this->bootIpPort = $ipPort;
104 $this->getDebugInstance()->output(__FUNCTION__.'['.__LINE__.']: IP matches remote address ' . $ipPort . '.');
106 // Stop further searching
108 } elseif ($ipPortArray[0] == $this->getConfigInstance()->readConfig('node_listen_addr')) {
109 // IP matches listen address. At this point we really don't care
110 // if we can also listen on that address!
113 // Remember the port number
114 $this->bootIpPort = $ipPort;
117 $this->getDebugInstance()->output(__FUNCTION__.'['.__LINE__.']: IP matches listen address ' . $ipPort . '.');
119 // Stop further searching
129 * Outputs the console teaser. This should only be executed on startup or
130 * full restarts. This method generates some space around the teaser.
134 public function outputConsoleTeaser () {
135 // Get the app instance (for shortening our code)
136 $app = $this->getApplicationInstance();
139 $this->getDebugInstance()->output(' ');
140 $this->getDebugInstance()->output($app->getAppName() . ' v' . $app->getAppVersion() . ' - ' . $this->getRequestInstance()->getRequestElement('mode') . ' mode active');
141 $this->getDebugInstance()->output('Copyright (c) 2007 - 2008 Roland Haeder, 2009 Hub Developer Team');
142 $this->getDebugInstance()->output(' ');
143 $this->getDebugInstance()->output('This program comes with ABSOLUTELY NO WARRANTY; for details see docs/COPYING.');
144 $this->getDebugInstance()->output('This is free software, and you are welcome to redistribute it under certain');
145 $this->getDebugInstance()->output('conditions; see docs/COPYING for details.');
146 $this->getDebugInstance()->output(' ');
150 * Do generic things for bootup phase. This can be e.g. checking if the
151 * right node mode is selected for this hub's IP number.
154 * @todo This method is maybe not yet finished.
156 protected function bootstrapGenericBootstrapping () {
157 // --------------------- Hub-id acquirement phase ---------------------
158 // Acquire a hub-id. This step generates on first launch a new one and
159 // on any later launches it will restore the hub-id from the database.
160 // A passed 'nickname=xxx' argument will be used to add some
161 // 'personality' to the hub.
162 $this->bootstrapAcquireHubId();
164 // ------------------- More generic bootstrap steps -------------------
165 // Generate the session id which will only be stored in RAM and kept for
166 // the whole "session".
167 $this->bootstrapGenerateSessionId();
169 // Restore a previously downloaded bootstrap-node list.
170 $this->bootstrapRestoreNodeList();
172 // @TODO Add some generic bootstrap steps
173 $this->partialStub('Add some generic bootstrap steps here.');
177 * Generic method to acquire a hub-id. On first run this generates a new one
178 * based on many pseudo-random data. On any later run, unless the id
179 * got not removed from database, it will be restored from the database.
183 private function bootstrapAcquireHubId () {
184 // Get a wrapper instance
185 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('node_info_db_wrapper_class');
187 // Now get a search criteria instance
188 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
190 // Search for the node number zero which is hard-coded the default
191 $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
192 $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_TYPE, $this->getRequestInstance()->getRequestElement('mode'));
193 $searchInstance->setLimit(1);
196 $resultInstance = $wrapperInstance->doSelectByCriteria($searchInstance);
199 if ($resultInstance->next()) {
200 // Save the result instance in this class
201 $this->setResultInstance($resultInstance);
203 // Get the node id from result and set it
204 $this->setNodeId($this->getField(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_ID));
207 $this->getDebugInstance()->output('BOOTSTRAP: Re-using found node-id: ' . $this->getNodeId() . '');
209 // Get an RNG instance (Random Number Generator)
210 $rngInstance = ObjectFactory::createObjectByConfiguredName('rng_class');
212 // Generate a pseudo-random string
213 $randomString = $rngInstance->randomString(255) . ':' . $this->getRequestInstance()->getRequestElement('mode');
215 // Get a crypto instance
216 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
218 // Hash and encrypt the string so we become a "node id" aka Hub-Id
219 $this->setNodeId($cryptoInstance->hashString($cryptoInstance->encryptString($randomString)));
221 // Register the node id with our wrapper
222 $wrapperInstance->registerNodeId($this, $this->getRequestInstance());
225 $this->getDebugInstance()->output('BOOTSTRAP: Created new node-id: ' . $this->getNodeId() . '');
230 * Getter for boot IP/port combination
232 * @return $bootIpPort The IP/port combination of the boot node
234 protected final function getBootIpPort () {
235 return $this->bootIpPort;
239 * Initializes queues which every node needs
243 protected function initGenericQueues () {
245 $this->queryInstance = ObjectFactory::createObjectByConfiguredName('query_connector_class', array($this));
249 * Adds hub data elements to a given dataset instance
251 * @param $criteriaInstance An instance of a storeable criteria
252 * @param $requestInstance An instance of a Requestable class
255 public function addElementsToDataSet (StoreableCriteria $criteriaInstance, Requestable $requestInstance) {
256 // Add node number and type
257 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
258 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_TYPE, $requestInstance->getRequestElement('mode'));
261 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_ID, $this->getNodeId());
265 * Updates a given field with new value
267 * @param $fieldName Field to update
268 * @param $fieldValue New value to store
270 * @throws DatabaseUpdateSupportException If this class does not support database updates
271 * @todo Try to make this method more generic so we can move it in BaseFrameworkSystem
273 public function updateDatabaseField ($fieldName, $fieldValue) {
275 $this->partialStub('Unfinished!');
278 // Get a critieria instance
279 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
281 // Add search criteria
282 $searchInstance->addCriteria(UserDatabaseWrapper::DB_COLUMN_USERNAME, $this->getUserName());
283 $searchInstance->setLimit(1);
285 // Now get another criteria
286 $updateInstance = ObjectFactory::createObjectByConfiguredName('update_criteria_class');
288 // Add criteria entry which we shall update
289 $updateInstance->addCriteria($fieldName, $fieldValue);
291 // Add the search criteria for searching for the right entry
292 $updateInstance->setSearchInstance($searchInstance);
294 // Set wrapper class name
295 $updateInstance->setWrapperConfigEntry('user_db_wrapper_class');
297 // Remember the update in database result
298 $this->getResultInstance()->add2UpdateQueue($updateInstance);
302 * Getter for $hubIsActive attribute
304 * @return $hubIsActive Wether the hub is activer
306 public final function isHubActive () {
307 return $this->hubIsActive;
311 * Activates the hub by doing some final preparation and setting
312 * $hubIsActive to true
316 public function activateHub () {
317 // Checks wether a listener is still active and shuts it down if one
318 // is still listening
319 if (($this->checkIfListenerIsActive()) && ($this->isHubActive())) {
320 // Shutdown them down before they can hurt anything
321 $this->shutdownListenerPool();
324 // Initialize the TCP/UDP listener pool
325 $this->initializeListenerPool();
327 // @TODO Do some final preparation
328 $this->partialStub('Do some final preparation before the hub gots activated.');
330 // ----------------------- Last step from here ------------------------
331 // Activate the hub. This is ALWAYS the last step in this method
332 $this->hubIsActive = true;
333 // ---------------------- Last step until here ------------------------
337 * Initializes the listener pool (class)
341 private function initializeListenerPool () {
342 // Get a new pool instance
343 $this->listenerPoolInstance = ObjectFactory::createObjectByConfiguredName('listener_pool_class', array($this));
345 // Initialize both listeners
346 foreach (array('tcp', 'udp') as $protocol) {
348 $listenerInstance = ObjectFactory::createObjectByConfiguredName($protocol . '_listener_class', array($this));
350 // Setup address and port
351 $listenerInstance->setListenAddressByConfiguration('node_listen_addr');
352 $listenerInstance->setListenPortByConfiguration('node_' . $protocol . '_listen_port');
354 // Initialize the listener
355 $listenerInstance->initListener();
357 // Add this listener to the pool
358 $this->listenerPoolInstance->addListener($listenerInstance);