Using QualNet Part II - University Of Delaware

Transcription

Using QualNet – Part IIAdding a Custom ProtocolQualNet’s Directory StructureDirectoryContainsaddonsComponents developed as custom addons for specific customersbinExecutable and other runtime files such as DLLscontributedModels contributed by QualNet customers.dataData files for the Wireless library: antenna configurations, modulation schemes and sample terraindocumentationUser Guide, release notes, etc.guiGraphical components including icons, Java class files, and GUI configuration.includeQualNet kernel header files.interfacesCode to interface QualNet to 3rd party tools or external networks, such as HLA, STK, or IPnetworks.kernelQualNet kernel objectsQjused duringg the build process.plib3rd party software libraries used during the build process.librariesSource code for model libraries such as Developer, Multimedia & Enterprise, & Wireless.license dirLicense files and license libraries required for the build process.mainKernel source files and Makefiles.scenariosSample scenarios.2

QualNet Layered ArchitectureThe simulation is a collection of network nodes, eachwith its own protocol stack parameters and statisticsaccessible from the “Node”Node structure File include/node.hGeneral node’s infoStruct Node {:NodeAddressnodeId;/* the user-specified node identifier */:Int32globalSeed;/* seed for random number generator */Int32numNodes;/* number of nodes in the simulation */:/* Layer-specific information for the node. */:MacData**macData;// MAC llayerM D t **D tMacSwitch*switchData;// MAC switchNetworkDatanetworkData;// network layerTransportDatatransportData;// transport layerAppDataappData;// application layer:};Layer-specific info3Messages, Packets, and TimersA message is a unit defining an interactionbetween protocols and between nodes File include/message.hTwo types of messages Packets (data or control) – used forcommunication between nodesTimers – allow protocols to schedule events ina future time4

Message-Related API FunctionsMESSAGE Alloc()Allocate a message and provide it with standardevent, layer, protocol infoMESSAGE InfoAlloc()Allocate additional user-specified space foroptional information about the eventMESSAGE PacketAlloc()Allocate space for the packet within the messageMESSAGE AddHeader()Add a header to the packet (usually called byeach layer in the protocol stack)MESSAGE RemoveHeader()Remove a header from the packetMESSAGE AddVirtualPayload()Add virtual payload to a Message (increase txdelay without increasing array size)MESSAGE Duplicate()MESSAGE Duplicate()Copy the messagemessage, including its packet anduser-specified space (info field)MESSAGE Send()Send the message as an event to the specifiedlayer and protocolMESSAGE Free()Free the message, once it has reached its finaldestination5Packet Life CycleApplicationApplicationMESSAGE Free( )MESSAGE Alloc( )MESSAGE PacketAlloc( )MESSAGE Send( )TransportTransportMESSAGE RemoveHeader()MESSAGE Send( )MESSAGE AddHeader()MESSAGE Send( )RoutingIPRoutingIPMACMACMESSAGE AddHeader()MESSAGE Send( )ChannelIPMESSAGE RemoveHeader()MESSAGE Send( )MESSAGE AddHeader()MESSAGE Send( )MACMESSAGE RemoveHeader()MESSAGE Send( )ChannelChannel6

Creating MessagesA pointer to the node creatingthe messageMessage*MESSAGE Alloc(Node *node*node,The stack layer at which this messagewill be processed nexte.g., NETWORK LAYERint layerType,int protocol,The specific protocol at the layerwhich will process this messagee.g., ROUTING PROTOCOL DSRint eventType);The event that this messageg representspe.g., MSG NETWORK FlushTables7Message ProcessingHandling functionfor tCheck eventType fieldIPDSRnewMsg AODVCheck protocolType fieldRadioMACNetworkTransportAppCheck layerType fieldEvent queuemsg8

QualNet’s Protocol ModelingInitialization Function Allocate memory for each node’slocal variables Initialize local variables Process configuration file(s) Schedule the first eventPacket arrival ortimer expirationIdleMessage (packet or timer)processing function Modify state variables Update local statistics Generate/forwardGt /fd packetsk tFinalization Function Output statistics9Adding a Protocol to QualNetDetermine what layer your protocol willoperate atImplement four/fiveffmain ffunctions Initialization functionPacket/event handling functionsRouter function (for routing protocol)Finalization functionHook up the above functions to theprotocol dispatching functions of thecorresponding layer10

Example: Adding a New Routing ProtocolSimplified Routing Information Protocol(SRIP) Table-driven, distance vector protocolUsing periodic route update, no triggeredupdate, no split horizonWorking properly in static networks with onlya small number of nodes ((no node failure))Supporting only one interface (wireless) pernode11Distributed Bellman-Ford AlgorithmWhat local information is maintained by each node?Initial routing table for ARouting Table)DestinationNext hopCostDestinationNext hop:::AA0B- :- CostWhat information is exchanged between neighboringnodes?)Route AdvertisementDestinationCost::How a node processes a route advertisement? Node A updates its entry for destination D only when theadvertised cost to D is lower than its current cost12

SRIP Header File (routing srip.h)#ifndef SRIP H#define SRIP H#define SRIP INFINITY16typedef struct srip table entry{NodeAddress destination;NodeAddress nextHop;unsigned int distance;} SripTableEntry;Routing table entrytypedef struct srip str{clocktypeupdateInterval;SripTableEntry* routingTable;Local SRIP variables per nodes/* statistic */unsigned int numRouteUpdatesBroadcast;} SripData;void SripInit(Node* node, SripData** sripPtr,const NodeInput* nodeInput, int interfaceIndex);Function prototypes to be recognizedvoid SripHandleProtocolEvent(Node* node, Message* msg);void SripHandleProtocolPacket(Node* node, Message* msg,by QualNet’s network layer (IP)NodeAddress sourceAddress);void SripFinalize(Node *node);void SripRouterFunction(Node* node, Message* msg, NodeAddress destAddr,NodeAddress previousHopAddress, BOOL* packetWasRouted);#endif13SRIP Initialization FunctionCalled when each node is initialized by QualNetvoid SripInit(Node*SripData**const NodeInputNodeInput*int{int i; BOOL retVal;Message* newMsg;SripData* x)if (MAC IsWiredNetwork(node, interfaceIndex))ERROR ReportError("SRIP supports only wireless interfaces");Make sure the node has exactlyone wireless interfaceif (node- numberInterfaces 1)ERROR ReportError("SRIP only supports one interface of node");/* allocate memory for SRIP's variables for this node */srip (SripData*) MEM malloc(sizeof(SripData));( sripPtr) srip;(*sripPtr)/* read parameter from the configuration file */IO ReadTime(node- nodeId,ANY (srip- updateInterval));if (retVal FALSE)ERROR ReportError("SRIP-UPDATE-INTERVAL not specified!");Allocate memory for local SRIPvariables within each nodeRead SRIP parameterfrom the main config file(to be continued)14

SRIP Initialization Function(continued)/* allocate and initialize the routing table for this node *//* Note: (n 1) entries are allocated for convenience*/srip- routingTable (SripTableEntry*)MEM malloc(sizeof(SripTableEntry)*(node- numNodes 1));for (i 1; i nodenode- numNodes; numNodes; i ) {srip- routingTable[i].destination i;srip- routingTable[i].nextHop INVALID ADDRESS;srip- routingTable[i].distance SRIP INFINITY;}srip- routingTable[node- nodeId].nextHop node- nodeId;srip- routingTable[node- nodeId].distance 0;Initialize routing table/* Initialize statistic */srip- numRouteUpdatesBroadcast 0;Initialize statistic/* Tell IP to use our function to route packets ion,interfaceIndex);Register routerfunction with IP/* schedule the very first route update broadcast*//* after a random delay of 0 srip- updateInterval-1 */newMsg MESSAGE Alloc(node, NETWORK LAYER,ROUTING PROTOCOL SRIP, MSG NETWORK RTBroadcastAlarm);RandomSeed startupSeed;RANDOM SetSeed(startupSeed, node- globalSeed, node- nodeId,ROUTING PROTOCOL SRIP, interface);clocktype delay RANDOM nrand(startupSeed)%srip- updateInterval;MESSAGE Send(node, newMsg, pc nrand(node- seed)%srip- updateInterval);Schedule the first routeadvertisement timer}15SRIP Event Handling FunctionCalled when a node’s timer expiresvoid SripHandleProtocolEvent(Node* node, Message* msg){int i, numEntries 0, pktSize;Message* newMsg;char*pktPtr;/* Obtain a pointer to the local variable space */SripData* srip (SripData*)NetworkIpGetRoutingProtocol(node, ROUTING PROTOCOL SRIP);Obtain pointer to localvariable spacefor (i 1; i node- numNodes; i ) {if (srip- routingTable[i].distance SRIP INFINITY)numEntries ;}Count the number ofvalid entriesnewMsg MESSAGE Alloc(node, 0, 0, 0);pktSize sizeof(unsigned int) tries;numEntries;MESSAGE PacketAlloc(node, newMsg, pktSize, TRACE ANY PROTOCOL);pktPtr newMsg- packet;memcpy(pktPtr, &numEntries, sizeof(unsigned int)); /* number of entries */pktPtr sizeof(unsigned int);Prepare a routepacket/* Fill the packet with the valid table entries */advertisementfor (i 1; i node- numNodes; i ) {if (srip- routingTable[i].distance SRIP INFINITY) {memcpy(pktPtr, &(srip- routingTable[i]), sizeof(SripTableEntry));pktPtr sizeof(SripTableEntry);}(to be continued)}16

SRIP Event Handling Function(continued)/* Send the route update packet to MAC layer */NetworkIpSendRawMessageToMacLayer(node,/* node pointer *//* raw message */newMsg,node- nodeId,/* source address */ANY DEST,/* destination address */0,/* priority for CONTROL packet */IPPROTO SRIP,/* IP Protocol */1,/* TTL */DEFAULT INTERFACE, /* output interface */ANY DEST);/* next hop address */Ask IP to add header andsend packet to MAC layer/* update statistic */srip- numRouteUpdatesBroadcast ;Update local statistic/* schedule the next route update broadcast*/Schedule the next/* after a fixed delay of srip- updateIntervalsrip updateInterval */b dbroadcasteventnewMsg MESSAGE Alloc(node, NETWORK LAYER,ROUTING PROTOCOL SRIP, MSG NETWORK RTBroadcastAlarm);MESSAGE Send(node, newMsg, srip- updateInterval);/* Free old message after being processed */MESSAGE Free(node, msg);Free the old message}17SRIP Packet Handling FunctionCalled when a node receives a route advertisementvoid eAddress sourceAddress){SripData* srip (SripData*)NetworkIpGetRoutingProtocol(node, ROUTING PROTOCOL SRIP);int i, numEntries;char *pktPtr;SripTableEntry entry;Obtain pointer to localpvariable spacePacket format#entries 1st entry 2nd entry pktPtr msg- packet;memcpy(&numEntries, pktPtr, sizeof(unsigned int));pktPtr sizeof(unsigned int);/* scan the entry list and update routing table only with entries with* shorter distance */for (i 0; i numEntries; i ){memcpy(&entry, pktPtr, sizeof(SripTableEntry));entry.distance ;if (entry.distance srip- routingTable[entry.destination].distance) {srip- routingTable[entry.destination].distance entry.distance;srip- routingTable[entry.destination].nextHop sourceAddress;}pktPtr sizeof(SripTableEntry);}MESSAGE Free(node, msg);}Free the message since this is itsfinal destination18

SRIP Router FunctionCalled when IP layer receives a data packet fromMAC or transport layervoid ss destAddr,NodeAddress ype *ipHeader (IpHeaderType *) msg- packet;/* Obtain a pointer to the local variable space */SripData* srip (SripData*)NetworkIpGetRoutingProtocol(node, ROUTING PROTOCOL SRIP);Ignore SRIP packetspacketsand myy own p/* do not route any SRIP packet, or any packets destined to myself */if (ipHeader- ip p IPPROTO SRIP ipHeader- ip dst node- nodeId)return;/* route the packet only when the destination is considered reachable */if (srip- routingTable[ipHeader- ip dst].distance SRIP INFINITY){*packetWasRouted T INTERFACE,srip- routingTable[ipHeader- ip dst].nextHop);}Route the packet ifthe destination isreachable}19SRIP Finalizing FunctionCalled at each node when QualNet isterminatingvoid SripFinalize(Node *node){char buf[MAX STRING LENGTH];/* Obtain a pointer to the local variable space */SripData* srip (SripData*)NetworkIpGetRoutingProtocol(node, ROUTING PROTOCOL SRIP);sprintf(buf, "Number of Route Updates Broadcast %u",srip- numRouteUpdatesBroadcast);IO PrintStat(node, "Network", "SRIP", ANY DEST, -1, buf);Report statistic}20

Make SRIP Recognized by QualNetLet QualNet know SRIP as a network layerprotocol In the file include/network.htypedefenum{NETWORK PROTOCOL IP 0,NETWORK PROTOCOL IPv6,NETWORK PROTOCOL MOBILE IP,::ROUTING PROTOCOL AODV6,ROUTING PROTOCOL AODV6ROUTING PROTOCOL DYMO,ROUTING PROTOCOL DYMO6,ROUTING PROTOCOL SRIP}NetworkRoutingProtocolType;21Make SRIP Recognized by QualNetLet IP module know SRIP as an IP protocol In the filelibraries/developer/src/network ip.h//// IP protocol numbers for network- and transport-layer protocols.//// /**// CONSTANT:: IPPROTO IP : 0// DESCRIPTION :: IP protocol numbers.// **/#ifndef IPPROTO IP#defineIPPROTO IP#d fiIPPROTOIP 0#endif://StartIARP#define IPPROTO IARP254//EndIARP//InsertPatch ROUTING IPPROTO#define IPPROTO SRIP:21122

Make SRIP Recognized by QualNetHave IP module recognize the five entryfunctions of SRIP Have thHthe filfilelibraries/developer/src/network ip.cppinclude routing srip.h#include stdio.h #include stdlib.h #include string.h #include math.h :://InsertPatch HEADER FILES#include “routing srip.h“:23Make SRIP Recognized by QualNetHave IP initialize SRIP if specified in the configuration file In the file network ip.cpp, function NetworkIpInit()p(, const NodeInputpp )void NetworkIpInit(Node*node,*nodeInput){NetworkDataIp *ip (NetworkDataIp *) node- networkData.networkVar;:if (NetworkIpGetInterfaceType(node, i) NETWORK IPV4) {IO ReadString(node- nodeId,NetworkIpGetInterfaceAddress(node, ring);}:if (retVal){://InsertPatch NETWORK INIT CODENETWORK INIT CODEelseif (strcmp(protocolString, "SRIP") 0) {NetworkIpAddUnicastRoutingProtocolType(node, ROUTING PROTOCOL SRIP, i);if (!NetworkIpGetRoutingProtocol(node, ROUTING PROTOCOL SRIP)) {SripInit(node,SripData **) &ip- interfaceInfo[i]- routingProtocol,nodeInput, i);}else ction(node, ROUTING PROTOCOL SRIP, i);}}:24

Make SRIP Recognized by QualNetWhen the network layer receives an event for SRIP,dispatch it to SRIP’s event handling function In the file network ip.cpp,network ip.cpp, function NetworkIpLayer()voidNetworkIpLayer(Node *node, Message *msg){switch (msg- protocolType){:case ROUTING PROTOCOL ALL:{ERROR Assert(FALSE, "IP event error");//HandleSpecialMacLayerStatusEvents(node, msg);break;}//InsertPatch NETWORK IP LAYERcase ROUTING PROTOCOL SRIP:{SripHandleProtocolEvent(node, msg);break;}:25Make SRIP Recognized by QualNetWhen IP receives an SRIP route advertisement packet,dispatch it to SRIP’s packet handling function In the file network ip.cpp,network ip.cpp, function DeliverPacket()static void //inline//DeliverPacket(Node *node, Message *msg,int interfaceIndex, NodeAddress previousHopAddress){:ipHeader (IpHeaderType *) msg- packet;ipProtocolNumber ipHeader- ip p;:switch (ipProtocolNumber){://InsertPatch NETWORK HANDLE PACKETNETWORK HANDLE PACKETcase IPPROTO ess);break;}:26

Make SRIP Recognized by QualNetCall SRIP’s finalizing function when IP is terminating In the file network ip.cpp, function NetworkIpFinalize()voidNetworkIpFinalize(Node *node){NetworkDataIp *ip (NetworkDataIp *) node- networkData.networkVar;:for (i 0; i node- numberInterfaces; i ){switch (NetworkIpGetUnicastRoutingProtocolType(node, i)){case MULTICAST PROTOCOL ;}://InsertPatch FINALIZE FUNCTIONcase ROUTING PROTOCOL SRIP:{SripFinalize(node);break;}:27Compiling QualNet with SRIPPut SRIP source files (routing srip.h/cpp) intothe directory libraries/developer/src/Edit libraries/developer/Makefile-commonEdi Add routing srip.cpp to DEVELOPER SRCSmacro as the following:# common sources#DEVELOPER SRCS \ (DEVELOPER SRCDIR)/adaptation aal5.cpp \ (DEVELOPER SRCDIR)/adaptation.cpp \: (DEVELOPER SRCDIR)/routing ripng.cpp \ (DEVELOPER SRCDIR)/routing srip.cpp \ (DEVELOPER SRCDIR)/routing static.cpp \:28

Compiling QualNet with SRIPRebuild header dependencies:cd QUALNET QUALNET HOME/mainHOME/mainmake dependRebuild QualNet executable:make29Creating a configuration file for SRIPIn QUALNET HOME/bin directory, copydefault.config into srip.config, thenmodify/add the following parameters:EXPERIMENT-NAME srip:ROUTING-PROTOCOL SRIPSRIP-UPDATE-INTERVAL 10S:30

Testing the ProtocolIn QUALNET HOME/bin directory, run qualneton the SRIP configuration file:cd QUALNET HOME/bin./qualnet srip.configCheck srip.stat file to find SRIP’s statisticsFor complete codes and instructions, refer gramming TipsMESSAGE Free() must be called only once per messageFilling data into a packet or a packet header can be tricky A fieldfi ld may span across a wordd boundary,bdcausingi ‘busb error’ inisome systemsUse memcpy() instead of an assignment operation (i.e., )Use message’s info field to carry extra informationinternally (within the same node)Add constants to the end of lists in header files (butbefore the “placeholder”)A good way to learn QualNet is to study the provided codeof another simple/similar protocols32

include QualNet kernel header files. interfaces Code to interface QualNet to 3rd party tools or external networks, such as HLA, STK, or IP networks. kernel QualNet kernel ob jects used during the build process. 2 Qj gp lib 3rd party software libraries used during the build process.