]> git.mxchange.org Git - hub.git/blob - application/hub/main/nodes/class_BaseHubNode.php
First attempt to store session id in database
[hub.git] / application / hub / main / nodes / class_BaseHubNode.php
1 <?php
2 /**
3  * A general hub node class
4  *
5  * @author              Roland Haeder <webmaster@ship-simu.org>
6  * @version             0.0.0
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
10  *
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.
15  *
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.
20  *
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/>.
23  */
24 class BaseHubNode extends BaseHubSystem implements Updateable {
25         /**
26          * Node id
27          */
28         private $nodeId = '';
29
30         /**
31          * Session id
32          */
33         private $sessionId = '';
34
35         /**
36          * IP/port number of bootstrapping node
37          */
38         private $bootIpPort = '';
39
40         /**
41          * Query connector instance
42          */
43         private $queryInstance = null;
44
45         /**
46          * Listener pool instance
47          */
48         private $listenerPoolInstance = null;
49
50         /**
51          * Wether the hub is active (true/false)
52          */
53         private $hubIsActive = false;
54
55         /**
56          * Protected constructor
57          *
58          * @param       $className      Name of the class
59          * @return      void
60          */
61         protected function __construct ($className) {
62                 // Call parent constructor
63                 parent::__construct($className);
64         }
65
66         /**
67          * Setter for node id
68          *
69          * @param       $nodeId         Our new node id
70          * @return      void
71          */
72         private final function setNodeId ($nodeId) {
73                 $this->nodeId = (string) $nodeId;
74         }
75
76         /**
77          * Getter for node id
78          *
79          * @return      $nodeId         Our new node id
80          */
81         private final function getNodeId () {
82                 return $this->nodeId;
83         }
84
85         /**
86          * Setter for session id
87          *
88          * @param       $sessionId              Our new session id
89          * @return      void
90          */
91         private final function setSessionId ($sessionId) {
92                 $this->sessionId = (string) $sessionId;
93         }
94
95         /**
96          * Getter for session id
97          *
98          * @return      $sessionId              Our new session id
99          */
100         private final function getSessionId () {
101                 return $this->sessionId;
102         }
103
104         /**
105          * Setter for query instance
106          *
107          * @param       $queryInstance          Our new query instance
108          * @return      void
109          */
110         private final function setQueryInstance (Queryable $queryInstance) {
111                 $this->queryInstance = $queryInstance;
112         }
113
114         /**
115          * Getter for query instance
116          *
117          * @return      $queryInstance          Our new query instance
118          */
119         protected final function getQueryInstance () {
120                 return $this->queryInstance;
121         }
122
123         /**
124          * Checks wether the given IP address matches one of the bootstrapping nodes
125          *
126          * @param       $remoteAddr             IP address to checkout against our bootstrapping list
127          * @return      $isFound                Wether the IP is found
128          */
129         protected function ifAddressMatchesBootstrappingNodes ($remoteAddr) {
130                 // By default nothing is found
131                 $isFound = false;
132
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);
137
138                         // Does it match?
139                         if ($ipPortArray[0] == $remoteAddr) {
140                                 // Found it!
141                                 $isFound = true;
142
143                                 // Remember the port number
144                                 $this->bootIpPort = $ipPort;
145
146                                 // Output message
147                                 $this->debugOutput('BOOTSTRAP: ' . __FUNCTION__ . '[' . __LINE__ . ']: IP matches remote address ' . $ipPort . '.');
148
149                                 // Stop further searching
150                                 break;
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!
154                                 $isFound = true;
155
156                                 // Remember the port number
157                                 $this->bootIpPort = $ipPort;
158
159                                 // Output message
160                                 $this->debugOutput('BOOTSTRAP: ' . __FUNCTION__ . '[' . __LINE__ . ']: IP matches listen address ' . $ipPort . '.');
161
162                                 // Stop further searching
163                                 break;
164                         }
165                 } // END - foreach
166
167                 // Return the result
168                 return $isFound;
169         }
170
171         /**
172          * Outputs the console teaser. This should only be executed on startup or
173          * full restarts. This method generates some space around the teaser.
174          *
175          * @return      void
176          */
177         public function outputConsoleTeaser () {
178                 // Get the app instance (for shortening our code)
179                 $app = $this->getApplicationInstance();
180
181                 // Output all lines
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(' ');
190         }
191
192         /**
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.
196          *
197          * @return      void
198          */
199         public function bootstrapAcquireHubId () {
200                 // Get a wrapper instance
201                 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('node_info_db_wrapper_class');
202
203                 // Now get a search criteria instance
204                 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
205
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);
210
211                 // Get a result back
212                 $resultInstance = $wrapperInstance->doSelectByCriteria($searchInstance);
213
214                 // Is it valid?
215                 if ($resultInstance->next()) {
216                         // Save the result instance in this class
217                         $this->setResultInstance($resultInstance);
218
219                         // Get the node id from result and set it
220                         $this->setNodeId($this->getField(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_ID));
221
222                         // Output message
223                         $this->debugOutput('BOOTSTRAP: Re-using found node-id: ' . $this->getNodeId() . '');
224                 } else {
225                         // Get an RNG instance (Random Number Generator)
226                         $rngInstance = ObjectFactory::createObjectByConfiguredName('rng_class');
227
228                         // Generate a pseudo-random string
229                         $randomString = $rngInstance->randomString(255) . ':' . $this->getBootIpPort()  . ':' . $this->getRequestInstance()->getRequestElement('mode');
230
231                         // Get a crypto instance
232                         $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
233
234                         // Hash and encrypt the string so we become a "node id" aka Hub-Id
235                         $this->setNodeId($cryptoInstance->hashString($cryptoInstance->encryptString($randomString)));
236
237                         // Register the node id with our wrapper
238                         $wrapperInstance->registerNodeId($this, $this->getRequestInstance());
239
240                         // Output message
241                         $this->debugOutput('BOOTSTRAP: Created new node-id: ' . $this->getNodeId() . '');
242                 }
243         }
244
245         /**
246          * Generates a session id which will be sent to the other hubs and clients
247          *
248          * @return      void
249          */
250         public function bootstrapGenerateSessionId () {
251                 // Get an RNG instance
252                 $rngInstance = ObjectFactory::createObjectByConfiguredName('rng_class');
253
254                 // Generate a pseudo-random string
255                 $randomString = $rngInstance->randomString(255) . ':' . $this->getBootIpPort() . ':' . $this->getRequestInstance()->getRequestElement('mode');
256
257                 // Get a crypto instance
258                 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
259
260                 // Hash and encrypt the string so we become a "node id" aka Hub-Id
261                 $this->setSessionId($cryptoInstance->hashString($cryptoInstance->encryptString($randomString)));
262
263                 // Get a wrapper instance
264                 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('node_info_db_wrapper_class');
265
266                 // Register the node id with our wrapper
267                 $wrapperInstance->registerSessionId($this, $this->getRequestInstance());
268
269                 // Output message
270                 $this->debugOutput('BOOTSTRAP: Created new session-id: ' . $this->getSessionId() . '');
271         }
272
273         /**
274          * Getter for boot IP/port combination
275          *
276          * @return      $bootIpPort             The IP/port combination of the boot node
277          */
278         protected final function getBootIpPort () {
279                 return $this->bootIpPort;
280         }
281
282         /**
283          * Initializes queues which every node needs
284          *
285          * @return      void
286          */
287         protected function initGenericQueues () {
288                 // Debug message
289                 $this->debugOutput('BOOTSTRAP: Initialize queues: START');
290
291                 // Set the query connector instance
292                 $this->setQueryInstance(ObjectFactory::createObjectByConfiguredName('query_connector_class', array($this)));
293
294                 // Run a test query
295                 $this->getQueryInstance()->doTestQuery();
296
297                 // Debug message
298                 $this->debugOutput('BOOTSTRAP: Initialize queues: FINISHED');
299         }
300         
301         /**
302          * Adds hub data elements to a given dataset instance
303          *
304          * @param       $criteriaInstance       An instance of a storeable criteria
305          * @param       $requestInstance        An instance of a Requestable class
306          * @return      void
307          */
308         public function addElementsToDataSet (StoreableCriteria $criteriaInstance, Requestable $requestInstance) {
309                 // Add node number and type
310                 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
311                 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_TYPE, $requestInstance->getRequestElement('mode'));
312
313                 // Add the node id
314                 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_ID, $this->getNodeId());
315         }
316
317         /**
318          * Updates a given field with new value
319          *
320          * @param       $fieldName              Field to update
321          * @param       $fieldValue             New value to store
322          * @return      void
323          * @throws      DatabaseUpdateSupportException  If this class does not support database updates
324          * @todo        Try to make this method more generic so we can move it in BaseFrameworkSystem
325          */
326         public function updateDatabaseField ($fieldName, $fieldValue) {
327                 // Unfinished
328                 $this->partialStub('Unfinished!');
329                 return;
330
331                 // Get a critieria instance
332                 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
333
334                 // Add search criteria
335                 $searchInstance->addCriteria(UserDatabaseWrapper::DB_COLUMN_USERNAME, $this->getUserName());
336                 $searchInstance->setLimit(1);
337
338                 // Now get another criteria
339                 $updateInstance = ObjectFactory::createObjectByConfiguredName('update_criteria_class');
340
341                 // Add criteria entry which we shall update
342                 $updateInstance->addCriteria($fieldName, $fieldValue);
343
344                 // Add the search criteria for searching for the right entry
345                 $updateInstance->setSearchInstance($searchInstance);
346
347                 // Set wrapper class name
348                 $updateInstance->setWrapperConfigEntry('user_db_wrapper_class');
349
350                 // Remember the update in database result
351                 $this->getResultInstance()->add2UpdateQueue($updateInstance);
352         }
353
354         /**
355          * Getter for $hubIsActive attribute
356          *
357          * @return      $hubIsActive    Wether the hub is activer
358          */
359         public final function isHubActive () {
360                 return $this->hubIsActive;
361         }
362
363         /**
364          * Setter for $hubIsActive attribute
365          *
366          * @param       $hubIsActive    Wether the hub is activer
367          */
368         public final function enableHubIsActive ($hubIsActive = true) {
369                 $this->hubIsActive = $hubIsActive;
370         }
371
372         /**
373          * Activates the hub by doing some final preparation and setting
374          * $hubIsActive to true
375          *
376          * @param       $requestInstance        A Requestable class
377          * @param       $responseInstance       A Responseable class
378          * @return      void
379          */
380         public function activateHub (Requestable $requestInstance, Responseable $responseInstance) {
381                 // Checks wether a listener is still active and shuts it down if one
382                 // is still listening
383                 if (($this->determineIfListenerIsActive()) && ($this->isHubActive())) {
384                         // Shutdown them down before they can hurt anything
385                         $this->shutdownListenerPool();
386                 } // END - if
387
388                 // Get the controller here
389                 $controllerInstance = Registry::getRegistry()->getInstance('controller');
390
391                 // Run all filters for the hub activation
392                 $controllerInstance->executeHubActivationFilters($requestInstance, $responseInstance);
393
394                 // ----------------------- Last step from here ------------------------
395                 // Activate the hub. This is ALWAYS the last step in this method
396                 $this->enableHubIsActive();
397                 // ---------------------- Last step until here ------------------------
398         }
399
400         /**
401          * Initializes the listener pool (class)
402          *
403          * @return      void
404          */
405         public function initializeListenerPool () {
406                 // Debug output
407                 $this->debugOutput('HUB: Initialize listener: START');
408
409                 // Get a new pool instance
410                 $this->listenerPoolInstance = ObjectFactory::createObjectByConfiguredName('listener_pool_class', array($this));
411
412                 // Get an instance of the low-level listener
413                 $listenerInstance = ObjectFactory::createObjectByConfiguredName('tcp_listener_class', array($this));
414
415                 // Setup address and port
416                 $listenerInstance->setListenAddressByConfiguration('node_listen_addr');
417                 $listenerInstance->setListenPortByConfiguration('node_tcp_listen_port');
418
419                 // Initialize the listener
420                 $listenerInstance->initListener();
421
422                 // Get a decorator class
423                 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('hub_tcp_listener_class', array($listenerInstance));
424
425                 // Add this listener to the pool
426                 $this->listenerPoolInstance->addListener($decoratorInstance);
427
428                 // Get a decorator class
429                 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('client_tcp_listener_class', array($listenerInstance));
430
431                 // Add this listener to the pool
432                 $this->listenerPoolInstance->addListener($decoratorInstance);
433
434                 // Get an instance of the low-level listener
435                 $listenerInstance = ObjectFactory::createObjectByConfiguredName('udp_listener_class', array($this));
436
437                 // Setup address and port
438                 $listenerInstance->setListenAddressByConfiguration('node_listen_addr');
439                 $listenerInstance->setListenPortByConfiguration('node_udp_listen_port');
440
441                 // Initialize the listener
442                 $listenerInstance->initListener();
443
444                 // Get a decorator class
445                 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('hub_udp_listener_class', array($listenerInstance));
446
447                 // Add this listener to the pool
448                 $this->listenerPoolInstance->addListener($decoratorInstance);
449
450                 // Get a decorator class
451                 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('client_udp_listener_class', array($listenerInstance));
452
453                 // Add this listener to the pool
454                 $this->listenerPoolInstance->addListener($decoratorInstance);
455
456                 // Debug output
457                 $this->debugOutput('HUB: Initialize listener: FINISHED.');
458         }
459
460         /**
461          * Restores a previously stored node list from database
462          *
463          * @return      void
464          */
465         public function bootstrapRestoreNodeList () {
466                 // Debug output
467                 $this->debugOutput('HUB: Restore node list: START');
468
469                 // Get a wrapper instance
470                 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('node_list_db_wrapper_class');
471
472                 // Now get a search criteria instance
473                 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
474
475                 // Search for the node number zero which is hard-coded the default
476                 // @TODO Add some criteria, e.g. if the node is active or so
477                 //$searchInstance->addCriteria(NodeListDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
478                 //$searchInstance->addCriteria(NodeListDatabaseWrapper::DB_COLUMN_NODE_TYPE, $this->getRequestInstance()->getRequestElement('mode'));
479                 //$searchInstance->setLimit(1);
480
481                 // Get a result back
482                 $resultInstance = $wrapperInstance->doSelectByCriteria($searchInstance);
483
484                 // Is it valid?
485                 if ($resultInstance->next()) {
486                         $this->partialStub('Do something for restoring the list.');
487                         // Output message
488                         //$this->debugOutput('BOOTSTRAP: ');
489                 } // END - if
490
491                 // Debug output
492                 $this->debugOutput('HUB: Restore node list: FINISHED.');
493         }
494 }
495
496 // [EOF]
497 ?>