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