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