SimpleUnderlayConfigurator.cc

Go to the documentation of this file.
00001 //
00002 // This program is free software; you can redistribute it and/or
00003 // modify it under the terms of the GNU General Public License
00004 // as published by the Free Software Foundation; either version 2
00005 // of the License, or (at your option) any later version.
00006 //
00007 // This program is distributed in the hope that it will be useful,
00008 // but WITHOUT ANY WARRANTY; without even the implied warranty of
00009 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00010 // GNU General Public License for more details.
00011 //
00012 // You should have received a copy of the GNU General Public License
00013 // along with this program; if not, write to the Free Software
00014 // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
00015 //
00016 
00023 #include <omnetpp.h>
00024 #include <vector>
00025 #include <map>
00026 
00027 #include <fstream>
00028 
00029 #include <NodeHandle.h>
00030 #include "IInterfaceTable.h"
00031 #include "InterfaceEntry.h"
00032 #include "IPv4InterfaceData.h"
00033 #include "TransportAddress.h"
00034 #include "IPAddressResolver.h"
00035 #include <cenvir.h>
00036 #include <cxmlelement.h>
00037 #include "ChurnGenerator.h"
00038 #include "GlobalNodeList.h"
00039 
00040 #include "SimpleUDP.h"
00041 
00042 #include "SimpleUnderlayConfigurator.h"
00043 
00044 Define_Module(SimpleUnderlayConfigurator);
00045 
00046 using namespace std;
00047 
00048 SimpleUnderlayConfigurator::~SimpleUnderlayConfigurator()
00049 {
00050     for (uint32_t i = 0; i < nodeRecordPool.size(); ++i) {
00051         //std::cout << (nodeRecordPool[i].second ? "+" : "_");
00052         delete nodeRecordPool[i].first;
00053     }
00054     nodeRecordPool.clear();
00055 }
00056 
00057 void SimpleUnderlayConfigurator::initializeUnderlay(int stage)
00058 {
00059     if (stage != MAX_STAGE_UNDERLAY)
00060         return;
00061 
00062     // fetch some parameters
00063     fixedNodePositions = par("fixedNodePositions");
00064 
00065     // set maximum coordinates and send queue length
00066     fieldSize = par("fieldSize");
00067     sendQueueLength = par("sendQueueLength");
00068 
00069     // get parameter of sourcefile's name
00070     nodeCoordinateSource = par("nodeCoordinateSource");
00071 
00072     // check if exists and process xml-file containing coordinates
00073     std::ifstream check_for_xml_file(nodeCoordinateSource);
00074     if (check_for_xml_file) {
00075         useXmlCoords = 1;
00076 
00077         EV<< "[SimpleNetConfigurator::initializeUnderlay()]\n"
00078         << "    Using '" << nodeCoordinateSource
00079         << "' as Coordinate-Sourcefile" << endl;
00080 
00081         maxCoordinate = parseCoordFile(nodeCoordinateSource);
00082     } else {
00083         useXmlCoords = 0;
00084         dimensions = 2;
00085         EV << "[SimpleNetConfigurator::initializeUnderlay()]\n"
00086         << "    Using conventional (random) coordinates for placing nodes!\n"
00087         << "    (An XML-Sourcefile could not be opened)" << endl;
00088     }
00089     check_for_xml_file.close();
00090 
00091     // FIXME get address from parameter
00092     nextFreeAddress = 0x1000001;
00093 
00094     // count the overlay clients
00095     overlayTerminalCount = 0;
00096 
00097     numCreated = 0;
00098     numKilled = 0;
00099 }
00100 
00101 TransportAddress* SimpleUnderlayConfigurator::createNode(NodeType type,
00102                                                          bool initialize)
00103 {
00104     Enter_Method_Silent();
00105     // derive overlay node from ned
00106     cModuleType* moduleType = cModuleType::get(type.terminalType.c_str());
00107 
00108     cModule* node = moduleType->create("overlayTerminal", getParentModule(),
00109                                        numCreated + 1, numCreated);
00110 
00111     node->par("overlayType").setStringValue(type.overlayType.c_str());
00112     node->par("tier1Type").setStringValue(type.tier1Type.c_str());
00113     node->par("tier2Type").setStringValue(type.tier2Type.c_str());
00114     node->par("tier3Type").setStringValue(type.tier3Type.c_str());
00115 
00116     std::string displayString;
00117 
00118     if ((type.typeID > 1) && (type.typeID <= (NUM_COLORS + 1))) {
00119         ((displayString += "i=device/wifilaptop_l,") += colorNames[type.typeID
00120                 - 2]) += ",40;i2=block/circle_s";
00121     } else {
00122         displayString = "i=device/wifilaptop_l;i2=block/circle_s";
00123     }
00124 
00125     node->finalizeParameters();
00126     node->setDisplayString(displayString.c_str());
00127     node->buildInside();
00128     node->scheduleStart(simTime());
00129 
00130     for (int i = 0; i < MAX_STAGE_UNDERLAY + 1; i++) {
00131         node->callInitialize(i);
00132     }
00133 
00134     // FIXME use only IPv4?
00135     IPvXAddress addr = IPAddress(nextFreeAddress++);
00136 
00137     cChannelType* chan = cChannelType::find(type.channelTypes[intuniform(0,
00138             type.channelTypes.size() - 1)].c_str());
00139 
00140     if (!chan) {
00141         opp_error("Could not find Channel Type. Most likely parameter "
00142             "channelTypes does not match the channels defined in "
00143             "channels.ned");
00144     }
00145 
00146     SimpleNodeEntry* entry;
00147 
00148     if (!useXmlCoords) {
00149         entry = new SimpleNodeEntry(node, chan, fieldSize, sendQueueLength);
00150     } else {
00151         //get random unused node
00152         uint32_t volunteer = intuniform(0, nodeRecordPool.size() - 1);
00153         uint32_t temp = volunteer;
00154         while (nodeRecordPool[volunteer].second == false) {
00155             ++volunteer;
00156             if (volunteer >= nodeRecordPool.size())
00157                 volunteer = 0;
00158             // stop with errormessage if no more unused nodes available
00159             if (temp == volunteer)
00160                 throw cRuntimeError("No unused coordinates left -> "
00161                     "cannot create any more nodes. "
00162                     "Provide %s-file with more nodes!\n", nodeCoordinateSource);
00163         }
00164 
00165         entry = new SimpleNodeEntry(node, chan, sendQueueLength,
00166                                     nodeRecordPool[volunteer].first, volunteer);
00167 
00168         //insert IP-address into noderecord used
00169         nodeRecordPool[volunteer].first->ip = addr;
00170         nodeRecordPool[volunteer].second = false;
00171     }
00172 
00173     SimpleUDP* simple = check_and_cast<SimpleUDP*> (node->getSubmodule("udp"));
00174     simple->setNodeEntry(entry);
00175 
00176     // Add pseudo-Interface to node's interfaceTable
00177     IPv4InterfaceData* ifdata = new IPv4InterfaceData;
00178     ifdata->setIPAddress(addr.get4());
00179     ifdata->setNetmask(IPAddress("255.255.255.255"));
00180     InterfaceEntry* e = new InterfaceEntry;
00181     e->setName("dummy interface");
00182     e->setIPv4Data(ifdata);
00183 
00184     IPAddressResolver().interfaceTableOf(node)->addInterface(e, NULL);
00185 
00186     // create meta information
00187     SimpleInfo* info = new SimpleInfo(type.typeID, node->getId());
00188     info->setEntry(entry);
00189 
00190     //add node to bootstrap oracle
00191     globalNodeList->addPeer(addr, info);
00192 
00193     // if the node was not created during startup we have to
00194     // finish the initialization process manually
00195     if (!initialize) {
00196         for (int i = MAX_STAGE_UNDERLAY + 1; i < NUM_STAGES_ALL; i++) {
00197             node->callInitialize(i);
00198         }
00199     }
00200 
00201     //show ip...
00202     //TODO: migrate
00203     if (fixedNodePositions && ev.isGUI()) {
00204         node->getDisplayString().insertTag("p");
00205         node->getDisplayString().setTagArg("p", 0, (long int) entry->getX());
00206         node->getDisplayString().setTagArg("p", 1, (long int) entry->getY());
00207         node->getDisplayString().insertTag("t", 0);
00208         node->getDisplayString().setTagArg("t", 0, addr.str().c_str());
00209         node->getDisplayString().setTagArg("t", 1, "l");
00210     }
00211 
00212     overlayTerminalCount++;
00213     numCreated++;
00214 
00215     churnGenerator[type.typeID - 1]->terminalCount++;
00216 
00217     TransportAddress *address = new TransportAddress(addr);
00218 
00219     // update display
00220     setDisplayString();
00221 
00222     return address;
00223 }
00224 
00225 uint32_t SimpleUnderlayConfigurator::parseCoordFile(const char* nodeCoordinateSource)
00226 {
00227     cXMLElement* rootElement = ev.getXMLDocument(nodeCoordinateSource);
00228 
00229     // get number of dimensions from attribute of xml rootelement
00230     dimensions = atoi(rootElement->getAttribute("dimensions"));
00231     EV << "[SimpleNetConfigurator::parseCoordFile()]\n"
00232        << "    using " << dimensions << " dimensions: ";
00233 
00234     double max_coord = 0;
00235 
00236     for (cXMLElement *tmpElement = rootElement->getFirstChild(); tmpElement;
00237          tmpElement = tmpElement->getNextSibling()) {
00238 
00239         // get "ip" and "isRoot" from Attributes (not needed yet)
00240       /*
00241        const char* str_ip = tmpElement->getAttribute("ip");
00242        int tmpIP = 0;
00243        if (str_ip) sscanf(str_ip, "%x", &tmpIP);
00244        bool tmpIsRoot = atoi(tmpElement->getAttribute("isroot"));
00245        */
00246 
00247         // create tmpNode to be added to vector
00248         NodeRecord* tmpNode = new NodeRecord(dimensions);
00249 
00250         // get coords from childEntries and fill tmpNodes Array
00251         int i = 0;
00252         for (cXMLElement *coord = tmpElement->getFirstChild(); coord;
00253              coord = coord->getNextSibling()) {
00254 
00255             tmpNode->coords[i] = atof(coord->getNodeValue());
00256 
00257             double newMax = fabs(tmpNode->coords[i]);
00258             if (newMax > max_coord) {
00259                max_coord = newMax;
00260             }
00261             i++;
00262         }
00263 
00264         // add to vector
00265         nodeRecordPool.push_back(make_pair(tmpNode, true));
00266 
00267         //if (nodeRecordPool.size() >= maxSize) break; //TODO use other xml lib
00268     }
00269 
00270     EV << nodeRecordPool.size()
00271        << " nodes added to vector \"nodeRecordPool\"." << endl;
00272 
00273     return (uint32_t)ceil(max_coord);
00274 }
00275 
00276 void SimpleUnderlayConfigurator::preKillNode(NodeType type, TransportAddress* addr)
00277 {
00278     Enter_Method_Silent();
00279 
00280     SimpleNodeEntry* entry = NULL;
00281     SimpleInfo* info;
00282 
00283     if (addr == NULL) {
00284         addr = globalNodeList->getRandomAliveNode(type.typeID);
00285 
00286         if (addr == NULL) {
00287             // all nodes are already prekilled
00288             std::cout << "all nodes are already prekilled" << std::endl;
00289             return;
00290         }
00291     }
00292 
00293     info = dynamic_cast<SimpleInfo*> (globalNodeList->getPeerInfo(*addr));
00294 
00295     if (info != NULL) {
00296         entry = info->getEntry();
00297         globalNodeList->setPreKilled(*addr);
00298     } else {
00299         opp_error("SimpleNetConfigurator: Trying to pre kill node "
00300                   "with nonexistant TransportAddress!");
00301     }
00302 
00303     uint32_t effectiveType = info->getTypeID();
00304     cGate* gate = entry->getGate();
00305 
00306     cModule* node = gate->getOwnerModule()->getParentModule();
00307 
00308     if (scheduledID.count(node->getId())) {
00309         std::cout << "SchedID" << std::endl;
00310         return;
00311     }
00312 
00313     // remove node from bootstrap oracle
00314     globalNodeList->removePeer(IPAddressResolver().addressOf(node));
00315 
00316     // put node into the kill list and schedule a message for final removal
00317     // of the node
00318     killList.push_front(IPAddressResolver().addressOf(node));
00319     scheduledID.insert(node->getId());
00320 
00321     overlayTerminalCount--;
00322     numKilled++;
00323 
00324     churnGenerator[effectiveType - 1]->terminalCount--;
00325 
00326     // update display
00327     setDisplayString();
00328 
00329     // inform the notification board about the removal
00330     NotificationBoard* nb = check_and_cast<NotificationBoard*> (
00331                              node-> getSubmodule("notificationBoard"));
00332     nb->fireChangeNotification(NF_OVERLAY_NODE_LEAVE);
00333 
00334     double random = uniform(0, 1);
00335     if (random < gracefulLeaveProbability) {
00336         nb->fireChangeNotification(NF_OVERLAY_NODE_GRACEFUL_LEAVE);
00337     }
00338 
00339     cMessage* msg = new cMessage();
00340     scheduleAt(simTime() + gracefulLeaveDelay, msg);
00341 }
00342 
00343 void SimpleUnderlayConfigurator::migrateNode(NodeType type, TransportAddress* addr)
00344 {
00345     Enter_Method_Silent();
00346 
00347     SimpleNodeEntry* entry = NULL;
00348 
00349     if (addr != NULL) {
00350         SimpleInfo* info =
00351               dynamic_cast<SimpleInfo*> (globalNodeList->getPeerInfo(*addr));
00352         if (info != NULL) {
00353             entry = info->getEntry();
00354         } else {
00355             opp_error("SimpleNetConfigurator: Trying to migrate node with "
00356                       "nonexistant TransportAddress!");
00357         }
00358     } else {
00359         SimpleInfo* info = dynamic_cast<SimpleInfo*> (
00360                 globalNodeList-> getRandomPeerInfo(type.typeID));
00361         entry = info->getEntry();
00362     }
00363 
00364     cGate* gate = entry->getGate();
00365     cModule* node = gate->getOwnerModule()->getParentModule();
00366 
00367     // do not migrate node that is already scheduled
00368     if (scheduledID.count(node->getId()))
00369         return;
00370 
00371     //std::cout << "migration @ " << tmp_ip << " --> " << address << std::endl;
00372 
00373     // FIXME use only IPv4?
00374     IPvXAddress address = IPAddress(nextFreeAddress++);
00375 
00376     IPvXAddress tmp_ip = IPAddressResolver().addressOf(node);
00377     SimpleNodeEntry* newentry;
00378 
00379     if (useXmlCoords) {
00380         newentry = new SimpleNodeEntry(node, cChannelType::find(
00381             channelTypes[intuniform(0, channelTypes.size() - 1)].c_str()),
00382             sendQueueLength, entry->getNodeRecord(), entry->getRecordIndex());
00383 
00384         newentry->getNodeRecord()->ip = address;
00385     } else {
00386         newentry = new SimpleNodeEntry(node, cChannelType::find(
00387             channelTypes[intuniform(0, channelTypes.size() - 1)].c_str()),
00388             fieldSize, sendQueueLength);
00389     }
00390 
00391     node->bubble("I am migrating!");
00392 
00393     //remove node from bootstrap oracle
00394     globalNodeList->killPeer(tmp_ip);
00395 
00396     SimpleUDP* simple = check_and_cast<SimpleUDP*> (gate->getOwnerModule());
00397     simple->setNodeEntry(newentry);
00398 
00399     InterfaceEntry* ie = IPAddressResolver().interfaceTableOf(node)->
00400                                       getInterfaceByName("dummy interface");
00401     delete ie->ipv4Data();
00402 
00403     // Add pseudo-Interface to node's interfaceTable
00404     IPv4InterfaceData* ifdata = new IPv4InterfaceData;
00405     ifdata->setIPAddress(address.get4());
00406     ifdata->setNetmask(IPAddress("255.255.255.255"));
00407     ie->setIPv4Data(ifdata);
00408 
00409     // create meta information
00410     SimpleInfo* newinfo = new SimpleInfo(type.typeID, node->getId());
00411     newinfo->setEntry(newentry);
00412 
00413     //add node to bootstrap oracle
00414     globalNodeList->addPeer(address, newinfo);
00415 
00416     // inform the notification board about the migration
00417     NotificationBoard* nb = check_and_cast<NotificationBoard*> (
00418                                       node->getSubmodule("notificationBoard"));
00419     nb->fireChangeNotification(NF_OVERLAY_TRANSPORTADDRESS_CHANGED);
00420 }
00421 
00422 void SimpleUnderlayConfigurator::handleTimerEvent(cMessage* msg)
00423 {
00424     Enter_Method_Silent();
00425 
00426     // get next scheduled node and remove it from the kill list
00427     IPvXAddress addr = killList.back();
00428     killList.pop_back();
00429 
00430     SimpleNodeEntry* entry = NULL;
00431 
00432     SimpleInfo* info =
00433             dynamic_cast<SimpleInfo*> (globalNodeList->getPeerInfo(addr));
00434 
00435     if (info != NULL) {
00436         entry = info->getEntry();
00437     } else {
00438         throw cRuntimeError("SimpleNetConfigurator: Trying to kill node with "
00439                             "unknown TransportAddress!");
00440     }
00441 
00442     cGate* gate = entry->getGate();
00443     cModule* node = gate->getOwnerModule()->getParentModule();
00444 
00445     if (useXmlCoords) {
00446         nodeRecordPool[entry->getRecordIndex()].second = true;
00447     }
00448 
00449     scheduledID.erase(node->getId());
00450     globalNodeList->killPeer(addr);
00451 
00452     InterfaceEntry* ie = IPAddressResolver().interfaceTableOf(node)->
00453                                          getInterfaceByName("dummy interface");
00454     delete ie->ipv4Data();
00455 
00456     node->callFinish();
00457     node->deleteModule();
00458 
00459     delete msg;
00460 }
00461 
00462 void SimpleUnderlayConfigurator::setDisplayString()
00463 {
00464     // Updates the statistics display string.
00465     char buf[80];
00466     sprintf(buf, "%i overlay terminals", overlayTerminalCount);
00467     getDisplayString().setTagArg("t", 0, buf);
00468 }
00469 
00470 void SimpleUnderlayConfigurator::finishUnderlay()
00471 {
00472     // statistics
00473     recordScalar("Terminals added", numCreated);
00474     recordScalar("Terminals removed", numKilled);
00475 
00476     if (!isInInitPhase()) {
00477         struct timeval now, diff;
00478         gettimeofday(&now, NULL);
00479         timersub(&now, &initFinishedTime, &diff);
00480         printf("Simulation time: %li.%06li\n", diff.tv_sec, diff.tv_usec);
00481     }
00482 }

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