#include <Kademlia.h>

Definition at line 41 of file Kademlia.h.
Public Member Functions | |
| Kademlia () | |
| ~Kademlia () | |
| void | initializeOverlay (int stage) |
| Initializes derived-class-attributes. | |
| void | finishOverlay () |
| collects statistical data in derived class | |
| void | joinOverlay () |
| Join the overlay with a given nodeID in thisNode.key. | |
| bool | isSiblingFor (const NodeHandle &node, const OverlayKey &key, int numSiblings, bool *err) |
| Query if a node is among the siblings for a given key. | |
| int | getMaxNumSiblings () |
| Query the maximum number of siblings (nodes close to a key) that are maintained by this overlay protocol. | |
| int | getMaxNumRedundantNodes () |
| Query the maximum number of redundant next hop nodes that are returned by findNode(). | |
| void | handleTimerEvent (cMessage *msg) |
| Processes "timer" self-messages. | |
| bool | handleRpc (BaseCallMessage *msg) |
| Processes Remote-Procedure-Call invokation messages. | |
Protected Member Functions | |
| NodeVector * | findNode (const OverlayKey &key, int numRedundantNodes, int numSiblings, BaseOverlayMessage *msg) |
| Implements the find node call. | |
| void | handleRpcResponse (BaseResponseMessage *msg, cPolymorphic *context, int rpcId, simtime_t rtt) |
| This method is called if an RPC response has been received. | |
| void | handleRpcTimeout (BaseCallMessage *msg, const TransportAddress &dest, cPolymorphic *context, int rpcId, const OverlayKey &destKey) |
| This method is called if an RPC timeout has been reached. | |
| void | handleBucketRefreshTimerExpired () |
| handle a expired stabilize timer | |
| OverlayKey | distance (const OverlayKey &x, const OverlayKey &y) const |
| This method should implement the distance between two keys. | |
| void | updateTooltip () |
| updates information shown in GUI | |
| virtual void | lookupFinished (bool isValid) |
Protected Attributes | |
| uint32_t | k |
| uint32_t | b |
| uint32_t | s |
| uint32_t | maxStaleCount |
| bool | pingNewSiblings |
| simtime_t | minSiblingTableRefreshInterval |
| simtime_t | minBucketRefreshInterval |
| cMessage * | bucketRefreshTimer |
| uint32_t | nodesReplaced |
Private Member Functions | |
| void | routingInit () |
| void | routingDeinit () |
| int | routingBucketIndex (const OverlayKey &key, bool firstOnLayer=false) |
| Returns the index of the bucket the key would reside with respect to Kademlia parameters. | |
| KademliaBucket * | routingBucket (const OverlayKey &key, bool ensure) |
Returns a Bucket or NULL if the bucket has not yet allocated. | |
| bool | routingAdd (const NodeHandle &handle, bool isAlive, simtime_t rtt=MAXTIME) |
| Adds a node to the routing table. | |
| bool | routingRemove (const OverlayKey &key) |
| Removes a node from the routing table. | |
| bool | routingTimeout (const OverlayKey &key, bool immediately=false) |
| Removes a node after a number of timeouts or immediately if immediately is true (behaves like routingRemove). | |
| void | refillSiblingTable () |
| void | setBucketUsage (const OverlayKey &key) |
| bool | handleFailedNode (const TransportAddress &failed) |
| Handles a failed node. | |
Private Attributes | |
| KeyDistanceComparator < KeyXorMetric > * | comparator |
| KademliaBucket * | siblingTable |
| std::vector< KademliaBucket * > | routingTable |
| int | numBuckets |
| std::map< NodeHandle, NodeHandle > | replacementCache |
Friends | |
| class | KademliaLookupListener |
| Kademlia::Kademlia | ( | ) |
Definition at line 133 of file Kademlia.cc.
00134 { 00135 siblingTable = NULL; 00136 comparator = NULL; 00137 }
| Kademlia::~Kademlia | ( | ) |
Definition at line 139 of file Kademlia.cc.
00140 { 00141 routingDeinit(); 00142 00143 replacementCache.clear(); 00144 delete siblingTable; 00145 delete comparator; 00146 cancelAndDelete(bucketRefreshTimer); 00147 }
| void Kademlia::initializeOverlay | ( | int | stage | ) | [virtual] |
Initializes derived-class-attributes.
Initializes derived-class-attributes, called by BaseOverlay::initialize(). By default this method is called once. If more stages are needed one can overload numInitStages() and add more stages.
| stage | the init stage |
Reimplemented from BaseOverlay.
Definition at line 94 of file Kademlia.cc.
00095 { 00096 if (stage != MIN_STAGE_OVERLAY) 00097 return; 00098 00099 // Kademlia provides KBR services 00100 kbr = true; 00101 00102 // setup kademlia parameters 00103 minSiblingTableRefreshInterval = par("minSiblingTableRefreshInterval"); 00104 minBucketRefreshInterval = par("minBucketRefreshInterval"); 00105 maxStaleCount = par("maxStaleCount"); 00106 pingNewSiblings = par("pingNewSiblings"); 00107 00108 00109 k = par("k"); 00110 b = par("b"); 00111 s = par("s"); 00112 00113 // calculate number of buckets: ( (2^b)-1 ) * ( keylength / b ) 00114 numBuckets = ((1L << b) - 1L) * (OverlayKey::getLength() / b); 00115 00116 // init routing and sibling table 00117 siblingTable = new KademliaBucket(s * 5, NULL); 00118 00119 // initialize pointers 00120 routingTable.assign(numBuckets, (KademliaBucket*)NULL); 00121 00122 WATCH_VECTOR(*siblingTable); 00123 WATCH_VECTOR(routingTable); 00124 00125 // self-message 00126 bucketRefreshTimer = new cMessage("bucketRefreshTimer"); 00127 00128 nodesReplaced = 0; 00129 00130 comparator = NULL; 00131 }
| void Kademlia::finishOverlay | ( | ) | [virtual] |
collects statistical data in derived class
Reimplemented from BaseOverlay.
Definition at line 149 of file Kademlia.cc.
00150 { 00151 // cancel timer 00152 cancelEvent(bucketRefreshTimer); 00153 00154 simtime_t time = globalStatistics->calcMeasuredLifetime(creationTime); 00155 if(time == 0) return; 00156 00157 globalStatistics->addStdDev("Kademlia: Nodes replaced in buckets/s", 00158 nodesReplaced / time); 00159 }
| void Kademlia::joinOverlay | ( | ) | [virtual] |
Join the overlay with a given nodeID in thisNode.key.
Join the overlay with a given nodeID in thisNode.key. This method may be called by an application to join the overlay with a specific nodeID. It is also called if the node's IP address changes.
Reimplemented from BaseOverlay.
Definition at line 161 of file Kademlia.cc.
Referenced by handleRpcTimeout(), and routingTimeout().
00162 { 00163 // remove current node handle from the bootstrap list 00164 if (!thisNode.key.isUnspecified()) { 00165 bootstrapList->removeBootstrapNode(thisNode); 00166 } 00167 00168 // initialize routing 00169 routingDeinit(); 00170 routingInit(); 00171 00172 TransportAddress handle = bootstrapList->getBootstrapNode(); 00173 00174 if (!handle.isUnspecified()) { 00175 // ping the bootstrap node to start bootstrapping 00176 pingNode(handle); 00177 00178 /* 00179 FindNodeCall* findNodeCall = new FindNodeCall(); 00180 findNodeCall->setLookupKey(handle.getKey()); 00181 findNodeCall->setSrcNode(getThisNode()); 00182 findNodeCall->setNumRedundantNodes(getMaxNumRedundantNodes()); 00183 findNodeCall->setNumSiblings(getMaxNumSiblings()); 00184 findNodeCall->setBitLength(FINDNODECALL_L(call)); 00185 00186 RECORD_STATS(numFindNodeSent++; 00187 bytesFindNodeSent += findNodeCall->getByteLength()); 00188 00189 sendUdpRpcCall(handle, findNodeCall); 00190 */ 00191 00192 } else { 00193 // we're the only node in the network 00194 state = READY; 00195 setOverlayReady(true); 00196 00197 // schedule bucket refresh timer 00198 cancelEvent(bucketRefreshTimer); 00199 scheduleAt(simTime(), bucketRefreshTimer); 00200 } 00201 }
| bool Kademlia::isSiblingFor | ( | const NodeHandle & | node, | |
| const OverlayKey & | key, | |||
| int | numSiblings, | |||
| bool * | err | |||
| ) | [virtual] |
Query if a node is among the siblings for a given key.
Query if a node is among the siblings for a given key. This means, that the nodeId of this node is among the closest numSiblings nodes to the key and that by a local findNode() call all other siblings to this key can be retrieved.
| node | the NodeHandle | |
| key | destination key | |
| numSiblings | The nodes knows all numSiblings nodes close to this key | |
| err | return false if the range could not be determined |
Reimplemented from BaseOverlay.
Definition at line 558 of file Kademlia.cc.
Referenced by findNode().
00560 { 00561 if (key.isUnspecified()) 00562 error("Kademlia::isSiblingFor(): key is unspecified!"); 00563 00564 if (state != READY) { 00565 *err = true; 00566 return false; 00567 } 00568 00569 if (numSiblings > getMaxNumSiblings()) { 00570 opp_error("Kademlia::isSiblingFor(): numSiblings too big!"); 00571 } 00572 00573 // set default number of siblings to consider 00574 if (numSiblings == -1) { 00575 numSiblings = getMaxNumSiblings(); 00576 } 00577 00578 if (numSiblings == 0) { 00579 *err = false; 00580 return (node.getKey() == key); 00581 } 00582 00583 if ((siblingTable->size() + 1) < (uint32_t)getMaxNumSiblings()) { 00584 *err = false; 00585 return true; 00586 } 00587 00588 if ((thisNode.key ^ key) > (thisNode.key ^ siblingTable->back().key)) { 00589 *err = true; 00590 return false; 00591 } 00592 00593 KeyDistanceComparator<KeyXorMetric>* comp = 00594 new KeyDistanceComparator<KeyXorMetric>(key); 00595 00596 // create result vector 00597 NodeVector* result = new NodeVector(numSiblings, comp); 00598 00599 for (KademliaBucket::iterator i=siblingTable->begin(); 00600 i != siblingTable->end(); i++) { 00601 result->add( *i); 00602 } 00603 00604 // add local node 00605 result->add(thisNode); 00606 00607 *err = false; 00608 delete comp; 00609 00610 if (result->contains(node.key)) { 00611 delete result; 00612 return true; 00613 } else { 00614 delete result; 00615 assert(!(numSiblings == 1 && key == node.key)); 00616 return false; 00617 } 00618 }
| int Kademlia::getMaxNumSiblings | ( | ) | [virtual] |
Query the maximum number of siblings (nodes close to a key) that are maintained by this overlay protocol.
Reimplemented from BaseOverlay.
Definition at line 241 of file Kademlia.cc.
Referenced by findNode(), handleFailedNode(), isSiblingFor(), routingAdd(), routingTimeout(), and setBucketUsage().
00242 { 00243 return s; 00244 }
| int Kademlia::getMaxNumRedundantNodes | ( | ) | [virtual] |
Query the maximum number of redundant next hop nodes that are returned by findNode().
Reimplemented from BaseOverlay.
Definition at line 246 of file Kademlia.cc.
Referenced by findNode().
00247 { 00248 return k; 00249 }
| void Kademlia::handleTimerEvent | ( | cMessage * | msg | ) | [virtual] |
Processes "timer" self-messages.
| msg | A self-message |
Reimplemented from BaseOverlay.
Definition at line 780 of file Kademlia.cc.
00781 { 00782 if (msg == bucketRefreshTimer) { 00783 handleBucketRefreshTimerExpired(); 00784 } 00785 }
| bool Kademlia::handleRpc | ( | BaseCallMessage * | msg | ) | [virtual] |
Processes Remote-Procedure-Call invokation messages.
This method should be overloaded when the overlay provides RPC functionality.
Reimplemented from BaseRpc.
Definition at line 788 of file Kademlia.cc.
00789 { 00790 RPC_SWITCH_START( msg ) 00791 RPC_ON_CALL( Ping ) { 00792 // add active node 00793 routingAdd( _PingCall->getSrcNode(), true ); 00794 break; 00795 } 00796 RPC_ON_CALL(FindNode) 00797 { 00798 // add active node 00799 routingAdd(_FindNodeCall->getSrcNode(), true); 00800 break; 00801 } 00802 RPC_SWITCH_END( ) 00803 return false; 00804 }
| NodeVector * Kademlia::findNode | ( | const OverlayKey & | key, | |
| int | numRedundantNodes, | |||
| int | numSiblings, | |||
| BaseOverlayMessage * | msg | |||
| ) | [protected, virtual] |
Implements the find node call.
This method simply returns the closest nodes known in the corresponding routing topology. If the node is a sibling for this key (isSiblingFor(key) = true), this method returns all numSiblings siblings, with the closest neighbor to the key first.
| key | The lookup key. | |
| numRedundantNodes | Maximum number of next hop nodes to return. | |
| numSiblings | number of siblings to return | |
| msg | A pointer to the BaseRouteMessage or FindNodeCall message of this lookup. |
Reimplemented from BaseOverlay.
Definition at line 673 of file Kademlia.cc.
00675 { 00676 if ((numRedundantNodes > getMaxNumRedundantNodes()) || (numSiblings 00677 > getMaxNumSiblings())) { 00678 00679 opp_error("(Kademlia::findNode()) numRedundantNodes or numSiblings " 00680 "too big!"); 00681 } 00682 00683 if (numRedundantNodes < 2) { 00684 throw cRuntimeError("Kademlia::findNode(): For Kademlia " 00685 "redundantNodes must be at least 2 " 00686 "and lookupMerge should be true!"); 00687 } 00688 00689 // create temporary comparator 00690 KeyDistanceComparator<KeyXorMetric>* comp = 00691 new KeyDistanceComparator<KeyXorMetric>( key ); 00692 00693 // select result set size 00694 bool err; 00695 int resultSize = isSiblingFor(thisNode, key, numSiblings, &err) ? 00696 (numSiblings ? numSiblings : 1) : numRedundantNodes; 00697 00698 assert(numSiblings || numRedundantNodes); 00699 00700 NodeVector* result = new NodeVector(resultSize, comp); 00701 00702 if (siblingTable->isEmpty()) { 00703 result->add(thisNode); 00704 delete comp; 00705 return result; 00706 } 00707 00708 // add items from buckets 00709 int index; 00710 int mainIndex = routingBucketIndex(key); 00711 int startIndex = routingBucketIndex(key, true); 00712 int endIndex = routingBucketIndex(siblingTable->back().key); 00713 00714 // add nodes from best fitting bucket 00715 if (mainIndex != -1) { 00716 KademliaBucket* bucket = routingTable[mainIndex]; 00717 if (bucket != NULL && bucket->size()) { 00718 for (KademliaBucket::iterator i=bucket->begin(); i!=bucket->end(); i++) { 00719 result->add(*i); 00720 //EV << "Kademlia::findNode(): Adding " 00721 // << *i << " from bucket " << mainIndex << endl; 00722 } 00723 } 00724 } 00725 00726 // add most fitting buckets 00727 if (startIndex >= endIndex || !result->isFull()) { 00728 for (index = startIndex; index >= endIndex; --index) { 00729 // old code... 00730 /* 00731 for (int i = 1; !result->isFull() && i < numBuckets * 3; i++) { 00732 int index = mainIndex + (((i & 1) == 1) ? -1 : 1) * (i / 2); 00733 if (index < 0 || index >= numBuckets) 00734 continue; 00735 */ 00736 00737 // add bucket to result vector 00738 if (index == mainIndex) continue; 00739 KademliaBucket* bucket = routingTable[index]; 00740 if (bucket != NULL && bucket->size()) { 00741 for (KademliaBucket::iterator i=bucket->begin(); i!=bucket->end(); i++) { 00742 result->add(*i); 00743 //EV << "Kademlia::routingGetClosestNodes(): Adding " 00744 // << *i << " from bucket " << index << endl; 00745 } 00746 } 00747 } 00748 00749 // add nodes from sibling table 00750 for (KademliaBucket::iterator i = siblingTable->begin(); 00751 i != siblingTable->end(); i++) { 00752 result->add(*i); 00753 } 00754 // add local node 00755 result->add(thisNode); 00756 } 00757 00758 // add more distant buckets 00759 for (index = mainIndex + 1; !result->isFull() && index < numBuckets; 00760 ++index) { 00761 // add bucket to result vector 00762 KademliaBucket* bucket = routingTable[index]; 00763 if (bucket != NULL && bucket->size()) { 00764 for (KademliaBucket::iterator i=bucket->begin(); i!=bucket->end(); i++) { 00765 result->add(*i); 00766 // << " Adding " << *i << " from bucket " << index 00767 // << endl; 00768 } 00769 } 00770 } 00771 00772 delete comp; 00773 00774 return result; 00775 }
| void Kademlia::handleRpcResponse | ( | BaseResponseMessage * | msg, | |
| cPolymorphic * | context, | |||
| int | rpcId, | |||
| simtime_t | rtt | |||
| ) | [protected, virtual] |
This method is called if an RPC response has been received.
| msg | The response message. | |
| context | Pointer to an optional state object. The object has to be handled/deleted by the handleRpcResponse() code | |
| rpcId | The RPC id. | |
| rtt | The Round-Trip-Time of this RPC |
Reimplemented from RpcListener.
Definition at line 807 of file Kademlia.cc.
00810 { 00811 RPC_SWITCH_START(msg) 00812 RPC_ON_RESPONSE(Ping) { 00813 if (state == INIT) { 00814 // schedule bucket refresh timer 00815 cancelEvent(bucketRefreshTimer); 00816 scheduleAt(simTime(), bucketRefreshTimer); 00817 state = JOIN; 00818 } 00819 00820 // delete replacement candidate //TODO 00821 replacementCache.erase(_PingResponse->getSrcNode()); 00822 } 00823 RPC_ON_RESPONSE(FindNode) 00824 { 00825 // add active node 00826 if (defaultRoutingType == SEMI_RECURSIVE_ROUTING || 00827 defaultRoutingType == FULL_RECURSIVE_ROUTING || 00828 defaultRoutingType == RECURSIVE_SOURCE_ROUTING) 00829 rtt = MAXTIME; 00830 setBucketUsage(_FindNodeResponse->getSrcNode().key); 00831 00832 // add inactive nodes 00833 for (uint32_t i=0; i<_FindNodeResponse->getClosestNodesArraySize(); i++) 00834 routingAdd(_FindNodeResponse->getClosestNodes(i), false); 00835 break; 00836 } 00837 RPC_SWITCH_END() 00838 00839 // add node that reponded 00840 routingAdd(msg->getSrcNode(), true, rtt); 00841 }
| void Kademlia::handleRpcTimeout | ( | BaseCallMessage * | msg, | |
| const TransportAddress & | dest, | |||
| cPolymorphic * | context, | |||
| int | rpcId, | |||
| const OverlayKey & | destKey | |||
| ) | [protected, virtual] |
This method is called if an RPC timeout has been reached.
| msg | The original RPC message. | |
| dest | The destination node | |
| context | Pointer to an optional state object. The object has to be handled/deleted by the handleRpcResponse() code | |
| rpcId | The RPC id. | |
| destKey | the destination OverlayKey |
Reimplemented from RpcListener.
Definition at line 844 of file Kademlia.cc.
00848 { 00849 if (dest.isUnspecified()) return; 00850 try { 00851 RPC_SWITCH_START(msg) 00852 if (state == JOIN || state == INIT) { 00853 joinOverlay(); 00854 return; 00855 } 00856 00857 const NodeHandle& handle = dynamic_cast<const NodeHandle&>(dest); 00858 RPC_ON_CALL(Ping) { 00859 routingTimeout(handle.key); 00860 00861 // remove node from replacementCache 00862 std::map<NodeHandle, NodeHandle>::iterator it 00863 = replacementCache.find(handle); 00864 if (it != replacementCache.end()) { 00865 replacementCache.erase(it); 00866 } 00867 00868 break; 00869 } 00870 RPC_ON_CALL(FindNode) { 00871 routingTimeout(handle.key); 00872 setBucketUsage(handle.key); 00873 break; 00874 } 00875 RPC_SWITCH_END() 00876 } catch (...) { 00877 EV << "[Kademlia:handleRpcTimout() @ " << thisNode.ip 00878 << " (" << thisNode.key.toString(16) << ")]\n" 00879 << " ERROR: RPC timeout without key (" 00880 << msg << " -> " << dest << ")" << endl; 00881 return; 00882 } 00883 }
| void Kademlia::handleBucketRefreshTimerExpired | ( | ) | [protected] |
handle a expired stabilize timer
handle a expired bucket refresh timer
Definition at line 897 of file Kademlia.cc.
Referenced by handleTimerEvent().
00898 { 00899 // refresh buckets 00900 if (state != READY || (((simTime() - siblingTable->getLastUsage()) > 00901 minSiblingTableRefreshInterval))) { 00902 //createLookup(EXHAUSTIVE_ITERATIVE_ROUTING); //TODO 00903 createLookup()->lookup(getThisNode().getKey() + 00904 OverlayKey::ONE, 0, 0, 0, 00905 new KademliaLookupListener(this)); 00906 } 00907 00908 if (state == READY) { 00909 if (siblingTable->size()) { 00910 int32_t diff = OverlayKey::getLength() - getThisNode().getKey(). 00911 sharedPrefixLength(siblingTable->front().key); 00912 for (int32_t i = OverlayKey::getLength() - 1; i >= (diff - 1); i--) { 00913 if ((routingTable[i] == NULL) || 00914 ((simTime() - routingTable[i]->getLastUsage()) > 00915 minBucketRefreshInterval)) { 00916 createLookup()->lookup(getThisNode().getKey() ^ 00917 (OverlayKey::ONE << i), 0, 0, 0, 00918 new KademliaLookupListener(this)); 00919 setBucketUsage(getThisNode().getKey() ^ 00920 (OverlayKey::ONE << i)); 00921 } 00922 } 00923 } 00924 // schedule next bucket refresh process 00925 cancelEvent(bucketRefreshTimer); 00926 scheduleAt(simTime() + 00927 (std::min(minSiblingTableRefreshInterval, 00928 minBucketRefreshInterval) / 10.0), 00929 bucketRefreshTimer); 00930 } 00931 }
| OverlayKey Kademlia::distance | ( | const OverlayKey & | x, | |
| const OverlayKey & | y | |||
| ) | const [protected, virtual] |
This method should implement the distance between two keys.
It may be overloaded to implement a new metric. The default implementation uses the standard-metric d = abs(x-y).
| x | Left-hand-side Key | |
| y | Right-hand-side key |
Reimplemented from BaseOverlay.
Definition at line 934 of file Kademlia.cc.
| void Kademlia::updateTooltip | ( | ) | [protected] |
updates information shown in GUI
Definition at line 939 of file Kademlia.cc.
Referenced by handleFailedNode(), routingAdd(), routingInit(), and routingTimeout().
00940 { 00941 if (ev.isGUI()) { 00942 std::stringstream ttString; 00943 00944 // show our nodeId in a tooltip 00945 ttString << "This: " << thisNode << endl << "Siblings: " 00946 << siblingTable->size(); 00947 00948 getParentModule()->getParentModule()->getDisplayString(). 00949 setTagArg("tt", 0, ttString.str().c_str()); 00950 getParentModule()->getDisplayString(). 00951 setTagArg("tt", 0, ttString.str().c_str()); 00952 getDisplayString().setTagArg("tt", 0, ttString.str().c_str()); 00953 } 00954 }
| void Kademlia::lookupFinished | ( | bool | isValid | ) | [protected, virtual] |
Definition at line 885 of file Kademlia.cc.
Referenced by KademliaLookupListener::lookupFinished().
00886 { 00887 if (state == JOIN) { 00888 cancelEvent(bucketRefreshTimer); 00889 scheduleAt(simTime(), bucketRefreshTimer); 00890 00891 state = READY; 00892 setOverlayReady(true); 00893 } 00894 }
| void Kademlia::routingInit | ( | ) | [private] |
Definition at line 205 of file Kademlia.cc.
Referenced by joinOverlay().
00206 { 00207 // set join state 00208 state = INIT; 00209 00210 setOverlayReady(false); 00211 00212 // setup comparator 00213 comparator = new KeyDistanceComparator<KeyXorMetric>( thisNode.getKey() ); 00214 00215 siblingTable->setComparator(comparator); 00216 00217 updateTooltip(); 00218 BUCKET_CONSISTENCY(routingInit: end); 00219 }
| void Kademlia::routingDeinit | ( | ) | [private] |
Definition at line 221 of file Kademlia.cc.
Referenced by joinOverlay(), and ~Kademlia().
00222 { 00223 // delete buckets 00224 for (uint32_t i = 0; i < routingTable.size(); i++) { 00225 if (routingTable[i] != NULL) { 00226 delete routingTable[i]; 00227 routingTable[i] = NULL; 00228 } 00229 } 00230 00231 if (siblingTable != NULL) { 00232 siblingTable->clear(); 00233 } 00234 00235 if (comparator != NULL) { 00236 delete comparator; 00237 comparator = NULL; 00238 } 00239 }
| int Kademlia::routingBucketIndex | ( | const OverlayKey & | key, | |
| bool | firstOnLayer = false | |||
| ) | [private] |
Returns the index of the bucket the key would reside with respect to Kademlia parameters.
| key | The key of the node | |
| firstOnLayer | If true bucket with smallest index on same layer is returned |
Definition at line 251 of file Kademlia.cc.
Referenced by findNode(), refillSiblingTable(), routingAdd(), and routingBucket().
00252 { 00253 // calculate XOR distance 00254 OverlayKey delta = key ^ getThisNode().getKey(); 00255 00256 // find first subinteger that is not zero... 00257 int i; 00258 for (i = key.getLength() - b; i >= 0 && delta.getBitRange(i, b) == 0; 00259 i -= b); 00260 00261 if (i < 0) 00262 return -1; 00263 00264 if (!firstOnLayer) 00265 return (i / b) * ((1 << b) - 1) + (delta.getBitRange(i, b) - 1); 00266 else 00267 return (i / b) * ((1 << b) - 1) + (pow(2, b) - 2); 00268 }
| KademliaBucket * Kademlia::routingBucket | ( | const OverlayKey & | key, | |
| bool | ensure | |||
| ) | [private] |
Returns a Bucket or NULL if the bucket has not yet allocated.
If ensure is true, the bucket allocation is ensured.
| key | The key of the node | |
| ensure | If true, the bucket allocation is ensured |
Definition at line 270 of file Kademlia.cc.
Referenced by routingAdd(), routingTimeout(), and setBucketUsage().
00271 { 00272 // get bucket index 00273 int num = routingBucketIndex(key); 00274 if (num < 0) 00275 return NULL; 00276 00277 // get bucket and allocate if necessary 00278 KademliaBucket* bucket = routingTable[ num ]; 00279 if (bucket == NULL && ensure) 00280 bucket = routingTable[ num ] = new KademliaBucket( k, comparator ); 00281 00282 // return bucket 00283 return bucket; 00284 }
| bool Kademlia::routingAdd | ( | const NodeHandle & | handle, | |
| bool | isAlive, | |||
| simtime_t | rtt = MAXTIME | |||
| ) | [private] |
Adds a node to the routing table.
| handle | handle to add | |
| isAlive | true, if it is known that the node is alive | |
| rtt | measured round-trip-time to node |
Definition at line 286 of file Kademlia.cc.
Referenced by handleRpc(), handleRpcResponse(), and routingTimeout().
00287 { 00288 BUCKET_CONSISTENCY(routingAdd: start); 00289 // never add unspecified node handles 00290 if (handle.isUnspecified() || handle.key == getThisNode().getKey() ) 00291 return false; 00292 00293 // bucket index 00294 KademliaBucket::iterator i; 00295 bool result = false; 00296 00297 // convert node handle 00298 KademliaBucketEntry kadHandle = handle; 00299 kadHandle.setRtt(rtt); 00300 kadHandle.setLastSeen(simTime()); 00301 00302 /* check if node is already a sibling -----------------------------------*/ 00303 if ((i = siblingTable->findIterator(handle.getKey())) 00304 != siblingTable->end()) { 00305 // not alive? -> do not change routing information 00306 if (isAlive) { 00307 if (kadHandle.getRtt() != i->getRtt()) { 00308 siblingTable->setLastUpdate(simTime()); 00309 if (kadHandle.getRtt() == MAXTIME) 00310 kadHandle.setRtt(i->getRtt()); 00311 } 00312 // refresh sibling 00313 (*i) = kadHandle; 00314 } 00315 BUCKET_CONSISTENCY(routingAdd: node is sibling); 00316 return true; 00317 } 00318 00319 /* check if node is already in a bucket ---------------------------------*/ 00320 KademliaBucket* bucket = routingBucket(handle.getKey(), false); 00321 if (bucket != NULL && (i = bucket->findIterator(handle.getKey() ) ) 00322 != bucket->end() ) { 00323 // not alive? -> do not change routing information 00324 if (isAlive) { 00325 if (kadHandle.getRtt() == MAXTIME) { 00326 kadHandle.setRtt(i->getRtt()); 00327 } 00328 // remove old handle 00329 bucket->erase(i); 00330 // re-add to tail 00331 bucket->push_back(kadHandle); 00332 00333 bucket->setLastUpdate(simTime()); 00334 } 00335 BUCKET_CONSISTENCY(routingAdd: node is in bucket); 00336 return true; 00337 } 00338 00339 /* check if node can be added to the sibling list -----------------------*/ 00340 if (siblingTable->isAddable(handle) ) { 00341 00342 bool finished = false; 00343 int siblingPos = -1; 00344 00345 // check if sibling list is full so a handle is preemted from the list 00346 if (siblingTable->isFull()) { 00347 // get handle thats about to be preempted 00348 KademliaBucketEntry oldHandle = siblingTable->back(); 00349 assert(oldHandle.key != kadHandle.key); 00350 // add handle to the sibling list 00351 siblingPos = siblingTable->add(kadHandle); 00352 00353 // change, so that the preempted handle is added to a bucket 00354 kadHandle = oldHandle; 00355 00356 // return always true, since the handle has been added 00357 result = true; 00358 } else { 00359 // simply add the handle and stop 00360 siblingPos = siblingTable->add(kadHandle); 00361 00362 // don't need to add kadHandle also to regular buckets 00363 finished = true; 00364 } 00365 assert(siblingPos > -1); 00366 00367 // ping new siblings 00368 if (pingNewSiblings && !isAlive) { 00369 pingNode(handle); 00370 } 00371 00372 siblingTable->setLastUpdate(simTime()); 00373 00374 updateTooltip(); 00375 00376 // call update() for real siblings 00377 if (siblingPos < getMaxNumSiblings()) { 00378 if (siblingTable->size() > (uint32_t)getMaxNumSiblings()) { 00379 // removed old sibling 00380 NodeHandle& removedSibling = siblingTable->at(getMaxNumSiblings()); 00381 deleteOverlayNeighborArrow(removedSibling); 00382 callUpdate(removedSibling, false); 00383 } 00384 // new sibling 00385 showOverlayNeighborArrow(handle, false, 00386 "m=m,50,100,50,100;ls=green,1"); 00387 callUpdate(handle, true); 00388 } 00389 00390 if (finished) { 00391 BUCKET_CONSISTENCY(routingAdd: node is now sibling); 00392 return true; 00393 } 00394 } 00395 00396 /* add node to the appropriate bucket, if not full ---------------------*/ 00397 bucket = routingBucket(kadHandle.getKey(), true); 00398 if (!bucket->isFull()) { 00399 EV << "[Kademlia::routingAdd()]\n" 00400 << " Adding new node " << kadHandle 00401 << " to bucket " << routingBucketIndex(kadHandle.getKey()) 00402 << endl; 00403 bucket->push_back(kadHandle); 00404 bucket->setLastUpdate(simTime()); 00405 result = true; 00406 } else if (isAlive) { 00407 //TODO parameter for usage of replacement cache 00408 // save candidate, ping head, 00409 KademliaBucket::iterator it = bucket->begin(); 00410 while (it != bucket->end() && 00411 replacementCache.find(*it) != replacementCache.end()) { 00412 ++it; 00413 } 00414 if (it != bucket->end()) { 00415 replacementCache.insert(std::make_pair(*it, kadHandle)); 00416 //TODO paper: probing should be delayed until useful messages are 00417 //there to send to head 00418 pingNode(*it); 00419 } 00420 } 00421 00422 BUCKET_CONSISTENCY(routingAdd: end); 00423 return result; 00424 }
| bool Kademlia::routingRemove | ( | const OverlayKey & | key | ) | [private] |
Removes a node from the routing table.
| key | Key of the Node |
Definition at line 426 of file Kademlia.cc.
00427 { 00428 return routingTimeout(key, true); 00429 }
| bool Kademlia::routingTimeout | ( | const OverlayKey & | key, | |
| bool | immediately = false | |||
| ) | [private] |
Removes a node after a number of timeouts or immediately if immediately is true (behaves like routingRemove).
| key | Node's key to remove | |
| immediately | If true, the node is removed immediately |
Definition at line 431 of file Kademlia.cc.
Referenced by handleRpcTimeout(), refillSiblingTable(), and routingRemove().
00432 { 00433 BUCKET_CONSISTENCY(routingTimeout: start); 00434 // key unspecified? yes -> ignore 00435 if (key.isUnspecified()) 00436 return false; 00437 00438 // bucket index 00439 KademliaBucket::iterator i; 00440 00441 /* check if the node is one of the siblings -----------------------------*/ 00442 if ((i = siblingTable->findIterator(key)) != siblingTable->end()) { 00443 00444 i->incStaleCount(); 00445 00446 if (i->getStaleCount() > maxStaleCount || immediately) { 00447 // remove from sibling table 00448 NodeHandle oldSibling = *i; 00449 siblingTable->erase(i); 00450 00451 if (siblingTable->size() < (uint32_t)getMaxNumSiblings()) { 00452 // no new replacement sibling 00453 deleteOverlayNeighborArrow(oldSibling); 00454 callUpdate(oldSibling, false); 00455 } else if (comparator->compare(oldSibling.key, 00456 siblingTable->at(getMaxNumSiblings() - 1).key) < 0) { 00457 // failed sibling was replaced by next closest node in siblingTable 00458 deleteOverlayNeighborArrow(oldSibling); 00459 callUpdate(oldSibling, false); 00460 00461 showOverlayNeighborArrow(siblingTable->at(getMaxNumSiblings() - 1), 00462 false, "m=m,50,100,50,100;ls=green,1"); 00463 callUpdate(siblingTable->at(getMaxNumSiblings() - 1), true); 00464 } 00465 00466 updateTooltip(); 00467 00468 // lost last sibling? 00469 if (siblingTable->size() == 0) { 00470 joinOverlay(); 00471 return true; 00472 } 00473 00474 BUCKET_CONSISTENCY(routingTimeout: is sibling); 00475 00476 // try to refill with new closest contact 00477 refillSiblingTable(); 00478 00479 return true; 00480 } 00481 } 00482 00483 /* check if node is already in a bucket ---------------------------------*/ 00484 KademliaBucket* bucket = routingBucket(key, false); 00485 if (bucket != NULL && (i = bucket->findIterator(key) ) != bucket->end() ) { 00486 00487 i->incStaleCount(); 00488 std::map<NodeHandle, NodeHandle>::iterator it 00489 = replacementCache.find(*i); 00490 if (i->getStaleCount() > maxStaleCount || 00491 it != replacementCache.end() || immediately) { 00492 // remove from routing table 00493 bucket->erase(i); 00494 } 00495 if (it != replacementCache.end()) { 00496 routingAdd(it->second, true); 00497 nodesReplaced++; 00498 //EV << "node replaced" << endl; 00499 } 00500 BUCKET_CONSISTENCY(routingTimeout: is in bucket); 00501 return true; 00502 } 00503 BUCKET_CONSISTENCY(routingTimeout: end); 00504 return false; 00505 }
| void Kademlia::refillSiblingTable | ( | ) | [private] |
Definition at line 507 of file Kademlia.cc.
Referenced by handleFailedNode(), and routingTimeout().
00508 { 00509 if (siblingTable->size() == 0 || 00510 siblingTable->isFull()) 00511 return; 00512 00513 int index = routingBucketIndex(siblingTable->back().key) - 1; 00514 assert(index > 0); 00515 00516 while ((routingTable[index] == NULL || 00517 routingTable[index]->empty()) && 00518 index < (int)(OverlayKey::getLength() - 1)) { 00519 index++; 00520 } 00521 if (index < (int)OverlayKey::getLength() && 00522 routingTable[index] != NULL && routingTable[index]->size()) { 00523 KademliaBucket sortedBucket(k, comparator); 00524 for (uint32_t i = 0; i < routingTable[index]->size(); ++i) 00525 sortedBucket.add(routingTable[index]->at(i)); 00526 siblingTable->add(sortedBucket.front()); 00527 // no need to callUpdate(), because s < siblingTable->size(), thus 00528 // new sibling talbe entry is no real sibling 00529 routingTable[index]-> 00530 erase(routingTable[index]-> 00531 findIterator(sortedBucket.front().key)); 00532 assert(siblingTable->isFull()); 00533 BUCKET_CONSISTENCY(routingTimeout: end refillSiblingTable()); 00534 } 00535 }
| void Kademlia::setBucketUsage | ( | const OverlayKey & | key | ) | [private] |
Definition at line 537 of file Kademlia.cc.
Referenced by handleBucketRefreshTimerExpired(), handleRpcResponse(), and handleRpcTimeout().
00538 { 00539 KademliaBucket* bucket = routingBucket(key, true); 00540 00541 if (bucket) 00542 bucket->setLastUsage(simTime()); 00543 00544 /* 00545 if (!siblingTable->size() || ((siblingTable->back().key ^ thisNode.key) >= 00546 (key ^ thisNode.key))) 00547 siblingTable->setLastUsage(simTime()); 00548 */ 00549 00550 if (((siblingTable->size() + 1) < (uint32_t)getMaxNumSiblings()) 00551 || ((siblingTable->at(getMaxNumSiblings() - 2).key ^ thisNode.key) 00552 >= (key ^ thisNode.key))) { 00553 siblingTable->setLastUsage(simTime()); 00554 } 00555 00556 }
| bool Kademlia::handleFailedNode | ( | const TransportAddress & | failed | ) | [private, virtual] |
Handles a failed node.
This method is called whenever a node given by findNode() was unreachable. The default implementation does nothing at all.
| failed | the failed node |
Reimplemented from BaseOverlay.
Definition at line 620 of file Kademlia.cc.
00621 { 00622 assert(!failed.isUnspecified()); 00623 00624 KademliaBucket::iterator i; 00625 // check sibling table 00626 for (i = siblingTable->begin(); i != siblingTable->end(); ++i) { 00627 if (failed == *i) break; 00628 } 00629 00630 if (i != siblingTable->end()) { 00631 // remove from sibling table 00632 NodeHandle oldSibling = *i; 00633 siblingTable->erase(i); 00634 00635 if (siblingTable->size() < (uint32_t)getMaxNumSiblings()) { 00636 // no new replacement sibling 00637 deleteOverlayNeighborArrow(oldSibling); 00638 callUpdate(oldSibling, false); 00639 } else if (comparator->compare(oldSibling.key, 00640 siblingTable->at(getMaxNumSiblings() - 1).key) < 0) { 00641 // failed sibling was replaced by next closest node in siblingTable 00642 deleteOverlayNeighborArrow(oldSibling); 00643 callUpdate(oldSibling, false); 00644 00645 showOverlayNeighborArrow(siblingTable->at(getMaxNumSiblings() - 1), 00646 false, "m=m,50,100,50,100;ls=green,1"); 00647 callUpdate(siblingTable->at(getMaxNumSiblings() - 1), true); 00648 } 00649 00650 updateTooltip(); 00651 00652 // try to refill with new closest contact 00653 refillSiblingTable(); 00654 } else { 00655 // check buckets 00656 uint32_t m; 00657 for (m = 0; m < routingTable.size(); ++m) { 00658 if (routingTable[m] != NULL) { 00659 for (i = routingTable[m]->begin(); i != routingTable[m]->end(); 00660 ++i) { 00661 if (failed == *i) { 00662 // remove from routing table 00663 routingTable[m]->erase(i); 00664 return (siblingTable->size() != 0); 00665 } 00666 } 00667 } 00668 } 00669 } 00670 return (siblingTable->size() != 0); 00671 }
friend class KademliaLookupListener [friend] |
uint32_t Kademlia::k [protected] |
Definition at line 44 of file Kademlia.h.
Referenced by getMaxNumRedundantNodes(), initializeOverlay(), refillSiblingTable(), and routingBucket().
uint32_t Kademlia::b [protected] |
Definition at line 45 of file Kademlia.h.
Referenced by initializeOverlay(), and routingBucketIndex().
uint32_t Kademlia::s [protected] |
Definition at line 46 of file Kademlia.h.
Referenced by getMaxNumSiblings(), and initializeOverlay().
uint32_t Kademlia::maxStaleCount [protected] |
bool Kademlia::pingNewSiblings [protected] |
simtime_t Kademlia::minSiblingTableRefreshInterval [protected] |
Definition at line 54 of file Kademlia.h.
Referenced by handleBucketRefreshTimerExpired(), and initializeOverlay().
simtime_t Kademlia::minBucketRefreshInterval [protected] |
Definition at line 55 of file Kademlia.h.
Referenced by handleBucketRefreshTimerExpired(), and initializeOverlay().
cMessage* Kademlia::bucketRefreshTimer [protected] |
Definition at line 57 of file Kademlia.h.
Referenced by finishOverlay(), handleBucketRefreshTimerExpired(), handleRpcResponse(), handleTimerEvent(), initializeOverlay(), joinOverlay(), lookupFinished(), and ~Kademlia().
uint32_t Kademlia::nodesReplaced [protected] |
Definition at line 116 of file Kademlia.h.
Referenced by finishOverlay(), initializeOverlay(), and routingTimeout().
KeyDistanceComparator<KeyXorMetric>* Kademlia::comparator [private] |
Definition at line 119 of file Kademlia.h.
Referenced by handleFailedNode(), initializeOverlay(), Kademlia(), refillSiblingTable(), routingBucket(), routingDeinit(), routingInit(), routingTimeout(), and ~Kademlia().
KademliaBucket* Kademlia::siblingTable [private] |
Definition at line 121 of file Kademlia.h.
Referenced by findNode(), handleBucketRefreshTimerExpired(), handleFailedNode(), initializeOverlay(), isSiblingFor(), Kademlia(), refillSiblingTable(), routingAdd(), routingDeinit(), routingInit(), routingTimeout(), setBucketUsage(), updateTooltip(), and ~Kademlia().
std::vector<KademliaBucket*> Kademlia::routingTable [private] |
Definition at line 122 of file Kademlia.h.
Referenced by findNode(), handleBucketRefreshTimerExpired(), handleFailedNode(), initializeOverlay(), refillSiblingTable(), routingBucket(), and routingDeinit().
int Kademlia::numBuckets [private] |
std::map<NodeHandle, NodeHandle> Kademlia::replacementCache [private] |
Definition at line 125 of file Kademlia.h.
Referenced by handleRpcResponse(), handleRpcTimeout(), routingAdd(), routingTimeout(), and ~Kademlia().
1.5.5