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