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 version 2 as
7 # published by the Free Software Foundation;
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
14 # You should have received a copy of the GNU General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
17 # Author: Alina Quereilhac <alina.quereilhac@inria.fr>
19 from nepi.execution.attribute import Attribute, Flags, Types
20 from nepi.execution.trace import Trace, TraceAttr
21 from nepi.execution.resource import ResourceManager, clsinit_copy, \
22 ResourceState, ResourceFactory
23 from nepi.resources.linux.application import LinuxApplication
24 from nepi.util.timefuncs import tnow, tdiffsec
25 from nepi.resources.ns3.ns3simulation import NS3Simulation
26 from nepi.resources.ns3.ns3wrapper import SIMULATOR_UUID, GLOBAL_VALUE_UUID, \
27 IPV4_GLOBAL_ROUTING_HELPER_UUID
28 from nepi.resources.linux.ns3.ns3client import LinuxNS3Client
35 class LinuxNS3Simulation(LinuxApplication, NS3Simulation):
36 _rtype = "linux::ns3::Simulation"
39 def _register_attributes(cls):
40 impl_type = Attribute("simulatorImplementationType",
41 "The object class to use as the simulator implementation",
42 allowed = ["ns3::DefaultSimulatorImpl", "ns3::RealtimeSimulatorImpl"],
43 default = "ns3::DefaultSimulatorImpl",
44 type = Types.Enumerate,
47 sched_type = Attribute("schedulerType",
48 "The object class to use as the scheduler implementation",
49 allowed = ["ns3::MapScheduler",
53 "ns3::CalendarScheduler"
55 default = "ns3::MapScheduler",
56 type = Types.Enumerate,
59 check_sum = Attribute("checksumEnabled",
60 "A global switch to enable all checksums for all protocols",
65 ns_log = Attribute("nsLog",
66 "NS_LOG environment variable. " \
67 " Will only generate output if ns-3 is compiled in DEBUG mode. ",
70 verbose = Attribute("verbose",
71 "True to output debugging info from the ns3 client-server communication",
75 enable_dump = Attribute("enableDump",
76 "Enable dumping the remote executed ns-3 commands to a script "
77 "in order to later reproduce and debug the experiment",
82 build_mode = Attribute("buildMode",
83 "Mode used to build ns-3 with waf. One if: debug, release, oprimized ",
84 default = "optimized",
85 allowed = ["debug", "release", "optimized"],
86 type = Types.Enumerate,
89 ns3_version = Attribute("ns3Version",
90 "Version of ns-3 to install from nsam repo",
92 #default = "ns-3-dev",
95 pybindgen_version = Attribute("pybindgenVersion",
96 "Version of pybindgen to install from bazar repo",
101 dce_version = Attribute("dceVersion",
102 "Version of dce to install from nsam repo (tag branch for repo)",
103 #default = "dce-1.3",
105 flags = Flags.Design)
107 populate_routing_tables = Attribute("populateRoutingTables",
108 "Invokes Ipv4GlobalRoutingHelper.PopulateRoutingTables() ",
111 flags = Flags.Design)
113 stoptime = Attribute("StopTime",
114 "Time at which the simulation will stop",
115 flags = Flags.Design)
117 cls._register_attribute(impl_type)
118 cls._register_attribute(sched_type)
119 cls._register_attribute(check_sum)
120 cls._register_attribute(ns_log)
121 cls._register_attribute(enable_dump)
122 cls._register_attribute(verbose)
123 cls._register_attribute(build_mode)
124 cls._register_attribute(ns3_version)
125 cls._register_attribute(pybindgen_version)
126 cls._register_attribute(dce_version)
127 cls._register_attribute(populate_routing_tables)
128 cls._register_attribute(stoptime)
130 def __init__(self, ec, guid):
131 LinuxApplication.__init__(self, ec, guid)
132 NS3Simulation.__init__(self)
135 self._home = "ns3-simu-%s" % self.guid
136 self._socket_name = "ns3-%s.sock" % os.urandom(4).encode('hex')
137 self._enable_dce = None
138 self._dce_helper = None
141 def socket_name(self):
142 return self._socket_name
145 def remote_socket(self):
146 return os.path.join(self.run_home, self.socket_name)
148 def trace(self, name, attr = TraceAttr.ALL, block = 512, offset = 0):
149 # stout needs to get flushed on the ns-3 server side, else we will
150 # get an empty stream. We try twice to retrieve the stream
151 # if we get empty stdout since the stream might not be
152 # flushed immediately.
153 if name.endswith("stdout"):
155 result = LinuxApplication.trace(self, name, attr, block, offset)
158 # Let the stream be flushed
161 return LinuxApplication.trace(self, name, attr, block, offset)
163 def upload_sources(self):
164 self.node.mkdir(os.path.join(self.node.src_dir, "ns3wrapper"))
166 # upload ns3 wrapper python script
167 ns3_wrapper = os.path.join(os.path.dirname(__file__), "..", "..", "ns3",
170 self.node.upload(ns3_wrapper,
171 os.path.join(self.node.src_dir, "ns3wrapper", "ns3wrapper.py"),
174 # upload ns3 wrapper debug python script
175 ns3_wrapper_debug = os.path.join(os.path.dirname(__file__), "..", "..", "ns3",
176 "ns3wrapper_debug.py")
178 self.node.upload(ns3_wrapper_debug,
179 os.path.join(self.node.src_dir, "ns3wrapper", "ns3wrapper_debug.py"),
182 # upload ns3_server python script
183 ns3_server = os.path.join(os.path.dirname(__file__), "..", "..", "ns3",
186 self.node.upload(ns3_server,
187 os.path.join(self.node.src_dir, "ns3wrapper", "ns3server.py"),
190 if self.node.use_rpm:
191 # upload pygccxml sources
192 pygccxml_tar = os.path.join(os.path.dirname(__file__), "dependencies",
193 "%s.tar.gz" % self.pygccxml_version)
195 self.node.upload(pygccxml_tar,
196 os.path.join(self.node.src_dir, "%s.tar.gz" % self.pygccxml_version),
199 # Upload user defined ns-3 sources
200 self.node.mkdir(os.path.join(self.node.src_dir, "ns-3"))
201 src_dir = os.path.join(self.node.src_dir, "ns-3")
203 super(LinuxNS3Simulation, self).upload_sources(src_dir = src_dir)
205 def upload_extra_sources(self, sources = None, src_dir = None):
206 return super(LinuxNS3Simulation, self).upload_sources(
210 def upload_start_command(self):
211 command = self.get("command")
212 env = self.get("env")
214 # We want to make sure the ccnd is running
215 # before the experiment starts.
216 # Run the command as a bash script in background,
217 # in the host ( but wait until the command has
218 # finished to continue )
219 env = self.replace_paths(env)
220 command = self.replace_paths(command)
222 shfile = os.path.join(self.app_home, "start.sh")
223 self.node.upload_command(command,
229 self._run_in_background()
231 # Wait until the remote socket is created
232 self.wait_remote_socket()
235 if self.has_changed("simulatorImplementationType"):
236 simu_type = self.get("simulatorImplementationType")
237 stype = self.create("StringValue", simu_type)
238 self.invoke(GLOBAL_VALUE_UUID, "Bind", "SimulatorImplementationType", stype)
240 if self.has_changed("checksumEnabled"):
241 check_sum = self.get("checksumEnabled")
242 btrue = self.create("BooleanValue", check_sum)
243 self.invoke(GLOBAL_VALUE_UUID, "Bind", "ChecksumEnabled", btrue)
245 if self.has_changed("schedulerType"):
246 sched_type = self.get("schedulerType")
247 stype = self.create("StringValue", sched_type)
248 self.invoke(GLOBAL_VALUE_UUID, "Bind", "SchedulerType", btrue)
251 if not self.node or self.node.state < ResourceState.READY:
252 self.debug("---- RESCHEDULING DEPLOY ---- node state %s " % self.node.state )
254 # ccnd needs to wait until node is deployed and running
255 self.ec.schedule(self.reschedule_delay, self.deploy)
257 if not self.get("command"):
258 self.set("command", self._start_command)
260 if not self.get("depends"):
261 self.set("depends", self._dependencies)
263 if self.get("sources"):
264 sources = self.get("sources")
265 source = sources.split(" ")[0]
266 basename = os.path.basename(source)
267 version = ( basename.strip().replace(".tar.gz", "")
270 .replace(".zip","") )
272 self.set("ns3Version", version)
273 self.set("sources", source)
275 if not self.get("build"):
276 self.set("build", self._build)
278 if not self.get("install"):
279 self.set("install", self._install)
281 if not self.get("env"):
282 self.set("env", self._environment)
288 self._client = LinuxNS3Client(self)
295 """ Starts simulation execution
298 self.info("Starting")
300 if self.state == ResourceState.READY:
301 if self.get("populateRoutingTables") == True:
302 self.invoke(IPV4_GLOBAL_ROUTING_HELPER_UUID, "PopulateRoutingTables")
304 time = self.get("StopTime")
306 self._client.stop(time=time)
312 msg = " Failed to execute command '%s'" % command
313 self.error(msg, out, err)
314 raise RuntimeError, msg
317 """ Stops simulation execution
320 if self.state == ResourceState.STARTED:
321 if not self.get("StopTime"):
325 def do_release(self):
326 self.info("Releasing resource")
328 tear_down = self.get("tearDown")
330 self.node.execute(tear_down)
333 self._client.shutdown()
334 LinuxApplication.do_stop(self)
336 super(LinuxApplication, self).do_release()
339 def enable_dce(self):
340 if self._enable_dce is None:
341 from nepi.resources.ns3.ns3dceapplication import NS3BaseDceApplication
342 rclass = ResourceFactory.get_resource_type(
343 NS3BaseDceApplication.get_rtype())
345 self._enable_dce = False
346 for guid in self.ec.resources:
347 rm = self.ec.get_resource(guid)
348 if isinstance(rm, rclass):
349 self._enable_dce = True
351 from nepi.resources.ns3.ns3dcehelper import NS3DceHelper
352 self._dce_helper = NS3DceHelper(self)
355 return self._enable_dce
358 def dce_helper(self):
359 return self._dce_helper
362 def _start_command(self):
365 command.append("PYTHONPATH=$PYTHONPATH:${SRC}/ns3wrapper/")
367 command.append("python ${SRC}/ns3wrapper/ns3server.py -S %s" % \
368 os.path.basename(self.remote_socket) )
370 ns_log = self.get("nsLog")
372 command.append("-L '%s'" % ns_log)
374 if self.get("enableDump"):
377 if self.get("verbose"):
380 command = " ".join(command)
384 def _dependencies(self):
385 if self.node.use_rpm:
386 return ( " gcc gcc-c++ python python-devel mercurial bzr tcpdump socat gccxml unzip")
387 elif self.node.use_deb:
388 return ( " gcc g++ python python-dev mercurial bzr tcpdump socat gccxml python-pygccxml unzip")
393 return "http://code.nsnam.org"
396 def pygccxml_version(self):
397 return "pygccxml-1.0.0"
401 return "http://code.nsnam.org/ns-3-dce"
402 #eturn "http://code.nsnam.org/epmancini/ns-3-dce"
405 def dce_version(self):
406 dce_version = self.get("dceVersion")
407 return dce_version or "dce-dev"
410 def ns3_build_location(self):
411 location = "${BIN}/ns-3/%(ns3_version)s%(dce_version)s/%(build_mode)s/build" \
413 "ns3_version": self.get("ns3Version"),
414 "dce_version": "-%s" % self.get("dceVersion") \
415 if self.enable_dce else "",
416 "build_mode": self.get("buildMode"),
423 def ns3_src_location(self):
424 location = "${SRC}/ns-3/%(ns3_version)s" \
426 "ns3_version": self.get("ns3Version"),
432 def dce_src_location(self):
433 location = "${SRC}/ns-3-dce/%(dce_version)s" \
435 "dce_version": self.get("dceVersion"),
441 def _clone_ns3_command(self):
442 source = self.get("sources")
445 clone_ns3_cmd = "hg clone %(ns3_repo)s/%(ns3_version)s %(ns3_src)s" \
447 "ns3_version": self.get("ns3Version"),
448 "ns3_repo": self.ns3_repo,
449 "ns3_src": self.ns3_src_location,
452 if source.find(".tar.gz") > -1:
454 "tar xzf ${SRC}/ns-3/%(basename)s "
455 " --strip-components=1 -C %(ns3_src)s"
457 "basename": os.path.basename(source),
458 "ns3_src": self.ns3_src_location,
460 elif source.find(".tar") > -1:
462 "tar xf ${SRC}/ns-3/%(basename)s "
463 " --strip-components=1 -C %(ns3_src)s"
465 "basename": os.path.basename(source),
466 "ns3_src": self.ns3_src_location,
468 elif source.find(".zip") > -1:
469 basename = os.path.basename(source)
470 bare_basename = basename.replace(".zip", "")
473 "unzip ${SRC}/ns-3/%(basename)s && "
474 "mv ${SRC}/ns-3/%(bare_basename)s %(ns3_src)s"
476 "bare_basename": basename_name,
477 "basename": basename,
478 "ns3_src": self.ns3_src_location,
484 def _clone_dce_command(self):
485 clone_dce_cmd = " echo 'DCE will not be built' "
488 dce_version = self.dce_version
490 if dce_version != "dce-dev":
491 dce_tag = "-r %s" % dce_version
495 # Test if dce is alredy cloned
498 " ( test -d %(dce_src)s ) "
499 " && echo 'dce binaries found, nothing to do'"
503 # Get dce source code
505 " mkdir -p %(dce_src)s && "
506 " hg clone %(dce_repo)s %(dce_tag)s %(dce_src)s"
509 "dce_repo": self.dce_repo,
511 "dce_src": self.dce_src_location,
518 # If the user defined local sources for ns-3, we uncompress the sources
519 # on the remote sources directory. Else we clone ns-3 from the official repo.
520 clone_ns3_cmd = self._clone_ns3_command
521 clone_dce_cmd = self._clone_dce_command
527 # Test if ns-3 is alredy cloned
528 " ((( test -d %(ns3_src)s ) || "
529 " ( test -d ${NS3BINDINGS:='None'} && test -d ${NS3LIBRARIES:='None'})) "
530 " && echo 'ns-3 binaries found, nothing to do' )"
533 # If not, install ns-3 and its dependencies
538 " python -c 'import pygccxml' && "
539 " echo 'pygccxml not found' "
543 " tar xf ${SRC}/%(pygccxml_version)s.tar.gz -C ${SRC} && "
544 " cd ${SRC}/%(pygccxml_version)s && "
545 " python setup.py build && "
546 " sudo -S python setup.py install "
553 " test -d ${SRC}/pybindgen/%(pybindgen_version)s && "
554 " echo 'binaries found, nothing to do' "
557 # If not, clone and build
559 " mkdir -p ${SRC}/pybindgen && "
560 " bzr checkout lp:pybindgen -r %(pybindgen_version)s ${SRC}/pybindgen/%(pybindgen_version)s && "
561 " cd ${SRC}/pybindgen/%(pybindgen_version)s && "
562 " ./waf configure && "
567 # Get ns-3 source code
569 " mkdir -p %(ns3_src)s && "
570 " %(clone_ns3_cmd)s "
576 " %(clone_dce_cmd)s "
579 "ns3_src": self.ns3_src_location,
580 "pybindgen_version": self.get("pybindgenVersion"),
581 "pygccxml_version": self.pygccxml_version,
582 "clone_ns3_cmd": clone_ns3_cmd,
583 "clone_dce_cmd": clone_dce_cmd,
589 def _install_dce_command(self):
590 install_dce_cmd = " echo 'DCE will not be installed'"
595 " ((test -d %(ns3_build)s/bin_dce ) && "
596 " echo 'dce binaries found, nothing to do' )"
600 # If not, copy build to dce
601 " cd %(dce_src)s && "
602 " rm -rf %(dce_src)s/build && "
603 " ./waf configure %(enable_opt)s --with-pybindgen=${SRC}/pybindgen/%(pybindgen_version)s "
604 " --prefix=%(ns3_build)s --with-ns3=%(ns3_build)s && "
607 " [ ! -e %(ns3_build)s/lib/python/site-packages/ns/dce.so ] && "
608 " mv %(ns3_build)s/lib*/python*/site-packages/ns/dce.so %(ns3_build)s/lib/python/site-packages/ns/ "
611 "pybindgen_version": self.get("pybindgenVersion"),
612 "enable_opt": "--enable-opt" if self.get("buildMode") == "optimized" else "",
613 "ns3_build": self.ns3_build_location,
614 "dce_src": self.dce_src_location,
617 return install_dce_cmd
621 install_dce_cmd = self._install_dce_command
624 # Test if ns-3 is alredy installed
627 " ( ( (test -d %(ns3_build)s/lib ) || "
628 " (test -d ${NS3BINDINGS:='None'} && test -d ${NS3LIBRARIES:='None'}) ) && "
629 " echo 'binaries found, nothing to do' )"
633 # If not, copy ns-3 build to bin
634 " mkdir -p %(ns3_build)s && "
635 " cd %(ns3_src)s && "
636 " rm -rf %(ns3_src)s/build && "
637 " ./waf configure -d %(build_mode)s --with-pybindgen=${SRC}/pybindgen/%(pybindgen_version)s "
638 " --prefix=%(ns3_build)s && "
641 " mv %(ns3_build)s/lib*/python* %(ns3_build)s/lib/python "
646 " %(install_dce_cmd)s "
649 "pybindgen_version": self.get("pybindgenVersion"),
650 "build_mode": self.get("buildMode"),
651 "install_dce_cmd": install_dce_cmd,
652 "ns3_build": self.ns3_build_location,
653 "ns3_src": self.ns3_src_location,
656 return install_ns3_cmd
659 def _environment(self):
661 env.append("PYTHONPATH=$PYTHONPATH:${NS3BINDINGS:=%(ns3_build)s/lib/python/site-packages}" % {
662 "ns3_build": self.ns3_build_location
664 # If NS3LIBRARIES is defined and not empty, assign its value,
665 # if not assign ns3_build_home/lib/ to NS3LIBRARIES and LD_LIBARY_PATH
666 env.append("LD_LIBRARY_PATH=${NS3LIBRARIES:=%(ns3_build)s/lib}" % {
667 "ns3_build": self.ns3_build_location
669 env.append("DCE_PATH=$NS3LIBRARIES/../bin_dce")
670 env.append("DCE_ROOT=$NS3LIBRARIES/..")
674 def replace_paths(self, command):
676 Replace all special path tags with shell-escaped actual paths.
679 .replace("${USR}", self.node.usr_dir)
680 .replace("${LIB}", self.node.lib_dir)
681 .replace("${BIN}", self.node.bin_dir)
682 .replace("${SRC}", self.node.src_dir)
683 .replace("${SHARE}", self.node.share_dir)
684 .replace("${EXP}", self.node.exp_dir)
685 .replace("${EXP_HOME}", self.node.exp_home)
686 .replace("${APP_HOME}", self.app_home)
687 .replace("${RUN_HOME}", self.run_home)
688 .replace("${NODE_HOME}", self.node.node_home)
689 .replace("${HOME}", self.node.home_dir)
690 # If NS3LIBRARIES is defined and not empty, use that value,
691 # if not use ns3_build_home/lib/
692 .replace("${BIN_DCE}", "${NS3LIBRARIES-%s/lib}/../bin_dce" % \
693 self.ns3_build_location)
696 def valid_connection(self, guid):
700 def wait_remote_socket(self):
701 """ Waits until the remote socket is created
703 command = " [ -e %s ] && echo 'DONE' " % self.remote_socket
705 for i in xrange(200):
706 (out, err), proc = self.node.execute(command, retry = 1,
709 if out.find("DONE") > -1:
712 raise RuntimeError("Remote socket not found at %s" % \