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