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