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