]> git.mxchange.org Git - hub.git/blob - application/hub/main/database/wrapper/node/class_NodeDistributedHashTableDatabaseWrapper.php
967941664345a40c6450d2c6f2bb449fbcbee2be
[hub.git] / application / hub / main / database / wrapper / node / class_NodeDistributedHashTableDatabaseWrapper.php
1 <?php
2 /**
3  * A database wrapper for distributed hash tables
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 NodeDistributedHashTableDatabaseWrapper extends BaseDatabaseWrapper implements NodeDhtWrapper, Registerable {
25         // Constants for database table names
26         const DB_TABLE_NODE_DHT = 'node_dht';
27
28         // Constants for database column names
29         const DB_COLUMN_NODE_ID          = 'node_id';
30         const DB_COLUMN_SESSION_ID       = 'session_id';
31         const DB_COLUMN_EXTERNAL_IP      = 'external_ip';
32         const DB_COLUMN_LISTEN_PORT      = 'listen_port';
33         const DB_COLUMN_PRIVATE_KEY      = 'private_key';
34         const DB_COLUMN_PRIVATE_KEY_HASH = 'private_key_hash';
35         const DB_COLUMN_NODE_MODE        = 'node_mode';
36         const DB_COLUMN_ACCEPTED_OBJECTS = 'accepted_object_types';
37
38         /**
39          * Protected constructor
40          *
41          * @return      void
42          */
43         protected function __construct () {
44                 // Call parent constructor
45                 parent::__construct(__CLASS__);
46         }
47
48         /**
49          * Creates an instance of this database wrapper by a provided user class
50          *
51          * @return      $wrapperInstance        An instance of the created wrapper class
52          */
53         public static final function createNodeDistributedHashTableDatabaseWrapper () {
54                 // Get a new instance
55                 $wrapperInstance = new NodeDistributedHashTableDatabaseWrapper();
56
57                 // Set (primary!) table name
58                 $wrapperInstance->setTableName(self::DB_TABLE_NODE_DHT);
59
60                 // Return the instance
61                 return $wrapperInstance;
62         }
63
64         /**
65          * Prepares a "local" instance of a StoreableCriteria class with all node
66          * data for insert/update queries. This data set contains data from *this*
67          * (local) node.
68          *
69          * @return      $dataSetInstance        An instance of a StoreableCriteria class
70          */
71         private function prepareLocalDataSetInstance () {
72                 // Get node/request instances
73                 $nodeInstance = Registry::getRegistry()->getInstance('node');
74                 $requestInstance = ApplicationHelper::getSelfInstance()->getRequestInstance();
75
76                 // Get a dataset instance
77                 $dataSetInstance = ObjectFactory::createObjectByConfiguredName('dataset_criteria_class', array(self::DB_TABLE_NODE_DHT));
78
79                 // Set the primary key
80                 $dataSetInstance->setUniqueKey(self::DB_COLUMN_NODE_ID);
81
82                 // Get ip:port combination and "explode" it
83                 $ipPort = $nodeInstance->getAddressPortArray();
84
85                 // Make sure both is valid
86                 assert(($ipPort[0] !== 'invalid') && ($ipPort[1] !== 'invalid'));
87
88                 // Get an array of all accepted object types
89                 $objectList = $nodeInstance->getListFromAcceptedObjectTypes();
90
91                 // Make sure this is an array
92                 assert(is_array($objectList));
93
94                 // Add public node data
95                 $dataSetInstance->addCriteria(self::DB_COLUMN_NODE_MODE       , $requestInstance->getRequestElement('mode'));
96                 $dataSetInstance->addCriteria(self::DB_COLUMN_EXTERNAL_IP     , $ipPort[0]);
97                 $dataSetInstance->addCriteria(self::DB_COLUMN_LISTEN_PORT     , $ipPort[1]);
98                 $dataSetInstance->addCriteria(self::DB_COLUMN_NODE_ID         , $nodeInstance->getNodeId());
99                 $dataSetInstance->addCriteria(self::DB_COLUMN_SESSION_ID      , $nodeInstance->getSessionId());
100                 $dataSetInstance->addCriteria(self::DB_COLUMN_PRIVATE_KEY_HASH, $nodeInstance->getPrivateKeyHash());
101                 $dataSetInstance->addCriteria(self::DB_COLUMN_ACCEPTED_OBJECTS, implode(BaseHubNode::OBJECT_LIST_SEPARATOR, $objectList));
102
103                 // Return it
104                 return $dataSetInstance;
105         }
106
107         /**
108          * Checks whether the local (*this*) node is registered in the DHT by
109          * checking if the external ip/port is found.
110          *
111          * @return      $isRegistered   Whether *this* node is registered in the DHT
112          */
113         public function isLocalNodeRegistered () {
114                 // Is there cache?
115                 if (!isset($GLOBALS[__METHOD__])) {
116                         // Get a search criteria instance
117                         $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
118
119                         // Get node instance
120                         $nodeInstance = Registry::getRegistry()->getInstance('node');
121
122                         // Get ip:port combination and "explode" it
123                         $ipPort = $nodeInstance->getAddressPortArray();
124
125                         /*
126                          * Make sure both is not 'invalid' which means that the resolver
127                          * didn't work.
128                          */
129                         assert(($ipPort[0] !== 'invalid') && ($ipPort[1] !== 'invalid'));
130
131                         // Add ip:port/node id as criteria
132                         $searchInstance->addCriteria(self::DB_COLUMN_EXTERNAL_IP, $ipPort[0]);
133                         $searchInstance->addCriteria(self::DB_COLUMN_LISTEN_PORT, $ipPort[1]);
134                         $searchInstance->addCriteria(self::DB_COLUMN_NODE_ID    , $nodeInstance->getNodeId());
135                         $searchInstance->setLimit(1);
136
137                         // Query database and get a result instance back
138                         $resultInstance = $this->doSelectByCriteria($searchInstance);
139
140                         // Cache result of if there is an entry, valid() will tell us if an entry is there
141                         $GLOBALS[__METHOD__] = $resultInstance->valid();
142                 } // END - if
143
144                 // Return result
145                 return $GLOBALS[__METHOD__];
146         }
147
148         /**
149          * Registeres the local (*this*) node with its data in the DHT.
150          *
151          * @return      void
152          */
153         public function registerLocalNode () {
154                 // Assert to make sure this method is called with no record in DB (the actual backend of the DHT)
155                 assert(!$this->isLocalNodeRegistered());
156
157                 // Get prepared data set instance
158                 $dataSetInstance = $this->prepareLocalDataSetInstance();
159
160                 // "Insert" this dataset instance completely into the database
161                 $this->queryInsertDataSet($dataSetInstance);
162         }
163
164         /**
165          * Updates local (*this*) node data in DHT, this is but not limited to the
166          * session id, ip number (and/or hostname) and port number.
167          *
168          * @return      void
169          */
170         public function updateLocalNode () {
171                 // Assert to make sure this method is called with one record in DB (the actual backend of the DHT)
172                 assert($this->isLocalNodeRegistered());
173
174                 // Get node instance
175                 $nodeInstance = Registry::getRegistry()->getInstance('node');
176
177                 // Get search criteria
178                 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
179
180                 // Search for node id and limit it to one entry
181                 $searchInstance->addCriteria(self::DB_COLUMN_NODE_ID, $nodeInstance->getNodeId());
182                 $searchInstance->setLimit(1);
183
184                 // Get a prepared dataset instance
185                 $dataSetInstance = $this->prepareLocalDataSetInstance();
186
187                 // Set search instance
188                 $dataSetInstance->setSearchInstance($searchInstance);
189
190                 // Update DHT database record
191                 $this->queryUpdateDataSet($dataSetInstance);
192         }
193
194         /**
195          * Finds a node locally by given session id
196          *
197          * @param       $sessionId      Session id to lookup
198          * @return      $nodeData       Node data array
199          */
200         public function findNodeLocalBySessionId ($sessionId) {
201                 // Get search criteria
202                 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
203
204                 // Search for session id and limit it to one entry
205                 $searchInstance->addCriteria(self::DB_COLUMN_SESSION_ID, $sessionId);
206                 $searchInstance->setLimit(1);
207
208                 // Query database and get a result instance back
209                 $resultInstance = $this->doSelectByCriteria($searchInstance);
210
211                 // Return result instance
212                 return $resultInstance;
213         }
214
215         /**
216          * Registeres a node by given message data.
217          *
218          * @param       $messageData            An array of all message data
219          * @param       $handlerInstance        An instance of a HandleableMessage class
220          * @return      void
221          */
222         public function registerNodeByMessageData (array $messageData, Handleable $handlerInstance) {
223                 // Get a data set instance
224                 $dataSetInstance = ObjectFactory::createObjectByConfiguredName('dataset_criteria_class', array(self::DB_TABLE_NODE_DHT));
225
226                 // Set primary key (session id)
227                 $dataSetInstance->setUniqueKey(self::DB_COLUMN_SESSION_ID);
228
229                 // Add all array elements
230                 $handlerInstance->addArrayToDataSet($dataSetInstance, $messageData);
231
232                 // Remove 'node_list'
233                 $dataSetInstance->unsetCriteria('node_list');
234
235                 // Run the "INSERT" query
236                 $this->queryInsertDataSet($dataSetInstance);
237         }
238
239         /**
240          * Updates an existing entry in node list
241          *
242          * @param       $messageData            An array of all message data
243          * @param       $handlerInstance        An instance of a HandleableMessage class
244          * @param       $searchInstance         An instance of LocalSearchCriteria class
245          * @return      void
246          */
247         public function updateNodeByMessageData (array $messageData, Handleable $handlerInstance, LocalSearchCriteria $searchInstance) {
248                 // Get a data set instance
249                 $dataSetInstance = ObjectFactory::createObjectByConfiguredName('dataset_criteria_class', array(self::DB_TABLE_NODE_DHT));
250
251                 // Add search instance
252                 $dataSetInstance->setSearchInstance($searchInstance);
253
254                 // Set primary key (session id)
255                 $dataSetInstance->setUniqueKey(self::DB_COLUMN_SESSION_ID);
256
257                 // Add all array elements
258                 $handlerInstance->addArrayToDataSet($dataSetInstance, $messageData);
259
260                 // Remove 'node_list'
261                 $dataSetInstance->unsetCriteria('node_list');
262
263                 // Run the "UPDATE" query
264                 $this->queryUpdateDataSet($dataSetInstance);
265         }
266
267         /**
268          * Determines whether the given node data is already inserted in the DHT
269          *
270          * @param       $nodeData               An array with valid node data
271          * @return      $isRegistered   Whether the given node data is already inserted
272          */
273         public function isNodeRegistered (array $nodeData) {
274                 // Get search criteria
275                 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
276
277                 // Search for node id and limit it to one entry
278                 $searchInstance->addCriteria(self::DB_COLUMN_NODE_ID, $nodeData[self::DB_COLUMN_NODE_ID]);
279                 $searchInstance->setLimit(1);
280
281                 // Query database and get a result instance back
282                 $resultInstance = $this->doSelectByCriteria($searchInstance);
283
284                 // Check if there is an entry
285                 $isRegistered = $resultInstance->valid();
286
287                 // Return registration status
288                 return $isRegistered;
289         }
290
291         /**
292          * Registers a node with given data in the DHT. If the node is already
293          * registered this method shall throw an exception.
294          *
295          * @param       $nodeData       An array with valid node data
296          * @return      void
297          * @throws      NodeAlreadyRegisteredException  If the node is already registered
298          */
299         public function registerNode (array $nodeData) {
300                 $this->partialStub('nodeData=' . print_r($nodeData, TRUE));
301         }
302
303         /**
304          * Updates a node's entry in the DHT with given data. This will enrich or
305          * just update already exsiting data. If the node is not found this method
306          * shall throw an exception.
307          *
308          * @param       $nodeData       An array with valid node data
309          * @return      void
310          * @throws      NodeDataMissingException        If the node's data is missing
311          */
312         public function updateNode (array $nodeData) {
313                 $this->partialStub('nodeData=' . print_r($nodeData, TRUE));
314         }
315 }
316
317 // [EOF]
318 ?>