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