]> git.mxchange.org Git - hub.git/blob - application/hub/main/database/wrapper/node/class_NodeDistributedHashTableDatabaseWrapper.php
f9d74bdad5d6074d7950a70adf2187646c889e75
[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                 // Add public node data
92                 $dataSetInstance->addCriteria(self::DB_COLUMN_NODE_MODE       , $requestInstance->getRequestElement('mode'));
93                 $dataSetInstance->addCriteria(self::DB_COLUMN_EXTERNAL_IP     , $ipPort[0]);
94                 $dataSetInstance->addCriteria(self::DB_COLUMN_LISTEN_PORT     , $ipPort[1]);
95                 $dataSetInstance->addCriteria(self::DB_COLUMN_NODE_ID         , $nodeInstance->getNodeId());
96                 $dataSetInstance->addCriteria(self::DB_COLUMN_SESSION_ID      , $nodeInstance->getSessionId());
97                 $dataSetInstance->addCriteria(self::DB_COLUMN_PRIVATE_KEY_HASH, $nodeInstance->getPrivateKeyHash());
98                 $dataSetInstance->addCriteria(self::DB_COLUMN_ACCEPTED_OBJECTS, implode(BaseHubNode::OBJECT_LIST_SEPARATOR, $objectList));
99
100                 // Return it
101                 return $dataSetInstance;
102         }
103
104         /**
105          * Checks whether the local (*this*) node is registered in the DHT by
106          * checking if the external ip/port is found.
107          *
108          * @return      $isRegistered   Whether *this* node is registered in the DHT
109          */
110         public function isLocalNodeRegistered () {
111                 // Is there cache?
112                 if (!isset($GLOBALS[__METHOD__])) {
113                         // Get a search criteria instance
114                         $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
115
116                         // Get node instance
117                         $nodeInstance = Registry::getRegistry()->getInstance('node');
118
119                         // Get ip:port combination and "explode" it
120                         $ipPort = $nodeInstance->getAddressPortArray();
121
122                         // Make sure both is valid
123                         assert(($ipPort[0] !== 'invalid') && ($ipPort[1] !== 'invalid'));
124
125                         // Add ip:port/node id as criteria
126                         $searchInstance->addCriteria(self::DB_COLUMN_EXTERNAL_IP, $ipPort[0]);
127                         $searchInstance->addCriteria(self::DB_COLUMN_LISTEN_PORT, $ipPort[1]);
128                         $searchInstance->addCriteria(self::DB_COLUMN_NODE_ID    , $nodeInstance->getNodeId());
129                         $searchInstance->setLimit(1);
130
131                         // Query database and get a result instance back
132                         $resultInstance = $this->doSelectByCriteria($searchInstance);
133
134                         // Cache result of if there is an entry, next() will tell us if the next entry is valid
135                         $GLOBALS[__METHOD__] = $resultInstance->next();
136                 } // END - if
137
138                 // Return result
139                 return $GLOBALS[__METHOD__];
140         }
141
142         /**
143          * Registeres the local (*this*) node with its data in the DHT.
144          *
145          * @return      void
146          */
147         public function registerLocalNode () {
148                 // Assert to make sure this method is called with no record in DB (the actual backend of the DHT)
149                 assert(!$this->isLocalNodeRegistered());
150
151                 // Get prepared data set instance
152                 $dataSetInstance = $this->prepareLocalDataSetInstance();
153
154                 // "Insert" this dataset instance completely into the database
155                 $this->queryInsertDataSet($dataSetInstance);
156         }
157
158         /**
159          * Updates local (*this*) node data in DHT, this is but not limited to the
160          * session id, ip number (and/or hostname) and port number.
161          *
162          * @return      void
163          */
164         public function updateLocalNode () {
165                 // Assert to make sure this method is called with one record in DB (the actual backend of the DHT)
166                 assert($this->isLocalNodeRegistered());
167
168                 // Get node instance
169                 $nodeInstance = Registry::getRegistry()->getInstance('node');
170
171                 // Get search criteria
172                 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
173
174                 // Search for node id and limit it to one entry
175                 $searchInstance->addCriteria(self::DB_COLUMN_NODE_ID, $nodeInstance->getNodeId());
176                 $searchInstance->setLimit(1);
177
178                 // Get a prepared dataset instance
179                 $dataSetInstance = $this->prepareLocalDataSetInstance();
180
181                 // Set search instance
182                 $dataSetInstance->setSearchInstance($searchInstance);
183
184                 // Update DHT database record
185                 $this->queryUpdateDataSet($dataSetInstance);
186         }
187
188         /**
189          * Finds a node locally by given session id
190          *
191          * @param       $sessionId      Session id to lookup
192          * @return      $nodeData       Node data array
193          */
194         public function findNodeLocalBySessionId ($sessionId) {
195                 // Get search criteria
196                 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
197
198                 // Search for session id and limit it to one entry
199                 $searchInstance->addCriteria(self::DB_COLUMN_SESSION_ID, $sessionId);
200                 $searchInstance->setLimit(1);
201
202                 // Query database and get a result instance back
203                 $resultInstance = $this->doSelectByCriteria($searchInstance);
204
205                 // Return result instance
206                 return $resultInstance;
207         }
208
209         /**
210          * Registeres a node by given message data.
211          *
212          * @param       $messageData            An array of all message data
213          * @param       $handlerInstance        An instance of a HandleableMessage class
214          * @return      void
215          */
216         public function registerNodeByMessageData (array $messageData, Handleable $handlerInstance) {
217                 // Get a data set instance
218                 $dataSetInstance = ObjectFactory::createObjectByConfiguredName('dataset_criteria_class', array(self::DB_TABLE_NODE_DHT));
219
220                 // Set primary key (session id)
221                 $dataSetInstance->setUniqueKey(self::DB_COLUMN_SESSION_ID);
222
223                 // Add all array elements
224                 $handlerInstance->addArrayToDataSet($dataSetInstance, $messageData);
225
226                 // Run the "INSERT" query
227                 $this->queryInsertDataSet($dataSetInstance);
228         }
229
230         /**
231          * Updates an existing entry in node list
232          *
233          * @param       $messageData            An array of all message data
234          * @param       $handlerInstance        An instance of a HandleableMessage class
235          * @param       $searchInstance         An instance of LocalSearchCriteria class
236          * @return      void
237          */
238         public function updateNodeByMessageData (array $messageData, Handleable $handlerInstance, LocalSearchCriteria $searchInstance) {
239                 // Get a data set instance
240                 $dataSetInstance = ObjectFactory::createObjectByConfiguredName('dataset_criteria_class', array(self::DB_TABLE_NODE_DHT));
241
242                 // Add search instance
243                 $dataSetInstance->setSearchInstance($searchInstance);
244
245                 // Set primary key (session id)
246                 $dataSetInstance->setUniqueKey(self::DB_COLUMN_SESSION_ID);
247
248                 // Add all array elements
249                 $handlerInstance->addArrayToDataSet($dataSetInstance, $messageData);
250
251                 // Run the "UPDATE" query
252                 $this->queryUpdateDataSet($dataSetInstance);
253         }
254 }
255
256 // [EOF]
257 ?>