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