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