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 BaseFrameworkSystem 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);
61 $this->removeNumberFormaters();
62 $this->removeSystemArray();
68 * @param $nodeId Our new node id
71 private final function setNodeId ($nodeId) {
72 $this->nodeId = (string) $nodeId;
78 * @return $nodeId Our new node id
80 private final function getNodeId () {
85 * Checks wether the given IP address matches one of the bootstrapping nodes
87 * @param $remoteAddr IP address to checkout against our bootstrapping list
88 * @return $isFound Wether the IP is found
90 protected function ifAddressMatchesBootstrappingNodes ($remoteAddr) {
91 // By default nothing is found
94 // Run through all configured IPs
95 foreach (explode(',', $this->getConfigInstance()->readConfig('hub_bootstrap_nodes')) as $ipPort) {
96 // Split it up in IP/port
97 $ipPortArray = explode(':', $ipPort);
100 if ($ipPortArray[0] == $remoteAddr) {
104 // Remember the port number
105 $this->bootIpPort = $ipPort;
108 $this->getDebugInstance()->output(__FUNCTION__.'['.__LINE__.']: IP matches remote address ' . $ipPort . '.');
110 // Stop further searching
112 } elseif ($ipPortArray[0] == $this->getConfigInstance()->readConfig('node_listen_addr')) {
113 // IP matches listen address. At this point we really don't care
114 // if we can also listen on that address!
117 // Remember the port number
118 $this->bootIpPort = $ipPort;
121 $this->getDebugInstance()->output(__FUNCTION__.'['.__LINE__.']: IP matches listen address ' . $ipPort . '.');
123 // Stop further searching
133 * Outputs the console teaser. This should only be executed on startup or
134 * full restarts. This method generates some space around the teaser.
138 public function outputConsoleTeaser () {
139 // Get the app instance (for shortening our code)
140 $app = $this->getApplicationInstance();
143 $this->getDebugInstance()->output(' ');
144 $this->getDebugInstance()->output($app->getAppName() . ' v' . $app->getAppVersion() . ' - ' . $this->getRequestInstance()->getRequestElement('mode') . ' mode active');
145 $this->getDebugInstance()->output('Copyright (c) 2007 - 2008 Roland Haeder, 2009 Hub Developer Team');
146 $this->getDebugInstance()->output(' ');
147 $this->getDebugInstance()->output('This program comes with ABSOLUTELY NO WARRANTY; for details see docs/COPYING.');
148 $this->getDebugInstance()->output('This is free software, and you are welcome to redistribute it under certain');
149 $this->getDebugInstance()->output('conditions; see docs/COPYING for details.');
150 $this->getDebugInstance()->output(' ');
154 * Do generic things for bootup phase. This can be e.g. checking if the
155 * right node mode is selected for this hub's IP number.
158 * @todo This method is maybe not yet finished.
160 protected function doGenericBootstrapping () {
161 // --------------------- Hub-id acquirement phase ---------------------
162 // Acquire a hub-id. This step generates on first launch a new one and
163 // on any later launches it will restore the hub-id from the database.
164 // A passed 'nickname=xxx' argument will be used to add some
165 // 'personality' to the hub.
166 $this->bootstrapAcquireHubId();
168 // ------------------- More generic bootstrap steps -------------------
169 // Generate the session id which will only be stored in RAM and kept for
170 // the whole "session".
171 $this->bootstrapGenerateSessionId();
173 // Restore a previously downloaded bootstrap-node list.
174 $this->bootstrapRestoreNodeList();
176 // @TODO Add some generic bootstrap steps
177 $this->partialStub('Add some generic bootstrap steps here.');
181 * Generic method to acquire a hub-id. On first run this generates a new one
182 * based on many pseudo-random data. On any later run, unless the id
183 * got not removed from database, it will be restored from the database.
187 private function bootstrapAcquireHubId () {
188 // Get a wrapper instance
189 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('node_info_db_wrapper_class');
191 // Now get a search criteria instance
192 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
194 // Search for the node number zero which is hard-coded the default
195 $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
196 $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_TYPE, $this->getRequestInstance()->getRequestElement('mode'));
197 $searchInstance->setLimit(1);
200 $resultInstance = $wrapperInstance->doSelectByCriteria($searchInstance);
203 if ($resultInstance->next()) {
204 // Save the result instance in this class
205 $this->setResultInstance($resultInstance);
207 // Get the node id from result and set it
208 $this->setNodeId($this->getField(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_ID));
211 $this->getDebugInstance()->output('BOOTSTRAP: Re-using found node-id: ' . $this->getNodeId() . '');
213 // Get an RNG instance (Random Number Generator)
214 $rngInstance = ObjectFactory::createObjectByConfiguredName('rng_class');
216 // Generate a pseudo-random string
217 $randomString = $rngInstance->randomString(255) . ':' . $this->getRequestInstance()->getRequestElement('mode');
219 // Get a crypto instance
220 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
222 // Hash and encrypt the string so we become a "node id" aka Hub-Id
223 $this->setNodeId($cryptoInstance->hashString($cryptoInstance->encryptString($randomString)));
225 // Register the node id with our wrapper
226 $wrapperInstance->registerNodeId($this, $this->getRequestInstance());
229 $this->getDebugInstance()->output('BOOTSTRAP: Created new node-id: ' . $this->getNodeId() . '');
234 * Initializes queues which every node needs
238 protected function initGenericQueues () {
240 $this->queryInstance = ObjectFactory::createObjectByConfiguredName('query_connector_class', array($this));
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
309 public function activateHub () {
310 // Checks wether a listener is still active and shuts it down if one
311 // is still listening
312 if (($this->checkIfListenerIsActive()) && ($this->isHubActive())) {
313 // Shutdown them down before they can hurt anything
314 $this->shutdownListenerPool();
317 // Initialize the TCP/UDP listener pool
318 $this->initializeListenerPool();
320 // @TODO Do some final preparation
321 $this->partialStub('Do some final preparation before the hub gots activated.');
323 // ----------------------- Last step from here ------------------------
324 // Activate the hub. This is ALWAYS the last step in this method
325 $this->hubIsActive = true;
326 // ---------------------- Last step until here ------------------------