]> git.mxchange.org Git - hub.git/blob - application/hub/main/dht/node/class_NodeDhtFacade.php
Opps :(
[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          * @todo        Please implement this method
59          */
60         public function initDht () {
61                 // Is the local node registered?
62                 if ($this->getWrapperInstance()->isLocalNodeRegistered()) {
63                         // Then only update session id
64                         $this->getWrapperInstance()->updateLocalNode();
65                 } else {
66                         // No, so register it
67                         $this->getWrapperInstance()->registerLocalNode();
68                 }
69         }
70
71         /**
72          * Finds a node by given session id
73          *
74          * @param       $sessionId      Session id to lookup
75          * @return      $nodeData       Node data array
76          */
77         public function findNodeBySessionId ($sessionId) {
78                 // Default is empty data array
79                 $nodeData = array();
80
81                 // Call the wrapper to do the job and get back a result instance
82                 $resultInstance = $this->getWrapperInstance()->findNodeBySessionId($sessionId);
83
84                 // Is the next entry valid?
85                 if ($resultInstance->next()) {
86                         // Then load the entry
87                         $nodeData = $resultInstance->current();
88                 } // END - if
89
90                 // Return node data
91                 return $nodeData;
92         }
93
94         /**
95          * Registers an other node with this node by given message data. The
96          * following data must always be present:
97          *
98          * - session-id  (for finding the node's record together with below data)
99          * - external-ip (hostname or IP number)
100          * - listen-port (TCP/UDP listen port for inbound connections)
101          *
102          * @param       $messageArray           An array with all minimum message data
103          * @param       $handlerInstance        An instance of a Handleable class
104          * @param       $forceUpdate            Optionally force update, don't register (default: register if not found)
105          * @return      void
106          * @throws      NodeSessionIdVerficationException       If the node was not found and update is forced
107          */
108         public function registerNodeByMessageData (array $messageData, Handleable $handlerInstance, $forceUpdate = FALSE) {
109                 // Get a search criteria class
110                 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
111
112                 // Debug message
113                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DHT-FACADE: messageData=' . print_r($messageData, true));
114
115                 // Search for the node's session id and external IP/hostname + TCP/UDP listen port
116                 foreach ($handlerInstance->getSearchData() as $key) {
117                         // Debug message
118                         /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DHT-FACADE: messageData[' . $key . ']=' . $messageData[$key]);
119
120                         // Is it there?
121                         assert(isset($messageData[$key]));
122
123                         // Add criteria
124                         $searchInstance->addCriteria(str_replace('my-', '', $key), $messageData[$key]);
125                 } // END - foreach
126
127                 // Only one entry is fine
128                 $searchInstance->setLimit(1);
129
130                 // Run the query
131                 $resultInstance = $this->getWrapperInstance()->doSelectByCriteria($searchInstance);
132
133                 // Is there already an entry?
134                 if ($resultInstance->next()) {
135                         // Entry found, so update it
136                         $this->getWrapperInstance()->updateNodeByMessageData($messageData, $handlerInstance, $searchInstance);
137                 } elseif ($forceUpdate === FALSE) {
138                         // Nothing found, so register it
139                         $this->getWrapperInstance()->registerNodeByMessageData($messageData, $handlerInstance);
140                 } else {
141                         /*
142                          * Do not register non-existent nodes here. This is maybe fatal,
143                          * caused by "stolen" session id and/or not matching IP
144                          * number/port combination.
145                          */
146                         throw new NodeSessionIdVerficationException(array($this, $messageData), BaseHubSystem::EXCEPTION_NODE_SESSION_ID_NOT_VERIFYING);
147                 }
148
149                 // Save last exception
150                 $handlerInstance->setLastException($this->getWrapperInstance()->getLastException());
151         }
152
153         /**
154          * Queries the local DHT data(base) for a node list with all supported
155          * object types except the node by given session id.
156          *
157          * @param       $messageData    An array with message data from a node_list request
158          * @param       $excludeKey             Array key which should be excluded
159          * @param       $andKey                 Array of $separator-separated list of elements which all must match
160          * @param       $separator              Sepator char (1st parameter for explode() call)
161          * @return      $nodeList               An array with all found nodes
162          */
163         public function queryLocalNodeListExceptByMessageData (array $messageData, $excludeKey, $andKey, $separator) {
164                 // Make sure both keys are there
165                 assert((isset($messageData[$excludeKey])) && (isset($messageData[$andKey])));
166
167                 // Debug message
168                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DHT-FACADE: messageData=' . print_r($messageData, true));
169
170                 // Get a search criteria class
171                 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
172
173                 // Add all keys
174                 foreach (explode($separator, $messageData[$andKey]) as $criteria) {
175                         // Debug message
176                         /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DHT-FACADE: andKey=' . $andKey . ',criteria=' . $criteria);
177
178                         // Add it and leave any 'my-' prefix out
179                         $searchInstance->addChoiceCriteria(str_replace('my-', '', $andKey), $criteria);
180                 } // END - foreach
181
182                 // Add exclusion key
183                 $searchInstance->addExcludeCriteria(str_replace('my-', '', $excludeKey), $messageData[$excludeKey]);
184
185                 // Only X entries are fine
186                 $searchInstance->setLimit($this->getConfigInstance()->getConfigEntry('node_dht_list_limit'));
187
188                 // Run the query
189                 $resultInstance = $this->getWrapperInstance()->doSelectByCriteria($searchInstance);
190
191                 // Get node list
192                 $nodeList = array();
193                 while ($resultInstance->next()) {
194                         // Add this entry
195                         array_push($nodeList, $resultInstance->current());
196                 } // END - while
197
198                 // Save last exception
199                 $handlerInstance->setLastException($this->getWrapperInstance()->getLastException());
200
201                 // Return node list (array)
202                 return $nodeList;
203         }
204 }
205
206 // [EOF]
207 ?>