]> git.mxchange.org Git - hub.git/blob
c61af61024f76810403472efe97990b82b2c7361
[hub.git] /
1 <?php
2 // Own namespace
3 namespace Org\Shipsimu\Hub\Database\Frontend\Node\Dht;
4
5 // Import application-specific stuff
6 use Org\Shipsimu\Hub\Database\Frontend\BaseHubDatabaseFrontend;
7 use Org\Shipsimu\Hub\Factory\Node\NodeObjectFactory;
8 use Org\Shipsimu\Hub\Locator\Node\LocateableNode;
9 use Org\Shipsimu\Hub\Network\Message\DeliverableMessage;
10 use Org\Shipsimu\Hub\Network\Package\DeliverablePackage;
11 use Org\Shipsimu\Hub\Node\BaseHubNode;
12
13 // Import framework stuff
14 use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
15 use Org\Mxchange\CoreFramework\Criteria\Local\LocalSearchCriteria;
16 use Org\Mxchange\CoreFramework\Criteria\Storing\StoreableCriteria;
17 use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
18 use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
19 use Org\Mxchange\CoreFramework\Handler\DataSet\HandleableDataSet;
20 use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
21 use Org\Mxchange\CoreFramework\Registry\Registerable;
22 use Org\Mxchange\CoreFramework\Result\Search\SearchableResult;
23
24 // Import SPL stuff
25 use \BadMethodCallException;
26 use \InvalidArgumentException;
27
28 /**
29  * A database frontend for distributed hash tables
30  *
31  * @author              Roland Haeder <webmaster@shipsimu.org>
32  * @version             0.0.0
33  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2022 Hub Developer Team
34  * @license             GNU GPL 3.0 or any newer version
35  * @link                http://www.shipsimu.org
36  *
37  * This program is free software: you can redistribute it and/or modify
38  * it under the terms of the GNU General Public License as published by
39  * the Free Software Foundation, either version 3 of the License, or
40  * (at your option) any later version.
41  *
42  * This program is distributed in the hope that it will be useful,
43  * but WITHOUT ANY WARRANTY; without even the implied warranty of
44  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
45  * GNU General Public License for more details.
46  *
47  * You should have received a copy of the GNU General Public License
48  * along with this program. If not, see <http://www.gnu.org/licenses/>.
49  */
50 class NodeDistributedHashTableDatabaseFrontend extends BaseHubDatabaseFrontend implements NodeDhtFrontend, Registerable {
51         /**
52          * "Cached" results for dabase for looking for unpublished entries
53          */
54         private $unpublishedEntriesInstance = NULL;
55
56         // Constants for database table names
57         const DB_TABLE_NODE_DHT = 'node_dht';
58
59         // Constants for database column names
60         const DB_COLUMN_NODE_ID            = 'node_id';
61         const DB_COLUMN_SESSION_ID         = 'session_id';
62         const DB_COLUMN_EXTERNAL_ADDRESS   = 'external_address';
63         const DB_COLUMN_PRIVATE_KEY_HASH   = 'private_key_hash';
64         const DB_COLUMN_NODE_MODE          = 'node_mode';
65         const DB_COLUMN_ACCEPTED_OBJECTS   = 'accepted_object_types';
66         const DB_COLUMN_NODE_LIST          = 'node_list';
67         const DB_COLUMN_PUBLICATION_STATUS = 'publication_status';
68         const DB_COLUMN_ANSWER_STATUS      = 'answer_status';
69         const DB_COLUMN_ACCEPT_BOOTSTRAP   = 'accept_bootstrap';
70
71         // Publication status'
72         const PUBLICATION_STATUS_PENDING = 'PENDING';
73
74         // Exception codes
75         const EXCEPTION_NODE_ALREADY_REGISTERED = 0x800;
76         const EXCEPTION_NODE_NOT_REGISTERED     = 0x801;
77
78         /**
79          * Protected constructor
80          *
81          * @return      void
82          */
83         private function __construct () {
84                 // Call parent constructor
85                 parent::__construct(__CLASS__);
86         }
87
88         /**
89          * Creates an instance of this database frontend by a provided user class
90          *
91          * @return      $frontendInstance       An instance of the created frontend class
92          */
93         public static final function createNodeDistributedHashTableDatabaseFrontend () {
94                 // Get a new instance
95                 $frontendInstance = new NodeDistributedHashTableDatabaseFrontend();
96
97                 // Set (primary!) table name
98                 $frontendInstance->setTableName(self::DB_TABLE_NODE_DHT);
99
100                 // Get node instance
101                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: Creating node instance ...');
102                 $nodeInstance = NodeObjectFactory::createNodeInstance();
103
104                 // And set it here
105                 $frontendInstance->setNodeInstance($nodeInstance);
106
107                 // Return the instance
108                 return $frontendInstance;
109         }
110
111         /**
112          * Static getter for an array of all DHT database entries
113          *
114          * @return      $elements       All elements for the DHT dabase
115          */
116         public static final function getAllElements () {
117                 // Create array and ...
118                 $elements = [
119                         self::DB_COLUMN_NODE_ID,
120                         self::DB_COLUMN_SESSION_ID,
121                         self::DB_COLUMN_EXTERNAL_ADDRESS,
122                         self::DB_COLUMN_PRIVATE_KEY_HASH,
123                         self::DB_COLUMN_NODE_MODE,
124                         self::DB_COLUMN_ACCEPTED_OBJECTS,
125                         self::DB_COLUMN_NODE_LIST
126                 ];
127
128                 // ... return it
129                 return $elements;
130         }
131
132         /**
133          * Prepares a search instance for given node data
134          *
135          * @param       $nodeData                       An array with valid node data
136          * @return      $searchInstance         An instance of a SearchCriteria class
137          */
138         private function prepareSearchInstance (array $nodeData) {
139                 // Assert on array elements
140                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: CALLED!');
141                 assert(isset($nodeData[self::DB_COLUMN_NODE_ID]));
142
143                 // Get instance
144                 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
145
146                 // Search for node id and limit it to one entry
147                 $searchInstance->addCriteria(self::DB_COLUMN_NODE_ID, $nodeData[self::DB_COLUMN_NODE_ID]);
148                 $searchInstance->setLimit(1);
149
150                 // Return it
151                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: EXIT!');
152                 return $searchInstance;
153         }
154
155         /**
156          * Prepares a "local" instance of a StoreableCriteria class with all node
157          * data for insert/update queries. This data set contains data from *this*
158          * (local) node.
159          *
160          * @return      $dataSetInstance        An instance of a StoreableCriteria class
161          */
162         private function prepareLocalDataSetInstance () {
163                 // Debug message
164                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: CALLED!');
165
166                 // Get request instances
167                 $requestInstance = FrameworkBootstrap::getRequestInstance();
168
169                 // Get a dataset instance
170                 $dataSetInstance = ObjectFactory::createObjectByConfiguredName('dataset_criteria_class', array(self::DB_TABLE_NODE_DHT));
171
172                 // Set the primary key
173                 $dataSetInstance->setUniqueKey(self::DB_COLUMN_NODE_ID);
174
175                 // Get Universal Node Locator and "explode" it
176                 $locatorInstance = $this->getNodeInstance()->determineUniversalNodeLocator();
177
178                 // Get external UNL
179                 $externalUnl = $locatorInstance->getExternalUnl();
180
181                 // Make sure both is valid
182                 // @TODO Bad check on UNL, better use a proper validator
183                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: externalUnl=' . $externalUnl);
184                 assert($externalUnl !== 'invalid');
185
186                 // Get an array of all accepted object types
187                 $objectList = $this->getNodeInstance()->getListFromAcceptedObjectTypes();
188
189                 // Make sure this is an array
190                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: objectList()=' . count($objectList));
191                 assert(is_array($objectList));
192
193                 // Add public node data
194                 $dataSetInstance->addCriteria(self::DB_COLUMN_NODE_MODE       , $requestInstance->getRequestElement('mode'));
195                 $dataSetInstance->addCriteria(self::DB_COLUMN_EXTERNAL_ADDRESS, $externalUnl);
196                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: nodeInstance->nodeId=' . $this->getNodeInstance()->getNodeId());
197                 $dataSetInstance->addCriteria(self::DB_COLUMN_NODE_ID         , $this->getNodeInstance()->getNodeId());
198                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: nodeInstance->sessionId=' . $this->getNodeInstance()->getSessionId());
199                 $dataSetInstance->addCriteria(self::DB_COLUMN_SESSION_ID      , $this->getNodeInstance()->getSessionId());
200                 $dataSetInstance->addCriteria(self::DB_COLUMN_PRIVATE_KEY_HASH, $this->getNodeInstance()->getNodePrivateKeyHash());
201                 $dataSetInstance->addCriteria(self::DB_COLUMN_ACCEPTED_OBJECTS, implode(BaseHubNode::OBJECT_LIST_SEPARATOR, $objectList));
202                 $dataSetInstance->addCriteria(self::DB_COLUMN_ACCEPT_BOOTSTRAP, $this->translateBooleanToYesNo($this->getNodeInstance()->isAcceptingDhtBootstrap()));
203
204                 // Return it
205                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: dataSetInstance=' . $dataSetInstance->__toString() . ' - EXIT!');
206                 return $dataSetInstance;
207         }
208
209         /**
210          * Getter for result instance for unpublished entries
211          *
212          * @return      $unpublishedEntriesInstance             Result instance
213          */
214         public final function getUnpublishedEntriesInstance () {
215                 return $this->unpublishedEntriesInstance;
216         }
217
218         /**
219          * Checks whether the local (*this*) node is registered in the DHT by
220          * checking if the external address is found.
221          *
222          * @return      $isRegistered   Whether *this* node is registered in the DHT
223          */
224         public function isLocalNodeRegistered () {
225                 // Get a search criteria instance
226                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: CALLED!');
227                 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
228
229                 // Get Universal Node Locator and "explode" it
230                 $locatorInstance = $this->getNodeInstance()->determineUniversalNodeLocator();
231
232                 // Make sure the external address is set and not invalid
233                 // @TODO Bad check on UNL, better use a proper validator
234                 $externalUnl = $locatorInstance->getExternalUnl();
235                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('DHT-FRONTEND: externalUnl=%s', $externalUnl));
236                 assert($externalUnl != 'invalid');
237
238                 // Add Universal Node Locator/node id as criteria
239                 $searchInstance->addCriteria(self::DB_COLUMN_EXTERNAL_ADDRESS, $externalUnl);
240                 $searchInstance->addCriteria(self::DB_COLUMN_NODE_ID         , $this->getNodeInstance()->getNodeId());
241                 $searchInstance->addCriteria(self::DB_COLUMN_SESSION_ID      , $this->getNodeInstance()->getSessionId());
242                 $searchInstance->setLimit(1);
243
244                 // Query database and get a result instance back
245                 $resultInstance = $this->doSelectByCriteria($searchInstance);
246
247                 // Cache result of if there is an entry, valid() will tell us if an entry is there
248                 $isRegistered = $resultInstance->valid();
249
250                 // Return result
251                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('DHT-FRONTEND: isRegistered=%d - EXIT!', intval($isRegistered)));
252                 return $isRegistered;
253         }
254
255         /**
256          * Registeres the local (*this*) node with its data in the DHT.
257          *
258          * @return      void
259          */
260         public function registerLocalNode () {
261                 // Debug message
262                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: CALLED!');
263
264                 // Assert to make sure this method is called with no record in DB (the actual backend of the DHT)
265                 assert(!$this->isLocalNodeRegistered());
266
267                 // Get prepared data set instance
268                 $dataSetInstance = $this->prepareLocalDataSetInstance();
269
270                 // "Insert" this dataset instance completely into the database
271                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: Invoking this->queryInsertDataSet(' . $dataSetInstance->__toString() . ') ...');
272                 $this->queryInsertDataSet($dataSetInstance);
273
274                 // Debug message
275                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: EXIT!');
276         }
277
278         /**
279          * Updates local (*this*) node's data in DHT, this is but not limited to the
280          * session id, ip number (and/or hostname) and port number.
281          *
282          * @return      void
283          * @throws      BadMethodCallException  If node is not locally registered
284          */
285         public function updateLocalNode () {
286                 // Check condition
287                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: CALLED!');
288                 if (!$this->isLocalNodeRegistered()) {
289                         // Not registered but methoded invoked
290                         throw new BadMethodCallException('Node is not locally registered but method called', FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
291                 }
292
293                 // Get search criteria
294                 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
295
296                 // Search for node id and limit it to one entry
297                 $searchInstance->addCriteria(self::DB_COLUMN_NODE_ID, $this->getNodeInstance()->getNodeId());
298                 $searchInstance->setLimit(1);
299
300                 // Get a prepared dataset instance
301                 $dataSetInstance = $this->prepareLocalDataSetInstance();
302
303                 // Set search instance
304                 $dataSetInstance->setSearchInstance($searchInstance);
305
306                 // Update DHT database record
307                 $this->queryUpdateDataSet($dataSetInstance);
308
309                 // Debug message
310                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: EXIT!');
311         }
312
313         /**
314          * Finds a node locally by given session id
315          *
316          * @param       $sessionId      Session id to lookup
317          * @return      $resultInstance         An instance of a SearchableResult class
318          * @throws      InvalidArgumentException        If parameter $sessionId is not valid
319          */
320         public function findNodeLocalBySessionId (string $sessionId) {
321                 // Validate parameter
322                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('DHT-FRONTEND: sessionId=%s - CALLED!', $sessionId));
323                 if (empty($sessionId)) {
324                         // Cannot be empty
325                         throw new InvalidArgumentException('Parameter "sessionId" is empty.');
326                 }
327
328                 // Get search criteria
329                 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
330
331                 // Search for session id and limit it to one entry
332                 $searchInstance->addCriteria(self::DB_COLUMN_SESSION_ID, $sessionId);
333                 $searchInstance->setLimit(1);
334
335                 // Query database and get a result instance back
336                 $resultInstance = $this->doSelectByCriteria($searchInstance);
337
338                 // Return result instance
339                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('DHT-FRONTEND: resultInstance->valid()=%d - EXIT!', intval($resultInstance->valid())));
340                 return $resultInstance;
341         }
342
343         /**
344          * Finds a node locally by given UNL instance
345          *
346          * @param       $locatorInstance        An instance of a LocateableNode class
347          * @return      $resultInstance         An instance of a SearchableResult class
348          */
349         public function findNodeLocalByLocatorInstance (LocateableNode $locatorInstance) {
350                 // Get search criteria
351                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('DHT-FRONTEND: locatorInstance=%s - CALLED!', $locatorInstance->__toString()));
352                 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
353
354                 // Search for session id and limit it to one entry
355                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('DHT-FRONTEND: externalUnl=%s', $locatorInstance->getExternalUnl()));
356                 $searchInstance->addCriteria(self::DB_COLUMN_EXTERNAL_ADDRESS, $locatorInstance->getExternalUnl());
357                 $searchInstance->setLimit(1);
358
359                 // Query database and get a result instance back
360                 $resultInstance = $this->doSelectByCriteria($searchInstance);
361
362                 // Return result instance
363                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('DHT-FRONTEND: resultInstance->valid()=%d - EXIT!', intval($resultInstance->valid())));
364                 return $resultInstance;
365         }
366
367         /**
368          * Registeres a node by given message data.
369          *
370          * @param       $messageInstance        An instance of a DeliverableMessage class
371          * @param       $handlerInstance        An instance of a HandleableDataSet class
372          * @return      void
373          */
374         public function registerNodeByMessageInstance (DeliverableMessage $messageInstance, HandleableDataSet $handlerInstance) {
375                 // Get a data set instance
376                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: handlerInstance=' . $handlerInstance->__toString() . ' - CALLED!');
377                 $dataSetInstance = ObjectFactory::createObjectByConfiguredName('dataset_criteria_class', array(self::DB_TABLE_NODE_DHT));
378
379                 // Set primary key (session id)
380                 $dataSetInstance->setUniqueKey(self::DB_COLUMN_SESSION_ID);
381
382                 // Add all array elements
383                 $handlerInstance->addArrayToDataSet($dataSetInstance, $messageInstance);
384
385                 // Remove 'node_list'
386                 $dataSetInstance->unsetCriteria(self::DB_COLUMN_NODE_LIST);
387
388                 // Run the "INSERT" query
389                 $this->queryInsertDataSet($dataSetInstance);
390
391                 // Trace message
392                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND - EXIT!');
393         }
394
395         /**
396          * Updates an existing entry in node list
397          *
398          * @param       $messageInstance        An instance of a DeliverableMessage class
399          * @param       $handlerInstance        An instance of a HandleableDataSet class
400          * @param       $searchInstance         An instance of LocalSearchCriteria class
401          * @return      void
402          */
403         public function updateNodeByMessageInstance (DeliverableMessage $messageInstance, HandleableDataSet $handlerInstance, LocalSearchCriteria $searchInstance) {
404                 // Debug message
405                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: CALLED!');
406
407                 // Get a data set instance
408                 $dataSetInstance = ObjectFactory::createObjectByConfiguredName('dataset_criteria_class', array(self::DB_TABLE_NODE_DHT));
409
410                 // Add search instance
411                 $dataSetInstance->setSearchInstance($searchInstance);
412
413                 // Set primary key (session id)
414                 $dataSetInstance->setUniqueKey(self::DB_COLUMN_SESSION_ID);
415
416                 // Add all array elements
417                 $handlerInstance->addArrayToDataSet($dataSetInstance, $messageInstance);
418
419                 // Remove 'node_list'
420                 $dataSetInstance->unsetCriteria(self::DB_COLUMN_NODE_LIST);
421
422                 // Run the "UPDATE" query
423                 $this->queryUpdateDataSet($dataSetInstance);
424
425                 // Debug message
426                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: EXIT!');
427         }
428
429         /**
430          * Determines whether the given node data is already inserted in the DHT
431          *
432          * @param       $nodeData               An array with valid node data
433          * @return      $isRegistered   Whether the given node data is already inserted
434          */
435         public function isNodeRegistered (array $nodeData) {
436                 // Debug message
437                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: CALLED!');
438
439                 // Assert on array elements
440                 assert(isset($nodeData[self::DB_COLUMN_NODE_ID]));
441
442                 // Debug message
443                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: node-id=' . $nodeData[self::DB_COLUMN_NODE_ID]);
444
445                 // Get search criteria
446                 $searchInstance = $this->prepareSearchInstance($nodeData);
447
448                 // Query database and get a result instance back
449                 $resultInstance = $this->doSelectByCriteria(
450                         // Search instance
451                         $searchInstance,
452                         // Only look for these array elements ("keys")
453                         array(
454                                 self::DB_COLUMN_NODE_ID          => TRUE,
455                                 self::DB_COLUMN_EXTERNAL_ADDRESS => TRUE
456                         )
457                 );
458
459                 // Check if there is an entry
460                 $isRegistered = $resultInstance->valid();
461
462                 // Debug message
463                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: isRegistered=' . intval($isRegistered) . ' - EXIT!');
464
465                 // Return registration status
466                 return $isRegistered;
467         }
468
469         /**
470          * Registers a node with given data in the DHT. If the node is already
471          * registered this method shall throw an exception.
472          *
473          * @param       $nodeData       An array with valid node data
474          * @return      void
475          * @throws      NodeAlreadyRegisteredException  If the node is already registered
476          */
477         public function registerNode (array $nodeData) {
478                 // Debug message
479                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: CALLED!');
480
481                 // Assert on array elements
482                 assert(isset($nodeData[self::DB_COLUMN_NODE_ID]));
483
484                 // Is the node registered?
485                 if ($this->isNodeRegistered($nodeData)) {
486                         // Throw an exception
487                         throw new NodeAlreadyRegisteredException(array($this, $nodeData), self::EXCEPTION_NODE_ALREADY_REGISTERED);
488                 }
489
490                 // @TODO Unimplemented part
491                 DebugMiddleware::getSelfInstance()->partialStub('nodeData=' . print_r($nodeData, TRUE));
492
493                 // Debug message
494                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: EXIT!');
495         }
496
497         /**
498          * Updates a node's entry in the DHT with given data. This will enrich or
499          * just update already exsiting data. If the node is not found this method
500          * shall throw an exception.
501          *
502          * @param       $nodeData       An array with valid node data
503          * @return      void
504          * @throws      NodeDataMissingException        If the node's data is missing
505          */
506         public function updateNode (array $nodeData) {
507                 // Debug message
508                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: nodeData=' . print_r($nodeData, TRUE));
509                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: CALLED!');
510
511                 // Assert on array elements
512                 assert(isset($nodeData[self::DB_COLUMN_NODE_ID]));
513
514                 // Debug message
515                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: Updating DHT entry for node-id=' . $nodeData[self::DB_COLUMN_NODE_ID] . ' ...');
516
517                 // Is the node registered?
518                 if (!$this->isNodeRegistered($nodeData)) {
519                         // No, then throw an exception
520                         throw new NodeDataMissingException(array($this, $nodeData), self::EXCEPTION_NODE_NOT_REGISTERED);
521                 }
522
523                 // Get a search instance
524                 $searchInstance = $this->prepareSearchInstance($nodeData);
525
526                 // Get a data set instance
527                 $dataSetInstance = ObjectFactory::createObjectByConfiguredName('dataset_criteria_class', array(self::DB_TABLE_NODE_DHT));
528
529                 // Add search instance
530                 $dataSetInstance->setSearchInstance($searchInstance);
531
532                 // Set primary key (session id)
533                 $dataSetInstance->setUniqueKey(self::DB_COLUMN_SESSION_ID);
534
535                 // Add all array elements
536                 $this->getNodeInstance()->addArrayToDataSet($dataSetInstance, $nodeData);
537
538                 // Remove 'node_list'
539                 $dataSetInstance->unsetCriteria(self::DB_COLUMN_NODE_LIST);
540
541                 // Run the "UPDATE" query
542                 $this->queryUpdateDataSet($dataSetInstance);
543
544                 // Debug message
545                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: EXIT!');
546         }
547
548         /**
549          * Checks whether there are unpublished entries
550          *
551          * @return      $hasUnpublished         Whether there are unpublished entries
552          * @todo        Add minimum/maximum age limitations
553          */
554         public function hasUnpublishedEntries () {
555                 // Get search instance
556                 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
557
558                 // Add exclusion key which is the publish status
559                 $searchInstance->addExcludeCriteria(NodeDistributedHashTableDatabaseFrontend::DB_COLUMN_PUBLICATION_STATUS, NodeDistributedHashTableDatabaseFrontend::PUBLICATION_STATUS_PENDING);
560
561                 // Remember search instance
562                 $this->setSearchInstance($searchInstance);
563
564                 // Run the query
565                 $this->unpublishedEntriesInstance = $this->doSelectByCriteria($searchInstance);
566
567                 // Check pending entries
568                 $hasUnpublished = $this->unpublishedEntriesInstance->valid();
569
570                 // Debug message
571                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: EXIT!');
572
573                 // Return it
574                 return $hasUnpublished;
575         }
576
577         /**
578          * Initializes publication of DHT entries. This does only prepare
579          * publication. The next step is to pickup such prepared entries and publish
580          * them by uploading to other (recently appeared) DHT members.
581          *
582          * @return      void
583          * @todo        Add timestamp to dataset instance
584          */
585         public function initEntryPublication () {
586                 // Debug message
587                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: CALLED!');
588
589                 /*
590                  * Make sure that hasUnpublishedEntries() has been called first by
591                  * asserting on the "cached" object instance. This "caching" saves some
592                  * needless queries as this method shall be called immediately after
593                  * hasUnpublishedEntries() returns TRUE.
594                  */
595                 assert($this->unpublishedEntriesInstance instanceof SearchableResult);
596
597                 // Result is still okay?
598                 assert($this->unpublishedEntriesInstance->valid());
599
600                 // Remove 'publication_status'
601                 $this->getSearchInstance()->unsetCriteria(self::DB_COLUMN_PUBLICATION_STATUS);
602
603                 // Make sure all entries are marked as pending, first get a dataset instance.
604                 $dataSetInstance = ObjectFactory::createObjectByConfiguredName('dataset_criteria_class', array(self::DB_TABLE_NODE_DHT));
605
606                 // Add search instance
607                 $dataSetInstance->setSearchInstance($this->getSearchInstance());
608
609                 // Set primary key (node id)
610                 $dataSetInstance->setUniqueKey(self::DB_COLUMN_NODE_ID);
611
612                 // Add criteria (that should be set)
613                 $dataSetInstance->addCriteria(self::DB_COLUMN_PUBLICATION_STATUS, self::PUBLICATION_STATUS_PENDING);
614
615                 // Run the "UPDATE" query
616                 $this->queryUpdateDataSet($dataSetInstance);
617
618                 // Debug message
619                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: EXIT!');
620         }
621
622         /**
623          * Removes non-public data from given array.
624          *
625          * @param       $data   An array with possible non-public data that needs to be removed.
626          * @return      $data   A cleaned up array with only public data.
627          */
628         public function removeNonPublicDataFromArray(array $data) {
629                 // Currently call only inner method
630                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: Invoking parent::removeNonPublicDataFromArray(data) ...');
631                 $data = parent::removeNonPublicDataFromArray($data);
632                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: data[]=' . gettype($data));
633
634                 // Return cleaned data
635                 return $data;
636         }
637
638         /**
639          * Find recipients for given package data and exclude the sender
640          *
641          * @param       $packageInstance        An instance of a DeliverablePackage class
642          * @return      $recipients                     An indexed array with DHT recipients
643          */
644         public function getResultFromExcludedSender (DeliverablePackage $packageInstance) {
645                 // Debug message
646                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: CALLED!');
647
648                 // Get max recipients
649                 $maxRecipients = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('max_dht_recipients');
650
651                 // First creata a search instance
652                 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
653
654                 // Then exclude 'sender' field as the sender is the current (*this*) node
655                 $searchInstance->addExcludeCriteria(NodeDistributedHashTableDatabaseFrontend::DB_COLUMN_SESSION_ID, $packageInstance->getSenderAddress());
656
657                 // Set limit to maximum DHT recipients
658                 $searchInstance->setLimit($maxRecipients);
659
660                 // Get a result instance back from DHT database frontend.
661                 $resultInstance = $this->doSelectByCriteria($searchInstance);
662
663                 // Debug message
664                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: EXIT!');
665
666                 // Return result instance
667                 return $resultInstance;
668         }
669
670         /**
671          * Find recopients by given key/value pair. First look for the key and if it
672          * matches, compare the value.
673          *
674          * @param       $key                    Key to look for
675          * @param       $value                  Value to compare if key matches
676          * @return      $recipients             An indexed array with DHT recipients
677          * @throws      InvalidArgumentException        If $key is empty
678          */
679         public function getResultFromKeyValue (string $key, $value) {
680                 // Is key parameter valid?
681                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('DHT-FRONTEND: key=%s,value[%s]=%s - CALLED!', $key, gettype($value), $value));
682                 if (empty($key)) {
683                         // Throw exception
684                         throw new InvalidArgumentException('Parameter key is empty');
685                 }
686
687                 // Get max recipients
688                 $maxRecipients = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('max_dht_recipients');
689
690                 // First creata a search instance
691                 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
692
693                 // Find the key/value pair
694                 $searchInstance->addCriteria($key, $value);
695
696                 // Get a result instance back from DHT database frontend.
697                 $resultInstance = $this->doSelectByCriteria($searchInstance);
698
699                 // Return result instance
700                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('DHT-FRONTEND: resultInstance=%s - EXIT!', $resultInstance->__toString()));
701                 return $resultInstance;
702         }
703
704         /**
705          * Enable DHT bootstrap request acceptance for local node
706          *
707          * @return      void
708          */
709         public function enableAcceptDhtBootstrap () {
710                 // Debug message
711                 /* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: Enabling DHT bootstrap requests ...');
712
713                 // Is the node already registered?
714                 if ($this->isLocalNodeRegistered()) {
715                         // Just update our record
716                         $this->updateLocalNode();
717                 } else {
718                         // Register it
719                         $this->registerLocalNode();
720                 }
721         }
722
723 }