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\Generic\FrameworkInterface;
19 use Org\Mxchange\CoreFramework\Handler\DataSet\HandleableDataSet;
20 use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
21 use Org\Mxchange\CoreFramework\Registry\Registerable;
22 use Org\Mxchange\CoreFramework\Result\Search\SearchableResult;
25 use \BadMethodCallException;
26 use \InvalidArgumentException;
29 * A database frontend for distributed hash tables
31 * @author Roland Haeder <webmaster@shipsimu.org>
33 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2022 Hub Developer Team
34 * @license GNU GPL 3.0 or any newer version
35 * @link http://www.shipsimu.org
37 * This program is free software: you can redistribute it and/or modify
38 * it under the terms of the GNU General Public License as published by
39 * the Free Software Foundation, either version 3 of the License, or
40 * (at your option) any later version.
42 * This program is distributed in the hope that it will be useful,
43 * but WITHOUT ANY WARRANTY; without even the implied warranty of
44 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
45 * GNU General Public License for more details.
47 * You should have received a copy of the GNU General Public License
48 * along with this program. If not, see <http://www.gnu.org/licenses/>.
50 class NodeDistributedHashTableDatabaseFrontend extends BaseHubDatabaseFrontend implements NodeDhtFrontend, Registerable {
52 * "Cached" results for dabase for looking for unpublished entries
54 private $unpublishedEntriesInstance = NULL;
56 // Constants for database table names
57 const DB_TABLE_NODE_DHT = 'node_dht';
59 // Constants for database column names
60 const DB_COLUMN_NODE_ID = 'node_id';
61 const DB_COLUMN_SESSION_ID = 'session_id';
62 const DB_COLUMN_EXTERNAL_ADDRESS = 'external_address';
63 const DB_COLUMN_PRIVATE_KEY_HASH = 'private_key_hash';
64 const DB_COLUMN_NODE_MODE = 'node_mode';
65 const DB_COLUMN_ACCEPTED_OBJECTS = 'accepted_object_types';
66 const DB_COLUMN_NODE_LIST = 'node_list';
67 const DB_COLUMN_PUBLICATION_STATUS = 'publication_status';
68 const DB_COLUMN_ANSWER_STATUS = 'answer_status';
69 const DB_COLUMN_ACCEPT_BOOTSTRAP = 'accept_bootstrap';
71 // Publication status'
72 const PUBLICATION_STATUS_PENDING = 'PENDING';
75 const EXCEPTION_NODE_ALREADY_REGISTERED = 0x800;
76 const EXCEPTION_NODE_NOT_REGISTERED = 0x801;
79 * Protected constructor
83 private function __construct () {
84 // Call parent constructor
85 parent::__construct(__CLASS__);
89 * Creates an instance of this database frontend by a provided user class
91 * @return $frontendInstance An instance of the created frontend class
93 public static final function createNodeDistributedHashTableDatabaseFrontend () {
95 $frontendInstance = new NodeDistributedHashTableDatabaseFrontend();
97 // Set (primary!) table name
98 $frontendInstance->setTableName(self::DB_TABLE_NODE_DHT);
101 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: Creating node instance ...');
102 $nodeInstance = NodeObjectFactory::createNodeInstance();
105 $frontendInstance->setNodeInstance($nodeInstance);
107 // Return the instance
108 return $frontendInstance;
112 * Static getter for an array of all DHT database entries
114 * @return $elements All elements for the DHT dabase
116 public static final function getAllElements () {
117 // Create array and ...
119 self::DB_COLUMN_NODE_ID,
120 self::DB_COLUMN_SESSION_ID,
121 self::DB_COLUMN_EXTERNAL_ADDRESS,
122 self::DB_COLUMN_PRIVATE_KEY_HASH,
123 self::DB_COLUMN_NODE_MODE,
124 self::DB_COLUMN_ACCEPTED_OBJECTS,
125 self::DB_COLUMN_NODE_LIST
133 * Prepares a search instance for given node data
135 * @param $nodeData An array with valid node data
136 * @return $searchInstance An instance of a SearchCriteria class
138 private function prepareSearchInstance (array $nodeData) {
139 // Assert on array elements
140 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: CALLED!');
141 assert(isset($nodeData[self::DB_COLUMN_NODE_ID]));
144 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
146 // Search for node id and limit it to one entry
147 $searchInstance->addCriteria(self::DB_COLUMN_NODE_ID, $nodeData[self::DB_COLUMN_NODE_ID]);
148 $searchInstance->setLimit(1);
151 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: EXIT!');
152 return $searchInstance;
156 * Prepares a "local" instance of a StoreableCriteria class with all node
157 * data for insert/update queries. This data set contains data from *this*
160 * @return $dataSetInstance An instance of a StoreableCriteria class
162 private function prepareLocalDataSetInstance () {
164 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: CALLED!');
166 // Get request instances
167 $requestInstance = FrameworkBootstrap::getRequestInstance();
169 // Get a dataset instance
170 $dataSetInstance = ObjectFactory::createObjectByConfiguredName('dataset_criteria_class', array(self::DB_TABLE_NODE_DHT));
172 // Set the primary key
173 $dataSetInstance->setUniqueKey(self::DB_COLUMN_NODE_ID);
175 // Get Universal Node Locator and "explode" it
176 $locatorInstance = $this->getNodeInstance()->determineUniversalNodeLocator();
179 $externalUnl = $locatorInstance->getExternalUnl();
181 // Make sure both is valid
182 // @TODO Bad check on UNL, better use a proper validator
183 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: externalUnl=' . $externalUnl);
184 assert($externalUnl !== 'invalid');
186 // Get an array of all accepted object types
187 $objectList = $this->getNodeInstance()->getListFromAcceptedObjectTypes();
189 // Make sure this is an array
190 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: objectList()=' . count($objectList));
191 assert(is_array($objectList));
193 // Add public node data
194 $dataSetInstance->addCriteria(self::DB_COLUMN_NODE_MODE , $requestInstance->getRequestElement('mode'));
195 $dataSetInstance->addCriteria(self::DB_COLUMN_EXTERNAL_ADDRESS, $externalUnl);
196 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: nodeInstance->nodeId=' . $this->getNodeInstance()->getNodeId());
197 $dataSetInstance->addCriteria(self::DB_COLUMN_NODE_ID , $this->getNodeInstance()->getNodeId());
198 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: nodeInstance->sessionId=' . $this->getNodeInstance()->getSessionId());
199 $dataSetInstance->addCriteria(self::DB_COLUMN_SESSION_ID , $this->getNodeInstance()->getSessionId());
200 $dataSetInstance->addCriteria(self::DB_COLUMN_PRIVATE_KEY_HASH, $this->getNodeInstance()->getNodePrivateKeyHash());
201 $dataSetInstance->addCriteria(self::DB_COLUMN_ACCEPTED_OBJECTS, implode(BaseHubNode::OBJECT_LIST_SEPARATOR, $objectList));
202 $dataSetInstance->addCriteria(self::DB_COLUMN_ACCEPT_BOOTSTRAP, $this->translateBooleanToYesNo($this->getNodeInstance()->isAcceptingDhtBootstrap()));
205 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: dataSetInstance=' . $dataSetInstance->__toString() . ' - EXIT!');
206 return $dataSetInstance;
210 * Getter for result instance for unpublished entries
212 * @return $unpublishedEntriesInstance Result instance
214 public final function getUnpublishedEntriesInstance () {
215 return $this->unpublishedEntriesInstance;
219 * Checks whether the local (*this*) node is registered in the DHT by
220 * checking if the external address is found.
222 * @return $isRegistered Whether *this* node is registered in the DHT
224 public function isLocalNodeRegistered () {
225 // Get a search criteria instance
226 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: CALLED!');
227 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
229 // Get Universal Node Locator and "explode" it
230 $locatorInstance = $this->getNodeInstance()->determineUniversalNodeLocator();
232 // Make sure the external address is set and not invalid
233 // @TODO Bad check on UNL, better use a proper validator
234 $externalUnl = $locatorInstance->getExternalUnl();
235 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('DHT-FRONTEND: externalUnl=%s', $externalUnl));
236 assert($externalUnl != 'invalid');
238 // Add Universal Node Locator/node id as criteria
239 $searchInstance->addCriteria(self::DB_COLUMN_EXTERNAL_ADDRESS, $externalUnl);
240 $searchInstance->addCriteria(self::DB_COLUMN_NODE_ID , $this->getNodeInstance()->getNodeId());
241 $searchInstance->addCriteria(self::DB_COLUMN_SESSION_ID , $this->getNodeInstance()->getSessionId());
242 $searchInstance->setLimit(1);
244 // Query database and get a result instance back
245 $resultInstance = $this->doSelectByCriteria($searchInstance);
247 // Cache result of if there is an entry, valid() will tell us if an entry is there
248 $isRegistered = $resultInstance->valid();
251 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('DHT-FRONTEND: isRegistered=%d - EXIT!', intval($isRegistered)));
252 return $isRegistered;
256 * Registeres the local (*this*) node with its data in the DHT.
260 public function registerLocalNode () {
262 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: CALLED!');
264 // Assert to make sure this method is called with no record in DB (the actual backend of the DHT)
265 assert(!$this->isLocalNodeRegistered());
267 // Get prepared data set instance
268 $dataSetInstance = $this->prepareLocalDataSetInstance();
270 // "Insert" this dataset instance completely into the database
271 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: Invoking this->queryInsertDataSet(' . $dataSetInstance->__toString() . ') ...');
272 $this->queryInsertDataSet($dataSetInstance);
275 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: EXIT!');
279 * Updates local (*this*) node's data in DHT, this is but not limited to the
280 * session id, ip number (and/or hostname) and port number.
283 * @throws BadMethodCallException If node is not locally registered
285 public function updateLocalNode () {
287 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: CALLED!');
288 if (!$this->isLocalNodeRegistered()) {
289 // Not registered but methoded invoked
290 throw new BadMethodCallException('Node is not locally registered but method called', FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
293 // Get search criteria
294 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
296 // Search for node id and limit it to one entry
297 $searchInstance->addCriteria(self::DB_COLUMN_NODE_ID, $this->getNodeInstance()->getNodeId());
298 $searchInstance->setLimit(1);
300 // Get a prepared dataset instance
301 $dataSetInstance = $this->prepareLocalDataSetInstance();
303 // Set search instance
304 $dataSetInstance->setSearchInstance($searchInstance);
306 // Update DHT database record
307 $this->queryUpdateDataSet($dataSetInstance);
310 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: EXIT!');
314 * Finds a node locally by given session id
316 * @param $sessionId Session id to lookup
317 * @return $resultInstance An instance of a SearchableResult class
318 * @throws InvalidArgumentException If parameter $sessionId is not valid
320 public function findNodeLocalBySessionId (string $sessionId) {
321 // Validate parameter
322 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('DHT-FRONTEND: sessionId=%s - CALLED!', $sessionId));
323 if (empty($sessionId)) {
325 throw new InvalidArgumentException('Parameter "sessionId" is empty.');
328 // Get search criteria
329 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
331 // Search for session id and limit it to one entry
332 $searchInstance->addCriteria(self::DB_COLUMN_SESSION_ID, $sessionId);
333 $searchInstance->setLimit(1);
335 // Query database and get a result instance back
336 $resultInstance = $this->doSelectByCriteria($searchInstance);
338 // Return result instance
339 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('DHT-FRONTEND: resultInstance->valid()=%d - EXIT!', intval($resultInstance->valid())));
340 return $resultInstance;
344 * Finds a node locally by given UNL instance
346 * @param $locatorInstance An instance of a LocateableNode class
347 * @return $resultInstance An instance of a SearchableResult class
349 public function findNodeLocalByLocatorInstance (LocateableNode $locatorInstance) {
350 // Get search criteria
351 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('DHT-FRONTEND: locatorInstance=%s - CALLED!', $locatorInstance->__toString()));
352 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
354 // Search for session id and limit it to one entry
355 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('DHT-FRONTEND: externalUnl=%s', $locatorInstance->getExternalUnl()));
356 $searchInstance->addCriteria(self::DB_COLUMN_EXTERNAL_ADDRESS, $locatorInstance->getExternalUnl());
357 $searchInstance->setLimit(1);
359 // Query database and get a result instance back
360 $resultInstance = $this->doSelectByCriteria($searchInstance);
362 // Return result instance
363 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('DHT-FRONTEND: resultInstance->valid()=%d - EXIT!', intval($resultInstance->valid())));
364 return $resultInstance;
368 * Registeres a node by given message data.
370 * @param $messageInstance An instance of a DeliverableMessage class
371 * @param $handlerInstance An instance of a HandleableDataSet class
374 public function registerNodeByMessageInstance (DeliverableMessage $messageInstance, HandleableDataSet $handlerInstance) {
375 // Get a data set instance
376 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: handlerInstance=' . $handlerInstance->__toString() . ' - CALLED!');
377 $dataSetInstance = ObjectFactory::createObjectByConfiguredName('dataset_criteria_class', array(self::DB_TABLE_NODE_DHT));
379 // Set primary key (session id)
380 $dataSetInstance->setUniqueKey(self::DB_COLUMN_SESSION_ID);
382 // Add all array elements
383 $handlerInstance->addArrayToDataSet($dataSetInstance, $messageInstance);
385 // Remove 'node_list'
386 $dataSetInstance->unsetCriteria(self::DB_COLUMN_NODE_LIST);
388 // Run the "INSERT" query
389 $this->queryInsertDataSet($dataSetInstance);
392 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND - EXIT!');
396 * Updates an existing entry in node list
398 * @param $messageInstance An instance of a DeliverableMessage class
399 * @param $handlerInstance An instance of a HandleableDataSet class
400 * @param $searchInstance An instance of LocalSearchCriteria class
403 public function updateNodeByMessageInstance (DeliverableMessage $messageInstance, HandleableDataSet $handlerInstance, LocalSearchCriteria $searchInstance) {
405 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: CALLED!');
407 // Get a data set instance
408 $dataSetInstance = ObjectFactory::createObjectByConfiguredName('dataset_criteria_class', array(self::DB_TABLE_NODE_DHT));
410 // Add search instance
411 $dataSetInstance->setSearchInstance($searchInstance);
413 // Set primary key (session id)
414 $dataSetInstance->setUniqueKey(self::DB_COLUMN_SESSION_ID);
416 // Add all array elements
417 $handlerInstance->addArrayToDataSet($dataSetInstance, $messageInstance);
419 // Remove 'node_list'
420 $dataSetInstance->unsetCriteria(self::DB_COLUMN_NODE_LIST);
422 // Run the "UPDATE" query
423 $this->queryUpdateDataSet($dataSetInstance);
426 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: EXIT!');
430 * Determines whether the given node data is already inserted in the DHT
432 * @param $nodeData An array with valid node data
433 * @return $isRegistered Whether the given node data is already inserted
435 public function isNodeRegistered (array $nodeData) {
437 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: CALLED!');
439 // Assert on array elements
440 assert(isset($nodeData[self::DB_COLUMN_NODE_ID]));
443 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: node-id=' . $nodeData[self::DB_COLUMN_NODE_ID]);
445 // Get search criteria
446 $searchInstance = $this->prepareSearchInstance($nodeData);
448 // Query database and get a result instance back
449 $resultInstance = $this->doSelectByCriteria(
452 // Only look for these array elements ("keys")
454 self::DB_COLUMN_NODE_ID => TRUE,
455 self::DB_COLUMN_EXTERNAL_ADDRESS => TRUE
459 // Check if there is an entry
460 $isRegistered = $resultInstance->valid();
463 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: isRegistered=' . intval($isRegistered) . ' - EXIT!');
465 // Return registration status
466 return $isRegistered;
470 * Registers a node with given data in the DHT. If the node is already
471 * registered this method shall throw an exception.
473 * @param $nodeData An array with valid node data
475 * @throws NodeAlreadyRegisteredException If the node is already registered
477 public function registerNode (array $nodeData) {
479 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: CALLED!');
481 // Assert on array elements
482 assert(isset($nodeData[self::DB_COLUMN_NODE_ID]));
484 // Is the node registered?
485 if ($this->isNodeRegistered($nodeData)) {
486 // Throw an exception
487 throw new NodeAlreadyRegisteredException(array($this, $nodeData), self::EXCEPTION_NODE_ALREADY_REGISTERED);
490 // @TODO Unimplemented part
491 DebugMiddleware::getSelfInstance()->partialStub('nodeData=' . print_r($nodeData, TRUE));
494 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: EXIT!');
498 * Updates a node's entry in the DHT with given data. This will enrich or
499 * just update already exsiting data. If the node is not found this method
500 * shall throw an exception.
502 * @param $nodeData An array with valid node data
504 * @throws NodeDataMissingException If the node's data is missing
506 public function updateNode (array $nodeData) {
508 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: nodeData=' . print_r($nodeData, TRUE));
509 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: CALLED!');
511 // Assert on array elements
512 assert(isset($nodeData[self::DB_COLUMN_NODE_ID]));
515 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: Updating DHT entry for node-id=' . $nodeData[self::DB_COLUMN_NODE_ID] . ' ...');
517 // Is the node registered?
518 if (!$this->isNodeRegistered($nodeData)) {
519 // No, then throw an exception
520 throw new NodeDataMissingException(array($this, $nodeData), self::EXCEPTION_NODE_NOT_REGISTERED);
523 // Get a search instance
524 $searchInstance = $this->prepareSearchInstance($nodeData);
526 // Get a data set instance
527 $dataSetInstance = ObjectFactory::createObjectByConfiguredName('dataset_criteria_class', array(self::DB_TABLE_NODE_DHT));
529 // Add search instance
530 $dataSetInstance->setSearchInstance($searchInstance);
532 // Set primary key (session id)
533 $dataSetInstance->setUniqueKey(self::DB_COLUMN_SESSION_ID);
535 // Add all array elements
536 $this->getNodeInstance()->addArrayToDataSet($dataSetInstance, $nodeData);
538 // Remove 'node_list'
539 $dataSetInstance->unsetCriteria(self::DB_COLUMN_NODE_LIST);
541 // Run the "UPDATE" query
542 $this->queryUpdateDataSet($dataSetInstance);
545 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: EXIT!');
549 * Checks whether there are unpublished entries
551 * @return $hasUnpublished Whether there are unpublished entries
552 * @todo Add minimum/maximum age limitations
554 public function hasUnpublishedEntries () {
555 // Get search instance
556 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
558 // Add exclusion key which is the publish status
559 $searchInstance->addExcludeCriteria(NodeDistributedHashTableDatabaseFrontend::DB_COLUMN_PUBLICATION_STATUS, NodeDistributedHashTableDatabaseFrontend::PUBLICATION_STATUS_PENDING);
561 // Remember search instance
562 $this->setSearchInstance($searchInstance);
565 $this->unpublishedEntriesInstance = $this->doSelectByCriteria($searchInstance);
567 // Check pending entries
568 $hasUnpublished = $this->unpublishedEntriesInstance->valid();
571 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: EXIT!');
574 return $hasUnpublished;
578 * Initializes publication of DHT entries. This does only prepare
579 * publication. The next step is to pickup such prepared entries and publish
580 * them by uploading to other (recently appeared) DHT members.
583 * @todo Add timestamp to dataset instance
585 public function initEntryPublication () {
587 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: CALLED!');
590 * Make sure that hasUnpublishedEntries() has been called first by
591 * asserting on the "cached" object instance. This "caching" saves some
592 * needless queries as this method shall be called immediately after
593 * hasUnpublishedEntries() returns TRUE.
595 assert($this->unpublishedEntriesInstance instanceof SearchableResult);
597 // Result is still okay?
598 assert($this->unpublishedEntriesInstance->valid());
600 // Remove 'publication_status'
601 $this->getSearchInstance()->unsetCriteria(self::DB_COLUMN_PUBLICATION_STATUS);
603 // Make sure all entries are marked as pending, first get a dataset instance.
604 $dataSetInstance = ObjectFactory::createObjectByConfiguredName('dataset_criteria_class', array(self::DB_TABLE_NODE_DHT));
606 // Add search instance
607 $dataSetInstance->setSearchInstance($this->getSearchInstance());
609 // Set primary key (node id)
610 $dataSetInstance->setUniqueKey(self::DB_COLUMN_NODE_ID);
612 // Add criteria (that should be set)
613 $dataSetInstance->addCriteria(self::DB_COLUMN_PUBLICATION_STATUS, self::PUBLICATION_STATUS_PENDING);
615 // Run the "UPDATE" query
616 $this->queryUpdateDataSet($dataSetInstance);
619 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: EXIT!');
623 * Removes non-public data from given array.
625 * @param $data An array with possible non-public data that needs to be removed.
626 * @return $data A cleaned up array with only public data.
628 public function removeNonPublicDataFromArray(array $data) {
629 // Currently call only inner method
630 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: Invoking parent::removeNonPublicDataFromArray(data) ...');
631 $data = parent::removeNonPublicDataFromArray($data);
632 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: data[]=' . gettype($data));
634 // Return cleaned data
639 * Find recipients for given package data and exclude the sender
641 * @param $packageInstance An instance of a DeliverablePackage class
642 * @return $recipients An indexed array with DHT recipients
644 public function getResultFromExcludedSender (DeliverablePackage $packageInstance) {
646 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: CALLED!');
648 // Get max recipients
649 $maxRecipients = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('max_dht_recipients');
651 // First creata a search instance
652 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
654 // Then exclude 'sender' field as the sender is the current (*this*) node
655 $searchInstance->addExcludeCriteria(NodeDistributedHashTableDatabaseFrontend::DB_COLUMN_SESSION_ID, $packageInstance->getSenderAddress());
657 // Set limit to maximum DHT recipients
658 $searchInstance->setLimit($maxRecipients);
660 // Get a result instance back from DHT database frontend.
661 $resultInstance = $this->doSelectByCriteria($searchInstance);
664 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: EXIT!');
666 // Return result instance
667 return $resultInstance;
671 * Find recopients by given key/value pair. First look for the key and if it
672 * matches, compare the value.
674 * @param $key Key to look for
675 * @param $value Value to compare if key matches
676 * @return $recipients An indexed array with DHT recipients
677 * @throws InvalidArgumentException If $key is empty
679 public function getResultFromKeyValue (string $key, $value) {
680 // Is key parameter valid?
681 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('DHT-FRONTEND: key=%s,value[%s]=%s - CALLED!', $key, gettype($value), $value));
684 throw new InvalidArgumentException('Parameter key is empty');
687 // Get max recipients
688 $maxRecipients = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('max_dht_recipients');
690 // First creata a search instance
691 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
693 // Find the key/value pair
694 $searchInstance->addCriteria($key, $value);
696 // Get a result instance back from DHT database frontend.
697 $resultInstance = $this->doSelectByCriteria($searchInstance);
699 // Return result instance
700 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('DHT-FRONTEND: resultInstance=%s - EXIT!', $resultInstance->__toString()));
701 return $resultInstance;
705 * Enable DHT bootstrap request acceptance for local node
709 public function enableAcceptDhtBootstrap () {
711 /* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: Enabling DHT bootstrap requests ...');
713 // Is the node already registered?
714 if ($this->isLocalNodeRegistered()) {
715 // Just update our record
716 $this->updateLocalNode();
719 $this->registerLocalNode();