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