]> git.mxchange.org Git - hub.git/blob - application/hub/main/nodes/class_BaseHubNode.php
4e903bddcb6aef99247c93358f35145a5b042a1d
[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                 // Add the session id if acquired
317                 if ($this->getSessionId() != '') {
318                         $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_SESSION_ID, $this->getSessionId());
319                 } // END - if
320         }
321
322         /**
323          * Updates a given field with new value
324          *
325          * @param       $fieldName              Field to update
326          * @param       $fieldValue             New value to store
327          * @return      void
328          * @throws      DatabaseUpdateSupportException  If this class does not support database updates
329          * @todo        Try to make this method more generic so we can move it in BaseFrameworkSystem
330          */
331         public function updateDatabaseField ($fieldName, $fieldValue) {
332                 // Unfinished
333                 $this->partialStub('Unfinished!');
334                 return;
335
336                 // Get a critieria instance
337                 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
338
339                 // Add search criteria
340                 $searchInstance->addCriteria(UserDatabaseWrapper::DB_COLUMN_USERNAME, $this->getUserName());
341                 $searchInstance->setLimit(1);
342
343                 // Now get another criteria
344                 $updateInstance = ObjectFactory::createObjectByConfiguredName('update_criteria_class');
345
346                 // Add criteria entry which we shall update
347                 $updateInstance->addCriteria($fieldName, $fieldValue);
348
349                 // Add the search criteria for searching for the right entry
350                 $updateInstance->setSearchInstance($searchInstance);
351
352                 // Set wrapper class name
353                 $updateInstance->setWrapperConfigEntry('user_db_wrapper_class');
354
355                 // Remember the update in database result
356                 $this->getResultInstance()->add2UpdateQueue($updateInstance);
357         }
358
359         /**
360          * Getter for $hubIsActive attribute
361          *
362          * @return      $hubIsActive    Wether the hub is activer
363          */
364         public final function isHubActive () {
365                 return $this->hubIsActive;
366         }
367
368         /**
369          * Setter for $hubIsActive attribute
370          *
371          * @param       $hubIsActive    Wether the hub is activer
372          */
373         public final function enableHubIsActive ($hubIsActive = true) {
374                 $this->hubIsActive = $hubIsActive;
375         }
376
377         /**
378          * Activates the hub by doing some final preparation and setting
379          * $hubIsActive to true
380          *
381          * @param       $requestInstance        A Requestable class
382          * @param       $responseInstance       A Responseable class
383          * @return      void
384          */
385         public function activateHub (Requestable $requestInstance, Responseable $responseInstance) {
386                 // Checks wether a listener is still active and shuts it down if one
387                 // is still listening
388                 if (($this->determineIfListenerIsActive()) && ($this->isHubActive())) {
389                         // Shutdown them down before they can hurt anything
390                         $this->shutdownListenerPool();
391                 } // END - if
392
393                 // Get the controller here
394                 $controllerInstance = Registry::getRegistry()->getInstance('controller');
395
396                 // Run all filters for the hub activation
397                 $controllerInstance->executeHubActivationFilters($requestInstance, $responseInstance);
398
399                 // ----------------------- Last step from here ------------------------
400                 // Activate the hub. This is ALWAYS the last step in this method
401                 $this->enableHubIsActive();
402                 // ---------------------- Last step until here ------------------------
403         }
404
405         /**
406          * Initializes the listener pool (class)
407          *
408          * @return      void
409          */
410         public function initializeListenerPool () {
411                 // Debug output
412                 $this->debugOutput('HUB: Initialize listener: START');
413
414                 // Get a new pool instance
415                 $this->listenerPoolInstance = ObjectFactory::createObjectByConfiguredName('listener_pool_class', array($this));
416
417                 // Get an instance of the low-level listener
418                 $listenerInstance = ObjectFactory::createObjectByConfiguredName('tcp_listener_class', array($this));
419
420                 // Setup address and port
421                 $listenerInstance->setListenAddressByConfiguration('node_listen_addr');
422                 $listenerInstance->setListenPortByConfiguration('node_tcp_listen_port');
423
424                 // Initialize the listener
425                 $listenerInstance->initListener();
426
427                 // Get a decorator class
428                 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('hub_tcp_listener_class', array($listenerInstance));
429
430                 // Add this listener to the pool
431                 $this->listenerPoolInstance->addListener($decoratorInstance);
432
433                 // Get a decorator class
434                 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('client_tcp_listener_class', array($listenerInstance));
435
436                 // Add this listener to the pool
437                 $this->listenerPoolInstance->addListener($decoratorInstance);
438
439                 // Get an instance of the low-level listener
440                 $listenerInstance = ObjectFactory::createObjectByConfiguredName('udp_listener_class', array($this));
441
442                 // Setup address and port
443                 $listenerInstance->setListenAddressByConfiguration('node_listen_addr');
444                 $listenerInstance->setListenPortByConfiguration('node_udp_listen_port');
445
446                 // Initialize the listener
447                 $listenerInstance->initListener();
448
449                 // Get a decorator class
450                 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('hub_udp_listener_class', array($listenerInstance));
451
452                 // Add this listener to the pool
453                 $this->listenerPoolInstance->addListener($decoratorInstance);
454
455                 // Get a decorator class
456                 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('client_udp_listener_class', array($listenerInstance));
457
458                 // Add this listener to the pool
459                 $this->listenerPoolInstance->addListener($decoratorInstance);
460
461                 // Debug output
462                 $this->debugOutput('HUB: Initialize listener: FINISHED.');
463         }
464
465         /**
466          * Restores a previously stored node list from database
467          *
468          * @return      void
469          */
470         public function bootstrapRestoreNodeList () {
471                 // Debug output
472                 $this->debugOutput('HUB: Restore node list: START');
473
474                 // Get a wrapper instance
475                 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('node_list_db_wrapper_class');
476
477                 // Now get a search criteria instance
478                 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
479
480                 // Search for the node number zero which is hard-coded the default
481                 // @TODO Add some criteria, e.g. if the node is active or so
482                 //$searchInstance->addCriteria(NodeListDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
483                 //$searchInstance->addCriteria(NodeListDatabaseWrapper::DB_COLUMN_NODE_TYPE, $this->getRequestInstance()->getRequestElement('mode'));
484                 //$searchInstance->setLimit(1);
485
486                 // Get a result back
487                 $resultInstance = $wrapperInstance->doSelectByCriteria($searchInstance);
488
489                 // Is it valid?
490                 if ($resultInstance->next()) {
491                         $this->partialStub('Do something for restoring the list.');
492                         // Output message
493                         //$this->debugOutput('BOOTSTRAP: ');
494                 } // END - if
495
496                 // Debug output
497                 $this->debugOutput('HUB: Restore node list: FINISHED.');
498         }
499 }
500
501 // [EOF]
502 ?>