]> git.mxchange.org Git - hub.git/blob - application/hub/main/nodes/class_BaseHubNode.php
Introduced updateNodeData() to update/refresh node data ... ;)
[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                 // Debug output
399                 $this->debugOutput('HUB-Announcement: START (taskInstance=' . $taskInstance->__toString(). ')');
400
401                 // Get a helper instance
402                 $helperInstance = ObjectFactory::createObjectByConfiguredName('hub_announcement_helper_class');
403
404                 // Load the announcement descriptor
405                 $helperInstance->loadDescriptorXml();
406
407                 // Compile all variables
408                 $helperInstance->getTemplateInstance()->compileConfigInVariables();
409
410                 // "Publish" the descriptor by sending it to the bootstrap/list nodes
411                 $helperInstance->sendPackage($this);
412
413                 // Change the state, this should be the last line except debug output
414                 $this->getStateInstance()->nodeAnnouncedToUpperHubs();
415
416                 // Debug output
417                 $this->debugOutput('HUB-Announcement: FINISHED');
418         }
419
420         /**
421          * Does a self-connect attempt on the public IP address. This should make
422          * it sure, we are reachable from outside world. For this kind of package we
423          * don't need that overload we have in the announcement phase.
424          *
425          * @param       $taskInstance   The task instance running this announcement
426          * @return      void
427          */
428         public function doSelfConnection (Taskable $taskInstance) {
429                 // Debug output
430                 $this->debugOutput('HUB: Self Connection: START (taskInstance=' . $taskInstance->__toString(). ')');
431
432                 // Get a helper instance
433                 $helperInstance = ObjectFactory::createObjectByConfiguredName('hub_self_connect_helper_class', array($this));
434
435                 // Load the descriptor (XML) file
436                 $helperInstance->loadDescriptorXml();
437
438                 // Compile all variables
439                 $helperInstance->getTemplateInstance()->compileConfigInVariables();
440
441                 // And send the package away
442                 $helperInstance->sendPackage($this);
443
444                 // Debug output
445                 $this->debugOutput('HUB: Self Connection: FINISHED');
446         }
447
448         /**
449          * Activates the hub by doing some final preparation and setting
450          * $hubIsActive to true
451          *
452          * @param       $requestInstance        A Requestable class
453          * @param       $responseInstance       A Responseable class
454          * @return      void
455          */
456         public function activateNode (Requestable $requestInstance, Responseable $responseInstance) {
457                 // Checks whether a listener is still active and shuts it down if one
458                 // is still listening.
459                 if (($this->determineIfListenerIsActive()) && ($this->isNodeActive())) {
460                         // Shutdown them down before they can hurt anything
461                         $this->shutdownListenerPool();
462                 } // END - if
463
464                 // Get the controller here
465                 $controllerInstance = Registry::getRegistry()->getInstance('controller');
466
467                 // Run all filters for the hub activation
468                 $controllerInstance->executeActivationFilters($requestInstance, $responseInstance);
469
470                 // ----------------------- Last step from here ------------------------
471                 // Activate the hub. This is ALWAYS the last step in this method
472                 $this->getStateInstance()->nodeIsActivated();
473                 // ---------------------- Last step until here ------------------------
474         }
475
476         /**
477          * Initializes the listener pool (class)
478          *
479          * @return      void
480          */
481         public function initializeListenerPool () {
482                 // Debug output
483                 $this->debugOutput('HUB: Initialize listener: START');
484
485                 // Get a new pool instance
486                 $this->setListenerPoolInstance(ObjectFactory::createObjectByConfiguredName('listener_pool_class', array($this)));
487
488                 // Get an instance of the low-level listener
489                 $listenerInstance = ObjectFactory::createObjectByConfiguredName('tcp_listener_class', array($this));
490
491                 // Setup address and port
492                 $listenerInstance->setListenAddressByConfiguration('node_listen_addr');
493
494                 /*
495                  * All nodes can now use the same configuration entry because it can be
496                  * customized in config-local.php.
497                  */
498                 $listenerInstance->setListenPortByConfiguration('node_tcp_listen_port');
499
500                 // Initialize the listener
501                 $listenerInstance->initListener();
502
503                 // Get a decorator class
504                 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('hub_tcp_listener_class', array($listenerInstance));
505
506                 // Add this listener to the pool
507                 $this->getListenerPoolInstance()->addListener($decoratorInstance);
508
509                 // Get a decorator class
510                 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('client_tcp_listener_class', array($listenerInstance));
511
512                 // Add this listener to the pool
513                 $this->getListenerPoolInstance()->addListener($decoratorInstance);
514
515                 // Get an instance of the low-level listener
516                 $listenerInstance = ObjectFactory::createObjectByConfiguredName('udp_listener_class', array($this));
517
518                 // Setup address and port
519                 $listenerInstance->setListenAddressByConfiguration('node_listen_addr');
520
521                 /*
522                  * All nodes can now use the same configuration entry because it can be
523                  * customized in config-local.php.
524                  */
525                 $listenerInstance->setListenPortByConfiguration('node_udp_listen_port');
526
527                 // Initialize the listener
528                 $listenerInstance->initListener();
529
530                 // Get a decorator class
531                 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('hub_udp_listener_class', array($listenerInstance));
532
533                 // Add this listener to the pool
534                 $this->getListenerPoolInstance()->addListener($decoratorInstance);
535
536                 // Get a decorator class
537                 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('client_udp_listener_class', array($listenerInstance));
538
539                 // Add this listener to the pool
540                 $this->getListenerPoolInstance()->addListener($decoratorInstance);
541
542                 // Debug output
543                 $this->debugOutput('HUB: Initialize listener: FINISHED.');
544         }
545
546         /**
547          * Restores a previously stored node list from database
548          *
549          * @return      void
550          */
551         public function bootstrapRestoreNodeList () {
552                 // Debug output
553                 $this->debugOutput('HUB: Restore node list: START');
554
555                 // Get a wrapper instance
556                 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('node_list_db_wrapper_class');
557
558                 // Now get a search criteria instance
559                 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
560
561                 // Search for the node number zero which is hard-coded the default
562                 // @TODO Add some criteria, e.g. if the node is active or so
563                 //$searchInstance->addCriteria(NodeListDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
564                 //$searchInstance->addCriteria(NodeListDatabaseWrapper::DB_COLUMN_NODE_TYPE, $this->getRequestInstance()->getRequestElement('mode'));
565                 //$searchInstance->setLimit(1);
566
567                 // Get a result back
568                 $resultInstance = $wrapperInstance->doSelectByCriteria($searchInstance);
569
570                 // Is it valid?
571                 if ($resultInstance->next()) {
572                         $this->partialStub('Do something for restoring the list.');
573                         // Output message
574                         //$this->debugOutput('HUB: ');
575                 } else {
576                         // No previously saved node list found!
577                         $this->debugOutput('HUB: No previously saved node list found. This is fine.');
578                 }
579
580                 // Debug output
581                 $this->debugOutput('HUB: Restore node list: FINISHED.');
582         }
583
584         /**
585          * Getter for isActive attribute
586          *
587          * @return      $isActive       Whether the hub is active
588          */
589         public final function isNodeActive () {
590                 return $this->isActive;
591         }
592
593         /**
594          * Enables (default) or disables isActive flag
595          *
596          * @param       $isActive       Whether the hub is active
597          * @return      void
598          */
599         public final function enableIsActive ($isActive = true) {
600                 $this->isActive = (bool) $isActive;
601         }
602
603         /**
604          * Checks whether this node accepts announcements
605          *
606          * @return      $acceptAnnouncements    Whether this node accepts announcements
607          */
608         public final function isAcceptingAnnouncements () {
609                 // Check it (this node must be active and not shutdown!)
610                 $acceptAnnouncements = (($this->acceptAnnouncements === true) && ($this->isNodeActive()));
611
612                 // Return it
613                 return $acceptAnnouncements;
614         }
615
616         /**
617          * Enables whether this node accepts announcements
618          *
619          * @param       $acceptAnnouncements    Whether this node accepts announcements (default: true)
620          * @return      void
621          */
622         protected final function enableAcceptingAnnouncements ($acceptAnnouncements = true) {
623                 $this->acceptAnnouncements = $acceptAnnouncements;
624         }
625         
626         
627         /**
628          * "Getter for address:port combination
629          *
630          * @param       $handlerInstance        A valid Networkable instance
631          * @return      $addressPort            A address:port combination for this node
632          */
633         public final function getAddressPort (Networkable $handlerInstance) {
634                 // Construct config entry
635                 $configEntry = 'node_' . $handlerInstance->getHandlerName() . '_listen_port';
636
637                 // Get IP and port
638                 $addressPort = $this->getConfigInstance()->detectServerAddress() . ':' . $this->getConfigInstance()->getConfigEntry($configEntry);
639
640                 // Return it
641                 return $addressPort;
642         }
643
644         /**
645          * Updates/refreshes node data (e.g. state).
646          *
647          * @return      void
648          * @todo        Find more to do here
649          */
650         public function updateNodeData () {
651                 // Set some dummy configuration entries, e.g. node_status
652                 $this->getConfigInstance()->setConfigEntry('node_status', $this->getStateInstance()->getStateName());
653         }
654 }
655
656 // [EOF]
657 ?>