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