2 # NEPI, a framework to manage network experiments
3 # Copyright (C) 2014 INRIA
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
18 # Author: Alina Quereilhac <alina.quereilhac@inria.fr>
20 from nepi.execution.attribute import Attribute, Flags, Types
21 from nepi.execution.trace import Trace, TraceAttr
22 from nepi.execution.resource import ResourceManager, clsinit_copy, \
23 ResourceState, ResourceFactory
24 from nepi.resources.linux.application import LinuxApplication
25 from nepi.util.timefuncs import tnow, tdiffsec
26 from nepi.resources.ns3.ns3simulation import NS3Simulation
27 from nepi.resources.ns3.ns3wrapper import SIMULATOR_UUID, GLOBAL_VALUE_UUID, \
28 IPV4_GLOBAL_ROUTING_HELPER_UUID
29 from nepi.resources.linux.ns3.ns3client import LinuxNS3Client
36 class LinuxNS3Simulation(LinuxApplication, NS3Simulation):
37 _rtype = "linux::ns3::Simulation"
40 def _register_attributes(cls):
41 impl_type = Attribute("simulatorImplementationType",
42 "The object class to use as the simulator implementation",
43 allowed = ["ns3::DefaultSimulatorImpl", "ns3::RealtimeSimulatorImpl"],
44 default = "ns3::DefaultSimulatorImpl",
45 type = Types.Enumerate,
48 sched_type = Attribute("schedulerType",
49 "The object class to use as the scheduler implementation",
50 allowed = ["ns3::MapScheduler",
54 "ns3::CalendarScheduler"
56 default = "ns3::MapScheduler",
57 type = Types.Enumerate,
60 check_sum = Attribute("checksumEnabled",
61 "A global switch to enable all checksums for all protocols",
66 ns_log = Attribute("nsLog",
67 "NS_LOG environment variable. " \
68 " Will only generate output if ns-3 is compiled in DEBUG mode. ",
71 verbose = Attribute("verbose",
72 "True to output debugging info from the ns3 client-server communication",
76 enable_dump = Attribute("enableDump",
77 "Enable dumping the remote executed ns-3 commands to a script "
78 "in order to later reproduce and debug the experiment",
83 build_mode = Attribute("buildMode",
84 "Mode used to build ns-3 with waf. One if: debug, release, oprimized ",
85 default = "optimized",
86 allowed = ["debug", "release", "optimized"],
87 type = Types.Enumerate,
90 ns3_version = Attribute("ns3Version",
91 "Version of ns-3 to install from nsam repo",
93 #default = "ns-3-dev",
96 pybindgen_version = Attribute("pybindgenVersion",
97 "Version of pybindgen to install from bazar repo",
100 flags = Flags.Design)
102 dce_version = Attribute("dceVersion",
103 "Version of dce to install from nsam repo (tag branch for repo)",
104 #default = "dce-1.3",
106 flags = Flags.Design)
108 populate_routing_tables = Attribute("populateRoutingTables",
109 "Invokes Ipv4GlobalRoutingHelper.PopulateRoutingTables() ",
112 flags = Flags.Design)
114 stoptime = Attribute("StopTime",
115 "Time at which the simulation will stop",
116 flags = Flags.Design)
118 cls._register_attribute(impl_type)
119 cls._register_attribute(sched_type)
120 cls._register_attribute(check_sum)
121 cls._register_attribute(ns_log)
122 cls._register_attribute(enable_dump)
123 cls._register_attribute(verbose)
124 cls._register_attribute(build_mode)
125 cls._register_attribute(ns3_version)
126 cls._register_attribute(pybindgen_version)
127 cls._register_attribute(dce_version)
128 cls._register_attribute(populate_routing_tables)
129 cls._register_attribute(stoptime)
131 def __init__(self, ec, guid):
132 LinuxApplication.__init__(self, ec, guid)
133 NS3Simulation.__init__(self)
136 self._home = "ns3-simu-%s" % self.guid
137 self._socket_name = "ns3-%s.sock" % os.urandom(4).encode('hex')
138 self._enable_dce = None
139 self._dce_helper = None
142 def socket_name(self):
143 return self._socket_name
146 def remote_socket(self):
147 return os.path.join(self.run_home, self.socket_name)
149 def trace(self, name, attr = TraceAttr.ALL, block = 512, offset = 0):
150 # stout needs to get flushed on the ns-3 server side, else we will
151 # get an empty stream. We try twice to retrieve the stream
152 # if we get empty stdout since the stream might not be
153 # flushed immediately.
154 if name.endswith("stdout"):
156 result = LinuxApplication.trace(self, name, attr, block, offset)
159 # Let the stream be flushed
162 return LinuxApplication.trace(self, name, attr, block, offset)
164 def upload_sources(self):
165 self.node.mkdir(os.path.join(self.node.src_dir, "ns3wrapper"))
167 # upload ns3 wrapper python script
168 ns3_wrapper = os.path.join(os.path.dirname(__file__), "..", "..", "ns3",
171 self.node.upload(ns3_wrapper,
172 os.path.join(self.node.src_dir, "ns3wrapper", "ns3wrapper.py"),
175 # upload ns3 wrapper debug python script
176 ns3_wrapper_debug = os.path.join(os.path.dirname(__file__), "..", "..", "ns3",
177 "ns3wrapper_debug.py")
179 self.node.upload(ns3_wrapper_debug,
180 os.path.join(self.node.src_dir, "ns3wrapper", "ns3wrapper_debug.py"),
183 # upload ns3_server python script
184 ns3_server = os.path.join(os.path.dirname(__file__), "..", "..", "ns3",
187 self.node.upload(ns3_server,
188 os.path.join(self.node.src_dir, "ns3wrapper", "ns3server.py"),
191 if self.node.use_rpm:
192 # upload pygccxml sources
193 pygccxml_tar = os.path.join(os.path.dirname(__file__), "dependencies",
194 "%s.tar.gz" % self.pygccxml_version)
196 self.node.upload(pygccxml_tar,
197 os.path.join(self.node.src_dir, "%s.tar.gz" % self.pygccxml_version),
200 # Upload user defined ns-3 sources
201 self.node.mkdir(os.path.join(self.node.src_dir, "ns-3"))
202 src_dir = os.path.join(self.node.src_dir, "ns-3")
204 super(LinuxNS3Simulation, self).upload_sources(src_dir = src_dir)
206 def upload_extra_sources(self, sources = None, src_dir = None):
207 return super(LinuxNS3Simulation, self).upload_sources(
211 def upload_start_command(self):
212 command = self.get("command")
213 env = self.get("env")
215 # We want to make sure the ccnd is running
216 # before the experiment starts.
217 # Run the command as a bash script in background,
218 # in the host ( but wait until the command has
219 # finished to continue )
220 env = self.replace_paths(env)
221 command = self.replace_paths(command)
223 shfile = os.path.join(self.app_home, "start.sh")
224 self.node.upload_command(command,
230 self._run_in_background()
232 # Wait until the remote socket is created
233 self.wait_remote_socket()
236 if self.has_changed("simulatorImplementationType"):
237 simu_type = self.get("simulatorImplementationType")
238 stype = self.create("StringValue", simu_type)
239 self.invoke(GLOBAL_VALUE_UUID, "Bind", "SimulatorImplementationType", stype)
241 if self.has_changed("checksumEnabled"):
242 check_sum = self.get("checksumEnabled")
243 btrue = self.create("BooleanValue", check_sum)
244 self.invoke(GLOBAL_VALUE_UUID, "Bind", "ChecksumEnabled", btrue)
246 if self.has_changed("schedulerType"):
247 sched_type = self.get("schedulerType")
248 stype = self.create("StringValue", sched_type)
249 self.invoke(GLOBAL_VALUE_UUID, "Bind", "SchedulerType", btrue)
252 if not self.node or self.node.state < ResourceState.READY:
253 self.debug("---- RESCHEDULING DEPLOY ---- node state %s " % self.node.state )
255 # ccnd needs to wait until node is deployed and running
256 self.ec.schedule(self.reschedule_delay, self.deploy)
258 if not self.get("command"):
259 self.set("command", self._start_command)
261 if not self.get("depends"):
262 self.set("depends", self._dependencies)
264 if self.get("sources"):
265 sources = self.get("sources")
266 source = sources.split(" ")[0]
267 basename = os.path.basename(source)
268 version = ( basename.strip().replace(".tar.gz", "")
271 .replace(".zip","") )
273 self.set("ns3Version", version)
274 self.set("sources", source)
276 if not self.get("build"):
277 self.set("build", self._build)
279 if not self.get("install"):
280 self.set("install", self._install)
282 if not self.get("env"):
283 self.set("env", self._environment)
289 self._client = LinuxNS3Client(self)
296 """ Starts simulation execution
299 self.info("Starting")
301 if self.state == ResourceState.READY:
302 if self.get("populateRoutingTables") == True:
303 self.invoke(IPV4_GLOBAL_ROUTING_HELPER_UUID, "PopulateRoutingTables")
305 time = self.get("StopTime")
307 self._client.stop(time=time)
313 msg = " Failed to execute command '%s'" % command
314 self.error(msg, out, err)
315 raise RuntimeError, msg
318 """ Stops simulation execution
321 if self.state == ResourceState.STARTED:
322 if not self.get("StopTime"):
326 def do_release(self):
327 self.info("Releasing resource")
329 tear_down = self.get("tearDown")
331 self.node.execute(tear_down)
334 self._client.shutdown()
335 LinuxApplication.do_stop(self)
337 super(LinuxApplication, self).do_release()
340 def enable_dce(self):
341 if self._enable_dce is None:
342 from nepi.resources.ns3.ns3dceapplication import NS3BaseDceApplication
343 rclass = ResourceFactory.get_resource_type(
344 NS3BaseDceApplication.get_rtype())
346 self._enable_dce = False
347 for guid in self.ec.resources:
348 rm = self.ec.get_resource(guid)
349 if isinstance(rm, rclass):
350 self._enable_dce = True
352 from nepi.resources.ns3.ns3dcehelper import NS3DceHelper
353 self._dce_helper = NS3DceHelper(self)
356 return self._enable_dce
359 def dce_helper(self):
360 return self._dce_helper
363 def _start_command(self):
366 command.append("PYTHONPATH=$PYTHONPATH:${SRC}/ns3wrapper/")
368 command.append("python ${SRC}/ns3wrapper/ns3server.py -S %s" % \
369 os.path.basename(self.remote_socket) )
371 ns_log = self.get("nsLog")
373 command.append("-L '%s'" % ns_log)
375 if self.get("enableDump"):
378 if self.get("verbose"):
381 command = " ".join(command)
385 def _dependencies(self):
386 if self.node.use_rpm:
387 return ( " gcc gcc-c++ python python-devel mercurial bzr tcpdump socat gccxml unzip")
388 elif self.node.use_deb:
389 return ( " gcc g++ python python-dev mercurial bzr tcpdump socat gccxml python-pygccxml unzip")
394 return "http://code.nsnam.org"
397 def pygccxml_version(self):
398 return "pygccxml-1.0.0"
402 return "http://code.nsnam.org/ns-3-dce"
403 #eturn "http://code.nsnam.org/epmancini/ns-3-dce"
406 def dce_version(self):
407 dce_version = self.get("dceVersion")
408 return dce_version or "dce-dev"
411 def ns3_build_location(self):
412 location = "${BIN}/ns-3/%(ns3_version)s%(dce_version)s/%(build_mode)s/build" \
414 "ns3_version": self.get("ns3Version"),
415 "dce_version": "-%s" % self.get("dceVersion") \
416 if self.enable_dce else "",
417 "build_mode": self.get("buildMode"),
424 def ns3_src_location(self):
425 location = "${SRC}/ns-3/%(ns3_version)s" \
427 "ns3_version": self.get("ns3Version"),
433 def dce_src_location(self):
434 location = "${SRC}/ns-3-dce/%(dce_version)s" \
436 "dce_version": self.get("dceVersion"),
442 def _clone_ns3_command(self):
443 source = self.get("sources")
446 clone_ns3_cmd = "hg clone %(ns3_repo)s/%(ns3_version)s %(ns3_src)s" \
448 "ns3_version": self.get("ns3Version"),
449 "ns3_repo": self.ns3_repo,
450 "ns3_src": self.ns3_src_location,
453 if source.find(".tar.gz") > -1:
455 "tar xzf ${SRC}/ns-3/%(basename)s "
456 " --strip-components=1 -C %(ns3_src)s"
458 "basename": os.path.basename(source),
459 "ns3_src": self.ns3_src_location,
461 elif source.find(".tar") > -1:
463 "tar xf ${SRC}/ns-3/%(basename)s "
464 " --strip-components=1 -C %(ns3_src)s"
466 "basename": os.path.basename(source),
467 "ns3_src": self.ns3_src_location,
469 elif source.find(".zip") > -1:
470 basename = os.path.basename(source)
471 bare_basename = basename.replace(".zip", "")
474 "unzip ${SRC}/ns-3/%(basename)s && "
475 "mv ${SRC}/ns-3/%(bare_basename)s %(ns3_src)s"
477 "bare_basename": basename_name,
478 "basename": basename,
479 "ns3_src": self.ns3_src_location,
485 def _clone_dce_command(self):
486 clone_dce_cmd = " echo 'DCE will not be built' "
489 dce_version = self.dce_version
491 if dce_version != "dce-dev":
492 dce_tag = "-r %s" % dce_version
496 # Test if dce is alredy cloned
499 " ( test -d %(dce_src)s ) "
500 " && echo 'dce binaries found, nothing to do'"
504 # Get dce source code
506 " mkdir -p %(dce_src)s && "
507 " hg clone %(dce_repo)s %(dce_tag)s %(dce_src)s"
510 "dce_repo": self.dce_repo,
512 "dce_src": self.dce_src_location,
519 # If the user defined local sources for ns-3, we uncompress the sources
520 # on the remote sources directory. Else we clone ns-3 from the official repo.
521 clone_ns3_cmd = self._clone_ns3_command
522 clone_dce_cmd = self._clone_dce_command
528 # Test if ns-3 is alredy cloned
529 " ((( test -d %(ns3_src)s ) || "
530 " ( test -d ${NS3BINDINGS:='None'} && test -d ${NS3LIBRARIES:='None'})) "
531 " && echo 'ns-3 binaries found, nothing to do' )"
534 # If not, install ns-3 and its dependencies
539 " python -c 'import pygccxml' && "
540 " echo 'pygccxml not found' "
544 " tar xf ${SRC}/%(pygccxml_version)s.tar.gz -C ${SRC} && "
545 " cd ${SRC}/%(pygccxml_version)s && "
546 " python setup.py build && "
547 " sudo -S python setup.py install "
554 " test -d ${SRC}/pybindgen/%(pybindgen_version)s && "
555 " echo 'binaries found, nothing to do' "
558 # If not, clone and build
560 " mkdir -p ${SRC}/pybindgen && "
561 " bzr checkout lp:pybindgen -r %(pybindgen_version)s ${SRC}/pybindgen/%(pybindgen_version)s && "
562 " cd ${SRC}/pybindgen/%(pybindgen_version)s && "
563 " ./waf configure && "
568 # Get ns-3 source code
570 " mkdir -p %(ns3_src)s && "
571 " %(clone_ns3_cmd)s "
577 " %(clone_dce_cmd)s "
580 "ns3_src": self.ns3_src_location,
581 "pybindgen_version": self.get("pybindgenVersion"),
582 "pygccxml_version": self.pygccxml_version,
583 "clone_ns3_cmd": clone_ns3_cmd,
584 "clone_dce_cmd": clone_dce_cmd,
590 def _install_dce_command(self):
591 install_dce_cmd = " echo 'DCE will not be installed'"
596 " ((test -d %(ns3_build)s/bin_dce ) && "
597 " echo 'dce binaries found, nothing to do' )"
601 # If not, copy build to dce
602 " cd %(dce_src)s && "
603 " rm -rf %(dce_src)s/build && "
604 " ./waf configure %(enable_opt)s --with-pybindgen=${SRC}/pybindgen/%(pybindgen_version)s "
605 " --prefix=%(ns3_build)s --with-ns3=%(ns3_build)s && "
608 " [ ! -e %(ns3_build)s/lib/python/site-packages/ns/dce.so ] && "
609 " mv %(ns3_build)s/lib*/python*/site-packages/ns/dce.so %(ns3_build)s/lib/python/site-packages/ns/ "
612 "pybindgen_version": self.get("pybindgenVersion"),
613 "enable_opt": "--enable-opt" if self.get("buildMode") == "optimized" else "",
614 "ns3_build": self.ns3_build_location,
615 "dce_src": self.dce_src_location,
618 return install_dce_cmd
622 install_dce_cmd = self._install_dce_command
625 # Test if ns-3 is alredy installed
628 " ( ( (test -d %(ns3_build)s/lib ) || "
629 " (test -d ${NS3BINDINGS:='None'} && test -d ${NS3LIBRARIES:='None'}) ) && "
630 " echo 'binaries found, nothing to do' )"
634 # If not, copy ns-3 build to bin
635 " mkdir -p %(ns3_build)s && "
636 " cd %(ns3_src)s && "
637 " rm -rf %(ns3_src)s/build && "
638 " ./waf configure -d %(build_mode)s --with-pybindgen=${SRC}/pybindgen/%(pybindgen_version)s "
639 " --prefix=%(ns3_build)s && "
642 " mv %(ns3_build)s/lib*/python* %(ns3_build)s/lib/python "
647 " %(install_dce_cmd)s "
650 "pybindgen_version": self.get("pybindgenVersion"),
651 "build_mode": self.get("buildMode"),
652 "install_dce_cmd": install_dce_cmd,
653 "ns3_build": self.ns3_build_location,
654 "ns3_src": self.ns3_src_location,
657 return install_ns3_cmd
660 def _environment(self):
662 env.append("PYTHONPATH=$PYTHONPATH:${NS3BINDINGS:=%(ns3_build)s/lib/python/site-packages}" % {
663 "ns3_build": self.ns3_build_location
665 # If NS3LIBRARIES is defined and not empty, assign its value,
666 # if not assign ns3_build_home/lib/ to NS3LIBRARIES and LD_LIBARY_PATH
667 env.append("LD_LIBRARY_PATH=${NS3LIBRARIES:=%(ns3_build)s/lib}" % {
668 "ns3_build": self.ns3_build_location
670 env.append("DCE_PATH=$NS3LIBRARIES/../bin_dce")
671 env.append("DCE_ROOT=$NS3LIBRARIES/..")
675 def replace_paths(self, command):
677 Replace all special path tags with shell-escaped actual paths.
680 .replace("${USR}", self.node.usr_dir)
681 .replace("${LIB}", self.node.lib_dir)
682 .replace("${BIN}", self.node.bin_dir)
683 .replace("${SRC}", self.node.src_dir)
684 .replace("${SHARE}", self.node.share_dir)
685 .replace("${EXP}", self.node.exp_dir)
686 .replace("${EXP_HOME}", self.node.exp_home)
687 .replace("${APP_HOME}", self.app_home)
688 .replace("${RUN_HOME}", self.run_home)
689 .replace("${NODE_HOME}", self.node.node_home)
690 .replace("${HOME}", self.node.home_dir)
691 # If NS3LIBRARIES is defined and not empty, use that value,
692 # if not use ns3_build_home/lib/
693 .replace("${BIN_DCE}", "${NS3LIBRARIES-%s/lib}/../bin_dce" % \
694 self.ns3_build_location)
697 def valid_connection(self, guid):
701 def wait_remote_socket(self):
702 """ Waits until the remote socket is created
704 command = " [ -e %s ] && echo 'DONE' " % self.remote_socket
706 for i in xrange(200):
707 (out, err), proc = self.node.execute(command, retry = 1,
710 if out.find("DONE") > -1:
713 raise RuntimeError("Remote socket not found at %s" % \