3 * A database wrapper for distributed hash tables
5 * @author Roland Haeder <webmaster@ship-simu.org>
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
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.
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.
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/>.
24 class NodeDistributedHashTableDatabaseWrapper extends BaseDatabaseWrapper implements NodeDhtWrapper, Registerable {
25 // Constants for database table names
26 const DB_TABLE_NODE_DHT = 'node_dht';
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';
39 * Protected constructor
43 protected function __construct () {
44 // Call parent constructor
45 parent::__construct(__CLASS__);
49 * Creates an instance of this database wrapper by a provided user class
51 * @return $wrapperInstance An instance of the created wrapper class
53 public static final function createNodeDistributedHashTableDatabaseWrapper () {
55 $wrapperInstance = new NodeDistributedHashTableDatabaseWrapper();
57 // Set (primary!) table name
58 $wrapperInstance->setTableName(self::DB_TABLE_NODE_DHT);
60 // Return the instance
61 return $wrapperInstance;
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*
69 * @return $dataSetInstance An instance of a StoreableCriteria class
71 private function prepareLocalDataSetInstance () {
72 // Get node/request instances
73 $nodeInstance = Registry::getRegistry()->getInstance('node');
74 $requestInstance = ApplicationHelper::getSelfInstance()->getRequestInstance();
76 // Get a dataset instance
77 $dataSetInstance = ObjectFactory::createObjectByConfiguredName('dataset_criteria_class', array(self::DB_TABLE_NODE_DHT));
79 // Set the primary key
80 $dataSetInstance->setUniqueKey(self::DB_COLUMN_NODE_ID);
82 // Get ip:port combination and "explode" it
83 $ipPort = $nodeInstance->getAddressPortArray();
85 // Make sure both is valid
86 assert(($ipPort[0] !== 'invalid') && ($ipPort[1] !== 'invalid'));
88 // Get an array of all accepted object types
89 $objectList = $nodeInstance->getListFromAcceptedObjectTypes();
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));
101 return $dataSetInstance;
105 * Checks whether the local (*this*) node is registered in the DHT by
106 * checking if the external ip/port is found.
108 * @return $isRegistered Whether *this* node is registered in the DHT
110 public function isLocalNodeRegistered () {
112 if (!isset($GLOBALS[__METHOD__])) {
113 // Get a search criteria instance
114 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
117 $nodeInstance = Registry::getRegistry()->getInstance('node');
119 // Get ip:port combination and "explode" it
120 $ipPort = $nodeInstance->getAddressPortArray();
123 * Make sure both is not 'invalid' which means that the resolver
126 assert(($ipPort[0] !== 'invalid') && ($ipPort[1] !== 'invalid'));
128 // Add ip:port/node id as criteria
129 $searchInstance->addCriteria(self::DB_COLUMN_EXTERNAL_IP, $ipPort[0]);
130 $searchInstance->addCriteria(self::DB_COLUMN_LISTEN_PORT, $ipPort[1]);
131 $searchInstance->addCriteria(self::DB_COLUMN_NODE_ID , $nodeInstance->getNodeId());
132 $searchInstance->setLimit(1);
134 // Query database and get a result instance back
135 $resultInstance = $this->doSelectByCriteria($searchInstance);
137 // Cache result of if there is an entry, valid() will tell us if an entry is there
138 $GLOBALS[__METHOD__] = $resultInstance->valid();
142 return $GLOBALS[__METHOD__];
146 * Registeres the local (*this*) node with its data in the DHT.
150 public function registerLocalNode () {
151 // Assert to make sure this method is called with no record in DB (the actual backend of the DHT)
152 assert(!$this->isLocalNodeRegistered());
154 // Get prepared data set instance
155 $dataSetInstance = $this->prepareLocalDataSetInstance();
157 // "Insert" this dataset instance completely into the database
158 $this->queryInsertDataSet($dataSetInstance);
162 * Updates local (*this*) node data in DHT, this is but not limited to the
163 * session id, ip number (and/or hostname) and port number.
167 public function updateLocalNode () {
168 // Assert to make sure this method is called with one record in DB (the actual backend of the DHT)
169 assert($this->isLocalNodeRegistered());
172 $nodeInstance = Registry::getRegistry()->getInstance('node');
174 // Get search criteria
175 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
177 // Search for node id and limit it to one entry
178 $searchInstance->addCriteria(self::DB_COLUMN_NODE_ID, $nodeInstance->getNodeId());
179 $searchInstance->setLimit(1);
181 // Get a prepared dataset instance
182 $dataSetInstance = $this->prepareLocalDataSetInstance();
184 // Set search instance
185 $dataSetInstance->setSearchInstance($searchInstance);
187 // Update DHT database record
188 $this->queryUpdateDataSet($dataSetInstance);
192 * Finds a node locally by given session id
194 * @param $sessionId Session id to lookup
195 * @return $nodeData Node data array
197 public function findNodeLocalBySessionId ($sessionId) {
198 // Get search criteria
199 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
201 // Search for session id and limit it to one entry
202 $searchInstance->addCriteria(self::DB_COLUMN_SESSION_ID, $sessionId);
203 $searchInstance->setLimit(1);
205 // Query database and get a result instance back
206 $resultInstance = $this->doSelectByCriteria($searchInstance);
208 // Return result instance
209 return $resultInstance;
213 * Registeres a node by given message data.
215 * @param $messageData An array of all message data
216 * @param $handlerInstance An instance of a HandleableMessage class
219 public function registerNodeByMessageData (array $messageData, Handleable $handlerInstance) {
220 // Get a data set instance
221 $dataSetInstance = ObjectFactory::createObjectByConfiguredName('dataset_criteria_class', array(self::DB_TABLE_NODE_DHT));
223 // Set primary key (session id)
224 $dataSetInstance->setUniqueKey(self::DB_COLUMN_SESSION_ID);
226 // Add all array elements
227 $handlerInstance->addArrayToDataSet($dataSetInstance, $messageData);
229 // Remove 'node_list'
230 $dataSetInstance->unsetCriteria('node_list');
232 // Run the "INSERT" query
233 $this->queryInsertDataSet($dataSetInstance);
237 * Updates an existing entry in node list
239 * @param $messageData An array of all message data
240 * @param $handlerInstance An instance of a HandleableMessage class
241 * @param $searchInstance An instance of LocalSearchCriteria class
244 public function updateNodeByMessageData (array $messageData, Handleable $handlerInstance, LocalSearchCriteria $searchInstance) {
245 // Get a data set instance
246 $dataSetInstance = ObjectFactory::createObjectByConfiguredName('dataset_criteria_class', array(self::DB_TABLE_NODE_DHT));
248 // Add search instance
249 $dataSetInstance->setSearchInstance($searchInstance);
251 // Set primary key (session id)
252 $dataSetInstance->setUniqueKey(self::DB_COLUMN_SESSION_ID);
254 // Add all array elements
255 $handlerInstance->addArrayToDataSet($dataSetInstance, $messageData);
257 // Remove 'node_list'
258 $dataSetInstance->unsetCriteria('node_list');
260 // Run the "UPDATE" query
261 $this->queryUpdateDataSet($dataSetInstance);
265 * Determines whether the given node data is already inserted in the DHT
267 * @param $nodeData An array with valid node data
268 * @return $isRegistered Whether the given node data is already inserted
270 public function isNodeRegistered (array $nodeData) {
271 // Get search criteria
272 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
274 // Search for node id and limit it to one entry
275 $searchInstance->addCriteria(self::DB_COLUMN_NODE_ID, $nodeData[self::DB_COLUMN_NODE_ID]);
276 $searchInstance->setLimit(1);
278 // Query database and get a result instance back
279 $resultInstance = $this->doSelectByCriteria($searchInstance);
281 // Check if there is an entry
282 $isRegistered = $resultInstance->valid();
284 // Return registration status
285 return $isRegistered;
290 * Registers a node with given data in the DHT. If the node is already
291 * registered this method shall throw an exception.
293 * @param $nodeData An array with valid node data
295 * @throws NodeAlreadyRegisteredException If the node is already registered
297 public function registerNode (array $nodeData) {
298 $this->partialStub('nodeData=' . print_r($nodeData, TRUE));
302 * Updates a node's entry in the DHT with given data. This will enrich or
303 * just update already exsiting data. If the node is not found this method
304 * shall throw an exception.
306 * @param $nodeData An array with valid node data
308 * @throws NodeDataMissingException If the node's data is missing
310 public function updateNode (array $nodeData) {
311 $this->partialStub('nodeData=' . print_r($nodeData, TRUE));