]> git.mxchange.org Git - hub.git/blob - application/hub/main/nodes/class_BaseHubNode.php
publishHubDescriptor() added, TODOs.txt updated
[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 $connectorInstance = 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 listener pool instance
87          *
88          * @param       $listenerPoolInstance   Our new listener pool instance
89          * @return      void
90          */
91         private final function setListenerPoolInstance (PoolableListener $listenerPoolInstance) {
92                 $this->listenerPoolInstance = $listenerPoolInstance;
93         }
94
95         /**
96          * Getter for listener pool instance
97          *
98          * @return      $listenerPoolInstance   Our current listener pool instance
99          */
100         public final function getListenerPoolInstance () {
101                 return $this->listenerPoolInstance;
102         }
103
104         /**
105          * Setter for session id
106          *
107          * @param       $sessionId              Our new session id
108          * @return      void
109          */
110         private final function setSessionId ($sessionId) {
111                 $this->sessionId = (string) $sessionId;
112         }
113
114         /**
115          * Getter for session id
116          *
117          * @return      $sessionId              Our new session id
118          */
119         public final function getSessionId () {
120                 return $this->sessionId;
121         }
122
123         /**
124          * Setter for query instance
125          *
126          * @param       $connectorInstance              Our new query instance
127          * @return      void
128          */
129         private final function setQueryConnectorInstance (Connectable $connectorInstance) {
130                 $this->connectorInstance = $connectorInstance;
131         }
132
133         /**
134          * Getter for query instance
135          *
136          * @return      $connectorInstance              Our new query instance
137          */
138         public final function getQueryConnectorInstance () {
139                 return $this->connectorInstance;
140         }
141
142         /**
143          * Getter for boot IP/port combination
144          *
145          * @return      $bootIpPort             The IP/port combination of the boot node
146          */
147         protected final function getBootIpPort () {
148                 return $this->bootIpPort;
149         }
150
151         /**
152          * Checks wether the given IP address matches one of the bootstrapping nodes
153          *
154          * @param       $remoteAddr             IP address to checkout against our bootstrapping list
155          * @return      $isFound                Wether the IP is found
156          */
157         protected function ifAddressMatchesBootstrappingNodes ($remoteAddr) {
158                 // By default nothing is found
159                 $isFound = false;
160
161                 // Run through all configured IPs
162                 foreach (explode(',', $this->getConfigInstance()->getConfigEntry('hub_bootstrap_nodes')) as $ipPort) {
163                         // Split it up in IP/port
164                         $ipPortArray = explode(':', $ipPort);
165
166                         // Does it match?
167                         if ($ipPortArray[0] == $remoteAddr) {
168                                 // Found it!
169                                 $isFound = true;
170
171                                 // Remember the port number
172                                 $this->bootIpPort = $ipPort;
173
174                                 // Output message
175                                 $this->debugOutput('BOOTSTRAP: ' . __FUNCTION__ . '[' . __LINE__ . ']: IP matches remote address ' . $ipPort . '.');
176
177                                 // Stop further searching
178                                 break;
179                         } elseif ($ipPortArray[0] == $this->getConfigInstance()->getConfigEntry('node_listen_addr')) {
180                                 // IP matches listen address. At this point we really don't care
181                                 // if we can also listen on that address!
182                                 $isFound = true;
183
184                                 // Remember the port number
185                                 $this->bootIpPort = $ipPort;
186
187                                 // Output message
188                                 $this->debugOutput('BOOTSTRAP: ' . __FUNCTION__ . '[' . __LINE__ . ']: IP matches listen address ' . $ipPort . '.');
189
190                                 // Stop further searching
191                                 break;
192                         }
193                 } // END - foreach
194
195                 // Return the result
196                 return $isFound;
197         }
198
199         /**
200          * Outputs the console teaser. This should only be executed on startup or
201          * full restarts. This method generates some space around the teaser.
202          *
203          * @return      void
204          */
205         public function outputConsoleTeaser () {
206                 // Get the app instance (for shortening our code)
207                 $app = $this->getApplicationInstance();
208
209                 // Output all lines
210                 $this->debugOutput(' ');
211                 $this->debugOutput($app->getAppName() . ' v' . $app->getAppVersion() . ' - ' . $this->getRequestInstance()->getRequestElement('mode') . ' mode active');
212                 $this->debugOutput('Copyright (c) 2007 - 2008 Roland Haeder, 2009 Hub Developer Team');
213                 $this->debugOutput(' ');
214                 $this->debugOutput('This program comes with ABSOLUTELY NO WARRANTY; for details see docs/COPYING.');
215                 $this->debugOutput('This is free software, and you are welcome to redistribute it under certain');
216                 $this->debugOutput('conditions; see docs/COPYING for details.');
217                 $this->debugOutput(' ');
218         }
219
220         /**
221          * Generic method to acquire a hub-id. On first run this generates a new one
222          * based on many pseudo-random data. On any later run, unless the id
223          * got not removed from database, it will be restored from the database.
224          *
225          * @return      void
226          */
227         public function bootstrapAcquireHubId () {
228                 // Get a wrapper instance
229                 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('node_info_db_wrapper_class');
230
231                 // Now get a search criteria instance
232                 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
233
234                 // Search for the node number zero which is hard-coded the default
235                 $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
236                 $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_TYPE, $this->getRequestInstance()->getRequestElement('mode'));
237                 $searchInstance->setLimit(1);
238
239                 // Get a result back
240                 $resultInstance = $wrapperInstance->doSelectByCriteria($searchInstance);
241
242                 // Is it valid?
243                 if ($resultInstance->next()) {
244                         // Save the result instance in this class
245                         $this->setResultInstance($resultInstance);
246
247                         // Get the node id from result and set it
248                         $this->setNodeId($this->getField(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_ID));
249
250                         // Output message
251                         $this->debugOutput('BOOTSTRAP: Re-using found node-id: ' . $this->getNodeId() . '');
252                 } else {
253                         // Get an RNG instance (Random Number Generator)
254                         $rngInstance = ObjectFactory::createObjectByConfiguredName('rng_class');
255
256                         // Generate a pseudo-random string
257                         $randomString = $rngInstance->randomString(255) . ':' . $this->getBootIpPort()  . ':' . $this->getRequestInstance()->getRequestElement('mode');
258
259                         // Get a crypto instance
260                         $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
261
262                         // Hash and encrypt the string so we become a "node id" aka Hub-Id
263                         $this->setNodeId($cryptoInstance->hashString($cryptoInstance->encryptString($randomString)));
264
265                         // Register the node id with our wrapper
266                         $wrapperInstance->registerNodeId($this, $this->getRequestInstance());
267
268                         // Output message
269                         $this->debugOutput('BOOTSTRAP: Created new node-id: ' . $this->getNodeId() . '');
270                 }
271         }
272
273         /**
274          * Generates a session id which will be sent to the other hubs and clients
275          *
276          * @return      void
277          */
278         public function bootstrapGenerateSessionId () {
279                 // Get an RNG instance
280                 $rngInstance = ObjectFactory::createObjectByConfiguredName('rng_class');
281
282                 // Generate a pseudo-random string
283                 $randomString = $rngInstance->randomString(255) . ':' . $this->getBootIpPort() . ':' . $this->getRequestInstance()->getRequestElement('mode');
284
285                 // Get a crypto instance
286                 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
287
288                 // Hash and encrypt the string so we become a "node id" aka Hub-Id
289                 $this->setSessionId($cryptoInstance->hashString($cryptoInstance->encryptString($randomString)));
290
291                 // Get a wrapper instance
292                 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('node_info_db_wrapper_class');
293
294                 // Register the node id with our wrapper
295                 $wrapperInstance->registerSessionId($this, $this->getRequestInstance());
296
297                 // Output message
298                 $this->debugOutput('BOOTSTRAP: Created new session-id: ' . $this->getSessionId() . '');
299         }
300
301         /**
302          * Initializes queues which every node needs
303          *
304          * @return      void
305          */
306         protected function initGenericQueues () {
307                 // Debug message
308                 $this->debugOutput('BOOTSTRAP: Initialize queues: START');
309
310                 // Set the query connector instance
311                 $this->setQueryConnectorInstance(ObjectFactory::createObjectByConfiguredName('query_connector_class', array($this)));
312
313                 // Run a test query
314                 $this->getQueryConnectorInstance()->doTestQuery();
315
316                 // Debug message
317                 $this->debugOutput('BOOTSTRAP: Initialize queues: FINISHED');
318         }
319
320         /**
321          * Publish our hub descriptor to the upper hub(s)
322          *
323          * @return      void
324          * @todo        This should be implemented in a generic way to keep things easy.
325          */
326         protected function publishHubDescriptor () {
327                 $this->partialStub('Unfinished method.');
328         }
329
330         /**
331          * Adds hub data elements to a given dataset instance
332          *
333          * @param       $criteriaInstance       An instance of a storeable criteria
334          * @param       $requestInstance        An instance of a Requestable class
335          * @return      void
336          */
337         public function addElementsToDataSet (StoreableCriteria $criteriaInstance, Requestable $requestInstance) {
338                 // Add node number and type
339                 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
340                 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_TYPE, $requestInstance->getRequestElement('mode'));
341
342                 // Add the node id
343                 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_ID, $this->getNodeId());
344
345                 // Add the session id if acquired
346                 if ($this->getSessionId() != '') {
347                         $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_SESSION_ID, $this->getSessionId());
348                 } // END - if
349         }
350
351         /**
352          * Updates a given field with new value
353          *
354          * @param       $fieldName              Field to update
355          * @param       $fieldValue             New value to store
356          * @return      void
357          * @throws      DatabaseUpdateSupportException  If this class does not support database updates
358          * @todo        Try to make this method more generic so we can move it in BaseFrameworkSystem
359          */
360         public function updateDatabaseField ($fieldName, $fieldValue) {
361                 // Unfinished
362                 $this->partialStub('Unfinished!');
363                 return;
364
365                 // Get a critieria instance
366                 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
367
368                 // Add search criteria
369                 $searchInstance->addCriteria(UserDatabaseWrapper::DB_COLUMN_USERNAME, $this->getUserName());
370                 $searchInstance->setLimit(1);
371
372                 // Now get another criteria
373                 $updateInstance = ObjectFactory::createObjectByConfiguredName('update_criteria_class');
374
375                 // Add criteria entry which we shall update
376                 $updateInstance->addCriteria($fieldName, $fieldValue);
377
378                 // Add the search criteria for searching for the right entry
379                 $updateInstance->setSearchInstance($searchInstance);
380
381                 // Set wrapper class name
382                 $updateInstance->setWrapperConfigEntry('user_db_wrapper_class');
383
384                 // Remember the update in database result
385                 $this->getResultInstance()->add2UpdateQueue($updateInstance);
386         }
387
388         /**
389          * Getter for $hubIsActive attribute
390          *
391          * @return      $hubIsActive    Wether the hub is activer
392          */
393         public final function isHubActive () {
394                 return $this->hubIsActive;
395         }
396
397         /**
398          * Setter for $hubIsActive attribute
399          *
400          * @param       $hubIsActive    Wether the hub is activer
401          */
402         public final function enableHubIsActive ($hubIsActive = true) {
403                 $this->hubIsActive = $hubIsActive;
404         }
405
406         /**
407          * Activates the hub by doing some final preparation and setting
408          * $hubIsActive to true
409          *
410          * @param       $requestInstance        A Requestable class
411          * @param       $responseInstance       A Responseable class
412          * @return      void
413          */
414         public function activateHub (Requestable $requestInstance, Responseable $responseInstance) {
415                 // Checks wether a listener is still active and shuts it down if one
416                 // is still listening
417                 if (($this->determineIfListenerIsActive()) && ($this->isHubActive())) {
418                         // Shutdown them down before they can hurt anything
419                         $this->shutdownListenerPool();
420                 } // END - if
421
422                 // Get the controller here
423                 $controllerInstance = Registry::getRegistry()->getInstance('controller');
424
425                 // Run all filters for the hub activation
426                 $controllerInstance->executeActivationFilters($requestInstance, $responseInstance);
427
428                 // ----------------------- Last step from here ------------------------
429                 // Activate the hub. This is ALWAYS the last step in this method
430                 $this->enableHubIsActive();
431                 // ---------------------- Last step until here ------------------------
432         }
433
434         /**
435          * Initializes the listener pool (class)
436          *
437          * @return      void
438          */
439         public function initializeListenerPool () {
440                 // Debug output
441                 $this->debugOutput('HUB: Initialize listener: START');
442
443                 // Get a new pool instance
444                 $this->setListenerPoolInstance(ObjectFactory::createObjectByConfiguredName('listener_pool_class', array($this)));
445
446                 // Get an instance of the low-level listener
447                 $listenerInstance = ObjectFactory::createObjectByConfiguredName('tcp_listener_class', array($this));
448
449                 // Setup address and port
450                 $listenerInstance->setListenAddressByConfiguration('node_listen_addr');
451                 $listenerInstance->setListenPortByConfiguration('node_tcp_listen_port');
452
453                 // Initialize the listener
454                 $listenerInstance->initListener();
455
456                 // Get a decorator class
457                 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('hub_tcp_listener_class', array($listenerInstance));
458
459                 // Add this listener to the pool
460                 $this->getListenerPoolInstance()->addListener($decoratorInstance);
461
462                 // Get a decorator class
463                 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('client_tcp_listener_class', array($listenerInstance));
464
465                 // Add this listener to the pool
466                 $this->getListenerPoolInstance()->addListener($decoratorInstance);
467
468                 // Get an instance of the low-level listener
469                 $listenerInstance = ObjectFactory::createObjectByConfiguredName('udp_listener_class', array($this));
470
471                 // Setup address and port
472                 $listenerInstance->setListenAddressByConfiguration('node_listen_addr');
473                 $listenerInstance->setListenPortByConfiguration('node_udp_listen_port');
474
475                 // Initialize the listener
476                 $listenerInstance->initListener();
477
478                 // Get a decorator class
479                 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('hub_udp_listener_class', array($listenerInstance));
480
481                 // Add this listener to the pool
482                 $this->getListenerPoolInstance()->addListener($decoratorInstance);
483
484                 // Get a decorator class
485                 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('client_udp_listener_class', array($listenerInstance));
486
487                 // Add this listener to the pool
488                 $this->getListenerPoolInstance()->addListener($decoratorInstance);
489
490                 // Debug output
491                 $this->debugOutput('HUB: Initialize listener: FINISHED.');
492         }
493
494         /**
495          * Restores a previously stored node list from database
496          *
497          * @return      void
498          */
499         public function bootstrapRestoreNodeList () {
500                 // Debug output
501                 $this->debugOutput('HUB: Restore node list: START');
502
503                 // Get a wrapper instance
504                 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('node_list_db_wrapper_class');
505
506                 // Now get a search criteria instance
507                 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
508
509                 // Search for the node number zero which is hard-coded the default
510                 // @TODO Add some criteria, e.g. if the node is active or so
511                 //$searchInstance->addCriteria(NodeListDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
512                 //$searchInstance->addCriteria(NodeListDatabaseWrapper::DB_COLUMN_NODE_TYPE, $this->getRequestInstance()->getRequestElement('mode'));
513                 //$searchInstance->setLimit(1);
514
515                 // Get a result back
516                 $resultInstance = $wrapperInstance->doSelectByCriteria($searchInstance);
517
518                 // Is it valid?
519                 if ($resultInstance->next()) {
520                         $this->partialStub('Do something for restoring the list.');
521                         // Output message
522                         //$this->debugOutput('HUB: ');
523                 } else {
524                         // No previously saved node list found!
525                         $this->debugOutput('HUB: No previously saved node list found. This is fine.');
526                 }
527
528                 // Debug output
529                 $this->debugOutput('HUB: Restore node list: FINISHED.');
530         }
531 }
532
533 // [EOF]
534 ?>