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
35 ## TODO: Clean up DCE part. All that is DCE specific should go
36 ## in the linux ns3dceapplication.py
39 class LinuxNS3Simulation(LinuxApplication, NS3Simulation):
40 _rtype = "LinuxNS3Simulation"
43 def _register_attributes(cls):
44 impl_type = Attribute("simulatorImplementationType",
45 "The object class to use as the simulator implementation",
46 allowed = ["ns3::DefaultSimulatorImpl", "ns3::RealtimeSimulatorImpl"],
47 default = "ns3::DefaultSimulatorImpl",
48 type = Types.Enumerate,
51 sched_type = Attribute("schedulerType",
52 "The object class to use as the scheduler implementation",
53 allowed = ["ns3::MapScheduler",
57 "ns3::CalendarScheduler"
59 default = "ns3::MapScheduler",
60 type = Types.Enumerate,
63 check_sum = Attribute("checksumEnabled",
64 "A global switch to enable all checksums for all protocols",
69 ns_log = Attribute("nsLog",
70 "NS_LOG environment variable. " \
71 " Will only generate output if ns-3 is compiled in DEBUG mode. ",
74 verbose = Attribute("verbose",
75 "True to output debugging info from the ns3 client-server communication",
79 enable_dump = Attribute("enableDump",
80 "Enable dumping the remote executed ns-3 commands to a script "
81 "in order to later reproduce and debug the experiment",
86 build_mode = Attribute("buildMode",
87 "Mode used to build ns-3 with waf. One if: debug, release, oprimized ",
88 default = "optimized",
89 allowed = ["debug", "release", "optimized"],
90 type = Types.Enumerate,
93 ns3_version = Attribute("ns3Version",
94 "Version of ns-3 to install from nsam repo",
96 #default = "ns-3-dev",
99 pybindgen_version = Attribute("pybindgenVersion",
100 "Version of pybindgen to install from bazar repo",
103 flags = Flags.Design)
105 dce_version = Attribute("dceVersion",
106 "Version of dce to install from nsam repo (tag branch for repo)",
107 #default = "dce-1.3",
109 flags = Flags.Design)
111 populate_routing_tables = Attribute("populateRoutingTables",
112 "Invokes Ipv4GlobalRoutingHelper.PopulateRoutingTables() ",
115 flags = Flags.Design)
117 stoptime = Attribute("StopTime",
118 "Time at which the simulation will stop",
119 flags = Flags.Design)
121 cls._register_attribute(impl_type)
122 cls._register_attribute(sched_type)
123 cls._register_attribute(check_sum)
124 cls._register_attribute(ns_log)
125 cls._register_attribute(enable_dump)
126 cls._register_attribute(verbose)
127 cls._register_attribute(build_mode)
128 cls._register_attribute(ns3_version)
129 cls._register_attribute(pybindgen_version)
130 cls._register_attribute(dce_version)
131 cls._register_attribute(populate_routing_tables)
132 cls._register_attribute(stoptime)
134 def __init__(self, ec, guid):
135 LinuxApplication.__init__(self, ec, guid)
136 NS3Simulation.__init__(self)
139 self._home = "ns3-simu-%s" % self.guid
140 self._socket_name = "ns3-%s.sock" % os.urandom(4).encode('hex')
141 self._enable_dce = None
144 def socket_name(self):
145 return self._socket_name
148 def remote_socket(self):
149 return os.path.join(self.run_home, self.socket_name)
151 def trace(self, name, attr = TraceAttr.ALL, block = 512, offset = 0):
152 # stout needs to get flushed on the ns-3 server side, else we will
153 # get an empty stream. We try twice to retrieve the stream
154 # if we get empty stdout since the stream might not be
155 # flushed immediately.
156 if name.endswith("stdout"):
158 result = LinuxApplication.trace(self, name, attr, block, offset)
161 # Let the stream be flushed
164 return LinuxApplication.trace(self, name, attr, block, offset)
166 def upload_sources(self):
167 self.node.mkdir(os.path.join(self.node.src_dir, "ns3wrapper"))
169 # upload ns3 wrapper python script
170 ns3_wrapper = os.path.join(os.path.dirname(__file__), "..", "..", "ns3",
173 self.node.upload(ns3_wrapper,
174 os.path.join(self.node.src_dir, "ns3wrapper", "ns3wrapper.py"),
177 # upload ns3 wrapper debug python script
178 ns3_wrapper_debug = os.path.join(os.path.dirname(__file__), "..", "..", "ns3",
179 "ns3wrapper_debug.py")
181 self.node.upload(ns3_wrapper_debug,
182 os.path.join(self.node.src_dir, "ns3wrapper", "ns3wrapper_debug.py"),
185 # upload ns3_server python script
186 ns3_server = os.path.join(os.path.dirname(__file__), "..", "..", "ns3",
189 self.node.upload(ns3_server,
190 os.path.join(self.node.src_dir, "ns3wrapper", "ns3server.py"),
193 if self.node.use_rpm:
194 # upload pygccxml sources
195 pygccxml_tar = os.path.join(os.path.dirname(__file__), "dependencies",
196 "%s.tar.gz" % self.pygccxml_version)
198 self.node.upload(pygccxml_tar,
199 os.path.join(self.node.src_dir, "%s.tar.gz" % self.pygccxml_version),
202 # Upload user defined ns-3 sources
203 self.node.mkdir(os.path.join(self.node.src_dir, "ns-3"))
204 src_dir = os.path.join(self.node.src_dir, "ns-3")
206 super(LinuxNS3Simulation, self).upload_sources(src_dir = src_dir)
208 def upload_extra_sources(self, sources = None, src_dir = None):
209 return super(LinuxNS3Simulation, self).upload_sources(
213 def upload_start_command(self):
214 command = self.get("command")
215 env = self.get("env")
217 # We want to make sure the ccnd is running
218 # before the experiment starts.
219 # Run the command as a bash script in background,
220 # in the host ( but wait until the command has
221 # finished to continue )
222 env = self.replace_paths(env)
223 command = self.replace_paths(command)
225 shfile = os.path.join(self.app_home, "start.sh")
226 self.node.upload_command(command,
232 self._run_in_background()
234 # Wait until the remote socket is created
235 self.wait_remote_socket()
238 if self.has_changed("simulatorImplementationType"):
239 simu_type = self.get("simulatorImplementationType")
240 stype = self.create("StringValue", simu_type)
241 self.invoke(GLOBAL_VALUE_UUID, "Bind", "SimulatorImplementationType", stype)
243 if self.has_changed("checksumEnabled"):
244 check_sum = self.get("checksumEnabled")
245 btrue = self.create("BooleanValue", check_sum)
246 self.invoke(GLOBAL_VALUE_UUID, "Bind", "ChecksumEnabled", btrue)
248 if self.has_changed("schedulerType"):
249 sched_type = self.get("schedulerType")
250 stype = self.create("StringValue", sched_type)
251 self.invoke(GLOBAL_VALUE_UUID, "Bind", "SchedulerType", btrue)
254 if not self.node or self.node.state < ResourceState.READY:
255 self.debug("---- RESCHEDULING DEPLOY ---- node state %s " % self.node.state )
257 # ccnd needs to wait until node is deployed and running
258 self.ec.schedule(self.reschedule_delay, self.deploy)
260 if not self.get("command"):
261 self.set("command", self._start_command)
263 if not self.get("depends"):
264 self.set("depends", self._dependencies)
266 if self.get("sources"):
267 sources = self.get("sources")
268 source = sources.split(" ")[0]
269 basename = os.path.basename(source)
270 version = ( basename.strip().replace(".tar.gz", "")
273 .replace(".zip","") )
275 self.set("ns3Version", version)
276 self.set("sources", source)
278 if not self.get("build"):
279 self.set("build", self._build)
281 if not self.get("install"):
282 self.set("install", self._install)
284 if not self.get("env"):
285 self.set("env", self._environment)
291 self._client = LinuxNS3Client(self)
298 """ Starts simulation execution
301 self.info("Starting")
303 if self.state == ResourceState.READY:
304 if self.get("populateRoutingTables") == True:
305 self.invoke(IPV4_GLOBAL_ROUTING_HELPER_UUID, "PopulateRoutingTables")
307 time = self.get("StopTime")
309 self._client.stop(time=time)
315 msg = " Failed to execute command '%s'" % command
316 self.error(msg, out, err)
317 raise RuntimeError, msg
320 """ Stops simulation execution
323 if self.state == ResourceState.STARTED:
324 if not self.get("StopTime"):
328 def do_release(self):
329 self.info("Releasing resource")
331 tear_down = self.get("tearDown")
333 self.node.execute(tear_down)
336 self._client.shutdown()
337 LinuxApplication.do_stop(self)
339 super(LinuxApplication, self).do_release()
342 def enable_dce(self):
343 if self._enable_dce is None:
344 from nepi.resources.ns3.ns3dceapplication import NS3BaseDceApplication
345 rclass = ResourceFactory.get_resource_type(
346 NS3BaseDceApplication.get_rtype())
348 self._enable_dce = False
349 for guid in self.ec.resources:
350 rm = self.ec.get_resource(guid)
351 if isinstance(rm, rclass):
352 self._enable_dce = True
355 return self._enable_dce
358 def _start_command(self):
361 command.append("PYTHONPATH=$PYTHONPATH:${SRC}/ns3wrapper/")
363 command.append("python ${SRC}/ns3wrapper/ns3server.py -S %s" % \
364 os.path.basename(self.remote_socket) )
366 ns_log = self.get("nsLog")
368 command.append("-L '%s'" % ns_log)
370 if self.get("enableDump"):
373 if self.get("verbose"):
376 command = " ".join(command)
380 def _dependencies(self):
381 if self.node.use_rpm:
382 return ( " gcc gcc-c++ python python-devel mercurial bzr tcpdump socat gccxml unzip")
383 elif self.node.use_deb:
384 return ( " gcc g++ python python-dev mercurial bzr tcpdump socat gccxml python-pygccxml unzip")
389 return "http://code.nsnam.org"
392 def pygccxml_version(self):
393 return "pygccxml-1.0.0"
397 return "http://code.nsnam.org/ns-3-dce"
398 #eturn "http://code.nsnam.org/epmancini/ns-3-dce"
401 def dce_version(self):
402 dce_version = self.get("dceVersion")
403 return dce_version or "dce-dev"
406 def ns3_build_location(self):
407 location = "${BIN}/ns-3/%(ns3_version)s%(dce_version)s/%(build_mode)s/build" \
409 "ns3_version": self.get("ns3Version"),
410 "dce_version": "-%s" % self.get("dceVersion") \
411 if self.enable_dce else "",
412 "build_mode": self.get("buildMode"),
419 def ns3_src_location(self):
420 location = "${SRC}/ns-3/%(ns3_version)s" \
422 "ns3_version": self.get("ns3Version"),
428 def dce_src_location(self):
429 location = "${SRC}/ns-3-dce/%(dce_version)s" \
431 "dce_version": self.get("dceVersion"),
437 def _clone_ns3_command(self):
438 source = self.get("sources")
441 clone_ns3_cmd = "hg clone %(ns3_repo)s/%(ns3_version)s %(ns3_src)s" \
443 "ns3_version": self.get("ns3Version"),
444 "ns3_repo": self.ns3_repo,
445 "ns3_src": self.ns3_src_location,
448 if source.find(".tar.gz") > -1:
450 "tar xzf ${SRC}/ns-3/%(basename)s "
451 " --strip-components=1 -C %(ns3_src)s"
453 "basename": os.path.basename(source),
454 "ns3_src": self.ns3_src_location,
456 elif source.find(".tar") > -1:
458 "tar xf ${SRC}/ns-3/%(basename)s "
459 " --strip-components=1 -C %(ns3_src)s"
461 "basename": os.path.basename(source),
462 "ns3_src": self.ns3_src_location,
464 elif source.find(".zip") > -1:
465 basename = os.path.basename(source)
466 bare_basename = basename.replace(".zip", "")
469 "unzip ${SRC}/ns-3/%(basename)s && "
470 "mv ${SRC}/ns-3/%(bare_basename)s %(ns3_src)s"
472 "bare_basename": basename_name,
473 "basename": basename,
474 "ns3_src": self.ns3_src_location,
480 def _clone_dce_command(self):
481 clone_dce_cmd = " echo 'DCE will not be built' "
484 dce_version = self.dce_version
486 if dce_version != "dce-dev":
487 dce_tag = "-r %s" % dce_version
491 # Test if dce is alredy cloned
494 " ( test -d %(dce_src)s ) "
495 " && echo 'dce binaries found, nothing to do'"
499 # Get dce source code
501 " mkdir -p %(dce_src)s && "
502 " hg clone %(dce_repo)s %(dce_tag)s %(dce_src)s"
505 "dce_repo": self.dce_repo,
507 "dce_src": self.dce_src_location,
514 # If the user defined local sources for ns-3, we uncompress the sources
515 # on the remote sources directory. Else we clone ns-3 from the official repo.
516 clone_ns3_cmd = self._clone_ns3_command
517 clone_dce_cmd = self._clone_dce_command
523 # Test if ns-3 is alredy cloned
524 " ((( test -d %(ns3_src)s ) || "
525 " ( test -d ${NS3BINDINGS:='None'} && test -d ${NS3LIBRARIES:='None'})) "
526 " && echo 'ns-3 binaries found, nothing to do' )"
529 # If not, install ns-3 and its dependencies
534 " python -c 'import pygccxml' && "
535 " echo 'pygccxml not found' "
539 " tar xf ${SRC}/%(pygccxml_version)s.tar.gz -C ${SRC} && "
540 " cd ${SRC}/%(pygccxml_version)s && "
541 " python setup.py build && "
542 " sudo -S python setup.py install "
549 " test -d ${SRC}/pybindgen/%(pybindgen_version)s && "
550 " echo 'binaries found, nothing to do' "
553 # If not, clone and build
555 " mkdir -p ${SRC}/pybindgen && "
556 " bzr checkout lp:pybindgen -r %(pybindgen_version)s ${SRC}/pybindgen/%(pybindgen_version)s && "
557 " cd ${SRC}/pybindgen/%(pybindgen_version)s && "
558 " ./waf configure && "
563 # Get ns-3 source code
565 " mkdir -p %(ns3_src)s && "
566 " %(clone_ns3_cmd)s "
572 " %(clone_dce_cmd)s "
575 "ns3_src": self.ns3_src_location,
576 "pybindgen_version": self.get("pybindgenVersion"),
577 "pygccxml_version": self.pygccxml_version,
578 "clone_ns3_cmd": clone_ns3_cmd,
579 "clone_dce_cmd": clone_dce_cmd,
585 def _install_dce_command(self):
586 install_dce_cmd = " echo 'DCE will not be installed'"
591 " ((test -d %(ns3_build)s/bin_dce ) && "
592 " echo 'dce binaries found, nothing to do' )"
596 # If not, copy build to dce
597 " cd %(dce_src)s && "
598 " rm -rf %(dce_src)s/build && "
599 " ./waf configure %(enable_opt)s --with-pybindgen=${SRC}/pybindgen/%(pybindgen_version)s "
600 " --prefix=%(ns3_build)s --with-ns3=%(ns3_build)s && "
603 " [ ! -e %(ns3_build)s/lib/python/site-packages/ns/dce.so ] && "
604 " mv %(ns3_build)s/lib*/python*/site-packages/ns/dce.so %(ns3_build)s/lib/python/site-packages/ns/ "
607 "pybindgen_version": self.get("pybindgenVersion"),
608 "enable_opt": "--enable-opt" if self.get("buildMode") == "optimized" else "",
609 "ns3_build": self.ns3_build_location,
610 "dce_src": self.dce_src_location,
613 return install_dce_cmd
617 install_dce_cmd = self._install_dce_command
620 # Test if ns-3 is alredy installed
623 " ( ( (test -d %(ns3_build)s/lib ) || "
624 " (test -d ${NS3BINDINGS:='None'} && test -d ${NS3LIBRARIES:='None'}) ) && "
625 " echo 'binaries found, nothing to do' )"
629 # If not, copy ns-3 build to bin
630 " mkdir -p %(ns3_build)s && "
631 " cd %(ns3_src)s && "
632 " rm -rf %(ns3_src)s/build && "
633 " ./waf configure -d %(build_mode)s --with-pybindgen=${SRC}/pybindgen/%(pybindgen_version)s "
634 " --prefix=%(ns3_build)s && "
637 " mv %(ns3_build)s/lib*/python* %(ns3_build)s/lib/python "
642 " %(install_dce_cmd)s "
645 "pybindgen_version": self.get("pybindgenVersion"),
646 "build_mode": self.get("buildMode"),
647 "install_dce_cmd": install_dce_cmd,
648 "ns3_build": self.ns3_build_location,
649 "ns3_src": self.ns3_src_location,
652 return install_ns3_cmd
655 def _environment(self):
657 env.append("PYTHONPATH=$PYTHONPATH:${NS3BINDINGS:=%(ns3_build)s/lib/python/site-packages}" % {
658 "ns3_build": self.ns3_build_location
660 # If NS3LIBRARIES is defined and not empty, assign its value,
661 # if not assign ns3_build_home/lib/ to NS3LIBRARIES and LD_LIBARY_PATH
662 env.append("LD_LIBRARY_PATH=${NS3LIBRARIES:=%(ns3_build)s/lib}" % {
663 "ns3_build": self.ns3_build_location
665 env.append("DCE_PATH=$NS3LIBRARIES/../bin_dce")
666 env.append("DCE_ROOT=$NS3LIBRARIES/..")
670 def replace_paths(self, command):
672 Replace all special path tags with shell-escaped actual paths.
675 .replace("${USR}", self.node.usr_dir)
676 .replace("${LIB}", self.node.lib_dir)
677 .replace("${BIN}", self.node.bin_dir)
678 .replace("${SRC}", self.node.src_dir)
679 .replace("${SHARE}", self.node.share_dir)
680 .replace("${EXP}", self.node.exp_dir)
681 .replace("${EXP_HOME}", self.node.exp_home)
682 .replace("${APP_HOME}", self.app_home)
683 .replace("${RUN_HOME}", self.run_home)
684 .replace("${NODE_HOME}", self.node.node_home)
685 .replace("${HOME}", self.node.home_dir)
686 # If NS3LIBRARIES is defined and not empty, use that value,
687 # if not use ns3_build_home/lib/
688 .replace("${BIN_DCE}", "${NS3LIBRARIES-%s/lib}/../bin_dce" % \
689 self.ns3_build_location)
692 def valid_connection(self, guid):
696 def wait_remote_socket(self):
697 """ Waits until the remote socket is created
699 command = " [ -e %s ] && echo 'DONE' " % self.remote_socket
701 for i in xrange(200):
702 (out, err), proc = self.node.execute(command, retry = 1,
705 if out.find("DONE") > -1:
708 raise RuntimeError("Remote socket not found at %s" % \