]> git.mxchange.org Git - hub.git/blob - application/hub/main/database/wrapper/node/class_NodeDistributedHashTableDatabaseWrapper.php
Expanded debug lines, renamed 'node_type' to 'node_mode' (which makes your DHT databa...
[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
37         /**
38          * Protected constructor
39          *
40          * @return      void
41          */
42         protected function __construct () {
43                 // Call parent constructor
44                 parent::__construct(__CLASS__);
45         }
46
47         /**
48          * Creates an instance of this database wrapper by a provided user class
49          *
50          * @return      $wrapperInstance        An instance of the created wrapper class
51          */
52         public static final function createNodeDistributedHashTableDatabaseWrapper () {
53                 // Get a new instance
54                 $wrapperInstance = new NodeDistributedHashTableDatabaseWrapper();
55
56                 // Set (primary!) table name
57                 $wrapperInstance->setTableName(self::DB_TABLE_NODE_DHT);
58
59                 // Return the instance
60                 return $wrapperInstance;
61         }
62
63         /**
64          * Prepares a "local" instance of a StoreableCriteria class with all node
65          * data for insert/update queries. This data set contains data from *this*
66          * (local) node.
67          *
68          * @return      $dataSetInstance        An instance of a StoreableCriteria class
69          */
70         private function prepareLocalDataSetInstance () {
71                 // Get node/request instances
72                 $nodeInstance = Registry::getRegistry()->getInstance('node');
73                 $requestInstance = ApplicationHelper::getSelfInstance()->getRequestInstance();
74
75                 // Get a dataset instance
76                 $dataSetInstance = ObjectFactory::createObjectByConfiguredName('dataset_criteria_class', array(self::DB_TABLE_NODE_DHT));
77
78                 // Set the primary key
79                 $dataSetInstance->setUniqueKey(self::DB_COLUMN_NODE_ID);
80
81                 // Get ip:port combination and "explode" it
82                 $ipPort = $nodeInstance->getAddressPortArray();
83
84                 // Make sure both is valid
85                 assert(($ipPort[0] !== 'invalid') && ($ipPort[1] !== 'invalid'));
86
87                 // Add public node data
88                 $dataSetInstance->addCriteria(self::DB_COLUMN_NODE_MODE       , $requestInstance->getRequestElement('mode'));
89                 $dataSetInstance->addCriteria(self::DB_COLUMN_EXTERNAL_IP     , $ipPort[0]);
90                 $dataSetInstance->addCriteria(self::DB_COLUMN_LISTEN_PORT     , $ipPort[1]);
91                 $dataSetInstance->addCriteria(self::DB_COLUMN_NODE_ID         , $nodeInstance->getNodeId());
92                 $dataSetInstance->addCriteria(self::DB_COLUMN_SESSION_ID      , $nodeInstance->getSessionId());
93                 $dataSetInstance->addCriteria(self::DB_COLUMN_PRIVATE_KEY_HASH, $nodeInstance->getPrivateKeyHash());
94
95                 // Return it
96                 return $dataSetInstance;
97         }
98
99         /**
100          * Checks whether the local (*this*) node is registered in the DHT by
101          * checking if the external ip/port is found.
102          *
103          * @return      $isRegistered   Whether *this* node is registered in the DHT
104          */
105         public function isLocalNodeRegistered () {
106                 // Is there cache?
107                 if (!isset($GLOBALS[__METHOD__])) {
108                         // Get a search criteria instance
109                         $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
110
111                         // Get node instance
112                         $nodeInstance = Registry::getRegistry()->getInstance('node');
113
114                         // Get ip:port combination and "explode" it
115                         $ipPort = $nodeInstance->getAddressPortArray();
116
117                         // Make sure both is valid
118                         assert(($ipPort[0] !== 'invalid') && ($ipPort[1] !== 'invalid'));
119
120                         // Add ip:port/node id as criteria
121                         $searchInstance->addCriteria(self::DB_COLUMN_EXTERNAL_IP, $ipPort[0]);
122                         $searchInstance->addCriteria(self::DB_COLUMN_LISTEN_PORT, $ipPort[1]);
123                         $searchInstance->addCriteria(self::DB_COLUMN_NODE_ID    , $nodeInstance->getNodeId());
124                         $searchInstance->setLimit(1);
125
126                         // Query database and get a result instance back
127                         $resultInstance = $this->doSelectByCriteria($searchInstance);
128
129                         // Cache result of if there is an entry, next() will tell us if the next entry is valid
130                         $GLOBALS[__METHOD__] = $resultInstance->next();
131                 } // END - if
132
133                 // Return result
134                 return $GLOBALS[__METHOD__];
135         }
136
137         /**
138          * Registeres the local (*this*) node with its data in the DHT.
139          *
140          * @return      void
141          */
142         public function registerLocalNode () {
143                 // Assert to make sure this method is called with no record in DB (the actual backend of the DHT)
144                 assert(!$this->isLocalNodeRegistered());
145
146                 // Get prepared data set instance
147                 $dataSetInstance = $this->prepareLocalDataSetInstance();
148
149                 // "Insert" this dataset instance completely into the database
150                 $this->queryInsertDataSet($dataSetInstance);
151         }
152
153         /**
154          * Updates local (*this*) node data in DHT, this is but not limited to the
155          * session id, ip number (and/or hostname) and port number.
156          *
157          * @return      void
158          */
159         public function updateLocalNode () {
160                 // Assert to make sure this method is called with one record in DB (the actual backend of the DHT)
161                 assert($this->isLocalNodeRegistered());
162
163                 // Get node instance
164                 $nodeInstance = Registry::getRegistry()->getInstance('node');
165
166                 // Get search criteria
167                 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
168
169                 // Search for node id and limit it to one entry
170                 $searchInstance->addCriteria(self::DB_COLUMN_NODE_ID, $nodeInstance->getNodeId());
171                 $searchInstance->setLimit(1);
172
173                 // Get a prepared dataset instance
174                 $dataSetInstance = $this->prepareLocalDataSetInstance();
175
176                 // Set search instance
177                 $dataSetInstance->setSearchInstance($searchInstance);
178
179                 // Update DHT database record
180                 $this->queryUpdateDataSet($dataSetInstance);
181         }
182
183         /**
184          * Finds a node locally by given session id
185          *
186          * @param       $sessionId      Session id to lookup
187          * @return      $nodeData       Node data array
188          */
189         public function findNodeLocalBySessionId ($sessionId) {
190                 // Get search criteria
191                 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
192
193                 // Search for session id and limit it to one entry
194                 $searchInstance->addCriteria(self::DB_COLUMN_SESSION_ID, $sessionId);
195                 $searchInstance->setLimit(1);
196
197                 // Query database and get a result instance back
198                 $resultInstance = $this->doSelectByCriteria($searchInstance);
199
200                 // Return result instance
201                 return $resultInstance;
202         }
203
204         /**
205          * Registeres a node by given message data.
206          *
207          * @param       $messageData            An array of all message data
208          * @param       $handlerInstance        An instance of a HandleableMessage class
209          * @return      void
210          */
211         public function registerNodeByMessageData (array $messageData, Handleable $handlerInstance) {
212                 // Get a data set instance
213                 $dataSetInstance = ObjectFactory::createObjectByConfiguredName('dataset_criteria_class', array(self::DB_TABLE_NODE_DHT));
214
215                 // Set primary key (session id)
216                 $dataSetInstance->setUniqueKey(self::DB_COLUMN_SESSION_ID);
217
218                 // Add all array elements
219                 $handlerInstance->addArrayToDataSet($dataSetInstance, $messageData);
220
221                 // Run the "INSERT" query
222                 $this->queryInsertDataSet($dataSetInstance);
223         }
224
225         /**
226          * Updates an existing entry in node list
227          *
228          * @param       $messageData            An array of all message data
229          * @param       $handlerInstance        An instance of a HandleableMessage class
230          * @param       $searchInstance         An instance of LocalSearchCriteria class
231          * @return      void
232          */
233         public function updateNodeByMessageData (array $messageData, Handleable $handlerInstance, LocalSearchCriteria $searchInstance) {
234                 // Get a data set instance
235                 $dataSetInstance = ObjectFactory::createObjectByConfiguredName('dataset_criteria_class', array(self::DB_TABLE_NODE_DHT));
236
237                 // Add search instance
238                 $dataSetInstance->setSearchInstance($searchInstance);
239
240                 // Set primary key (session id)
241                 $dataSetInstance->setUniqueKey(self::DB_COLUMN_SESSION_ID);
242
243                 // Add all array elements
244                 $handlerInstance->addArrayToDataSet($dataSetInstance, $messageData);
245
246                 // Run the "UPDATE" query
247                 $this->queryUpdateDataSet($dataSetInstance);
248         }
249 }
250
251 // [EOF]
252 ?>