]> git.mxchange.org Git - hub.git/blob - application/hub/main/nodes/class_BaseHubNode.php
Filters and chains added:
[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 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 id
27          */
28         private $nodeId = '';
29
30         /**
31          * Session id
32          */
33         private $sessionId = '';
34
35         /**
36          * IP/port number of bootstrapping node
37          */
38         private $bootIpPort = '';
39
40         /**
41          * Query connector instance
42          */
43         private $queryInstance = null;
44
45         /**
46          * Listener pool instance
47          */
48         private $listenerPoolInstance = null;
49
50         /**
51          * Wether the hub is active (true/false)
52          */
53         private $hubIsActive = false;
54
55         /**
56          * Protected constructor
57          *
58          * @param       $className      Name of the class
59          * @return      void
60          */
61         protected function __construct ($className) {
62                 // Call parent constructor
63                 parent::__construct($className);
64         }
65
66         /**
67          * Setter for node id
68          *
69          * @param       $nodeId         Our new node id
70          * @return      void
71          */
72         private final function setNodeId ($nodeId) {
73                 $this->nodeId = (string) $nodeId;
74         }
75
76         /**
77          * Getter for node id
78          *
79          * @return      $nodeId         Our new node id
80          */
81         private final function getNodeId () {
82                 return $this->nodeId;
83         }
84
85         /**
86          * Setter for session id
87          *
88          * @param       $sessionId              Our new session id
89          * @return      void
90          */
91         private final function setSessionId ($sessionId) {
92                 $this->sessionId = (string) $sessionId;
93         }
94
95         /**
96          * Getter for session id
97          *
98          * @return      $sessionId              Our new session id
99          */
100         private final function getSessionId () {
101                 return $this->sessionId;
102         }
103
104         /**
105          * Setter for query instance
106          *
107          * @param       $queryInstance          Our new query instance
108          * @return      void
109          */
110         private final function setQueryInstance (Queryable $queryInstance) {
111                 $this->queryInstance = $queryInstance;
112         }
113
114         /**
115          * Getter for query instance
116          *
117          * @return      $queryInstance          Our new query instance
118          */
119         protected final function getQueryInstance () {
120                 return $this->queryInstance;
121         }
122
123         /**
124          * Checks wether the given IP address matches one of the bootstrapping nodes
125          *
126          * @param       $remoteAddr             IP address to checkout against our bootstrapping list
127          * @return      $isFound                Wether the IP is found
128          */
129         protected function ifAddressMatchesBootstrappingNodes ($remoteAddr) {
130                 // By default nothing is found
131                 $isFound = false;
132
133                 // Run through all configured IPs
134                 foreach (explode(',', $this->getConfigInstance()->getConfigEntry('hub_bootstrap_nodes')) as $ipPort) {
135                         // Split it up in IP/port
136                         $ipPortArray = explode(':', $ipPort);
137
138                         // Does it match?
139                         if ($ipPortArray[0] == $remoteAddr) {
140                                 // Found it!
141                                 $isFound = true;
142
143                                 // Remember the port number
144                                 $this->bootIpPort = $ipPort;
145
146                                 // Output message
147                                 $this->debugOutput('BOOTSTRAP: ' . __FUNCTION__ . '[' . __LINE__ . ']: IP matches remote address ' . $ipPort . '.');
148
149                                 // Stop further searching
150                                 break;
151                         } elseif ($ipPortArray[0] == $this->getConfigInstance()->getConfigEntry('node_listen_addr')) {
152                                 // IP matches listen address. At this point we really don't care
153                                 // if we can also listen on that address!
154                                 $isFound = true;
155
156                                 // Remember the port number
157                                 $this->bootIpPort = $ipPort;
158
159                                 // Output message
160                                 $this->debugOutput('BOOTSTRAP: ' . __FUNCTION__ . '[' . __LINE__ . ']: IP matches listen address ' . $ipPort . '.');
161
162                                 // Stop further searching
163                                 break;
164                         }
165                 } // END - foreach
166
167                 // Return the result
168                 return $isFound;
169         }
170
171         /**
172          * Outputs the console teaser. This should only be executed on startup or
173          * full restarts. This method generates some space around the teaser.
174          *
175          * @return      void
176          */
177         public function outputConsoleTeaser () {
178                 // Get the app instance (for shortening our code)
179                 $app = $this->getApplicationInstance();
180
181                 // Output all lines
182                 $this->debugOutput(' ');
183                 $this->debugOutput($app->getAppName() . ' v' . $app->getAppVersion() . ' - ' . $this->getRequestInstance()->getRequestElement('mode') . ' mode active');
184                 $this->debugOutput('Copyright (c) 2007 - 2008 Roland Haeder, 2009 Hub Developer Team');
185                 $this->debugOutput(' ');
186                 $this->debugOutput('This program comes with ABSOLUTELY NO WARRANTY; for details see docs/COPYING.');
187                 $this->debugOutput('This is free software, and you are welcome to redistribute it under certain');
188                 $this->debugOutput('conditions; see docs/COPYING for details.');
189                 $this->debugOutput(' ');
190         }
191
192         /**
193          * Generic method to acquire a hub-id. On first run this generates a new one
194          * based on many pseudo-random data. On any later run, unless the id
195          * got not removed from database, it will be restored from the database.
196          *
197          * @return      void
198          */
199         public function bootstrapAcquireHubId () {
200                 // Get a wrapper instance
201                 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('node_info_db_wrapper_class');
202
203                 // Now get a search criteria instance
204                 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
205
206                 // Search for the node number zero which is hard-coded the default
207                 $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
208                 $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_TYPE, $this->getRequestInstance()->getRequestElement('mode'));
209                 $searchInstance->setLimit(1);
210
211                 // Get a result back
212                 $resultInstance = $wrapperInstance->doSelectByCriteria($searchInstance);
213
214                 // Is it valid?
215                 if ($resultInstance->next()) {
216                         // Save the result instance in this class
217                         $this->setResultInstance($resultInstance);
218
219                         // Get the node id from result and set it
220                         $this->setNodeId($this->getField(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_ID));
221
222                         // Output message
223                         $this->debugOutput('BOOTSTRAP: Re-using found node-id: ' . $this->getNodeId() . '');
224                 } else {
225                         // Get an RNG instance (Random Number Generator)
226                         $rngInstance = ObjectFactory::createObjectByConfiguredName('rng_class');
227
228                         // Generate a pseudo-random string
229                         $randomString = $rngInstance->randomString(255) . ':' . $this->getBootIpPort()  . ':' . $this->getRequestInstance()->getRequestElement('mode');
230
231                         // Get a crypto instance
232                         $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
233
234                         // Hash and encrypt the string so we become a "node id" aka Hub-Id
235                         $this->setNodeId($cryptoInstance->hashString($cryptoInstance->encryptString($randomString)));
236
237                         // Register the node id with our wrapper
238                         $wrapperInstance->registerNodeId($this, $this->getRequestInstance());
239
240                         // Output message
241                         $this->debugOutput('BOOTSTRAP: Created new node-id: ' . $this->getNodeId() . '');
242                 }
243         }
244
245         /**
246          * Generates a session id which will be sent to the other hubs and clients
247          *
248          * @return      void
249          */
250         public function bootstrapGenerateSessionId () {
251                 // Get an RNG instance
252                 $rngInstance = ObjectFactory::createObjectByConfiguredName('rng_class');
253
254                 // Generate a pseudo-random string
255                 $randomString = $rngInstance->randomString(255) . ':' . $this->getBootIpPort() . ':' . $this->getRequestInstance()->getRequestElement('mode');
256
257                 // Get a crypto instance
258                 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
259
260                 // Hash and encrypt the string so we become a "node id" aka Hub-Id
261                 $this->setSessionId($cryptoInstance->hashString($cryptoInstance->encryptString($randomString)));
262
263                 // Get a wrapper instance
264                 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('node_info_db_wrapper_class');
265
266                 // Register the node id with our wrapper
267                 $wrapperInstance->registerNodeId($this, $this->getRequestInstance());
268
269                 // Output message
270                 $this->debugOutput('BOOTSTRAP: Created new session-id: ' . $this->getSessionId() . '');
271         }
272
273         /**
274          * Getter for boot IP/port combination
275          *
276          * @return      $bootIpPort             The IP/port combination of the boot node
277          */
278         protected final function getBootIpPort () {
279                 return $this->bootIpPort;
280         }
281
282         /**
283          * Initializes queues which every node needs
284          *
285          * @return      void
286          */
287         protected function initGenericQueues () {
288                 // Set the query connector instance
289                 $this->setQueryInstance(ObjectFactory::createObjectByConfiguredName('query_connector_class', array($this)));
290
291                 // Run a test query
292                 $this->getQueryInstance()->doTestQuery();
293
294                 // Query queue initialized
295                 $this->debugOutput('BOOTSTRAP: Query queue initialized.');
296         }
297         
298         /**
299          * Adds hub data elements to a given dataset instance
300          *
301          * @param       $criteriaInstance       An instance of a storeable criteria
302          * @param       $requestInstance        An instance of a Requestable class
303          * @return      void
304          */
305         public function addElementsToDataSet (StoreableCriteria $criteriaInstance, Requestable $requestInstance) {
306                 // Add node number and type
307                 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
308                 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_TYPE, $requestInstance->getRequestElement('mode'));
309
310                 // Add the node id
311                 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_ID, $this->getNodeId());
312         }
313
314         /**
315          * Updates a given field with new value
316          *
317          * @param       $fieldName              Field to update
318          * @param       $fieldValue             New value to store
319          * @return      void
320          * @throws      DatabaseUpdateSupportException  If this class does not support database updates
321          * @todo        Try to make this method more generic so we can move it in BaseFrameworkSystem
322          */
323         public function updateDatabaseField ($fieldName, $fieldValue) {
324                 // Unfinished
325                 $this->partialStub('Unfinished!');
326                 return;
327
328                 // Get a critieria instance
329                 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
330
331                 // Add search criteria
332                 $searchInstance->addCriteria(UserDatabaseWrapper::DB_COLUMN_USERNAME, $this->getUserName());
333                 $searchInstance->setLimit(1);
334
335                 // Now get another criteria
336                 $updateInstance = ObjectFactory::createObjectByConfiguredName('update_criteria_class');
337
338                 // Add criteria entry which we shall update
339                 $updateInstance->addCriteria($fieldName, $fieldValue);
340
341                 // Add the search criteria for searching for the right entry
342                 $updateInstance->setSearchInstance($searchInstance);
343
344                 // Set wrapper class name
345                 $updateInstance->setWrapperConfigEntry('user_db_wrapper_class');
346
347                 // Remember the update in database result
348                 $this->getResultInstance()->add2UpdateQueue($updateInstance);
349         }
350
351         /**
352          * Getter for $hubIsActive attribute
353          *
354          * @return      $hubIsActive    Wether the hub is activer
355          */
356         public final function isHubActive () {
357                 return $this->hubIsActive;
358         }
359
360         /**
361          * Setter for $hubIsActive attribute
362          *
363          * @param       $hubIsActive    Wether the hub is activer
364          */
365         public final function enableHubIsActive ($hubIsActive = true) {
366                 $this->hubIsActive = $hubIsActive;
367         }
368
369         /**
370          * Activates the hub by doing some final preparation and setting
371          * $hubIsActive to true
372          *
373          * @param       $requestInstance        A Requestable class
374          * @param       $responseInstance       A Responseable class
375          * @return      void
376          */
377         public function activateHub (Requestable $requestInstance, Responseable $responseInstance) {
378                 // Checks wether a listener is still active and shuts it down if one
379                 // is still listening
380                 if (($this->determineIfListenerIsActive()) && ($this->isHubActive())) {
381                         // Shutdown them down before they can hurt anything
382                         $this->shutdownListenerPool();
383                 } // END - if
384
385                 // Get the controller here
386                 $controllerInstance = Registry::getRegistry()->getInstance('controller');
387
388                 // Run all filters for the hub activation
389                 $controllerInstance->executeHubActivationFilters($requestInstance, $responseInstance);
390
391                 // ----------------------- Last step from here ------------------------
392                 // Activate the hub. This is ALWAYS the last step in this method
393                 $this->enableHubIsActive();
394                 // ---------------------- Last step until here ------------------------
395         }
396
397         /**
398          * Initializes the listener pool (class)
399          *
400          * @return      void
401          */
402         public function initializeListenerPool () {
403                 // Debug output
404                 $this->debugOutput('HUB: Initializing listeners...');
405
406                 // Get a new pool instance
407                 $this->listenerPoolInstance = ObjectFactory::createObjectByConfiguredName('listener_pool_class', array($this));
408
409                 // Get an instance of the low-level listener
410                 $listenerInstance = ObjectFactory::createObjectByConfiguredName('tcp_listener_class', array($this));
411
412                 // Setup address and port
413                 $listenerInstance->setListenAddressByConfiguration('node_listen_addr');
414                 $listenerInstance->setListenPortByConfiguration('node_tcp_listen_port');
415
416                 // Initialize the listener
417                 $listenerInstance->initListener();
418
419                 // Get a decorator class
420                 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('hub_tcp_listener_class', array($listenerInstance));
421
422                 // Add this listener to the pool
423                 $this->listenerPoolInstance->addListener($decoratorInstance);
424
425                 // Get a decorator class
426                 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('client_tcp_listener_class', array($listenerInstance));
427
428                 // Add this listener to the pool
429                 $this->listenerPoolInstance->addListener($decoratorInstance);
430
431                 // Get an instance of the low-level listener
432                 $listenerInstance = ObjectFactory::createObjectByConfiguredName('udp_listener_class', array($this));
433
434                 // Setup address and port
435                 $listenerInstance->setListenAddressByConfiguration('node_listen_addr');
436                 $listenerInstance->setListenPortByConfiguration('node_udp_listen_port');
437
438                 // Initialize the listener
439                 $listenerInstance->initListener();
440
441                 // Get a decorator class
442                 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('hub_udp_listener_class', array($listenerInstance));
443
444                 // Add this listener to the pool
445                 $this->listenerPoolInstance->addListener($decoratorInstance);
446
447                 // Get a decorator class
448                 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('client_udp_listener_class', array($listenerInstance));
449
450                 // Add this listener to the pool
451                 $this->listenerPoolInstance->addListener($decoratorInstance);
452
453                 // Debug output
454                 $this->debugOutput('HUB: All listeners are initialized.');
455         }
456 }
457
458 // [EOF]
459 ?>