3 namespace Org\Shipsimu\Hub\Database\Frontend\Node\Dht;
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;
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;
23 use \BadMethodCallException;
24 use \InvalidArgumentException;
27 * A database frontend for distributed hash tables
29 * @author Roland Haeder <webmaster@shipsimu.org>
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
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.
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.
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/>.
48 class NodeDistributedHashTableDatabaseFrontend extends BaseHubDatabaseFrontend implements NodeDhtFrontend, Registerable {
50 * "Cached" results for dabase for looking for unpublished entries
52 private $unpublishedEntriesInstance = NULL;
54 // Constants for database table names
55 const DB_TABLE_NODE_DHT = 'node_dht';
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';
69 // Publication status'
70 const PUBLICATION_STATUS_PENDING = 'PENDING';
73 const EXCEPTION_NODE_ALREADY_REGISTERED = 0x800;
74 const EXCEPTION_NODE_NOT_REGISTERED = 0x801;
77 * Protected constructor
81 private function __construct () {
82 // Call parent constructor
83 parent::__construct(__CLASS__);
87 * Creates an instance of this database frontend by a provided user class
89 * @return $frontendInstance An instance of the created frontend class
91 public static final function createNodeDistributedHashTableDatabaseFrontend () {
93 $frontendInstance = new NodeDistributedHashTableDatabaseFrontend();
95 // Set (primary!) table name
96 $frontendInstance->setTableName(self::DB_TABLE_NODE_DHT);
99 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: Creating node instance ...');
100 $nodeInstance = NodeObjectFactory::createNodeInstance();
103 $frontendInstance->setNodeInstance($nodeInstance);
105 // Return the instance
106 return $frontendInstance;
110 * Static getter for an array of all DHT database entries
112 * @return $elements All elements for the DHT dabase
114 public static final function getAllElements () {
115 // Create array and ...
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
131 * Prepares a search instance for given node data
133 * @param $nodeData An array with valid node data
134 * @return $searchInstance An instance of a SearchCriteria class
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]));
142 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
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);
149 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: EXIT!');
150 return $searchInstance;
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*
158 * @return $dataSetInstance An instance of a StoreableCriteria class
160 private function prepareLocalDataSetInstance () {
162 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: CALLED!');
164 // Get request instances
165 $requestInstance = FrameworkBootstrap::getRequestInstance();
167 // Get a dataset instance
168 $dataSetInstance = ObjectFactory::createObjectByConfiguredName('dataset_criteria_class', array(self::DB_TABLE_NODE_DHT));
170 // Set the primary key
171 $dataSetInstance->setUniqueKey(self::DB_COLUMN_NODE_ID);
173 // Get Universal Node Locator and "explode" it
174 $locatorInstance = $this->getNodeInstance()->determineUniversalNodeLocator();
177 $externalUnl = $locatorInstance->getExternalUnl();
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');
184 // Get an array of all accepted object types
185 $objectList = $this->getNodeInstance()->getListFromAcceptedObjectTypes();
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));
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()));
203 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: dataSetInstance=' . $dataSetInstance->__toString() . ' - EXIT!');
204 return $dataSetInstance;
208 * Getter for result instance for unpublished entries
210 * @return $unpublishedEntriesInstance Result instance
212 public final function getUnpublishedEntriesInstance () {
213 return $this->unpublishedEntriesInstance;
217 * Checks whether the local (*this*) node is registered in the DHT by
218 * checking if the external address is found.
220 * @return $isRegistered Whether *this* node is registered in the DHT
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');
227 // Get Universal Node Locator and "explode" it
228 $locatorInstance = $this->getNodeInstance()->determineUniversalNodeLocator();
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');
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);
242 // Query database and get a result instance back
243 $resultInstance = $this->doSelectByCriteria($searchInstance);
245 // Cache result of if there is an entry, valid() will tell us if an entry is there
246 $isRegistered = $resultInstance->valid();
249 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('DHT-FRONTEND: isRegistered=%d - EXIT!', intval($isRegistered)));
250 return $isRegistered;
254 * Registeres the local (*this*) node with its data in the DHT.
258 public function registerLocalNode () {
260 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: CALLED!');
262 // Assert to make sure this method is called with no record in DB (the actual backend of the DHT)
263 assert(!$this->isLocalNodeRegistered());
265 // Get prepared data set instance
266 $dataSetInstance = $this->prepareLocalDataSetInstance();
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);
273 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: EXIT!');
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.
281 * @throws BadMethodCallException If node is not locally registered
283 public function updateLocalNode () {
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');
291 // Get search criteria
292 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
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);
298 // Get a prepared dataset instance
299 $dataSetInstance = $this->prepareLocalDataSetInstance();
301 // Set search instance
302 $dataSetInstance->setSearchInstance($searchInstance);
304 // Update DHT database record
305 $this->queryUpdateDataSet($dataSetInstance);
308 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: EXIT!');
312 * Finds a node locally by given session id
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
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)) {
323 throw new InvalidArgumentException('Parameter "sessionId" is empty.');
326 // Get search criteria
327 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
329 // Search for session id and limit it to one entry
330 $searchInstance->addCriteria(self::DB_COLUMN_SESSION_ID, $sessionId);
331 $searchInstance->setLimit(1);
333 // Query database and get a result instance back
334 $resultInstance = $this->doSelectByCriteria($searchInstance);
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;
342 * Finds a node locally by given UNL instance
344 * @param $locatorInstance An instance of a LocateableNode class
345 * @return $resultInstance An instance of a SearchableResult class
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');
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);
357 // Query database and get a result instance back
358 $resultInstance = $this->doSelectByCriteria($searchInstance);
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;
366 * Registeres a node by given message data.
368 * @param $messageInstance An instance of a DeliverableMessage class
369 * @param $handlerInstance An instance of a HandleableDataSet class
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));
377 // Set primary key (session id)
378 $dataSetInstance->setUniqueKey(self::DB_COLUMN_SESSION_ID);
380 // Add all array elements
381 $handlerInstance->addArrayToDataSet($dataSetInstance, $messageInstance);
383 // Remove 'node_list'
384 $dataSetInstance->unsetCriteria(self::DB_COLUMN_NODE_LIST);
386 // Run the "INSERT" query
387 $this->queryInsertDataSet($dataSetInstance);
390 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND - EXIT!');
394 * Updates an existing entry in node list
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
401 public function updateNodeByMessageInstance (DeliverableMessage $messageInstance, HandleableDataSet $handlerInstance, LocalSearchCriteria $searchInstance) {
403 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: CALLED!');
405 // Get a data set instance
406 $dataSetInstance = ObjectFactory::createObjectByConfiguredName('dataset_criteria_class', array(self::DB_TABLE_NODE_DHT));
408 // Add search instance
409 $dataSetInstance->setSearchInstance($searchInstance);
411 // Set primary key (session id)
412 $dataSetInstance->setUniqueKey(self::DB_COLUMN_SESSION_ID);
414 // Add all array elements
415 $handlerInstance->addArrayToDataSet($dataSetInstance, $messageInstance);
417 // Remove 'node_list'
418 $dataSetInstance->unsetCriteria(self::DB_COLUMN_NODE_LIST);
420 // Run the "UPDATE" query
421 $this->queryUpdateDataSet($dataSetInstance);
424 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: EXIT!');
428 * Determines whether the given node data is already inserted in the DHT
430 * @param $nodeData An array with valid node data
431 * @return $isRegistered Whether the given node data is already inserted
433 public function isNodeRegistered (array $nodeData) {
435 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: CALLED!');
437 // Assert on array elements
438 assert(isset($nodeData[self::DB_COLUMN_NODE_ID]));
441 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: node-id=' . $nodeData[self::DB_COLUMN_NODE_ID]);
443 // Get search criteria
444 $searchInstance = $this->prepareSearchInstance($nodeData);
446 // Query database and get a result instance back
447 $resultInstance = $this->doSelectByCriteria(
450 // Only look for these array elements ("keys")
452 self::DB_COLUMN_NODE_ID => TRUE,
453 self::DB_COLUMN_EXTERNAL_ADDRESS => TRUE
457 // Check if there is an entry
458 $isRegistered = $resultInstance->valid();
461 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: isRegistered=' . intval($isRegistered) . ' - EXIT!');
463 // Return registration status
464 return $isRegistered;
468 * Registers a node with given data in the DHT. If the node is already
469 * registered this method shall throw an exception.
471 * @param $nodeData An array with valid node data
473 * @throws NodeAlreadyRegisteredException If the node is already registered
475 public function registerNode (array $nodeData) {
477 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: CALLED!');
479 // Assert on array elements
480 assert(isset($nodeData[self::DB_COLUMN_NODE_ID]));
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);
488 // @TODO Unimplemented part
489 $this->partialStub('nodeData=' . print_r($nodeData, TRUE));
492 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: EXIT!');
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.
500 * @param $nodeData An array with valid node data
502 * @throws NodeDataMissingException If the node's data is missing
504 public function updateNode (array $nodeData) {
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!');
509 // Assert on array elements
510 assert(isset($nodeData[self::DB_COLUMN_NODE_ID]));
513 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: Updating DHT entry for node-id=' . $nodeData[self::DB_COLUMN_NODE_ID] . ' ...');
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);
521 // Get a search instance
522 $searchInstance = $this->prepareSearchInstance($nodeData);
524 // Get a data set instance
525 $dataSetInstance = ObjectFactory::createObjectByConfiguredName('dataset_criteria_class', array(self::DB_TABLE_NODE_DHT));
527 // Add search instance
528 $dataSetInstance->setSearchInstance($searchInstance);
530 // Set primary key (session id)
531 $dataSetInstance->setUniqueKey(self::DB_COLUMN_SESSION_ID);
533 // Add all array elements
534 $this->getNodeInstance()->addArrayToDataSet($dataSetInstance, $nodeData);
536 // Remove 'node_list'
537 $dataSetInstance->unsetCriteria(self::DB_COLUMN_NODE_LIST);
539 // Run the "UPDATE" query
540 $this->queryUpdateDataSet($dataSetInstance);
543 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: EXIT!');
547 * Checks whether there are unpublished entries
549 * @return $hasUnpublished Whether there are unpublished entries
550 * @todo Add minimum/maximum age limitations
552 public function hasUnpublishedEntries () {
553 // Get search instance
554 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
556 // Add exclusion key which is the publish status
557 $searchInstance->addExcludeCriteria(NodeDistributedHashTableDatabaseFrontend::DB_COLUMN_PUBLICATION_STATUS, NodeDistributedHashTableDatabaseFrontend::PUBLICATION_STATUS_PENDING);
559 // Remember search instance
560 $this->setSearchInstance($searchInstance);
563 $this->unpublishedEntriesInstance = $this->doSelectByCriteria($searchInstance);
565 // Check pending entries
566 $hasUnpublished = $this->unpublishedEntriesInstance->valid();
569 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: EXIT!');
572 return $hasUnpublished;
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.
581 * @todo Add timestamp to dataset instance
583 public function initEntryPublication () {
585 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: CALLED!');
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.
593 assert($this->unpublishedEntriesInstance instanceof SearchableResult);
595 // Result is still okay?
596 assert($this->unpublishedEntriesInstance->valid());
598 // Remove 'publication_status'
599 $this->getSearchInstance()->unsetCriteria(self::DB_COLUMN_PUBLICATION_STATUS);
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));
604 // Add search instance
605 $dataSetInstance->setSearchInstance($this->getSearchInstance());
607 // Set primary key (node id)
608 $dataSetInstance->setUniqueKey(self::DB_COLUMN_NODE_ID);
610 // Add criteria (that should be set)
611 $dataSetInstance->addCriteria(self::DB_COLUMN_PUBLICATION_STATUS, self::PUBLICATION_STATUS_PENDING);
613 // Run the "UPDATE" query
614 $this->queryUpdateDataSet($dataSetInstance);
617 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: EXIT!');
621 * Removes non-public data from given array.
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.
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));
632 // Return cleaned data
637 * Find recipients for given package data and exclude the sender
639 * @param $packageInstance An instance of a DeliverablePackage class
640 * @return $recipients An indexed array with DHT recipients
642 public function getResultFromExcludedSender (DeliverablePackage $packageInstance) {
644 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: CALLED!');
646 // Get max recipients
647 $maxRecipients = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('max_dht_recipients');
649 // First creata a search instance
650 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
652 // Then exclude 'sender' field as the sender is the current (*this*) node
653 $searchInstance->addExcludeCriteria(NodeDistributedHashTableDatabaseFrontend::DB_COLUMN_SESSION_ID, $packageInstance->getSenderAddress());
655 // Set limit to maximum DHT recipients
656 $searchInstance->setLimit($maxRecipients);
658 // Get a result instance back from DHT database frontend.
659 $resultInstance = $this->doSelectByCriteria($searchInstance);
662 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: EXIT!');
664 // Return result instance
665 return $resultInstance;
669 * Find recopients by given key/value pair. First look for the key and if it
670 * matches, compare the value.
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
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));
682 throw new InvalidArgumentException('Parameter key is empty');
685 // Get max recipients
686 $maxRecipients = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('max_dht_recipients');
688 // First creata a search instance
689 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
691 // Find the key/value pair
692 $searchInstance->addCriteria($key, $value);
694 // Get a result instance back from DHT database frontend.
695 $resultInstance = $this->doSelectByCriteria($searchInstance);
697 // Return result instance
698 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('DHT-FRONTEND: resultInstance=%s - EXIT!', $resultInstance->__toString()));
699 return $resultInstance;
703 * Enable DHT bootstrap request acceptance for local node
707 public function enableAcceptDhtBootstrap () {
709 /* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: Enabling DHT bootstrap requests ...');
711 // Is the node already registered?
712 if ($this->isLocalNodeRegistered()) {
713 // Just update our record
714 $this->updateLocalNode();
717 $this->registerLocalNode();