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, reschedule_delay
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 build_mode = Attribute("buildMode",
80 "Mode used to build ns-3 with waf. One if: debug, release, oprimized ",
81 default = "optimized",
82 allowed = ["debug", "release", "optimized"],
83 type = Types.Enumerate,
86 ns3_version = Attribute("ns3Version",
87 "Version of ns-3 to install from nsam repo",
89 #default = "ns-3-dev",
92 enable_dce = Attribute("enableDCE",
93 "Install DCE source code",
98 pybindgen_version = Attribute("pybindgenVersion",
99 "Version of pybindgen to install from bazar repo",
102 flags = Flags.Design)
104 populate_routing_tables = Attribute("populateRoutingTables",
105 "Invokes Ipv4GlobalRoutingHelper.PopulateRoutingTables() ",
108 flags = Flags.Design)
110 cls._register_attribute(impl_type)
111 cls._register_attribute(sched_type)
112 cls._register_attribute(check_sum)
113 cls._register_attribute(ns_log)
114 cls._register_attribute(verbose)
115 cls._register_attribute(build_mode)
116 cls._register_attribute(ns3_version)
117 cls._register_attribute(pybindgen_version)
118 cls._register_attribute(populate_routing_tables)
119 cls._register_attribute(enable_dce)
121 def __init__(self, ec, guid):
122 LinuxApplication.__init__(self, ec, guid)
123 NS3Simulation.__init__(self)
126 self._home = "ns3-simu-%s" % self.guid
127 self._socket_name = "ns3-%s.sock" % os.urandom(4).encode('hex')
128 self._dce_manager_helper_uuid = None
129 self._dce_application_helper_uuid = None
132 def socket_name(self):
133 return self._socket_name
136 def remote_socket(self):
137 return os.path.join(self.run_home, self.socket_name)
140 def ns3_build_home(self):
141 return os.path.join(self.node.bin_dir, "ns-3", self.get("ns3Version"),
142 self.get("buildMode"), "build")
144 def trace(self, name, attr = TraceAttr.ALL, block = 512, offset = 0):
146 return LinuxApplication.trace(self, name, attr, block, offset)
148 def upload_sources(self):
149 self.node.mkdir(os.path.join(self.node.src_dir, "ns3wrapper"))
151 # upload ns3 wrapper python script
152 ns3_wrapper = os.path.join(os.path.dirname(__file__), "..", "..", "ns3",
155 self.node.upload(ns3_wrapper,
156 os.path.join(self.node.src_dir, "ns3wrapper", "ns3wrapper.py"),
159 # upload ns3_server python script
160 ns3_server = os.path.join(os.path.dirname(__file__), "..", "..", "ns3",
163 self.node.upload(ns3_server,
164 os.path.join(self.node.src_dir, "ns3wrapper", "ns3server.py"),
167 if self.node.use_rpm:
168 # upload pygccxml sources
169 pygccxml_tar = os.path.join(os.path.dirname(__file__), "dependencies",
170 "%s.tar.gz" % self.pygccxml_version)
172 self.node.upload(pygccxml_tar,
173 os.path.join(self.node.src_dir, "%s.tar.gz" % self.pygccxml_version),
176 # Upload user defined ns-3 sources
177 self.node.mkdir(os.path.join(self.node.src_dir, "ns-3"))
178 src_dir = os.path.join(self.node.src_dir, "ns-3")
180 super(LinuxNS3Simulation, self).upload_sources(src_dir = src_dir)
182 def upload_extra_sources(self, sources = None, src_dir = None):
183 return super(LinuxNS3Simulation, self).upload_sources(
187 def upload_start_command(self):
188 command = self.get("command")
189 env = self.get("env")
191 # We want to make sure the ccnd is running
192 # before the experiment starts.
193 # Run the command as a bash script in background,
194 # in the host ( but wait until the command has
195 # finished to continue )
196 env = self.replace_paths(env)
197 command = self.replace_paths(command)
199 shfile = os.path.join(self.app_home, "start.sh")
200 self.node.upload_command(command,
206 self._run_in_background()
209 if self.has_changed("simulatorImplementationType"):
210 simu_type = self.get("simulatorImplementationType")
211 stype = self.create("StringValue", simu_type)
212 self.invoke(GLOBAL_VALUE_UUID, "Bind", "SimulatorImplementationType", stype)
214 if self.has_changed("checksumEnabled"):
215 check_sum = self.get("checksumEnabled")
216 btrue = self.create("BooleanValue", check_sum)
217 self.invoke(GLOBAL_VALUE_UUID, "Bind", "ChecksumEnabled", btrue)
219 if self.has_changed("schedulerType"):
220 sched_type = self.get("schedulerType")
221 stype = self.create("StringValue", sched_type)
222 self.invoke(GLOBAL_VALUE_UUID, "Bind", "SchedulerType", btrue)
225 if not self.node or self.node.state < ResourceState.READY:
226 self.debug("---- RESCHEDULING DEPLOY ---- node state %s " % self.node.state )
228 # ccnd needs to wait until node is deployed and running
229 self.ec.schedule(reschedule_delay, self.deploy)
231 if not self.get("command"):
232 self.set("command", self._start_command)
234 if not self.get("depends"):
235 self.set("depends", self._dependencies)
237 if self.get("sources"):
238 sources = self.get("sources")
239 source = sources.split(" ")[0]
240 basename = os.path.basename(source)
241 version = ( basename.strip().replace(".tar.gz", "")
244 .replace(".zip","") )
246 self.set("ns3Version", version)
247 self.set("sources", source)
249 if not self.get("build"):
250 self.set("build", self._build)
252 if not self.get("install"):
253 self.set("install", self._install)
255 if not self.get("env"):
256 self.set("env", self._environment)
262 self._client = LinuxNS3Client(self)
269 """ Starts simulation execution
272 self.info("Starting")
274 if self.state == ResourceState.READY:
275 if self.get("populateRoutingTables") == True:
276 self.invoke(IPV4_GLOBAL_ROUTING_HELPER_UUID, "PopulateRoutingTables")
282 msg = " Failed to execute command '%s'" % command
283 self.error(msg, out, err)
284 raise RuntimeError, msg
287 """ Stops simulation execution
290 if self.state == ResourceState.STARTED:
294 def do_release(self):
295 self.info("Releasing resource")
297 tear_down = self.get("tearDown")
299 self.node.execute(tear_down)
302 self._client.shutdown()
303 LinuxApplication.do_stop(self)
305 super(LinuxApplication, self).do_release()
308 def _start_command(self):
311 command.append("PYTHONPATH=$PYTHONPATH:${SRC}/ns3wrapper/")
313 command.append("python ${SRC}/ns3wrapper/ns3server.py -S %s" % \
314 os.path.basename(self.remote_socket) )
316 ns_log = self.get("nsLog")
318 command.append("-L '%s'" % ns_log)
320 if self.get("verbose"):
323 command = " ".join(command)
327 def _dependencies(self):
328 if self.node.use_rpm:
329 return ( " gcc gcc-c++ python python-devel mercurial bzr tcpdump socat gccxml unzip")
330 elif self.node.use_deb:
331 return ( " gcc g++ python python-dev mercurial bzr tcpdump socat gccxml python-pygccxml unzip")
336 return "http://code.nsnam.org"
339 def pygccxml_version(self):
340 return "pygccxml-1.0.0"
344 return "http://code.nsnam.org/ns-3-dce"
345 #eturn "http://code.nsnam.org/epmancini/ns-3-dce"
349 # If the user defined local sources for ns-3, we uncompress the sources
350 # on the remote sources directory. Else we clone ns-3 from the official repo.
351 source = self.get("sources")
353 clone_ns3_cmd = "hg clone %(ns3_repo)s/%(ns3_version)s ${SRC}/ns-3/%(ns3_version)s" \
355 'ns3_version': self.get("ns3Version"),
356 'ns3_repo': self.ns3_repo,
359 if source.find(".tar.gz") > -1:
361 "tar xzf ${SRC}/ns-3/%(basename)s "
362 " --strip-components=1 -C ${SRC}/ns-3/%(ns3_version)s "
364 'basename': os.path.basename(source),
365 'ns3_version': self.get("ns3Version"),
367 elif source.find(".tar") > -1:
369 "tar xf ${SRC}/ns-3/%(basename)s "
370 " --strip-components=1 -C ${SRC}/ns-3/%(ns3_version)s "
372 'basename': os.path.basename(source),
373 'ns3_version': self.get("ns3Version"),
375 elif source.find(".zip") > -1:
376 basename = os.path.basename(source)
377 bare_basename = basename.replace(".zip", "") \
378 .replace(".tar", "") \
379 .replace(".tar.gz", "")
382 "unzip ${SRC}/ns-3/%(basename)s && "
383 "mv ${SRC}/ns-3/%(bare_basename)s ${SRC}/ns-3/%(ns3_version)s "
385 'bare_basename': basename_name,
386 'basename': basename,
387 'ns3_version': self.get("ns3Version"),
390 clone_dce_cmd = " echo 'DCE will not be built' "
391 if self.get("enableDCE"):
394 # Test if dce is alredy installed
397 " ( test -d ${SRC}/dce/ns-3-dce ) "
398 " && echo 'dce binaries found, nothing to do'"
402 # Get dce source code
404 " mkdir -p ${SRC}/dce && "
405 " hg clone %(dce_repo)s ${SRC}/dce/ns-3-dce"
408 'dce_repo': self.dce_repo
416 # Test if ns-3 is alredy installed
417 " ((( test -d ${SRC}/ns-3/%(ns3_version)s ) || "
418 " ( test -d ${NS3BINDINGS:='None'} && test -d ${NS3LIBRARIES:='None'})) "
419 " && echo 'ns-3 binaries found, nothing to do' )"
422 # If not, install ns-3 and its dependencies
427 " python -c 'import pygccxml' && "
428 " echo 'pygccxml not found' "
432 " tar xf ${SRC}/%(pygccxml_version)s.tar.gz -C ${SRC} && "
433 " cd ${SRC}/%(pygccxml_version)s && "
434 " python setup.py build && "
435 " sudo -S python setup.py install "
442 " test -d ${SRC}/pybindgen/%(pybindgen_version)s && "
443 " echo 'binaries found, nothing to do' "
446 # If not, clone and build
448 " mkdir -p ${SRC}/pybindgen && "
449 " bzr checkout lp:pybindgen -r %(pybindgen_version)s ${SRC}/pybindgen/%(pybindgen_version)s && "
450 " cd ${SRC}/pybindgen/%(pybindgen_version)s && "
451 " ./waf configure && "
456 # Get ns-3 source code
458 " mkdir -p ${SRC}/ns-3/%(ns3_version)s && "
459 " %(clone_ns3_cmd)s "
465 " %(clone_dce_cmd)s "
468 'ns3_version': self.get("ns3Version"),
469 'pybindgen_version': self.get("pybindgenVersion"),
470 'pygccxml_version': self.pygccxml_version,
471 'clone_ns3_cmd': clone_ns3_cmd,
472 'clone_dce_cmd': clone_dce_cmd,
477 install_dce_cmd = " echo 'DCE will not be installed' "
478 if self.get("enableDCE"):
481 " ((test -d %(ns3_build_home)s/bin_dce ) && "
482 " echo 'dce binaries found, nothing to do' )"
486 # If not, copy ns-3 build to bin
487 " cd ${SRC}/dce/ns-3-dce && "
488 " ./waf configure %(enable_opt)s --with-pybindgen=${SRC}/pybindgen/%(pybindgen_version)s "
489 " --prefix=%(ns3_build_home)s --with-ns3=%(ns3_build_home)s && "
492 " mv %(ns3_build_home)s/lib*/python*/site-packages/ns/dce.so %(ns3_build_home)s/lib/python/site-packages/ns/ "
495 'ns3_version': self.get("ns3Version"),
496 'pybindgen_version': self.get("pybindgenVersion"),
497 'ns3_build_home': self.ns3_build_home,
498 'build_mode': self.get("buildMode"),
499 'enable_opt': "--enable-opt" if self.get("buildMode") == "optimized" else ""
503 # Test if ns-3 is alredy installed
506 " ( ( (test -d %(ns3_build_home)s/lib ) || "
507 " (test -d ${NS3BINDINGS:='None'} && test -d ${NS3LIBRARIES:='None'}) ) && "
508 " echo 'binaries found, nothing to do' )"
512 # If not, copy ns-3 build to bin
513 " mkdir -p %(ns3_build_home)s && "
514 " cd ${SRC}/ns-3/%(ns3_version)s && "
515 " ./waf configure -d %(build_mode)s --with-pybindgen=${SRC}/pybindgen/%(pybindgen_version)s "
516 " --prefix=%(ns3_build_home)s && "
519 " mv %(ns3_build_home)s/lib*/python* %(ns3_build_home)s/lib/python "
524 " %(install_dce_cmd)s "
527 'ns3_version': self.get("ns3Version"),
528 'pybindgen_version': self.get("pybindgenVersion"),
529 'build_mode': self.get("buildMode"),
530 'ns3_build_home': self.ns3_build_home,
531 'install_dce_cmd': install_dce_cmd
535 def _environment(self):
537 env.append("PYTHONPATH=$PYTHONPATH:${NS3BINDINGS:=%(ns3_build_home)s/lib/python/site-packages}" % {
538 'ns3_build_home': self.ns3_build_home
540 # If NS3LIBRARIES is defined and not empty, assign its value,
541 # if not assign ns3_build_home/lib/ to NS3LIBRARIES and LD_LIBARY_PATH
542 env.append("LD_LIBRARY_PATH=${NS3LIBRARIES:=%(ns3_build_home)s/lib}" % {
543 'ns3_build_home': self.ns3_build_home
545 env.append("DCE_PATH=$NS3LIBRARIES/../bin_dce")
546 env.append("DCE_ROOT=$NS3LIBRARIES/..")
550 def replace_paths(self, command):
552 Replace all special path tags with shell-escaped actual paths.
555 .replace("${USR}", self.node.usr_dir)
556 .replace("${LIB}", self.node.lib_dir)
557 .replace("${BIN}", self.node.bin_dir)
558 .replace("${SRC}", self.node.src_dir)
559 .replace("${SHARE}", self.node.share_dir)
560 .replace("${EXP}", self.node.exp_dir)
561 .replace("${EXP_HOME}", self.node.exp_home)
562 .replace("${APP_HOME}", self.app_home)
563 .replace("${RUN_HOME}", self.run_home)
564 .replace("${NODE_HOME}", self.node.node_home)
565 .replace("${HOME}", self.node.home_dir)
566 # If NS3LIBRARIES is defined and not empty, use that value,
567 # if not use ns3_build_home/lib/
568 .replace("${BIN_DCE}", "${NS3LIBRARIES-%s/lib}/../bin_dce" % \
572 def valid_connection(self, guid):