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