3 * A Node DHT facade class
5 * @author Roland Haeder <webmaster@ship-simu.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.ship-simu.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 Distributable, 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 * Initializes the distributed hash table (DHT)
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();
66 $this->getWrapperInstance()->registerLocalNode();
70 $this->getStateInstance()->dhtHasInitialized();
74 * Bootstraps the DHT by sending out a message to all available nodes
75 * (including itself). This step helps the node to get to know more nodes
76 * which can be queried later for object distribution.
80 public function bootstrapDht () {
81 // Get a helper instance
82 $helperInstance = ObjectFactory::createObjectByConfiguredName('dht_bootstrap_helper_class');
84 // Load the announcement descriptor
85 $helperInstance->loadDescriptorXml($this);
87 // Compile all variables
88 $helperInstance->getTemplateInstance()->compileConfigInVariables();
90 // "Publish" the descriptor by sending it to the bootstrap/list nodes
91 $helperInstance->sendPackage($this);
94 $this->getStateInstance()->dhtHasBooted();
98 * Finds a node locally by given session id
100 * @param $sessionId Session id to lookup
101 * @return $nodeData Node-data array
103 public function findNodeLocalBySessionId ($sessionId) {
104 // Default is empty data array
108 * Call the wrapper to do the job and get back a result instance. There
109 * will come back zero or one entry from the wrapper.
111 $resultInstance = $this->getWrapperInstance()->findNodeLocalBySessionId($sessionId);
113 // Is the next entry valid?
114 if ($resultInstance->next()) {
116 * Then load the first entry (more entries are being ignored and
117 * should not happen).
119 $nodeData = $resultInstance->current();
127 * Registers an other node with this node by given message data. The
128 * following data must always be present:
130 * - session-id (for finding the node's record together with below data)
131 * - external-ip (hostname or IP number)
132 * - listen-port (TCP/UDP listen port for inbound connections)
134 * @param $messageArray An array with all minimum message data
135 * @param $handlerInstance An instance of a Handleable class
136 * @param $forceUpdate Optionally force update, don't register (default: register if not found)
138 * @throws NodeSessionIdVerficationException If the node was not found and update is forced
140 public function registerNodeByMessageData (array $messageData, Handleable $handlerInstance, $forceUpdate = FALSE) {
141 // Get a search criteria class
142 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
145 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DHT-FACADE[' . __LINE__ . ']: state=' . $this->getPrintableState() . ',messageData=' . print_r($messageData, true) . ',handlerInstance=' . $handlerInstance->__toString() . ',forceUpdate=' . intval($forceUpdate) . ',count(getSearchData())=' . count($handlerInstance->getSearchData()));
147 // Search for the node's session id and external IP/hostname + TCP/UDP listen port
148 foreach ($handlerInstance->getSearchData() as $key) {
150 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DHT-FACADE[' . __LINE__ . ']: state=' . $this->getPrintableState() . ',key=' . $key);
153 assert(isset($messageData[$key]));
156 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DHT-FACADE[' . __LINE__ . ']: state=' . $this->getPrintableState() . ',messageData[' . $key . ']=' . $messageData[$key]);
159 $searchInstance->addCriteria(str_replace('my-', '', $key), $messageData[$key]);
162 // Only one entry is fine
163 $searchInstance->setLimit(1);
166 $resultInstance = $this->getWrapperInstance()->doSelectByCriteria($searchInstance);
168 // Is there already an entry?
169 if ($resultInstance->next()) {
170 // Entry found, so update it
171 $this->getWrapperInstance()->updateNodeByMessageData($messageData, $handlerInstance, $searchInstance);
172 } elseif ($forceUpdate === FALSE) {
173 // Nothing found, so register it
174 $this->getWrapperInstance()->registerNodeByMessageData($messageData, $handlerInstance);
177 * Do not register non-existent nodes here. This is maybe fatal,
178 * caused by "stolen" session id and/or not matching IP
179 * number/port combination.
181 throw new NodeSessionIdVerficationException(array($this, $messageData), BaseHubSystem::EXCEPTION_NODE_SESSION_ID_NOT_VERIFYING);
184 // Save last exception
185 $handlerInstance->setLastException($this->getWrapperInstance()->getLastException());
189 * Queries the local DHT data(base) for a node list with all supported
190 * object types except the node by given session id.
192 * @param $messageData An array with message data from a node_list request
193 * @param $handlerInstance An instance of a Handleable class
194 * @param $excludeKey Array key which should be excluded
195 * @param $andKey Array of $separator-separated list of elements which all must match
196 * @param $separator Sepator char (1st parameter for explode() call)
197 * @return $nodeList An array with all found nodes
199 public function queryLocalNodeListExceptByMessageData (array $messageData, Handleable $handlerInstance, $excludeKey, $andKey, $separator) {
200 // Make sure both keys are there
201 assert((isset($messageData[$excludeKey])) && (isset($messageData[$andKey])));
204 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DHT-FACADE[' . __LINE__ . ']: state=' . $this->getPrintableState() . ',messageData=' . print_r($messageData, true));
206 // Get a search criteria class
207 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
210 foreach (explode($separator, $messageData[$andKey]) as $criteria) {
212 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DHT-FACADE[' . __LINE__ . ']: andKey=' . $andKey . ',criteria=' . $criteria);
214 // Add it and leave any 'my-' prefix out
215 $searchInstance->addChoiceCriteria(str_replace('my-', '', $andKey), $criteria);
219 $searchInstance->addExcludeCriteria(str_replace('my-', '', $excludeKey), $messageData[$excludeKey]);
221 // Only X entries are fine
222 $searchInstance->setLimit($this->getConfigInstance()->getConfigEntry('node_dht_list_limit'));
225 $resultInstance = $this->getWrapperInstance()->doSelectByCriteria($searchInstance);
229 while ($resultInstance->next()) {
230 // Get current element (it should be an array, and have at least 1 entry)
231 $current = $resultInstance->current();
232 assert(is_array($current));
233 assert(count($current) > 0);
236 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DHT-FACADE[' . __LINE__ . ']: current(' . count($current) . ')[' . gettype($current) . ']=' . print_r($current, TRUE));
239 * Remove some keys as they should not be published.
241 unset($current[$this->getWrapperInstance()->getIndexKey()]);
244 array_push($nodeList, $current);
247 // Save last exception
248 $handlerInstance->setLastException($this->getWrapperInstance()->getLastException());
250 // Return node list (array)
255 * Inserts given node list array (from earlier database result produced by
256 * an other node) into the DHT. This array origins from above method
257 * queryLocalNodeListExceptByMessageData().
259 * @param $nodeList An array from an earlier database result instance
262 public function insertNodeList (array $nodeList) {
263 // If no node is in the list (array), skip the rest of this method
264 if (count($nodeList) == 0) {
266 self::createDebugInstance(__CLASS__)->debugOutput('DHT-FACADE[' . __LINE__ . ']: No node record has been returned.');
272 // Put them all into a stack
273 foreach ($nodeList as $nodeData) {
274 // Insert all entries
275 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_INSERT_NODE, $nodeData);