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