BaseOverlay.cc

Go to the documentation of this file.
00001 //
00002 // Copyright (C) 2006 Institut fuer Telematik, Universitaet Karlsruhe (TH)
00003 //
00004 // This program is free software; you can redistribute it and/or
00005 // modify it under the terms of the GNU General Public License
00006 // as published by the Free Software Foundation; either version 2
00007 // of the License, or (at your option) any later version.
00008 //
00009 // This program is distributed in the hope that it will be useful,
00010 // but WITHOUT ANY WARRANTY; without even the implied warranty of
00011 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00012 // GNU General Public License for more details.
00013 //
00014 // You should have received a copy of the GNU General Public License
00015 // along with this program; if not, write to the Free Software
00016 // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
00017 //
00018 
00028 #include <cassert>
00029 
00030 #include <RpcMacros.h>
00031 
00032 #include <UDPAppBase.h>
00033 #include <UDPSocket.h>
00034 #include <IPAddressResolver.h>
00035 #include <NotificationBoard.h>
00036 
00037 #include <GlobalNodeListAccess.h>
00038 #include <UnderlayConfiguratorAccess.h>
00039 #include <GlobalStatisticsAccess.h>
00040 #include <GlobalParametersAccess.h>
00041 
00042 #include <LookupListener.h>
00043 #include <RecursiveLookup.h>
00044 #include <IterativeLookup.h>
00045 
00046 #include <BootstrapList.h>
00047 
00048 #include "BaseOverlay.h"
00049 
00050 using namespace std;
00051 
00052 
00053 //------------------------------------------------------------------------
00054 //--- Initialization & finishing -----------------------------------------
00055 //------------------------------------------------------------------------
00056 
00057 BaseOverlay::BaseOverlay()
00058 {
00059     globalNodeList = NULL;
00060     underlayConfigurator = NULL;
00061     notificationBoard = NULL;
00062     globalParameters = NULL;
00063     bootstrapList = NULL;
00064 }
00065 
00066 BaseOverlay::~BaseOverlay()
00067 {
00068     finishLookups();
00069     finishRpcs();
00070 }
00071 
00072 int BaseOverlay::numInitStages() const
00073 {
00074     return NUM_STAGES_ALL;
00075 }
00076 
00077 void BaseOverlay::initialize(int stage)
00078 {
00079     if (stage == MIN_STAGE_OVERLAY) {
00080         OverlayKey::setKeyLength(par("keyLength"));
00081 
00082         // find friend modules
00083         globalNodeList = GlobalNodeListAccess().get();
00084         underlayConfigurator = UnderlayConfiguratorAccess().get();
00085         notificationBoard = NotificationBoardAccess().get();
00086         globalParameters = GlobalParametersAccess().get();
00087         bootstrapList = check_and_cast<BootstrapList*>(getParentModule()->
00088                 getParentModule()->getSubmodule("bootstrapList", 0));
00089 
00090         // fetch some parameters
00091         debugOutput = par("debugOutput");
00092         collectPerHopDelay = par("collectPerHopDelay");
00093         localPort = par("localPort");
00094         hopCountMax = par("hopCountMax");
00095         drawOverlayTopology = par("drawOverlayTopology");
00096 
00097         // we assume most overlays don't provide KBR services
00098         kbr = false;
00099 
00100         // set routing type
00101         std::string temp = par("routingType").stdstringValue();
00102         if (temp == "iterative")
00103             defaultRoutingType = ITERATIVE_ROUTING;
00104         else if (temp == "exhaustive-iterative")
00105             defaultRoutingType = EXHAUSTIVE_ITERATIVE_ROUTING;
00106         else if (temp == "semi-recursive")
00107             defaultRoutingType = SEMI_RECURSIVE_ROUTING;
00108         else if (temp == "full-recursive")
00109             defaultRoutingType = FULL_RECURSIVE_ROUTING;
00110         else if (temp == "source-routing-recursive")
00111             defaultRoutingType = RECURSIVE_SOURCE_ROUTING;
00112         else throw cRuntimeError((std::string("Wrong routing type: ")
00113                                       + temp).c_str());
00114 
00115         useCommonAPIforward = par("useCommonAPIforward");
00116         routeMsgAcks = par("routeMsgAcks");
00117         recNumRedundantNodes = par("recNumRedundantNodes");
00118         recursivePathRecord = false; //TODO par
00119 
00120         // set base lookup parameters
00121         iterativeLookupConfig.redundantNodes = par("lookupRedundantNodes");
00122         iterativeLookupConfig.parallelPaths = par("lookupParallelPaths");
00123         iterativeLookupConfig.parallelRpcs = par("lookupParallelRpcs");
00124         iterativeLookupConfig.secure = par("lookupSecure");
00125         iterativeLookupConfig.merge = par("lookupMerge");
00126         iterativeLookupConfig.failedNodeRpcs = par("lookupFailedNodeRpcs");
00127         iterativeLookupConfig.strictParallelRpcs =
00128             par("lookupStrictParallelRpcs");
00129         iterativeLookupConfig.useAllParallelResponses =
00130             par("lookupUseAllParallelResponses");
00131         iterativeLookupConfig.newRpcOnEveryTimeout =
00132             par("lookupNewRpcOnEveryTimeout");
00133         iterativeLookupConfig.newRpcOnEveryResponse =
00134             par("lookupNewRpcOnEveryResponse");
00135         iterativeLookupConfig.finishOnFirstUnchanged =
00136             par("lookupFinishOnFirstUnchanged");
00137 
00138         recursiveLookupConfig.redundantNodes = par("lookupRedundantNodes");
00139         recursiveLookupConfig.numRetries = 0; //TODO
00140 
00141         // statistics
00142         numAppDataSent = 0;
00143         bytesAppDataSent = 0;
00144         numAppLookupSent = 0;
00145         bytesAppLookupSent = 0;
00146         numMaintenanceSent = 0;
00147         bytesMaintenanceSent = 0;
00148         numAppDataReceived = 0;
00149         bytesAppDataReceived = 0;
00150         numAppLookupReceived = 0;
00151         bytesAppLookupReceived = 0;
00152         numMaintenanceReceived = 0;
00153         bytesMaintenanceReceived = 0;
00154         numAppDataForwarded = 0;
00155         bytesAppDataForwarded = 0;
00156         numAppLookupForwarded = 0;
00157         bytesAppLookupForwarded = 0;
00158         numMaintenanceForwarded = 0;
00159         bytesMaintenanceForwarded = 0;
00160 
00161         numDropped = 0;
00162         bytesDropped = 0;
00163         numFindNodeSent = 0;
00164         bytesFindNodeSent = 0;
00165         numFindNodeResponseSent = 0;
00166         bytesFindNodeResponseSent = 0;
00167         numFailedNodeSent = 0;
00168         bytesFailedNodeSent = 0;
00169         numFailedNodeResponseSent = 0;
00170         bytesFailedNodeResponseSent = 0;
00171 
00172         numInternalSent = 0;
00173         bytesInternalSent = 0;
00174         numInternalReceived = 0;
00175         bytesInternalReceived = 0;
00176 
00177         WATCH(numAppDataSent);
00178         WATCH(bytesAppDataSent);
00179         WATCH(numAppLookupSent);
00180         WATCH(bytesAppLookupSent);
00181         WATCH(numMaintenanceSent);
00182         WATCH(bytesMaintenanceSent);
00183         WATCH(numAppDataReceived);
00184         WATCH(bytesAppDataReceived);
00185         WATCH(numAppLookupReceived);
00186         WATCH(bytesAppLookupReceived);
00187         WATCH(numMaintenanceReceived);
00188         WATCH(bytesMaintenanceReceived);
00189         WATCH(numAppDataForwarded);
00190         WATCH(bytesAppDataForwarded);
00191         WATCH(numAppLookupForwarded);
00192         WATCH(bytesAppLookupForwarded);
00193         WATCH(numMaintenanceForwarded);
00194         WATCH(bytesMaintenanceForwarded);
00195 
00196         WATCH(numDropped);
00197         WATCH(bytesDropped);
00198         WATCH(numFindNodeSent);
00199         WATCH(bytesFindNodeSent);
00200         WATCH(numFindNodeResponseSent);
00201         WATCH(bytesFindNodeResponseSent);
00202         WATCH(numFailedNodeSent);
00203         WATCH(bytesFailedNodeSent);
00204         WATCH(numFailedNodeResponseSent);
00205         WATCH(bytesFailedNodeResponseSent);
00206 
00207         if (isInSimpleMultiOverlayHost()) {
00208             WATCH(numInternalSent);
00209             WATCH(bytesInternalSent);
00210             WATCH(numInternalReceived);
00211             WATCH(bytesInternalReceived);
00212         }
00213 
00214         // set up local nodehandle
00215         thisNode.ip = IPAddressResolver().
00216                       addressOf(getParentModule()->getParentModule()).get4();
00217         thisNode.key = OverlayKey::UNSPECIFIED_KEY;
00218 
00219         // set up UDP
00220         bindToPort(localPort);
00221 
00222         // subscribe to the notification board
00223         notificationBoard->subscribe(this, NF_OVERLAY_TRANSPORTADDRESS_CHANGED);
00224         notificationBoard->subscribe(this, NF_OVERLAY_NODE_LEAVE);
00225         notificationBoard->subscribe(this, NF_OVERLAY_NODE_GRACEFUL_LEAVE);
00226 
00227         // init visualization with terminal ptr
00228         if (drawOverlayTopology)
00229             initVis(getParentModule()->getParentModule());
00230 
00231         // init rpcs
00232         initRpcs();
00233         initLookups();
00234 
00235         // statistics
00236         globalStatistics->nodesInitialized++;
00237         creationTime = simTime();
00238         WATCH(creationTime);
00239     }
00240 
00241     if (stage >= MIN_STAGE_OVERLAY && stage <= MAX_STAGE_OVERLAY)
00242         initializeOverlay(stage);
00243 
00244     if (stage == MAX_STAGE_TIER_1) {
00245         // bootstrapList registered its gate to the overlay 0
00246         // if this is not overlay 0, we may not have the gate, so retrieve it
00247             // this assumes that the overlay is in a container module!
00248         if (!compModuleList.count(BOOTSTRAPLIST_COMP)) {
00249             BaseOverlay *firstOverlay = dynamic_cast<BaseOverlay*>
00250                     (getParentModule()->getParentModule()
00251                     ->getSubmodule("overlay", 0)->gate("appIn")
00252                     ->getNextGate()->getOwnerModule());
00253             if (!firstOverlay) {
00254                 opp_error("BaseOverlay.cc: Couldn't obtain bootstrap gate");
00255             }
00256             registerComp(BOOTSTRAPLIST_COMP,
00257                          firstOverlay->getCompModule(BOOTSTRAPLIST_COMP));
00258         }
00259     }
00260 
00261     // join after all components are registered
00262     if (stage == MAX_STAGE_TIER_3) {
00263         if ((bool)par("joinOnApplicationRequest") == false) {
00264             join();
00265         }
00266     }
00267 }
00268 
00269 void BaseOverlay::initializeOverlay(int stage)
00270 {
00271 }
00272 
00273 void BaseOverlay::finish()
00274 {
00275     finishOverlay();
00276 
00277     globalStatistics->nodesFinished++;
00278 
00279     simtime_t time = globalStatistics->calcMeasuredLifetime(creationTime);
00280     if (time == 0) return;
00281 
00282     if (collectPerHopDelay) {
00283         std::ostringstream singleHopName;
00284         HopDelayRecord* hdrl = NULL;
00285         HopDelayRecord* hdr = NULL;
00286         for (size_t i = 0; i < singleHopDelays.size();) {
00287             hdrl = singleHopDelays[i++];
00288             hdr = hdrl;
00289             for (size_t j = 1; j <= i; ++j) {
00290                 if (hdr->count == 0) continue;
00291                 singleHopName.str("");
00292                 singleHopName << "BaseOverlay: Average Delay in Hop "
00293                               << j << " of " << i;
00294                 globalStatistics->addStdDev(singleHopName.str(),
00295                                             SIMTIME_DBL(hdr->val / hdr->count));
00296                 ++hdr;
00297             }
00298             delete[] hdrl;
00299         }
00300         singleHopDelays.clear();
00301     }
00302 
00303     globalStatistics->addStdDev("BaseOverlay: Sent App Data Messages/s",
00304                                 numAppDataSent / time);
00305     globalStatistics->addStdDev("BaseOverlay: Sent App Data Bytes/s",
00306                                 bytesAppDataSent / time);
00307     if (isInSimpleMultiOverlayHost()) {
00308         globalStatistics->addStdDev("BaseOverlay: Internal Sent Messages/s",
00309                                     numInternalReceived / time);
00310         globalStatistics->addStdDev("BaseOverlay: Internal Sent Bytes/s",
00311                                     bytesInternalReceived / time);
00312     }
00313     globalStatistics->addStdDev("BaseOverlay: Sent App Lookup Messages/s",
00314                                 numAppLookupSent / time);
00315     globalStatistics->addStdDev("BaseOverlay: Sent App Lookup Bytes/s",
00316                                 bytesAppLookupSent / time);
00317     globalStatistics->addStdDev("BaseOverlay: Sent Maintenance Messages/s",
00318                                 numMaintenanceSent / time);
00319     globalStatistics->addStdDev("BaseOverlay: Sent Maintenance Bytes/s",
00320                                 bytesMaintenanceSent / time);
00321 
00322     globalStatistics->addStdDev("BaseOverlay: Sent Total Messages/s",
00323                                 (numAppDataSent + numAppLookupSent +
00324                                  numMaintenanceSent) / time);
00325     globalStatistics->addStdDev("BaseOverlay: Sent Total Bytes/s",
00326                                 (bytesAppDataSent + bytesAppLookupSent +
00327                                  bytesMaintenanceSent) / time);
00328     globalStatistics->addStdDev("BaseOverlay: Sent FindNode Messages/s",
00329                                 numFindNodeSent / time);
00330     globalStatistics->addStdDev("BaseOverlay: Sent FindNode Bytes/s",
00331                                 bytesFindNodeSent / time);
00332 
00333     globalStatistics->addStdDev("BaseOverlay: Sent FindNodeResponse Messages/s",
00334                                 numFindNodeResponseSent / time);
00335     globalStatistics->addStdDev("BaseOverlay: Sent FindNodeResponse Bytes/s",
00336                                 bytesFindNodeResponseSent / time);
00337     globalStatistics->addStdDev("BaseOverlay: Sent FailedNode Messages/s",
00338                                 numFailedNodeSent / time);
00339     globalStatistics->addStdDev("BaseOverlay: Sent FailedNode Bytes/s",
00340                                 bytesFailedNodeSent / time);
00341     globalStatistics->addStdDev("BaseOverlay: Sent FailedNodeResponse Messages/s",
00342                                 numFailedNodeResponseSent / time);
00343     globalStatistics->addStdDev("BaseOverlay: Sent FailedNodeResponse Bytes/s", bytesFailedNodeResponseSent / time);
00344 
00345     globalStatistics->addStdDev("BaseOverlay: Received App Data Messages/s",
00346                                 numAppDataReceived / time);
00347     globalStatistics->addStdDev("BaseOverlay: Received App Data Bytes/s",
00348                                 bytesAppDataReceived / time);
00349     if (isInSimpleMultiOverlayHost()) {
00350         globalStatistics->addStdDev("BaseOverlay: Internal Received Messages/s",
00351                                     numInternalReceived / time);
00352         globalStatistics->addStdDev("BaseOverlay: Internal Received Bytes/s",
00353                                     bytesInternalReceived / time);
00354     }
00355     globalStatistics->addStdDev("BaseOverlay: Received App Lookup Messages/s",
00356                                 numAppLookupReceived / time);
00357     globalStatistics->addStdDev("BaseOverlay: Received App Lookup Bytes/s",
00358                                 bytesAppLookupReceived / time);
00359     globalStatistics->addStdDev("BaseOverlay: Received Maintenance Messages/s",
00360                                 numMaintenanceReceived / time);
00361     globalStatistics->addStdDev("BaseOverlay: Received Maintenance Bytes/s",
00362                                 bytesMaintenanceReceived / time);
00363 
00364     globalStatistics->addStdDev("BaseOverlay: Received Total Messages/s",
00365                                 (numAppDataReceived + numAppLookupReceived +
00366                                  numMaintenanceReceived)/time);
00367     globalStatistics->addStdDev("BaseOverlay: Received Total Bytes/s",
00368                                 (bytesAppDataReceived + bytesAppLookupReceived +
00369                                  bytesMaintenanceReceived)/time);
00370     globalStatistics->addStdDev("BaseOverlay: Forwarded App Data Messages/s",
00371                                 numAppDataForwarded / time);
00372     globalStatistics->addStdDev("BaseOverlay: Forwarded App Data Bytes/s",
00373                                 bytesAppDataForwarded / time);
00374     globalStatistics->addStdDev("BaseOverlay: Forwarded App Lookup Messages/s",
00375                                 numAppLookupForwarded / time);
00376     globalStatistics->addStdDev("BaseOverlay: Forwarded Signaling Bytes/s",
00377                                 bytesAppLookupForwarded / time);
00378     globalStatistics->addStdDev("BaseOverlay: Forwarded Maintenance Messages/s",
00379                                 numMaintenanceForwarded / time);
00380     globalStatistics->addStdDev("BaseOverlay: Forwarded Maintenance Bytes/s",
00381                                 bytesMaintenanceForwarded / time);
00382     globalStatistics->addStdDev("BaseOverlay: Forwarded Total Messages/s",
00383                                 (numAppDataForwarded + numAppLookupForwarded +
00384                                  numMaintenanceForwarded) / time);
00385     globalStatistics->addStdDev("BaseOverlay: Forwarded Total Bytes/s",
00386                                 (bytesAppDataForwarded + bytesAppLookupForwarded +
00387                                  bytesMaintenanceForwarded) / time);
00388 
00389     globalStatistics->addStdDev("BaseOverlay: Dropped Messages/s",
00390                                 numDropped / time);
00391     globalStatistics->addStdDev("BaseOverlay: Dropped Bytes/s",
00392                                 bytesDropped / time);
00393 
00394     globalStatistics->addStdDev("BaseOverlay: Measured Session Time",
00395                                 SIMTIME_DBL(simTime() - creationTime));
00396 
00397     globalStatistics->addStdDev("BaseRpc: Sent Ping Messages/s",
00398                                 numPingSent / time);
00399     globalStatistics->addStdDev("BaseRpc: Sent Ping Bytes/s",
00400                                 bytesPingSent / time);
00401     globalStatistics->addStdDev("BaseRpc: Sent Ping Response Messages/s",
00402                                 numPingResponseSent / time);
00403     globalStatistics->addStdDev("BaseRpc: Sent Ping Response Bytes/s",
00404                                 bytesPingResponseSent / time);
00405 
00406     globalStatistics->doFinish();
00407 
00408 }
00409 
00410 void BaseOverlay::finishOverlay()
00411 {
00412 }
00413 
00414 //------------------------------------------------------------------------
00415 //--- General Overlay Parameters (getter and setters) --------------------
00416 //------------------------------------------------------------------------
00417 bool BaseOverlay::isMalicious()
00418 {
00419     return globalNodeList->isMalicious(getThisNode());
00420 }
00421 
00422 CompType BaseOverlay::getThisCompType()
00423 {
00424     return OVERLAY_COMP;
00425 }
00426 
00427 //------------------------------------------------------------------------
00428 //--- UDP functions copied from the INET framework .----------------------
00429 //------------------------------------------------------------------------
00430 void BaseOverlay::bindToPort(int port)
00431 {
00432     EV << "[BaseOverlay::bindToPort() @ " << thisNode.ip
00433        << " (" << thisNode.key.toString(16) << ")]\n"
00434        << "    Binding to UDP port " << port
00435        << endl;
00436 
00437     thisNode.port = port;
00438 
00439     // TODO UDPAppBase should be ported to use UDPSocket sometime, but for now
00440     // we just manage the UDP socket by hand...
00441     cMessage *msg = new cMessage("UDP_C_BIND", UDP_C_BIND);
00442     UDPControlInfo *ctrl = new UDPControlInfo();
00443     ctrl->setSrcPort(port);
00444     ctrl->setSockId(UDPSocket::generateSocketId());
00445     msg->setControlInfo(ctrl);
00446     send(msg, "udpOut", 0);
00447 }
00448 
00449 
00450 //------------------------------------------------------------------------
00451 //--- Overlay Common API: Key-based Routing ------------------------------
00452 //------------------------------------------------------------------------
00453 
00454 void BaseOverlay::callDeliver(BaseOverlayMessage* msg,
00455                               const OverlayKey& destKey)
00456 {
00457     KBRdeliver* deliverMsg = new KBRdeliver();
00458 
00459     OverlayCtrlInfo* overlayCtrlInfo =
00460         check_and_cast<OverlayCtrlInfo*>(msg->removeControlInfo());
00461 
00462     BaseAppDataMessage* appDataMsg = dynamic_cast<BaseAppDataMessage*>(msg);
00463 
00464     // TODO GIA
00465     if (appDataMsg != NULL) {
00466         overlayCtrlInfo->setSrcComp(appDataMsg->getSrcComp());
00467         overlayCtrlInfo->setDestComp(appDataMsg->getDestComp());
00468     }
00469 
00470     deliverMsg->setControlInfo(overlayCtrlInfo);
00471     deliverMsg->setDestKey(destKey);
00472     deliverMsg->encapsulate(msg->decapsulate());
00473     deliverMsg->setType(KBR_DELIVER);
00474 
00475     cGate* destGate = getCompRpcGate(static_cast<CompType>(
00476             overlayCtrlInfo->getDestComp()));
00477 
00478     if (destGate == NULL) {
00479         opp_error("BaseOverlay::callDeliver(): Unknown destComp!");
00480     }
00481 
00482     sendDirect(deliverMsg, destGate);
00483 
00484     delete msg;
00485 }
00486 
00487 void BaseOverlay::callForward(const OverlayKey& key, BaseRouteMessage* msg,
00488                               const NodeHandle& nextHopNode)
00489 {
00490     KBRforward* forwardMsg = new KBRforward();
00491 
00492     forwardMsg->setDestKey(msg->getDestKey());
00493     forwardMsg->setNextHopNode(nextHopNode);
00494     forwardMsg->encapsulate(msg->getEncapsulatedMsg()->decapsulate());
00495 
00496     OverlayCtrlInfo* overlayCtrlInfo =
00497         new OverlayCtrlInfo();
00498     overlayCtrlInfo->setTransportType(ROUTE_TRANSPORT);
00499     overlayCtrlInfo->setRoutingType(msg->getRoutingType());
00500     overlayCtrlInfo->setHopCount(msg->getHopCount());
00501     overlayCtrlInfo->setSrcNode(msg->getSrcNode());
00502     overlayCtrlInfo->setSrcComp(check_and_cast<BaseAppDataMessage*>
00503         (msg->getEncapsulatedMsg())->getSrcComp());
00504     overlayCtrlInfo->setDestComp(check_and_cast<BaseAppDataMessage*>
00505         (msg->getEncapsulatedMsg())->getDestComp());
00506 
00507     if (msg->getControlInfo() != NULL) {
00508         OverlayCtrlInfo* ctrlInfo =
00509             check_and_cast<OverlayCtrlInfo*>(msg->removeControlInfo());
00510 
00511         overlayCtrlInfo->setLastHop(ctrlInfo->getLastHop());
00512 
00513         delete ctrlInfo;
00514     }
00515 
00516     forwardMsg->setControlInfo(overlayCtrlInfo);
00517 
00518     forwardMsg->setType(KBR_FORWARD);
00519 
00520     send(forwardMsg, "appOut");
00521 
00522     delete msg;
00523 }
00524 
00525 NodeVector* BaseOverlay::local_lookup(const OverlayKey& key,
00526                                       int num, bool safe)
00527 {
00528     Enter_Method("local_lookup()");
00529 
00530     if (safe == true) {
00531         error("BaseOverlay::local_lookup(): safe flag is not implemented!");
00532     }
00533 
00534     if (num < 0) num = INT_MAX;
00535     NodeVector* nodeVector = findNode(key, min(num, getMaxNumRedundantNodes()),
00536                                       min(num,getMaxNumSiblings()));
00537 
00538     if (((int)nodeVector->size()) > num)
00539         nodeVector->resize(num);
00540 
00541     return nodeVector;
00542 }
00543 
00544 void BaseOverlay::join(const OverlayKey& nodeID)
00545 {
00546     Enter_Method("join()");
00547 
00548     // set nodeID and IP
00549     thisNode.ip =
00550         IPAddressResolver().addressOf(getParentModule()->getParentModule()).get4();
00551     if (nodeID.isUnspecified())  {
00552         setOwnNodeID();
00553     } else {
00554         thisNode.key = nodeID;
00555     }
00556 
00557     joinOverlay();
00558 }
00559 
00560 void BaseOverlay::joinForeignPartition(const NodeHandle& node)
00561 {
00562     throw cRuntimeError("BaseOverlay::joinForeignPartition(): "
00563                             "This overlay doesn't support merging!");
00564 }
00565 
00566 void BaseOverlay::setOwnNodeID()
00567 {
00568     thisNode.key = OverlayKey::random();
00569 }
00570 
00571 NodeVector* BaseOverlay::neighborSet(int num)
00572 {
00573     Enter_Method("neighborSet()");
00574 
00575     return local_lookup(thisNode.key, num, false);
00576 }
00577 
00578 void BaseOverlay::callUpdate(const NodeHandle& node, bool joined)
00579 {
00580     if ((!node.isUnspecified()) && (node != thisNode)) {
00581         if (joined) {
00582             EV << "[BaseOverlay::callUpdate() @ " << thisNode.ip
00583                << " (" << thisNode.key.toString(16) << ")]\n"
00584                << "    (" << node << ", " << joined << ") joined"
00585                << endl;
00586         } else {
00587             EV << "[BaseOverlay::callUpdate() @ " << thisNode.ip
00588                << " (" << thisNode.key.toString(16) << ")]\n"
00589                << "    (" << node << ", " << joined << ") left"
00590                << endl;
00591         }
00592     }
00593 
00594     KBRupdate* updateMsg = new KBRupdate("UPDATE");
00595 
00596     updateMsg->setNode(node);
00597     updateMsg->setJoined(joined);
00598 
00599     updateMsg->setType(KBR_UPDATE);
00600 
00601     send(updateMsg, "appOut");
00602 }
00603 
00604 bool BaseOverlay::isSiblingFor(const NodeHandle& node, const OverlayKey& key,
00605                                int numSiblings, bool* err)
00606 {
00607     Enter_Method("isSiblingFor()");
00608 
00609     opp_error( "isSiblingFor: Not implemented!" );
00610 
00611     return false;
00612 }
00613 
00614 int BaseOverlay::getMaxNumSiblings()
00615 {
00616     Enter_Method("getMaxNumSiblings()");
00617 
00618     opp_error( "getMaxNumSiblings: Not implemented!" );
00619 
00620     return false;
00621 }
00622 
00623 int BaseOverlay::getMaxNumRedundantNodes()
00624 {
00625     Enter_Method("getMaxNumRedundantNodes()");
00626 
00627     opp_error( "getMaxNumRedundantNodes: Not implemented!" );
00628 
00629     return false;
00630 }
00631 
00632 
00633 //------------------------------------------------------------------------
00634 //--- Message Handlers ---------------------------------------------------
00635 //------------------------------------------------------------------------
00636 
00637 //private
00638 void BaseOverlay::handleMessage(cMessage* msg)
00639 {
00640     // process self-messages
00641     if (msg->isSelfMessage()) {
00642         // process rpc self-messages
00643         BaseRpcMessage* rpcMessage = dynamic_cast<BaseRpcMessage*>(msg);
00644         if (rpcMessage!=NULL) {
00645             internalHandleRpcMessage(rpcMessage);
00646             return;
00647         }
00648         // process all other self-messages
00649         handleTimerEvent(msg);
00650     }
00651 
00652     // process messages from UDP
00653     else if (msg->arrivedOn("udpIn")) {
00654         UDPControlInfo* udpControlInfo =
00655             check_and_cast<UDPControlInfo*>(msg->removeControlInfo());
00656         OverlayCtrlInfo* overlayCtrlInfo = new OverlayCtrlInfo;
00657         overlayCtrlInfo
00658             ->setLastHop(TransportAddress(udpControlInfo->getSrcAddr(),
00659                                           udpControlInfo->getSrcPort()));
00660         overlayCtrlInfo->setTransportType(UDP_TRANSPORT);
00661 
00662         msg->setControlInfo(overlayCtrlInfo);
00663         delete udpControlInfo;
00664 
00665         // debug message
00666         if (debugOutput) {
00667             EV << "[BaseOverlay:handleMessage() @ " << thisNode.ip
00668             << " (" << thisNode.key.toString(16) << ")]\n"
00669             << "    Received " << *msg << " from "
00670             << overlayCtrlInfo->getLastHop().ip << endl;
00671         }
00672 
00673         BaseOverlayMessage* baseOverlayMsg =
00674             dynamic_cast<BaseOverlayMessage*>(msg);
00675 
00676         if (baseOverlayMsg == NULL) {
00677             cPacket* packet = check_and_cast<cPacket*>(msg);
00678             RECORD_STATS(numDropped++; bytesDropped += packet->getByteLength());
00679             delete msg;
00680             return;
00681         }
00682 
00683         // records stats if message is not a UDP "self message"
00684         if (overlayCtrlInfo->getLastHop() != thisNode) {
00685             // is this from anywhere else?
00686             if (baseOverlayMsg->getStatType() == APP_DATA_STAT)
00687                 RECORD_STATS(numAppDataReceived++; bytesAppDataReceived +=
00688                              baseOverlayMsg->getByteLength());
00689             else if (baseOverlayMsg->getStatType() == APP_LOOKUP_STAT)
00690                 RECORD_STATS(numAppLookupReceived++;bytesAppLookupReceived +=
00691                              baseOverlayMsg->getByteLength());
00692             else // MAINTENANCE_STAT
00693                 RECORD_STATS(numMaintenanceReceived++;
00694                              bytesMaintenanceReceived +=
00695                                  baseOverlayMsg->getByteLength());
00696         }
00697         if (overlayCtrlInfo->getLastHop().ip == thisNode.ip) {
00698             // is this from the same node?
00699             RECORD_STATS(numInternalReceived++; bytesInternalReceived +=
00700                              baseOverlayMsg->getByteLength());
00701         }
00702 
00703         handleBaseOverlayMessage(baseOverlayMsg);
00704     }
00705 
00706     // process CommonAPIMessages from App
00707     else if (dynamic_cast<CommonAPIMessage*>(msg) != NULL) {
00708         if (dynamic_cast<KBRroute*>(msg) != NULL) {
00709             KBRroute* apiMsg = static_cast<KBRroute*>(msg);
00710 
00711             std::vector<TransportAddress> sourceRoute;
00712             for (uint32_t i = 0; i < apiMsg->getSourceRouteArraySize(); ++i)
00713                 sourceRoute.push_back(apiMsg->getSourceRoute(i));
00714 
00715             route(apiMsg->getDestKey(), static_cast<CompType>(apiMsg->getDestComp()),
00716                   static_cast<CompType>(apiMsg->getSrcComp()), apiMsg->decapsulate(),
00717                           sourceRoute);
00718         } else if (dynamic_cast<KBRforward*>(msg) != NULL) {
00719             KBRforward* apiMsg = static_cast<KBRforward*>(msg);
00720             OverlayCtrlInfo* overlayCtrlInfo =
00721                 check_and_cast<OverlayCtrlInfo*>
00722                 (msg->removeControlInfo());
00723 
00724             BaseAppDataMessage* dataMsg =
00725                 new BaseAppDataMessage();
00726             dataMsg->setType(APPDATA);
00727             dataMsg->setBitLength(BASEAPPDATA_L(dataMsg));
00728             dataMsg->setName(apiMsg->getEncapsulatedMsg()->getName());
00729             dataMsg->encapsulate(apiMsg->decapsulate());
00730             dataMsg->setSrcComp(overlayCtrlInfo->getSrcComp());
00731             dataMsg->setDestComp(overlayCtrlInfo->getDestComp());
00732             dataMsg->setStatType(APP_DATA_STAT);
00733 
00734             BaseRouteMessage* routeMsg = new BaseRouteMessage(dataMsg->getName());
00735             routeMsg->setType(OVERLAYROUTE);
00736             routeMsg->setBitLength(BASEROUTE_L(routeMsg));
00737             routeMsg->encapsulate(dataMsg);
00738 
00739             routeMsg->setStatType(APP_DATA_STAT);
00740             routeMsg->setRoutingType(overlayCtrlInfo->getRoutingType());
00741             routeMsg->setDestKey(apiMsg->getDestKey());
00742             routeMsg->setSrcNode(overlayCtrlInfo->getSrcNode());
00743             routeMsg->setHopCount(overlayCtrlInfo->getHopCount());
00744             routeMsg->setControlInfo(overlayCtrlInfo);
00745 
00746             // message marked with this-pointer as already forwarded to tier1
00747             routeMsg->setContextPointer(this);
00748 
00749             std::vector<TransportAddress> sourceRoute;
00750             sourceRoute.push_back(apiMsg->getNextHopNode());
00751             sendToKey(apiMsg->getDestKey(), routeMsg, 1, sourceRoute);
00752         }
00753 
00754         delete msg;
00755     } else if (dynamic_cast<BaseRpcMessage*>(msg) != NULL) {
00756         BaseRpcMessage* rpcMessage =
00757             static_cast<BaseRpcMessage*>(msg);
00758         internalHandleRpcMessage(rpcMessage);
00759     }
00760 
00761     // process other messages from App
00762     else if (msg->arrivedOn("appIn")) {
00763         handleAppMessage(msg);
00764 
00765     } else {
00766         opp_error("BaseOverlay::handleMessage(): Received msg with "
00767                   "unknown type!");
00768         delete msg;
00769     }
00770 }
00771 
00772 void BaseOverlay::handleBaseOverlayMessage(BaseOverlayMessage* msg,
00773                                            const OverlayKey& destKey)
00774 {
00775     switch (msg->getType()) {
00776     case OVERLAYSIGNALING:
00777         handleUDPMessage(msg);
00778         return;
00779 
00780     case RPC: {
00781         // process rpc-messages
00782         BaseRpcMessage* rpcMessage =
00783             check_and_cast<BaseRpcMessage*>(msg);
00784         internalHandleRpcMessage(rpcMessage);
00785         return;
00786     }
00787 
00788     case APPDATA: {
00789         //TODO use route messages? here: set transport type to ROUTE for "naked"
00790         // app messages
00791         OverlayCtrlInfo* overlayCtrlInfo = check_and_cast<OverlayCtrlInfo*>(msg->getControlInfo());
00792         overlayCtrlInfo->setTransportType(ROUTE_TRANSPORT);
00793 
00794         // TODO: Should be removed if we used route messages here (definition of srcNode?)
00795         //if (overlayCtrlInfo->getSrcNode().isUnspecified()) {
00796         //    overlayCtrlInfo->setSrcNode(NodeHandle(overlayCtrlInfo->getLastHop()));
00797         //}
00798 
00799         BaseAppDataMessage* baseAppDataMsg =
00800             check_and_cast<BaseAppDataMessage*>(msg);
00801         callDeliver(baseAppDataMsg, destKey);
00802         return;
00803     }
00804 
00805     case OVERLAYROUTE: {
00806         BaseRouteMessage* baseRouteMsg =
00807             check_and_cast<BaseRouteMessage*>(msg);
00808 
00809         // if this node is malicious drop the message
00810         if (isMalicious()) {
00811             EV << "[BaseOverlay::handleBaseOverlayMessage() @ " << thisNode.ip
00812             << " (" << thisNode.key.toString(16) << ")]\n"
00813             << "    BaseRouteMessage gets dropped because this node is malicious"
00814             << endl;
00815             //std::cout << "malicious!" << std::endl;
00816             RECORD_STATS(numDropped++;
00817                          bytesDropped += baseRouteMsg->getByteLength());
00818             delete msg;
00819             return;
00820         }
00821 
00822         // collect delay-value of completed hop
00823         if (collectPerHopDelay) {
00824             baseRouteMsg->setHopDelayArraySize(baseRouteMsg->
00825                                                getHopDelayArraySize() + 1);
00826             baseRouteMsg->setHopDelay(baseRouteMsg->getHopDelayArraySize() - 1,
00827                                       simTime() - baseRouteMsg->getHopStamp());
00828         }
00829 
00830         OverlayCtrlInfo* overlayCtrlInfo
00831             = check_and_cast<OverlayCtrlInfo*>(baseRouteMsg
00832                                                ->removeControlInfo());
00833         // set transport type
00834         overlayCtrlInfo->setTransportType(ROUTE_TRANSPORT);
00835 
00836         // source routing: save visited nodes, copy next hops
00837         std::vector<TransportAddress> sourceRoute;
00838         if ((baseRouteMsg->getNextHopsArraySize() > 0) ||
00839              (baseRouteMsg->getRoutingType() == RECURSIVE_SOURCE_ROUTING) ||
00840              recursivePathRecord) {
00841             // save this node as visited
00842             baseRouteMsg
00843                 ->setVisitedHopsArraySize(baseRouteMsg
00844                                           ->getVisitedHopsArraySize() + 1);
00845             baseRouteMsg->setVisitedHops(baseRouteMsg
00846                                              ->getVisitedHopsArraySize() - 1,
00847                                          thisNode);
00848 
00849             // remove nodes from next hops and copy them to sourceRoute
00850             if (baseRouteMsg->getNextHopsArraySize() > 0) {
00851                 sourceRoute.resize(baseRouteMsg->getNextHopsArraySize()- 1);
00852                 for (uint32_t i = 1; i < baseRouteMsg->getNextHopsArraySize();
00853                      ++i) {
00854                     sourceRoute[i - 1] = baseRouteMsg->getNextHops(i);
00855                 }
00856                 baseRouteMsg->setNextHopsArraySize(0);
00857             }
00858         }
00859 
00860         // decapsulate msg if node is sibling for destKey
00861         // or message is at its destination node
00862         bool err;
00863         if ((sourceRoute.size() == 0) &&
00864             (baseRouteMsg->getDestKey().isUnspecified() ||
00865              isSiblingFor(thisNode, baseRouteMsg->getDestKey(), 1, &err)
00866              /*&& !err*/)) {
00867             overlayCtrlInfo->setHopCount(baseRouteMsg->getHopCount());
00868             overlayCtrlInfo->setSrcNode(baseRouteMsg->getSrcNode());
00869             overlayCtrlInfo->setRoutingType(baseRouteMsg->getRoutingType());
00870 
00871             // copy visited nodes to control info
00872             overlayCtrlInfo
00873                 ->setVisitedHopsArraySize(baseRouteMsg
00874                                               ->getVisitedHopsArraySize());
00875             for (uint32_t i = 0; i < baseRouteMsg->getVisitedHopsArraySize(); ++i)
00876                 overlayCtrlInfo
00877                     ->setVisitedHops(i, baseRouteMsg->getVisitedHops(i));
00878 
00879             BaseOverlayMessage* tmpMsg
00880                 = check_and_cast<BaseOverlayMessage*>(baseRouteMsg
00881                                                       ->decapsulate());
00882             tmpMsg->setControlInfo(overlayCtrlInfo);
00883 
00884             // delay between hops
00885             if (collectPerHopDelay) {
00886                 RECORD_STATS(
00887                     size_t i;
00888                     for (i = singleHopDelays.size();
00889                              i < baseRouteMsg->getHopDelayArraySize();) {
00890                         singleHopDelays.push_back(new HopDelayRecord[++i]);
00891                     }
00892 
00893                     i = baseRouteMsg->getHopDelayArraySize() - 1;
00894                     HopDelayRecord* hdr = singleHopDelays[i];
00895 
00896                     for (size_t j = 0; j <= i; ++j) {
00897                         hdr[j].count++;
00898                         hdr[j].val += baseRouteMsg->getHopDelay(j);
00899                     }
00900                 );
00901             }
00902 
00903             // handle encapsulated message at destination node
00904             if (((baseRouteMsg->getRoutingType() == ITERATIVE_ROUTING)
00905                     || (baseRouteMsg->getRoutingType() == EXHAUSTIVE_ITERATIVE_ROUTING))
00906                     || recursiveRoutingHook(thisNode, baseRouteMsg)) {
00907                 handleBaseOverlayMessage(tmpMsg, baseRouteMsg->getDestKey());
00908                 delete baseRouteMsg;
00909             }
00910             return;
00911         } else {
00912             // forward msg if this node is not responsible for the key
00913             baseRouteMsg->setControlInfo(overlayCtrlInfo);
00914             sendToKey(baseRouteMsg->getDestKey(), baseRouteMsg, 1, sourceRoute);
00915             return;
00916         }
00917         break;
00918     }
00919 
00920     default:
00921         EV << "[BaseOverlay::handleBaseOverlayMessage() @ " << thisNode.ip
00922         << " (" << thisNode.key.toString(16) << ")]\n"
00923         << "    Received unknown message from UDP of type " << msg->getName()
00924         << endl;
00925         break;
00926     }
00927 }
00928 
00929 void BaseOverlay::receiveChangeNotification(int category, const cPolymorphic * details)
00930 {
00931     Enter_Method_Silent();
00932     if (category == NF_OVERLAY_TRANSPORTADDRESS_CHANGED) {
00933         handleTransportAddressChangedNotification();
00934     } else if (category == NF_OVERLAY_NODE_LEAVE) {
00935         handleNodeLeaveNotification();
00936     } else if (category == NF_OVERLAY_NODE_GRACEFUL_LEAVE) {
00937         handleNodeGracefulLeaveNotification();
00938     }
00939 }
00940 
00941 void BaseOverlay::handleTransportAddressChangedNotification()
00942 {
00943     // get new ip address
00944     thisNode.ip = IPAddressResolver().addressOf(
00945                       getParentModule()->getParentModule()).get4();
00946 
00947     joinOverlay();
00948 }
00949 
00950 void BaseOverlay::handleNodeLeaveNotification()
00951 {
00952     // ...
00953 }
00954 
00955 void BaseOverlay::handleNodeGracefulLeaveNotification()
00956 {
00957     // ...
00958 }
00959 
00960 //virtual protected
00961 void BaseOverlay::handleTimerEvent(cMessage* msg)
00962 {
00963     // timer...
00964 }
00965 
00966 //virtual protected
00967 void BaseOverlay::handleAppMessage(cMessage* msg)
00968 {
00969     delete msg;
00970 }
00971 
00972 void BaseOverlay::handleUDPMessage(BaseOverlayMessage* msg)
00973 {
00974     delete msg;
00975 }
00976 
00977 //virtual protected
00978 void BaseOverlay::recordOverlaySentStats(BaseOverlayMessage* msg)
00979 {
00980     // collect statistics ...
00981 }
00982 
00983 void BaseOverlay::setOverlayReady(bool ready)
00984 {
00985     //TODO new setOverlayState(State state) function
00986     //if (ready && state == READY) return;
00987 
00988     getDisplayString().setTagArg("i", 1, ready ? "" : "red");
00989     globalNodeList->setOverlayReadyIcon(getThisNode(), ready);
00990 
00991     if (ready) {
00992         bootstrapList->registerBootstrapNode(thisNode);
00993     } else {
00994         bootstrapList->removeBootstrapNode(thisNode);
00995     }
00996 
00997     if (globalParameters->getPrintStateToStdOut()) {
00998         std::cout << "OVERLAY STATE: " << (ready ? "READY (" : "OFFLINE (")
00999                   << thisNode << ")" << std::endl;
01000     }
01001 
01002     CompReadyMessage* msg = new CompReadyMessage;
01003     msg->setReady(ready);
01004     msg->setComp(OVERLAY_COMP);
01005     // TODO: fix MMOG protocols to handle new CompReadyMessage
01006     //sendMessageToAllComp(msg, OVERLAY_COMP);
01007     sendDirect((cMessage*)msg->dup(), getCompRpcGate(TIER1_COMP));
01008     sendDirect(msg, getCompRpcGate(BOOTSTRAPLIST_COMP));
01009 }
01010 
01011 
01012 
01013 //------------------------------------------------------------------------
01014 //--- Messages -----------------------------------------------------------
01015 //------------------------------------------------------------------------
01016 
01017 void BaseOverlay::sendRouteMessage(const TransportAddress& dest,
01018                                    BaseRouteMessage* msg,
01019                                    bool ack)
01020 {
01021     delete msg->removeControlInfo();
01022 
01023     if (msg && (dest != thisNode)) {
01024         msg->setHopCount(msg->getHopCount() + 1);
01025     }
01026     if (!ack)
01027         sendMessageToUDP(dest, msg);
01028     else {
01029         NextHopCall* nextHopCall = new NextHopCall(msg->getName());
01030         nextHopCall->setBitLength(NEXTHOPCALL_L(nextHopCall));
01031         nextHopCall->encapsulate(msg);
01032         nextHopCall->setStatType(msg->getStatType());
01033         sendUdpRpcCall(dest, nextHopCall);
01034     }
01035 }
01036 void BaseOverlay::sendMessageToUDP(const TransportAddress& dest,
01037                                    cPacket* msg)
01038 {
01039     // if there's still a control info attached to the message, remove it
01040     cPolymorphic* ctrlInfo = msg->removeControlInfo();
01041     if (ctrlInfo != NULL)
01042         delete ctrlInfo;
01043 
01044     // debug message
01045     if (debugOutput) {
01046         EV << "[BaseOverlay::sendMessageToUDP() @ " << thisNode.ip
01047         << " (" << thisNode.key.toString(16) << ")]\n"
01048         << "    Sending " << *msg << " to " << dest.ip
01049         << endl;
01050     }
01051 
01052     msg->setKind(UDP_C_DATA);
01053     UDPControlInfo* udpControlInfo = new UDPControlInfo();
01054     udpControlInfo->setSrcAddr(thisNode.ip);
01055     udpControlInfo->setSrcPort(thisNode.port);
01056     udpControlInfo->setDestAddr(dest.ip);
01057     udpControlInfo->setDestPort(dest.port);
01058     msg->setControlInfo(udpControlInfo);
01059 
01060     send(msg, "udpOut", 0);
01061 
01062     if (dest != thisNode) {
01063         BaseOverlayMessage* baseOverlayMsg
01064             = check_and_cast<BaseOverlayMessage*>(msg);
01065         // record statistics, if message is not local
01066         if (baseOverlayMsg->getStatType() == APP_DATA_STAT) {
01067             RECORD_STATS(numAppDataSent++;
01068                          bytesAppDataSent += msg->getByteLength());
01069         } else if (baseOverlayMsg->getStatType() == APP_LOOKUP_STAT){
01070             RECORD_STATS(numAppLookupSent++; bytesAppLookupSent +=
01071                          msg->getByteLength());
01072         } else { // MAINTENANCE_STAT
01073             RECORD_STATS(numMaintenanceSent++; bytesMaintenanceSent +=
01074                          msg->getByteLength());
01075         }
01076         recordOverlaySentStats(baseOverlayMsg);
01077     } else {
01078         if (dest.ip == thisNode.ip) { // to same node, but different port
01079             RECORD_STATS(numInternalSent++; bytesInternalSent += msg->getByteLength());
01080         }
01081     }
01082 }
01083 
01084 //------------------------------------------------------------------------
01085 //--- Basic Routing ------------------------------------------------------
01086 //------------------------------------------------------------------------
01087 
01088 static int pendingLookups = 0;
01089 
01090 void BaseOverlay::initLookups()
01091 {
01092     lookups = LookupSet();
01093 }
01094 
01095 void BaseOverlay::finishLookups()
01096 {
01097     while (lookups.size() > 0) {
01098         (*lookups.begin())->abortLookup();
01099     }
01100     lookups.clear();
01101 }
01102 
01103 class SendToKeyListener : public LookupListener
01104 {
01105 private:
01106     BaseOverlay* overlay;
01107     BaseOverlayMessage* msg;
01108     GlobalStatistics* globalStatistics;
01109 public:
01110     SendToKeyListener( BaseOverlay* overlay, BaseOverlayMessage* msg ) {
01111         this->overlay = overlay;
01112         this->msg = msg;
01113         globalStatistics = overlay->globalStatistics;
01114         pendingLookups++;
01115     }
01116 
01117     ~SendToKeyListener() {
01118         pendingLookups--;
01119         overlay = NULL;
01120         if (msg != NULL) {
01121             delete msg;
01122             msg = NULL;
01123         }
01124     }
01125 
01126     virtual void lookupFinished(AbstractLookup *lookup) {
01127         if (dynamic_cast<BaseRouteMessage*>(msg)) {
01128             BaseRouteMessage* routeMsg = static_cast<BaseRouteMessage*>(msg);
01129             if (lookup->isValid()) {
01130                 if (lookup->getResult().size()==0) {
01131                     EV << "[SendToKeyListener::lookupFinished()]\n"
01132                           "    [ERROR] SendToKeyListener: Valid result, "
01133                           "but empty array." << endl;
01134                 } else {
01135                     routeMsg->setHopCount(routeMsg->getHopCount()
01136                                           + lookup->getAccumulatedHops());
01137 
01138                     for (uint32_t i=0; i<lookup->getResult().size(); i++) {
01139                         overlay->sendRouteMessage(lookup->getResult()[i],
01140                                                   static_cast<BaseRouteMessage*>
01141                                                    (routeMsg->dup()),
01142                                                   overlay->routeMsgAcks);
01143                     }
01144                 }
01145             } else {
01146                 EV << "[SendToKeyListener::lookupFinished()]\n"
01147                    << "    Lookup failed - dropping message"
01148                    << endl;
01149                 //std::cout << simulation.simTime() << " "
01150                 //          << routeMsg->getSrcNode()
01151                 //          << " [SendToKeyListener::lookupFinished()]\n"
01152                 //          << "    Lookup failed - dropping message"
01153                 //          << std::endl;
01154                 RECORD_STATS(overlay->numDropped++;
01155                              overlay->bytesDropped += routeMsg->getByteLength());
01156             }
01157         } else if (dynamic_cast<LookupCall*>(msg)) {
01158             LookupCall* call = static_cast<LookupCall*>(msg);
01159             LookupResponse* response = new LookupResponse();
01160 
01161             if (lookup->isValid()) {
01162 
01163                 response->setIsValid(true);
01164                 response->setKey(call->getKey());
01165                 response->setSiblingsArraySize(lookup->getResult().size());
01166                 for (uint32_t i=0; i<lookup->getResult().size(); i++) {
01167                     response->setSiblings(i, lookup->getResult()[i]);
01168                 }
01169                 if (lookup->getResult().size() == 0) {
01170                     EV << "[SendToKeyListener::lookupFinished() @ "
01171                        << overlay->thisNode.ip
01172                        << " (" << overlay->thisNode.key.toString(16) << ")]\n"
01173                        << "    LookupCall "
01174                        << call->getNonce()
01175                        << " failed! (size=0)" << endl;
01176                 }
01177             } else {
01178                 response->setIsValid(false);
01179                 EV << "[SendToKeyListener::lookupFinished() @ "
01180                    << overlay->thisNode.ip
01181                    << " (" << overlay->thisNode.key.toString(16) << ")]\n"
01182                    << "    LookupCall "
01183                    << call->getNonce()
01184                    << " failed!" << endl;
01185             }
01186             overlay->sendRpcResponse(call, response);
01187             msg = NULL;
01188         } else {
01189             throw cRuntimeError("SendToKeyListener::lookupFinished(): "
01190                                     "Unkown message type!");
01191         }
01192         delete this;
01193     }
01194 };
01195 
01196 void BaseOverlay::route(const OverlayKey& key, CompType destComp,
01197                         CompType srcComp, cPacket* msg,
01198                         const std::vector<TransportAddress>& sourceRoute,
01199                         RoutingType routingType)
01200 {
01201     if (key.isUnspecified() &&
01202         (!sourceRoute.size() || sourceRoute[0].isUnspecified()))
01203         error("getRoute(): Key and hint unspecified!");
01204 
01205     // create base route message
01206     BaseAppDataMessage* baseAppDataMsg =
01207         new BaseAppDataMessage("BaseAppDataMessage");
01208     baseAppDataMsg->setType(APPDATA);
01209     baseAppDataMsg->setDestComp(destComp);
01210     baseAppDataMsg->setSrcComp(srcComp);
01211     baseAppDataMsg->setBitLength(BASEAPPDATA_L(baseAppDataMsg));
01212     baseAppDataMsg->setName(msg->getName());
01213 
01214     baseAppDataMsg->setStatType(APP_DATA_STAT);
01215     baseAppDataMsg->encapsulate(msg);
01216 
01217     // debug output
01218     if (debugOutput) {
01219         EV << "[BaseOverlay::getRoute() @ " << thisNode.ip
01220         << " (" << thisNode.key.toString(16) << ")]\n"
01221         << "    Received message from application"
01222         << endl;
01223     }
01224 
01225     if (key.isUnspecified()) {
01226         sendMessageToUDP(sourceRoute[0], baseAppDataMsg);
01227     } else {
01228         sendToKey(key, baseAppDataMsg, 1, sourceRoute, routingType);
01229     }
01230 }
01231 
01232 bool BaseOverlay::recursiveRoutingHook(const TransportAddress& dest,
01233                                        BaseRouteMessage* msg)
01234 {
01235     return true;
01236 }
01237 
01238 void BaseOverlay::sendToKey(const OverlayKey& key, BaseOverlayMessage* msg,
01239                             int numSiblings,
01240                             const std::vector<TransportAddress>& sourceRoute,
01241                             RoutingType routingType)
01242 {
01243     BaseRouteMessage* routeMsg = NULL;
01244 
01245     if (routingType == DEFAULT_ROUTING) routingType = defaultRoutingType;
01246 
01247     if (debugOutput) {
01248         EV << "[BaseOverlay::sendToKey() @ " << thisNode.ip
01249         << " (" << thisNode.key.toString(16) << ")]\n"
01250         << "    Sending " << msg <<  " to " << key
01251         << endl;
01252     }
01253 
01254     if (key.isUnspecified() &&
01255         !(sourceRoute.size() && !sourceRoute[0].isUnspecified()))
01256         error("BaseOverlay::sendToKey(): unspecified destination key!");
01257 
01258     if (msg->getType() != OVERLAYROUTE) {
01259         assert(!msg->getControlInfo());
01260         routeMsg = new BaseRouteMessage("BaseRouteMessage");
01261         routeMsg->setType(OVERLAYROUTE);
01262         routeMsg->setRoutingType(routingType);
01263         routeMsg->setDestKey(key);
01264         routeMsg->setSrcNode(thisNode);
01265         routeMsg->setStatType(msg->getStatType());
01266         // copy the name of the inner message
01267         routeMsg->setName(msg->getName());
01268         routeMsg->setBitLength(BASEROUTE_L(routeMsg));
01269         routeMsg->encapsulate(msg);
01270 
01271         OverlayCtrlInfo* routeCtrlInfo = new OverlayCtrlInfo;
01272         routeCtrlInfo->setLastHop(thisNode);
01273         routeCtrlInfo->setTransportType(ROUTE_TRANSPORT);
01274         routeCtrlInfo->setRoutingType(routingType);
01275         routeMsg->setControlInfo(routeCtrlInfo);
01276 
01277         //message marked as not already forwarded to tier1
01278         routeMsg->setContextPointer(NULL);
01279     } else {
01280         routeMsg = check_and_cast<BaseRouteMessage*>(msg);
01281         routingType = static_cast<RoutingType>(routeMsg->getRoutingType());
01282     }
01283 
01284     /* // only used as workaround - uncomment if assert fails!
01285     if (!routeMsg->getControlInfo()) {
01286         // workaround
01287         OverlayCtrlInfo* routeCtrlInfo = new OverlayCtrlInfo;
01288         routeCtrlInfo->setLastHopAddr(thisNode.ip);
01289         routeCtrlInfo->setLastHopPort(thisNode.port);
01290         routeCtrlInfo->setTransportType(ROUTE_TRANSPORT);
01291         routeMsg->setControlInfo(routeCtrlInfo);
01292     }
01293     */
01294 
01295     // set timestamp for next hop
01296     if (collectPerHopDelay) {
01297         routeMsg->setHopStamp(simTime());
01298     }
01299 
01300     if (sourceRoute.size() && !sourceRoute[0].isUnspecified()) {
01301         // send msg to nextHop if specified (used for e.g. join rpcs)
01302         OverlayCtrlInfo* ctrlInfo = check_and_cast<OverlayCtrlInfo*>
01303             (routeMsg->getControlInfo());
01304         ctrlInfo->setTransportType(UDP_TRANSPORT);
01305         assert(routeMsg->getNextHopsArraySize() == 0);
01306         routeMsg->setNextHopsArraySize(sourceRoute.size());
01307         for (uint32_t i = 0; i < sourceRoute.size(); ++i)
01308             routeMsg->setNextHops(i, sourceRoute[i]);
01309         if (recursiveRoutingHook(sourceRoute[0], routeMsg)) { //test
01310             sendRouteMessage(sourceRoute[0], routeMsg, routeMsgAcks);
01311         }
01312         return;
01313     }
01314 
01315     if ((routingType == ITERATIVE_ROUTING)
01316         || (routingType == EXHAUSTIVE_ITERATIVE_ROUTING)) {
01317 
01318         // create lookup and sent to key
01319         AbstractLookup* lookup = createLookup(routingType, routeMsg, NULL, true);
01320         lookup->lookup(routeMsg->getDestKey(), numSiblings, hopCountMax,
01321                        0, new SendToKeyListener(this, routeMsg));
01322     } else  {
01323         // recursive routing
01324         NodeVector* nextHops = findNode(routeMsg->getDestKey(),
01325                                         recNumRedundantNodes,
01326                                         numSiblings, routeMsg);
01327 
01328         if (nextHops->size() == 0) {
01329             EV << "[BaseOverlay::sendToKey() @ " << thisNode.ip
01330                << " (" << thisNode.key.toString(16) << ")]\n"
01331                << "    FindNode() returned NULL - dropping message"
01332                << endl;
01333             //std::cout << simTime() << " " << thisNode.ip << " " << state
01334             //          << " FindNode() returned NULL - dropping message "
01335             //          << routeMsg->getName() << " from "
01336             //          << routeMsg->getSrcNode() << std::endl;
01337 
01338             // statistics
01339             RECORD_STATS(numDropped++; bytesDropped += routeMsg->getByteLength());
01340             delete routeMsg;
01341         } else {
01342             // delete message if the hop count maximum is exceeded
01343             if (routeMsg->getHopCount() >= hopCountMax) {
01344 
01345                 EV << "[BaseOverlay::sendToKey() @ " << thisNode.ip
01346                    << " (" << thisNode.key.toString(16) << ")]\n"
01347                    << "    Discards " << routeMsg->getName() << " from "
01348                    << routeMsg->getSrcNode().ip << "\n"
01349                    << "    The hop count maximum has been exceeded ("
01350                    << routeMsg->getHopCount() << ">="
01351                    << hopCountMax << ")"
01352                    << endl;
01353                 //std::cout << "[BaseOverlay::sendToKey() @ " << thisNode.ip
01354                 //          << " (" << thisNode.key.toString(16) << ")]\n"
01355                 //          << "    Discards " << routeMsg->getName() << " from "
01356                 //          << routeMsg->getSrcNode().ip << "\n"
01357                 //          << "    The hop count maximum has been exceeded ("
01358                 //          << routeMsg->getHopCount() << ">="
01359                 //          << hopCountMax << ")"
01360                 //          << std::endl;
01361 
01362                 // statistics
01363                 RECORD_STATS(numDropped++;
01364                              bytesDropped += routeMsg->getByteLength());
01365                 delete routeMsg;
01366                 delete nextHops;
01367                 return;
01368             }
01369 
01370             OverlayCtrlInfo* overlayCtrlInfo =
01371                 dynamic_cast<OverlayCtrlInfo*>(routeMsg->getControlInfo());
01372             assert(overlayCtrlInfo);
01373 
01374             // check and choose nextHop candidate
01375             NodeHandle* nextHop = NULL;
01376             bool err, isSibling;
01377             isSibling = isSiblingFor(thisNode, routeMsg->getDestKey(),
01378                                      numSiblings, &err);
01379 
01380             // if route is recorded we can do a real loop detection
01381             std::set<TransportAddress> visitedHops;
01382             for (uint32_t i = 0; i < routeMsg->getVisitedHopsArraySize(); ++i) {
01383                 visitedHops.insert(routeMsg->getVisitedHops(i));
01384             }
01385 
01386             for (uint32_t index = 0; nextHop == NULL && nextHops->size() > index;
01387                  ++index) {
01388                 nextHop = &((*nextHops)[index]);
01389                 // loop detection
01390                 if (((overlayCtrlInfo->getLastHop() == *nextHop) &&
01391                      (*nextHop != thisNode)) ||
01392                      (visitedHops.find(*nextHop) != visitedHops.end()) ||
01393                      // do not forward msg to source node
01394                     ((*nextHop == routeMsg->getSrcNode()) &&
01395                      (thisNode != routeMsg->getSrcNode())) ||
01396                      // nextHop is thisNode, but isSiblingFor() is false
01397                     ((*nextHop == thisNode) && (!isSibling))) {
01398                     nextHop = NULL;
01399                 }
01400             }
01401 
01402             if (nextHop == NULL) {
01403                 if (!checkFindNode(routeMsg)) {
01404                     EV << "[BaseOverlay::sendToKey() @ " << thisNode.ip
01405                        << " (" << thisNode.key.toString(16) << ")]\n"
01406                        << "    Discards " << routeMsg->getName() << " from "
01407                        << routeMsg->getSrcNode().ip << "\n"
01408                        << "    No useful nextHop found!"
01409                        << endl;
01410                     //std::cout << thisNode.ip << " packet from "
01411                     //          << routeMsg->getSrcNode().ip
01412                     //          << " dropped: " << routeMsg
01413                     //          << " " << state << std::endl;
01414                     RECORD_STATS(numDropped++;
01415                                  bytesDropped += routeMsg->getByteLength());
01416                 }
01417                 delete routeMsg;
01418                 delete nextHops;
01419                 return;
01420             }
01421 
01422             assert(!nextHop->isUnspecified());
01423 
01424             // callForward to app
01425             if (useCommonAPIforward &&
01426                 dynamic_cast<BaseAppDataMessage*>(
01427                         routeMsg->getEncapsulatedMsg()) &&
01428                 routeMsg->getContextPointer() == NULL) {
01429                 callForward(routeMsg->getDestKey(), routeMsg, *nextHop);
01430                 delete nextHops;
01431                 return;
01432             }
01433             //message marked as not already forwarded
01434             routeMsg->setContextPointer(NULL);
01435 
01436             // is this node responsible?
01437             if (*nextHop == thisNode) {
01438                 if (isSibling && !err) {
01439                     //EV << "[BaseOverlay::sendToKey() @ " << thisNode.ip
01440                     //   << " (" << thisNode.key.toString(16) << ")]\n"
01441                     //   << "    Forwards msg for key " << routeMsg->getDestKey() "\n"
01442                     //   << "    to node " << (*nextHops)[0]
01443                     //   << endl;
01444                     delete nextHops;
01445                     assert(routeMsg->getControlInfo());
01446                     handleBaseOverlayMessage(routeMsg, key);
01447                     return;
01448                 } else {
01449                     error("isSiblingsFor() is true with an error: "
01450                           "Erroneous method isSiblingFor()!");
01451                 }
01452             } // else forward msg if this node is not responsible for the key
01453 
01454             // records statistics, if we forward this message
01455             if (overlayCtrlInfo->getLastHop().ip != thisNode.ip) {
01456                 if (routeMsg->getStatType() == APP_DATA_STAT) {
01457                     RECORD_STATS(numAppDataForwarded++; bytesAppDataForwarded +=
01458                                  routeMsg->getByteLength());
01459                 } else if (routeMsg->getStatType() == APP_LOOKUP_STAT){
01460                     RECORD_STATS(numAppLookupForwarded++;
01461                                  bytesAppLookupForwarded +=
01462                                      routeMsg->getByteLength());
01463                 } else {
01464                     RECORD_STATS(numMaintenanceForwarded++;
01465                                  bytesMaintenanceForwarded +=
01466                                      routeMsg->getByteLength());
01467                 }
01468             }
01469             overlayCtrlInfo->setHopCount(routeMsg->getHopCount());
01470             if (recursiveRoutingHook(*nextHop, routeMsg)) {
01471                 sendRouteMessage(*nextHop, routeMsg, routeMsgAcks);
01472             }
01473         }
01474         delete nextHops;
01475     }
01476 }
01477 
01478 bool BaseOverlay::checkFindNode(BaseRouteMessage* routeMsg)
01479 {
01480     if (dynamic_cast<FindNodeCall*>(routeMsg->getEncapsulatedMsg())) {
01481         FindNodeCall* findNodeCall =
01482             static_cast<FindNodeCall*>(routeMsg->decapsulate());
01483         findNodeCall
01484             ->setControlInfo(check_and_cast<OverlayCtrlInfo*>
01485             (routeMsg->removeControlInfo()));
01486         findNodeRpc(findNodeCall);
01487         return true;
01488     }
01489     return false;
01490 }
01491 
01492 //protected: create a lookup class
01493 AbstractLookup* BaseOverlay::createLookup(RoutingType routingType,
01494                                           const BaseOverlayMessage* msg,
01495                                           const cObject* findNodeExt,
01496                                           bool appLookup)
01497 {
01498     AbstractLookup* newLookup;
01499 
01500     if (routingType == DEFAULT_ROUTING) {
01501         routingType = defaultRoutingType;
01502     }
01503 
01504     switch (routingType) {
01505         case ITERATIVE_ROUTING:
01506         case EXHAUSTIVE_ITERATIVE_ROUTING:
01507             newLookup = new IterativeLookup(this, routingType,
01508                                             iterativeLookupConfig, findNodeExt,
01509                                             appLookup);
01510             break;
01511         case RECURSIVE_SOURCE_ROUTING:
01512         case SEMI_RECURSIVE_ROUTING:
01513         case FULL_RECURSIVE_ROUTING:
01514             newLookup = new RecursiveLookup(this, routingType,
01515                                             recursiveLookupConfig,
01516                                             appLookup);
01517             break;
01518         default:
01519             throw cRuntimeError("BaseOverlay::createLookup():"
01520                                     " Unknown routingType!");
01521             break;
01522     }
01523 
01524     lookups.insert(newLookup);
01525     return newLookup;
01526 }
01527 
01528 void BaseOverlay::removeLookup(AbstractLookup* lookup)
01529 {
01530     lookups.erase(lookup);
01531 }
01532 
01533 //virtual public
01534 OverlayKey BaseOverlay::distance( const OverlayKey& x,
01535                                   const OverlayKey& y ) const
01536 {
01537     opp_error("BaseOverlay::distance(): Not implemented!");
01538     return OverlayKey::UNSPECIFIED_KEY;
01539 }
01540 
01541 //protected: find closest nodes
01542 NodeVector* BaseOverlay::findNode(const OverlayKey& key,
01543                                   int numRedundantNodes,
01544                                   int numSiblings,
01545                                   BaseOverlayMessage* msg)
01546 {
01547     opp_error( "findNode: Not implemented!" );
01548     return NULL;
01549 }
01550 
01551 //protected: join the overlay with a given nodeID
01552 void BaseOverlay::joinOverlay()
01553 {
01554 //  std::cout << "BaseOverlay::joinOverlay(): Not implemented!" << endl;
01555     return;
01556 }
01557 
01558 bool BaseOverlay::handleFailedNode(const TransportAddress& failed)
01559 {
01560     return true;
01561 }
01562 
01563 //------------------------------------------------------------------------
01564 //--- RPCs ---------------------------------------------------------------
01565 //------------------------------------------------------------------------
01566 
01567 //private
01568 bool BaseOverlay::internalHandleRpc( BaseCallMessage* msg )
01569 {
01570     // call rpc stubs
01571     RPC_SWITCH_START( msg );
01572     RPC_DELEGATE( FindNode, findNodeRpc );
01573     RPC_DELEGATE( FailedNode, failedNodeRpc );
01574     RPC_DELEGATE( Lookup, lookupRpc );
01575     RPC_DELEGATE( NextHop, nextHopRpc );
01576     RPC_SWITCH_END( );
01577 
01578     // if RPC was handled return true, else tell the parent class to handle it
01579     return RPC_HANDLED || BaseRpc::internalHandleRpc(msg);
01580 }
01581 
01582 bool BaseOverlay::internalHandleRpcResponse(BaseResponseMessage* msg,
01583                                             cPolymorphic* context,
01584                                             int rpcId, simtime_t rtt)
01585 {
01586     // if RPC was handled return true, else tell the parent class to handle it
01587     //RPC_SWITCH_START( msg );
01588     //RPC_ON_RESPONSE( NextHop ) {
01589         //if (rtt > 1.0) std::cout << rtt  << " to "
01590         //                         << msg->getSrcNode() << std::endl;
01591     //}
01592     //RPC_SWITCH_END( );
01593 
01594     return /*RPC_HANDLED ||*/ BaseRpc::internalHandleRpcResponse(msg, context,
01595                                                              rpcId, rtt);
01596 }
01597 
01598 void BaseOverlay::internalHandleRpcTimeout(BaseCallMessage* msg,
01599                                            const TransportAddress& dest,
01600                                            cPolymorphic* context, int rpcId,
01601                                            const OverlayKey& destKey)
01602 {
01603     RPC_SWITCH_START( msg )
01604         RPC_ON_CALL( NextHop )
01605         {
01606             BaseRouteMessage* tempMsg
01607                 = check_and_cast<BaseRouteMessage*>(msg->decapsulate());
01608 
01609             if (!tempMsg->getControlInfo()) {
01610                 OverlayCtrlInfo* overlayCtrlInfo = new OverlayCtrlInfo;
01611                 overlayCtrlInfo->setLastHop(thisNode);
01612                 overlayCtrlInfo->setHopCount(tempMsg->getHopCount());
01613                 overlayCtrlInfo->setSrcNode(tempMsg->getSrcNode());
01614                 overlayCtrlInfo->setRoutingType(tempMsg->getRoutingType());
01615                 overlayCtrlInfo->setTransportType(UDP_TRANSPORT);
01616                 tempMsg->setControlInfo(overlayCtrlInfo);
01617             }
01618             // remove node from local routing tables
01619             // + send message again
01620             if (handleFailedNode(dest)) {
01621                 handleBaseOverlayMessage(tempMsg, destKey);
01622             } else {
01623                 RECORD_STATS(numDropped++;
01624                              bytesDropped += tempMsg->getByteLength());
01625                 delete tempMsg;
01626                 joinOverlay();
01627             }
01628             break;
01629         }
01630     RPC_SWITCH_END( )
01631 
01632     BaseRpc::internalHandleRpcTimeout(msg, dest, context, rpcId, destKey);
01633 }
01634 
01635 void BaseOverlay::internalSendRouteRpc(BaseRpcMessage* message,
01636                                        const OverlayKey& destKey,
01637                                        const std::vector<TransportAddress>&
01638                                        sourceRoute,
01639                                        RoutingType routingType) {
01640     FindNodeCall* findNodeCall;
01641     uint32_t numSiblings = 1;
01642     if ((findNodeCall = dynamic_cast<FindNodeCall*>(message)))
01643         numSiblings = findNodeCall->getNumSiblings();
01644 
01645     sendToKey(destKey, message, numSiblings, sourceRoute, routingType);
01646 }
01647 
01648 void BaseOverlay::internalSendRpcResponse(BaseCallMessage* call,
01649                                           BaseResponseMessage* response)
01650 {
01651     OverlayCtrlInfo* overlayCtrlInfo =
01652         check_and_cast<OverlayCtrlInfo*>(call->getControlInfo());
01653 
01654     TransportType transportType = ROUTE_TRANSPORT;
01655     const TransportAddress* destNode;
01656     if (overlayCtrlInfo->getSrcNode().isUnspecified())
01657         destNode = &(overlayCtrlInfo->getLastHop());
01658     else
01659         destNode = &(overlayCtrlInfo->getSrcNode());
01660     const OverlayKey* destKey = &OverlayKey::UNSPECIFIED_KEY;
01661 
01662     RoutingType routingType
01663         = static_cast<RoutingType>(overlayCtrlInfo->getRoutingType());
01664 
01665     assert(overlayCtrlInfo->getTransportType() != INTERNAL_TRANSPORT);
01666 
01667     if ((overlayCtrlInfo->getTransportType() == UDP_TRANSPORT) ||
01668         (routingType == SEMI_RECURSIVE_ROUTING) ||
01669         (routingType == ITERATIVE_ROUTING) ||
01670         (routingType == EXHAUSTIVE_ITERATIVE_ROUTING)) {
01671         // received by UDP or direct response (IR, EIR or SRR routing)
01672         transportType = UDP_TRANSPORT;
01673         overlayCtrlInfo->setVisitedHopsArraySize(0); //???
01674     } else if ((static_cast<RoutingType> (overlayCtrlInfo->getRoutingType())
01675             == FULL_RECURSIVE_ROUTING)) {
01676         // full recursive routing
01677         destKey = &(overlayCtrlInfo->getSrcNode().key);
01678         destNode = &NodeHandle::UNSPECIFIED_NODE;
01679     }
01680     // else: source routing -> route back over visited hops
01681 
01682     sendRpcResponse(transportType,
01683                     static_cast<CompType>(overlayCtrlInfo->getSrcComp()),
01684                     *destNode, *destKey, call, response);
01685 }
01686 
01687 //protected: statistic helpers for IterativeLookup
01688 void BaseOverlay::countFindNodeCall( const FindNodeCall* call )
01689 {
01690     RECORD_STATS(numFindNodeSent++;
01691                  bytesFindNodeSent += call->getByteLength());
01692 }
01693 
01694 void BaseOverlay::countFailedNodeCall( const FailedNodeCall* call )
01695 {
01696     RECORD_STATS(numFailedNodeSent++;
01697                  bytesFailedNodeSent += call->getByteLength());
01698 }
01699 
01700 //private: rpc stub
01701 void BaseOverlay::findNodeRpc( FindNodeCall* call )
01702 {
01703     // if this node is malicious don't answer a findNodeCall
01704     if (isMalicious()) {
01705         EV << "[BaseOverlay::findNodeRpc() @ " << thisNode.ip
01706         << " (" << thisNode.key.toString(16) << ")]\n"
01707         << "    Node ignores findNodeCall because this node is malicious"
01708         << endl;
01709         delete call;
01710         return;
01711     }
01712 
01713     FindNodeResponse* findNodeResponse =
01714         new FindNodeResponse("FindNodeResponse");
01715 
01716     NodeVector* nextHops = findNode(call->getLookupKey(),
01717                                     call->getNumRedundantNodes(),
01718                                     call->getNumSiblings(), call);
01719 
01720     findNodeResponse->setClosestNodesArraySize(nextHops->size());
01721 
01722     for (uint32_t i=0; i < nextHops->size(); i++) {
01723         findNodeResponse->setClosestNodes(i, (*nextHops)[i]);
01724     }
01725 
01726     bool err;
01727     if (isSiblingFor(thisNode, call->getLookupKey(), call->getNumSiblings(),
01728                      &err)) {
01729         findNodeResponse->setSiblings(true);
01730     }
01731 
01732     findNodeResponse->setBitLength(FINDNODERESPONSE_L(findNodeResponse));
01733 
01734     if (call->hasObject("findNodeExt")) {
01735         cPacket* findNodeExt = check_and_cast<cPacket*>(call->removeObject("findNodeExt"));
01736         findNodeResponse->addObject(findNodeExt);
01737         findNodeResponse->addBitLength(findNodeExt->getBitLength());
01738     }
01739 
01740     RECORD_STATS(numFindNodeResponseSent++; bytesFindNodeResponseSent +=
01741                      findNodeResponse->getByteLength());
01742 
01743     delete nextHops;
01744 
01745     sendRpcResponse(call, findNodeResponse);
01746 }
01747 
01748 void BaseOverlay::failedNodeRpc( FailedNodeCall* call )
01749 {
01750     FailedNodeResponse* failedNodeResponse =
01751         new FailedNodeResponse("FailedNodeResponse");
01752     failedNodeResponse->setTryAgain(handleFailedNode(call->getFailedNode()));
01753     failedNodeResponse->setBitLength(FAILEDNODERESPONSE_L(failedNodeResponse));
01754 
01755     if (call->hasObject("findNodeExt")) {
01756         cPacket* findNodeExt = check_and_cast<cPacket*>(
01757                                     call->removeObject("findNodeExt"));
01758         failedNodeResponse->addObject(findNodeExt);
01759         failedNodeResponse->addBitLength(findNodeExt->getBitLength());
01760     }
01761 
01762     RECORD_STATS(numFailedNodeResponseSent++; bytesFailedNodeResponseSent +=
01763                      failedNodeResponse->getByteLength());
01764 
01765     sendRpcResponse(call, failedNodeResponse);
01766 }
01767 
01768 void BaseOverlay::lookupRpc(LookupCall* call)
01769 {
01770     int numSiblings = call->getNumSiblings();
01771 
01772     if (numSiblings < 0) {
01773         numSiblings = getMaxNumSiblings();
01774     }
01775 
01776     // create lookup and sent to key
01777     AbstractLookup* lookup = createLookup(static_cast<RoutingType>(
01778             call->getRoutingType()), call, NULL, true);
01779     lookup->lookup(call->getKey(), numSiblings, hopCountMax,
01780                    1, new SendToKeyListener( this, call ));
01781 
01782 }
01783 
01784 void BaseOverlay::nextHopRpc(NextHopCall* call)
01785 {
01786     if (state != READY) {
01787         //TODO EV...
01788         delete call;
01789         return;
01790     }
01791 
01792     BaseRouteMessage* routeMsg
01793         = check_and_cast<BaseRouteMessage*>(call->decapsulate());
01794 
01795     OverlayCtrlInfo* overlayCtrlInfo =
01796         check_and_cast<OverlayCtrlInfo*>(call->getControlInfo()->dup());
01797     overlayCtrlInfo->setHopCount(routeMsg->getHopCount());
01798     overlayCtrlInfo->setSrcNode(routeMsg->getSrcNode());
01799     overlayCtrlInfo->setRoutingType(routeMsg->getRoutingType());
01800 
01801     routeMsg->setControlInfo(overlayCtrlInfo);
01802     assert(routeMsg->getControlInfo());
01803 
01804     std::string temp("ACK: [");
01805     (temp += routeMsg->getName()) += "]";
01806 
01807     NextHopResponse* response
01808         = new NextHopResponse(temp.c_str());
01809     response->setBitLength(NEXTHOPRESPONSE_L(response));
01810     sendRpcResponse(call, response);
01811 
01812     handleBaseOverlayMessage(routeMsg, routeMsg->getDestKey());
01813 }
01814 
01815 void BaseOverlay::registerComp(CompType compType, cModule *module)
01816 {
01817     cGate *gate = NULL;
01818 
01819     if (module != NULL)
01820         gate = module->gate("direct_in");
01821 
01822     compModuleList[compType] = make_pair<cModule*, cGate*>(module, gate);
01823 }
01824 
01825 cModule* BaseOverlay::getCompModule(CompType compType)
01826 {
01827     CompModuleList::iterator it = compModuleList.find(compType);
01828 
01829     if (it != compModuleList.end())
01830         return it->second.first;
01831     else
01832         return NULL;
01833 }
01834 
01835 cGate* BaseOverlay::getCompRpcGate(CompType compType)
01836 {
01837     CompModuleList::iterator it = compModuleList.find(compType);
01838 
01839     if (it != compModuleList.end())
01840         return it->second.second;
01841     else
01842         return NULL;
01843 }
01844 
01845 void BaseOverlay::sendMessageToAllComp(cMessage* msg, CompType srcComp)
01846 {
01847     for (CompModuleList::iterator it = compModuleList.begin();
01848          it != compModuleList.end(); it++) {
01849 
01850         // don't send message to the origination component
01851         if (it->first != srcComp)
01852             sendDirect((cMessage*)msg->dup(), it->second.second);
01853     }
01854 
01855     delete msg;
01856 }
01857 
01858 bool BaseOverlay::isInSimpleMultiOverlayHost()
01859 {
01860     return isVector() || getParentModule()->isVector();
01861 }
01862 

Generated on Wed Mar 25 16:32:48 2009 for OverSim by  doxygen 1.5.5