]> git.mxchange.org Git - hub.git/blob - application/hub/main/dht/node/class_NodeDhtFacade.php
56c69efe21efe1a255ea3160444ba090be31dab8
[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@ship-simu.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.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 NodeDhtFacade extends BaseDht implements Distributable, 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          * Initializes the distributed hash table (DHT)
56          *
57          * @return      void
58          */
59         public function initDht () {
60                 // Is the local node registered?
61                 if ($this->getWrapperInstance()->isLocalNodeRegistered()) {
62                         // Then only update session id
63                         $this->getWrapperInstance()->updateLocalNode();
64                 } else {
65                         // No, so register it
66                         $this->getWrapperInstance()->registerLocalNode();
67                 }
68         }
69
70         /**
71          * Bootstraps the DHT by sending out a message to all available nodes
72          * (including itself). This step helps the node to get to know more nodes
73          * which can be queried later for object distribution.
74          *
75          * @return      void
76          */
77         public function bootstrapDht () {
78         }
79
80         /**
81          * Finds a node locally by given session id
82          *
83          * @param       $sessionId      Session id to lookup
84          * @return      $nodeData       Node-data array
85          */
86         public function findNodeLocalBySessionId ($sessionId) {
87                 // Default is empty data array
88                 $nodeData = array();
89
90                 /*
91                  * Call the wrapper to do the job and get back a result instance. There
92                  * will come back zero or one entry from the wrapper.
93                  */
94                 $resultInstance = $this->getWrapperInstance()->findNodeLocalBySessionId($sessionId);
95
96                 // Is the next entry valid?
97                 if ($resultInstance->next()) {
98                         /*
99                          * Then load the first entry (more entries are being ignored and
100                          * should not happen).
101                          */
102                         $nodeData = $resultInstance->current();
103                 } // END - if
104
105                 // Return node data
106                 return $nodeData;
107         }
108
109         /**
110          * Registers an other node with this node by given message data. The
111          * following data must always be present:
112          *
113          * - session-id  (for finding the node's record together with below data)
114          * - external-ip (hostname or IP number)
115          * - listen-port (TCP/UDP listen port for inbound connections)
116          *
117          * @param       $messageArray           An array with all minimum message data
118          * @param       $handlerInstance        An instance of a Handleable class
119          * @param       $forceUpdate            Optionally force update, don't register (default: register if not found)
120          * @return      void
121          * @throws      NodeSessionIdVerficationException       If the node was not found and update is forced
122          */
123         public function registerNodeByMessageData (array $messageData, Handleable $handlerInstance, $forceUpdate = FALSE) {
124                 // Get a search criteria class
125                 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
126
127                 // Debug message
128                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DHT-FACADE: messageData=' . print_r($messageData, true));
129
130                 // Search for the node's session id and external IP/hostname + TCP/UDP listen port
131                 foreach ($handlerInstance->getSearchData() as $key) {
132                         // Debug message
133                         /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DHT-FACADE: messageData[' . $key . ']=' . $messageData[$key]);
134
135                         // Is it there?
136                         assert(isset($messageData[$key]));
137
138                         // Add criteria
139                         $searchInstance->addCriteria(str_replace('my-', '', $key), $messageData[$key]);
140                 } // END - foreach
141
142                 // Only one entry is fine
143                 $searchInstance->setLimit(1);
144
145                 // Run the query
146                 $resultInstance = $this->getWrapperInstance()->doSelectByCriteria($searchInstance);
147
148                 // Is there already an entry?
149                 if ($resultInstance->next()) {
150                         // Entry found, so update it
151                         $this->getWrapperInstance()->updateNodeByMessageData($messageData, $handlerInstance, $searchInstance);
152                 } elseif ($forceUpdate === FALSE) {
153                         // Nothing found, so register it
154                         $this->getWrapperInstance()->registerNodeByMessageData($messageData, $handlerInstance);
155                 } else {
156                         /*
157                          * Do not register non-existent nodes here. This is maybe fatal,
158                          * caused by "stolen" session id and/or not matching IP
159                          * number/port combination.
160                          */
161                         throw new NodeSessionIdVerficationException(array($this, $messageData), BaseHubSystem::EXCEPTION_NODE_SESSION_ID_NOT_VERIFYING);
162                 }
163
164                 // Save last exception
165                 $handlerInstance->setLastException($this->getWrapperInstance()->getLastException());
166         }
167
168         /**
169          * Queries the local DHT data(base) for a node list with all supported
170          * object types except the node by given session id.
171          *
172          * @param       $messageData            An array with message data from a node_list request
173          * @param       $handlerInstance        An instance of a Handleable class
174          * @param       $excludeKey                     Array key which should be excluded
175          * @param       $andKey                         Array of $separator-separated list of elements which all must match
176          * @param       $separator                      Sepator char (1st parameter for explode() call)
177          * @return      $nodeList                       An array with all found nodes
178          */
179         public function queryLocalNodeListExceptByMessageData (array $messageData, Handleable $handlerInstance, $excludeKey, $andKey, $separator) {
180                 // Make sure both keys are there
181                 assert((isset($messageData[$excludeKey])) && (isset($messageData[$andKey])));
182
183                 // Debug message
184                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DHT-FACADE: messageData=' . print_r($messageData, true));
185
186                 // Get a search criteria class
187                 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
188
189                 // Add all keys
190                 foreach (explode($separator, $messageData[$andKey]) as $criteria) {
191                         // Debug message
192                         /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DHT-FACADE: andKey=' . $andKey . ',criteria=' . $criteria);
193
194                         // Add it and leave any 'my-' prefix out
195                         $searchInstance->addChoiceCriteria(str_replace('my-', '', $andKey), $criteria);
196                 } // END - foreach
197
198                 // Add exclusion key
199                 $searchInstance->addExcludeCriteria(str_replace('my-', '', $excludeKey), $messageData[$excludeKey]);
200
201                 // Only X entries are fine
202                 $searchInstance->setLimit($this->getConfigInstance()->getConfigEntry('node_dht_list_limit'));
203
204                 // Run the query
205                 $resultInstance = $this->getWrapperInstance()->doSelectByCriteria($searchInstance);
206
207                 // Get node list
208                 $nodeList = array();
209                 while ($resultInstance->next()) {
210                         // Add this entry
211                         array_push($nodeList, $resultInstance->current());
212                 } // END - while
213
214                 // Save last exception
215                 $handlerInstance->setLastException($this->getWrapperInstance()->getLastException());
216
217                 // Return node list (array)
218                 return $nodeList;
219         }
220
221         /**
222          * Inserts given node list array (from earlier database result produced by
223          * an other node) into the DHT. This array origins from above method
224          * queryLocalNodeListExceptByMessageData().
225          *
226          * @param       $nodeList       An array from an earlier database result instance
227          * @return      void
228          */
229         public function insertNodeList (array $nodeList) {
230                 // If no node is in the list (array), skip the rest of this method silently
231                 if (count($nodeList) == 0) {
232                         // Debug message
233                         self::createDebugInstance(__CLASS__)->debugOutput('DHT-FACADE: No node record has been returned.');
234
235                         // Abort here
236                         return;
237                 } // END - if
238
239                 // @TODO Not finish yet
240                 $this->partialStub('DHT: Needs implementing to insert ' . count($nodeList) . ' entry(-ies) into DHT.');
241         }
242 }
243
244 // [EOF]
245 ?>