3 * A Node DHT facade class
5 * @author Roland Haeder <webmaster@shipsimu.org>
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
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.
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.
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/>.
24 class NodeDhtFacade extends BaseDht implements DistributableNode, Registerable {
26 * Protected constructor
30 protected function __construct () {
31 // Call parent constructor
32 parent::__construct(__CLASS__);
36 * Creates an instance of this class
38 * @return $dhtInstance An instance of a Distributable class
40 public final static function createNodeDhtFacade () {
42 $dhtInstance = new NodeDhtFacade();
44 // Get a database wrapper instance
45 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName('node_dht_db_wrapper_class');
47 // Set it in this class
48 $dhtInstance->setWrapperInstance($wrapperInstance);
50 // Return the prepared instance
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.
59 * @param $dhtData A valid array with DHT-related data (e.g. node/peer data)
61 * @todo Does this data need to be enriched with more meta data?
63 protected function insertDataIntoDht (array $dhtData) {
64 // Check if there is already an entry for given node_id
65 if ($this->getWrapperInstance()->isNodeRegistered($dhtData)) {
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').
71 $this->getWrapperInstance()->updateNode($dhtData);
74 * Inserts given node data into the DHT. As above, this step does
75 * currently not perform any security checks.
77 $this->getWrapperInstance()->registerNode($dhtData);
82 * Initializes the distributed hash table (DHT)
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();
93 $this->getWrapperInstance()->registerLocalNode();
97 $this->getStateInstance()->dhtHasInitialized();
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.
107 public function bootstrapDht () {
108 // Get a helper instance
109 $helperInstance = ObjectFactory::createObjectByConfiguredName('dht_bootstrap_helper_class');
111 // Load the announcement descriptor
112 $helperInstance->loadDescriptorXml($this);
114 // Compile all variables
115 $helperInstance->getTemplateInstance()->compileConfigInVariables();
117 // "Publish" the descriptor by sending it to the bootstrap/list nodes
118 $helperInstance->sendPackage($this);
121 $this->getStateInstance()->dhtIsBooting();
125 * Finds a node locally by given session id
127 * @param $sessionId Session id to lookup
128 * @return $nodeData Node-data array
130 public function findNodeLocalBySessionId ($sessionId) {
131 // Default is empty data array
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.
138 $resultInstance = $this->getWrapperInstance()->findNodeLocalBySessionId($sessionId);
140 // Make sure the result instance is valid
141 assert($resultInstance instanceof SearchableResult);
143 // Is the next entry valid?
144 if (($resultInstance->valid()) && ($resultInstance->next())) {
146 * Then load the first entry (more entries are being ignored and
147 * should not happen).
149 $nodeData = $resultInstance->current();
157 * Registers an other node with this node by given message data. The
158 * following data must always be present:
160 * - session-id (for finding the node's record together with below data)
161 * - external-ip (hostname or IP number)
162 * - listen-port (TCP/UDP listen port for inbound connections)
164 * @param $messageArray An array with all minimum message data
165 * @param $handlerInstance An instance of a HandleableDataSet class
166 * @param $forceUpdate Optionally force update, don't register (default: register if not found)
168 * @throws NodeSessionIdVerficationException If the node was not found and update is forced
170 public function registerNodeByMessageData (array $messageData, HandleableDataSet $handlerInstance, $forceUpdate = FALSE) {
171 // Get a search criteria class
172 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
175 //* 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 // Search for the node's session id and external IP/hostname + TCP/UDP listen port
178 foreach ($handlerInstance->getSearchData() as $key) {
180 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DHT-FACADE[' . __METHOD__ . ':' . __LINE__ . ']: state=' . $this->getPrintableState() . ',key=' . $key);
183 assert(isset($messageData[$key]));
186 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DHT-FACADE[' . __METHOD__ . ':' . __LINE__ . ']: state=' . $this->getPrintableState() . ',messageData[' . $key . ']=' . $messageData[$key]);
189 $searchInstance->addCriteria(str_replace('my-', '', $key), $messageData[$key]);
192 // Only one entry is fine
193 $searchInstance->setLimit(1);
196 $resultInstance = $this->getWrapperInstance()->doSelectByCriteria($searchInstance);
198 // Make sure the result instance is valid
199 assert($resultInstance instanceof SearchableResult);
201 // Is there already an entry?
202 if ($resultInstance->valid()) {
203 // Entry found, so update it
204 $this->getWrapperInstance()->updateNodeByMessageData($messageData, $handlerInstance, $searchInstance);
205 } elseif ($forceUpdate === FALSE) {
206 // Nothing found, so register it
207 $this->getWrapperInstance()->registerNodeByMessageData($messageData, $handlerInstance);
210 * Do not register non-existent nodes here. This is maybe fatal,
211 * caused by "stolen" session id and/or not matching IP
212 * number/port combination.
214 throw new NodeSessionIdVerficationException(array($this, $messageData), BaseHubSystem::EXCEPTION_NODE_SESSION_ID_NOT_VERIFYING);
217 // Save last exception
218 $handlerInstance->setLastException($this->getWrapperInstance()->getLastException());
222 * Queries the local DHT data(base) for a node list with all supported
223 * object types except the node by given session id.
225 * @param $messageData An array with message data from a node_list request
226 * @param $handlerInstance An instance of a HandleableDataSet class
227 * @param $excludeKey Array key which should be excluded
228 * @param $andKey Array of $separator-separated list of elements which all must match
229 * @param $separator Sepator char (1st parameter for explode() call)
230 * @return $nodeList An array with all found nodes
232 public function queryLocalNodeListExceptByMessageData (array $messageData, HandleableDataSet $handlerInstance, $excludeKey, $andKey, $separator) {
233 // Make sure both keys are there
234 assert((isset($messageData[$excludeKey])) && (isset($messageData[$andKey])));
237 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DHT-FACADE[' . __METHOD__ . ':' . __LINE__ . ']: state=' . $this->getPrintableState() . ',messageData=' . print_r($messageData, TRUE));
239 // Get a search criteria class
240 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
243 foreach (explode($separator, $messageData[$andKey]) as $criteria) {
245 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DHT-FACADE[' . __METHOD__ . ':' . __LINE__ . ']: andKey=' . $andKey . ',criteria=' . $criteria);
247 // Add it and leave any 'my-' prefix out
248 $searchInstance->addChoiceCriteria(str_replace('my-', '', $andKey), $criteria);
252 $searchInstance->addExcludeCriteria(str_replace('my-', '', $excludeKey), $messageData[$excludeKey]);
254 // Only X entries are fine
255 $searchInstance->setLimit($this->getConfigInstance()->getConfigEntry('node_dht_list_limit'));
258 $resultInstance = $this->getWrapperInstance()->doSelectByCriteria($searchInstance);
260 // Make sure the result instance is valid
261 assert($resultInstance instanceof SearchableResult);
262 assert($resultInstance->valid());
268 while ($resultInstance->next()) {
269 // Get current element (it should be an array, and have at least 1 entry)
270 $current = $resultInstance->current();
271 assert(is_array($current));
272 assert(count($current) > 0);
275 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DHT-FACADE[' . __METHOD__ . ':' . __LINE__ . ']: current(' . count($current) . ')[' . gettype($current) . ']=' . print_r($current, TRUE));
278 * Remove some keys as they should not be published.
280 unset($current[$this->getWrapperInstance()->getIndexKey()]);
283 array_push($nodeList, $current);
286 // Save last exception
287 $handlerInstance->setLastException($this->getWrapperInstance()->getLastException());
289 // Return node list (array)
294 * Inserts given node list array (from earlier database result produced by
295 * an other node) into the DHT. This array origins from above method
296 * queryLocalNodeListExceptByMessageData().
298 * @param $nodeList An array from an earlier database result instance
301 public function insertNodeList (array $nodeList) {
302 // If no node is in the list (array), skip the rest of this method
303 if (count($nodeList) == 0) {
305 self::createDebugInstance(__CLASS__)->debugOutput('DHT-FACADE[' . __METHOD__ . ':' . __LINE__ . ']: No node record has been returned.');
311 // Put them all into a stack
312 foreach ($nodeList as $nodeData) {
313 // Insert all entries
314 $this->getStackInstance()->pushNamed(self::STACKER_NAME_INSERT_NODE, $nodeData);
319 * Find recipients for given package data
321 * @param $packageData An array of valid package data
322 * @return $recipients An indexed array with DHT recipients
324 public function findRecipientsByPackageData (array $packageData) {
325 // Query get a result instance back from DHT database wrapper.
326 $resultInstance = $this->getWrapperInstance()->getResultFromExcludedSender($packageData);
328 // Make sure the result instance is valid
329 assert($resultInstance instanceof SearchableResult);
332 if (!$resultInstance->valid()) {
333 // Then skip below loop
338 $recipients = array();
340 // Search for all recipients
341 while ($resultInstance->next()) {
343 $current = $resultInstance->current();
344 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DHT-FACADE[' . __METHOD__ . ':' . __LINE__ . ']: current=' . print_r($current, TRUE));
346 // Add instance to recipient list
347 array_push($recipients, $current);
350 // Return filled array
355 * Finds DHT recipients by given key/value pair
357 * @param $key Key to search for
358 * @param $value Value to check on found key
359 * @return $recipiens Array with DHT recipients from given key/value pair
361 public function findRecipientsByKey ($key, $value) {
362 // Look for all suitable nodes
363 $resultInstance = $this->getWrapperInstance()->getResultFromKeyValue($key, $value);
365 // Make sure the result instance is valid
366 assert($resultInstance instanceof SearchableResult);
367 assert($resultInstance->valid());
370 $recipients = array();
372 // "Walk" through all entries
373 while ($resultInstance->next()) {
375 $current = $resultInstance->current();
377 // Add instance to recipient list
378 array_push($recipients, $current);
381 // Return filled array