]> git.mxchange.org Git - hub.git/blob - application/hub/main/dht/node/class_NodeDhtFacade.php
This assertion cannot work here as a new node has no entry in the DHT (bad copy-paste...
[hub.git] / application / hub / main / dht / node / class_NodeDhtFacade.php
1 <?php
2 /**
3  * A Node DHT facade class
4  *
5  * @author              Roland Haeder <webmaster@shipsimu.org>
6  * @version             0.0.0
7  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2012 Hub Developer Team
8  * @license             GNU GPL 3.0 or any newer version
9  * @link                http://www.shipsimu.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 NodeDhtFacade extends BaseDht implements DistributableNode, Registerable {
25         /**
26          * Protected constructor
27          *
28          * @return      void
29          */
30         protected function __construct () {
31                 // Call parent constructor
32                 parent::__construct(__CLASS__);
33         }
34
35         /**
36          * Creates an instance of this class
37          *
38          * @return      $dhtInstance    An instance of a Distributable class
39          */
40         public final static function createNodeDhtFacade () {
41                 // Get new instance
42                 $dhtInstance = new NodeDhtFacade();
43
44                 // Get a database wrapper instance
45                 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName('node_dht_db_wrapper_class');
46
47                 // Set it in this class
48                 $dhtInstance->setWrapperInstance($wrapperInstance);
49
50                 // Return the prepared instance
51                 return $dhtInstance;
52         }
53
54         /**
55          * Registers/updates an entry in the DHT with given data from $dhtData
56          * array. Different DHT implemtations may handle this differently as they
57          * may enrich the data with more meta data.
58          *
59          * @param       $dhtData        A valid array with DHT-related data (e.g. node/peer data)
60          * @return      void
61          * @todo        Does this data need to be enriched with more meta data?
62          */
63         protected function insertDataIntoDht (array $dhtData) {
64                 // Check if there is already an entry for given node_id
65                 if ($this->getWrapperInstance()->isNodeRegistered($dhtData)) {
66                         /*
67                          * Update existing record. Please note that this step is not secure
68                          * (e.g. DHT poisoning) it would be good to implement some checks if
69                          * the both node owner trust each other (see sub-project 'DSHT').
70                          */
71                         $this->getWrapperInstance()->updateNode($dhtData);
72                 } else {
73                         /*
74                          * Inserts given node data into the DHT. As above, this step does
75                          * currently not perform any security checks.
76                          */
77                         $this->getWrapperInstance()->registerNode($dhtData);
78                 }
79         }
80
81         /**
82          * Initializes the distributed hash table (DHT)
83          *
84          * @return      void
85          */
86         public function initDht () {
87                 // Is the local node registered?
88                 if ($this->getWrapperInstance()->isLocalNodeRegistered()) {
89                         // Then only update session id
90                         $this->getWrapperInstance()->updateLocalNode();
91                 } else {
92                         // No, so register it
93                         $this->getWrapperInstance()->registerLocalNode();
94                 }
95
96                 // Change state
97                 $this->getStateInstance()->dhtHasInitialized();
98         }
99
100         /**
101          * Bootstraps the DHT by sending out a message to all available nodes
102          * (including itself). This step helps the node to get to know more nodes
103          * which can be queried later for object distribution.
104          *
105          * @return      void
106          */
107         public function bootstrapDht () {
108                 // Get a helper instance
109                 $helperInstance = ObjectFactory::createObjectByConfiguredName('dht_bootstrap_helper_class');
110
111                 // Load the announcement descriptor
112                 $helperInstance->loadDescriptorXml($this);
113
114                 // Compile all variables
115                 $helperInstance->getTemplateInstance()->compileConfigInVariables();
116
117                 // "Publish" the descriptor by sending it to the bootstrap/list nodes
118                 $helperInstance->sendPackage($this);
119
120                 // Change state
121                 $this->getStateInstance()->dhtIsBooting();
122         }
123
124         /**
125          * Finds a node locally by given session id
126          *
127          * @param       $sessionId      Session id to lookup
128          * @return      $nodeData       Node-data array
129          */
130         public function findNodeLocalBySessionId ($sessionId) {
131                 // Default is empty data array
132                 $nodeData = array();
133
134                 /*
135                  * Call the wrapper to do the job and get back a result instance. There
136                  * will come back zero or one entry from the wrapper.
137                  */
138                 $resultInstance = $this->getWrapperInstance()->findNodeLocalBySessionId($sessionId);
139
140                 // Make sure the result instance is valid
141                 assert($resultInstance instanceof SearchableResult);
142                 assert($resultInstance->valid());
143
144                 // Is the next entry valid?
145                 if (($resultInstance->valid()) && ($resultInstance->next())) {
146                         /*
147                          * Then load the first entry (more entries are being ignored and
148                          * should not happen).
149                          */
150                         $nodeData = $resultInstance->current();
151                 } // END - if
152
153                 // Return node data
154                 return $nodeData;
155         }
156
157         /**
158          * Registers an other node with this node by given message data. The
159          * following data must always be present:
160          *
161          * - session-id  (for finding the node's record together with below data)
162          * - external-ip (hostname or IP number)
163          * - listen-port (TCP/UDP listen port for inbound connections)
164          *
165          * @param       $messageArray           An array with all minimum message data
166          * @param       $handlerInstance        An instance of a Handleable class
167          * @param       $forceUpdate            Optionally force update, don't register (default: register if not found)
168          * @return      void
169          * @throws      NodeSessionIdVerficationException       If the node was not found and update is forced
170          */
171         public function registerNodeByMessageData (array $messageData, Handleable $handlerInstance, $forceUpdate = FALSE) {
172                 // Get a search criteria class
173                 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
174
175                 // Debug message
176                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DHT-FACADE[' . __METHOD__ . ':' . __LINE__ . ']: state=' . $this->getPrintableState() . ',messageData=' . print_r($messageData, TRUE) . ',handlerInstance=' . $handlerInstance->__toString() . ',forceUpdate=' . intval($forceUpdate) . ',count(getSearchData())=' . count($handlerInstance->getSearchData()));
177
178                 // Search for the node's session id and external IP/hostname + TCP/UDP listen port
179                 foreach ($handlerInstance->getSearchData() as $key) {
180                         // Debug message
181                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DHT-FACADE[' . __METHOD__ . ':' . __LINE__ . ']: state=' . $this->getPrintableState() . ',key=' . $key);
182
183                         // Is it there?
184                         assert(isset($messageData[$key]));
185
186                         // Debug message
187                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DHT-FACADE[' . __METHOD__ . ':' . __LINE__ . ']: state=' . $this->getPrintableState() . ',messageData[' . $key . ']=' . $messageData[$key]);
188
189                         // Add criteria
190                         $searchInstance->addCriteria(str_replace('my-', '', $key), $messageData[$key]);
191                 } // END - foreach
192
193                 // Only one entry is fine
194                 $searchInstance->setLimit(1);
195
196                 // Run the query
197                 $resultInstance = $this->getWrapperInstance()->doSelectByCriteria($searchInstance);
198
199                 // Make sure the result instance is valid
200                 assert($resultInstance instanceof SearchableResult);
201
202                 // Is there already an entry?
203                 if ($resultInstance->valid()) {
204                         // Entry found, so update it
205                         $this->getWrapperInstance()->updateNodeByMessageData($messageData, $handlerInstance, $searchInstance);
206                 } elseif ($forceUpdate === FALSE) {
207                         // Nothing found, so register it
208                         $this->getWrapperInstance()->registerNodeByMessageData($messageData, $handlerInstance);
209                 } else {
210                         /*
211                          * Do not register non-existent nodes here. This is maybe fatal,
212                          * caused by "stolen" session id and/or not matching IP
213                          * number/port combination.
214                          */
215                         throw new NodeSessionIdVerficationException(array($this, $messageData), BaseHubSystem::EXCEPTION_NODE_SESSION_ID_NOT_VERIFYING);
216                 }
217
218                 // Save last exception
219                 $handlerInstance->setLastException($this->getWrapperInstance()->getLastException());
220         }
221
222         /**
223          * Queries the local DHT data(base) for a node list with all supported
224          * object types except the node by given session id.
225          *
226          * @param       $messageData            An array with message data from a node_list request
227          * @param       $handlerInstance        An instance of a Handleable class
228          * @param       $excludeKey                     Array key which should be excluded
229          * @param       $andKey                         Array of $separator-separated list of elements which all must match
230          * @param       $separator                      Sepator char (1st parameter for explode() call)
231          * @return      $nodeList                       An array with all found nodes
232          */
233         public function queryLocalNodeListExceptByMessageData (array $messageData, Handleable $handlerInstance, $excludeKey, $andKey, $separator) {
234                 // Make sure both keys are there
235                 assert((isset($messageData[$excludeKey])) && (isset($messageData[$andKey])));
236
237                 // Debug message
238                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DHT-FACADE[' . __METHOD__ . ':' . __LINE__ . ']: state=' . $this->getPrintableState() . ',messageData=' . print_r($messageData, TRUE));
239
240                 // Get a search criteria class
241                 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
242
243                 // Add all keys
244                 foreach (explode($separator, $messageData[$andKey]) as $criteria) {
245                         // Debug message
246                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DHT-FACADE[' . __METHOD__ . ':' . __LINE__ . ']: andKey=' . $andKey . ',criteria=' . $criteria);
247
248                         // Add it and leave any 'my-' prefix out
249                         $searchInstance->addChoiceCriteria(str_replace('my-', '', $andKey), $criteria);
250                 } // END - foreach
251
252                 // Add exclusion key
253                 $searchInstance->addExcludeCriteria(str_replace('my-', '', $excludeKey), $messageData[$excludeKey]);
254
255                 // Only X entries are fine
256                 $searchInstance->setLimit($this->getConfigInstance()->getConfigEntry('node_dht_list_limit'));
257
258                 // Run the query
259                 $resultInstance = $this->getWrapperInstance()->doSelectByCriteria($searchInstance);
260
261                 // Make sure the result instance is valid
262                 assert($resultInstance instanceof SearchableResult);
263                 assert($resultInstance->valid());
264
265                 // Init array
266                 $nodeList = array();
267
268                 // Get node list
269                 while ($resultInstance->next()) {
270                         // Get current element (it should be an array, and have at least 1 entry)
271                         $current = $resultInstance->current();
272                         assert(is_array($current));
273                         assert(count($current) > 0);
274
275                         // Debug message
276                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DHT-FACADE[' . __METHOD__ . ':' . __LINE__ . ']: current(' . count($current) . ')[' . gettype($current) . ']=' . print_r($current, TRUE));
277
278                         /*
279                          * Remove some keys as they should not be published.
280                          */
281                         unset($current[$this->getWrapperInstance()->getIndexKey()]);
282
283                         // Add this entry
284                         array_push($nodeList, $current);
285                 } // END - while
286
287                 // Save last exception
288                 $handlerInstance->setLastException($this->getWrapperInstance()->getLastException());
289
290                 // Return node list (array)
291                 return $nodeList;
292         }
293
294         /**
295          * Inserts given node list array (from earlier database result produced by
296          * an other node) into the DHT. This array origins from above method
297          * queryLocalNodeListExceptByMessageData().
298          *
299          * @param       $nodeList       An array from an earlier database result instance
300          * @return      void
301          */
302         public function insertNodeList (array $nodeList) {
303                 // If no node is in the list (array), skip the rest of this method
304                 if (count($nodeList) == 0) {
305                         // Debug message
306                         self::createDebugInstance(__CLASS__)->debugOutput('DHT-FACADE[' . __METHOD__ . ':' . __LINE__ . ']: No node record has been returned.');
307
308                         // Abort here
309                         return;
310                 } // END - if
311
312                 // Put them all into a stack
313                 foreach ($nodeList as $nodeData) {
314                         // Insert all entries
315                         $this->getStackerInstance()->pushNamed(self::STACKER_NAME_INSERT_NODE, $nodeData);
316                 } // END - foreach
317         }
318
319         /**
320          * Find recipients for given package data
321          *
322          * @param       $packageData    An array of valid package data
323          * @return      $recipients             An indexed array with DHT recipients
324          */
325         public function findRecipientsByPackageData (array $packageData) {
326                 // Query get a result instance back from DHT database wrapper.
327                 $resultInstance = $this->getWrapperInstance()->getResultFromExcludedSender($packageData);
328
329                 // Make sure the result instance is valid
330                 assert($resultInstance instanceof SearchableResult);
331                 assert($resultInstance->valid());
332
333                 // Init array
334                 $recipients = array();
335
336                 // Search for all recipients
337                 while ($resultInstance->next()) {
338                         // Get current entry
339                         $current = $resultInstance->current();
340                         /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DHT-FACADE[' . __METHOD__ . ':' . __LINE__ . ']: current=' . print_r($current, TRUE));
341
342                         // Add instance to recipient list
343                         array_push($recipients, $current);
344                 } // END - while
345
346                 // Return filled array
347                 return $recipients;
348         }
349
350         /**
351          * Finds DHT recipients by given key/value pair
352          *
353          * @param       $key            Key to search for
354          * @param       $value          Value to check on found key
355          * @return      $recipiens      Array with DHT recipients from given key/value pair
356          */
357         public function findRecipientsByKey ($key, $value) {
358                 // Look for all suitable nodes
359                 $resultInstance = $this->getWrapperInstance()->getResultFromKeyValue($key, $value);
360
361                 // Make sure the result instance is valid
362                 assert($resultInstance instanceof SearchableResult);
363                 assert($resultInstance->valid());
364
365                 // Init array
366                 $recipients = array();
367
368                 // "Walk" through all entries
369                 while ($resultInstance->next()) {
370                         // Get current entry
371                         $current = $resultInstance->current();
372
373                         // Add instance to recipient list
374                         array_push($recipients, $current);
375                 } // END - while
376
377                 // Return filled array
378                 return $recipients;
379         }
380 }
381
382 // [EOF]
383 ?>