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