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