examples/flowmon.py
author Gustavo J. A. M. Carneiro <gjc@inescporto.pt>
Mon May 11 17:43:35 2009 +0100 (2009-05-11)
changeset 3975 9e833fd91f0d
parent 3969 a7a41ad7f52e
permissions -rw-r--r--
Add APIs to easily serialize FlowMonitor results to XML
     1 # -*-  Mode: Python; -*-
     2 #  Copyright (c) 2009 INESC Porto
     3 # 
     4 #  This program is free software; you can redistribute it and/or modify
     5 #  it under the terms of the GNU General Public License version 2 as
     6 #  published by the Free Software Foundation;
     7 # 
     8 #  This program is distributed in the hope that it will be useful,
     9 #  but WITHOUT ANY WARRANTY; without even the implied warranty of
    10 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    11 #  GNU General Public License for more details.
    12 # 
    13 #  You should have received a copy of the GNU General Public License
    14 #  along with this program; if not, write to the Free Software
    15 #  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
    16 # 
    17 #  Authors: Gustavo Carneiro <gjc@inescporto.pt>
    18 
    19 import sys
    20 import ns3
    21 
    22 DISTANCE = 150 # (m)
    23 NUM_NODES_SIDE = 3
    24 
    25 def main(argv):
    26 
    27     cmd = ns3.CommandLine()
    28 
    29     cmd.Viz = None
    30     cmd.AddValue("Viz", "Enable visualizer")
    31 
    32     cmd.NumNodesSide = None
    33     cmd.AddValue("NumNodesSide", "Grid side number of nodes (total number of nodes will be this number squared)")
    34 
    35     cmd.Results = None
    36     cmd.AddValue("Results", "Write XML results to file")
    37 
    38     cmd.Parse(argv)
    39 
    40     ns3.RandomVariable.UseGlobalSeed(1, 1, 2, 3, 5, 8)
    41 
    42     #ns3.Config.SetDefault("ns3::Ipv4L3Protocol::CalcChecksum", ns3.BooleanValue(True))
    43 
    44     channel = ns3.WifiChannel()
    45     channel.SetPropagationDelayModel(ns3.ConstantSpeedPropagationDelayModel())
    46     log = ns3.LogDistancePropagationLossModel()
    47     log.SetReferenceModel(ns3.FriisPropagationLossModel())
    48     channel.SetPropagationLossModel(log)
    49 
    50     wifi = ns3.WifiHelper()
    51     wifi.SetMac("ns3::AdhocWifiMac")
    52     wifi.SetPhy("ns3::WifiPhy");
    53     wifi.SetRemoteStationManager ("ns3::ArfWifiManager");
    54 
    55     internet = ns3.InternetStackHelper()
    56     ipv4Addresses = ns3.Ipv4AddressHelper()
    57     ipv4Addresses.SetBase(ns3.Ipv4Address("10.0.0.0"), ns3.Ipv4Mask("255.255.255.255"))
    58     
    59     olsrHelper = ns3.OlsrHelper()
    60 
    61     port = 9   # Discard port(RFC 863)
    62     onOffHelper = ns3.OnOffHelper("ns3::UdpSocketFactory",
    63                                   ns3.Address(ns3.InetSocketAddress(ns3.Ipv4Address("10.0.0.1"), port)))
    64     onOffHelper.SetAttribute("DataRate", ns3.DataRateValue(ns3.DataRate("100kbps")))
    65     onOffHelper.SetAttribute("OnTime", ns3.RandomVariableValue(ns3.ConstantVariable(1)))
    66     onOffHelper.SetAttribute("OffTime", ns3.RandomVariableValue(ns3.ConstantVariable(0)))
    67 
    68     addresses = []
    69     nodes = []
    70 
    71     if cmd.NumNodesSide is None:
    72         num_nodes_side = NUM_NODES_SIDE
    73     else:
    74         num_nodes_side = int(cmd.NumNodesSide)
    75 
    76     for xi in range(num_nodes_side):
    77         for yi in range(num_nodes_side):
    78 
    79             node = ns3.Node()
    80             nodes.append(node)
    81 
    82             internet.Install(ns3.NodeContainer(node))
    83 
    84             mobility = ns3.StaticMobilityModel()
    85             mobility.SetPosition(ns3.Vector(xi*DISTANCE, yi*DISTANCE, 0))
    86             node.AggregateObject(mobility)
    87             
    88             devices = wifi.Install(ns3.NodeContainer(node), channel)
    89             ipv4_interfaces = ipv4Addresses.Assign(devices)
    90             addresses.append(ipv4_interfaces.GetAddress(0))
    91             
    92             olsrHelper.Install(ns3.NodeContainer(node))
    93 
    94     for i, node in enumerate(nodes):
    95         destaddr = addresses[(len(addresses) - 1 - i) % len(addresses)]
    96         #print i, destaddr
    97         onOffHelper.SetAttribute("Remote", ns3.AddressValue(ns3.InetSocketAddress(destaddr, port)))
    98         app = onOffHelper.Install(ns3.NodeContainer(node))
    99         app.Start(ns3.Seconds(ns3.UniformVariable(20, 30).GetValue()))
   100             
   101     #internet.EnablePcapAll("wifi-olsr")
   102     flowmon_helper = ns3.FlowMonitorHelper()
   103     #flowmon_helper.SetMonitorAttribute("StartTime", ns3.TimeValue(ns3.Seconds(31)))
   104     monitor = flowmon_helper.InstallAll()
   105     monitor.SetAttribute("DelayBinWidth", ns3.DoubleValue(0.001))
   106     monitor.SetAttribute("JitterBinWidth", ns3.DoubleValue(0.001))
   107     monitor.SetAttribute("PacketSizeBinWidth", ns3.DoubleValue(20))
   108 
   109     ns3.Simulator.Stop(ns3.Seconds(44.0))
   110     if cmd.Viz is not None:
   111         import visualizer
   112         visualizer.start()
   113     else:
   114         ns3.Simulator.Run()
   115 
   116     def print_stats(os, st):
   117         print >> os, "  Tx Bytes: ", st.txBytes
   118         print >> os, "  Rx Bytes: ", st.rxBytes
   119         print >> os, "  Tx Packets: ", st.txPackets
   120         print >> os, "  Rx Packets: ", st.rxPackets
   121         print >> os, "  Lost Packets: ", st.lostPackets
   122         if st.rxPackets > 0:
   123             print >> os, "  Mean{Delay}: ", (st.delaySum.GetSeconds() / st.rxPackets)
   124 	    print >> os, "  Mean{Jitter}: ", (st.jitterSum.GetSeconds() / (st.rxPackets-1))
   125             print >> os, "  Mean{Hop Count}: ", float(st.timesForwarded) / st.rxPackets + 1
   126 
   127         if 1:
   128             print >> os, "Delay Histogram"
   129             for i in range(st.delayHistogram.GetNBins () ):
   130               print >> os, " ",i,"(", st.delayHistogram.GetBinStart (i), "-", \
   131                   st.delayHistogram.GetBinEnd (i), "): ", st.delayHistogram.GetBinCount (i)
   132             print >> os, "Jitter Histogram"
   133             for i in range(st.jitterHistogram.GetNBins () ):
   134               print >> os, " ",i,"(", st.jitterHistogram.GetBinStart (i), "-", \
   135                   st.jitterHistogram.GetBinEnd (i), "): ", st.jitterHistogram.GetBinCount (i)
   136             print >> os, "PacketSize Histogram"
   137             for i in range(st.packetSizeHistogram.GetNBins () ):
   138               print >> os, " ",i,"(", st.packetSizeHistogram.GetBinStart (i), "-", \
   139                   st.packetSizeHistogram.GetBinEnd (i), "): ", st.packetSizeHistogram.GetBinCount (i)
   140 
   141         for reason, drops in enumerate(st.packetsDropped):
   142             print "  Packets dropped by reason %i: %i" % (reason, drops)
   143         #for reason, drops in enumerate(st.bytesDropped):
   144         #    print "Bytes dropped by reason %i: %i" % (reason, drops)
   145 
   146     monitor.CheckForLostPackets()
   147     classifier = flowmon_helper.GetClassifier()
   148 
   149     if cmd.Results is None:
   150         for flow_id, flow_stats in monitor.GetFlowStats():
   151             t = classifier.FindFlow(flow_id)
   152             proto = {6: 'TCP', 17: 'UDP'} [t.protocol]
   153             print "FlowID: %i (%s %s/%s --> %s/%i)" % \
   154                 (flow_id, proto, t.sourceAddress, t.sourcePort, t.destinationAddress, t.destinationPort)
   155             print_stats(sys.stdout, flow_stats)
   156     else:
   157         print monitor.SerializeToXmlFile(cmd.Results, True, True)
   158 
   159 
   160     return 0
   161 
   162 
   163 if __name__ == '__main__':
   164     sys.exit(main(sys.argv))
   165