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