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, 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",
92 pybindgen_version = Attribute("pybindgenVersion",
93 "Version of pybindgen to install from bazar repo",
98 populate_routing_tables = Attribute("populateRoutingTables",
99 "Invokes Ipv4GlobalRoutingHelper.PopulateRoutingTables() ",
102 flags = Flags.Design)
104 cls._register_attribute(impl_type)
105 cls._register_attribute(sched_type)
106 cls._register_attribute(check_sum)
107 cls._register_attribute(ns_log)
108 cls._register_attribute(verbose)
109 cls._register_attribute(build_mode)
110 cls._register_attribute(ns3_version)
111 cls._register_attribute(pybindgen_version)
112 cls._register_attribute(populate_routing_tables)
114 def __init__(self, ec, guid):
115 LinuxApplication.__init__(self, ec, guid)
116 NS3Simulation.__init__(self)
119 self._home = "ns3-simu-%s" % self.guid
120 self._socket_name = "ns3-%s.sock" % os.urandom(4).encode('hex')
121 self._dce_manager_helper_uuid = None
122 self._dce_application_helper_uuid = None
123 self._enable_dce = None
126 def socket_name(self):
127 return self._socket_name
130 def remote_socket(self):
131 return os.path.join(self.run_home, self.socket_name)
134 def ns3_build_home(self):
135 return os.path.join(self.node.bin_dir, "ns-3", self.get("ns3Version"),
136 self.get("buildMode"), "build")
138 def trace(self, name, attr = TraceAttr.ALL, block = 512, offset = 0):
140 return LinuxApplication.trace(self, name, attr, block, offset)
142 def upload_sources(self):
143 self.node.mkdir(os.path.join(self.node.src_dir, "ns3wrapper"))
145 # upload ns3 wrapper python script
146 ns3_wrapper = os.path.join(os.path.dirname(__file__), "..", "..", "ns3",
149 self.node.upload(ns3_wrapper,
150 os.path.join(self.node.src_dir, "ns3wrapper", "ns3wrapper.py"),
153 # upload ns3_server python script
154 ns3_server = os.path.join(os.path.dirname(__file__), "..", "..", "ns3",
157 self.node.upload(ns3_server,
158 os.path.join(self.node.src_dir, "ns3wrapper", "ns3server.py"),
161 if self.node.use_rpm:
162 # upload pygccxml sources
163 pygccxml_tar = os.path.join(os.path.dirname(__file__), "dependencies",
164 "%s.tar.gz" % self.pygccxml_version)
166 self.node.upload(pygccxml_tar,
167 os.path.join(self.node.src_dir, "%s.tar.gz" % self.pygccxml_version),
170 # Upload user defined ns-3 sources
171 self.node.mkdir(os.path.join(self.node.src_dir, "ns-3"))
172 src_dir = os.path.join(self.node.src_dir, "ns-3")
174 super(LinuxNS3Simulation, self).upload_sources(src_dir = src_dir)
176 def upload_extra_sources(self, sources = None, src_dir = None):
177 return super(LinuxNS3Simulation, self).upload_sources(
181 def upload_start_command(self):
182 command = self.get("command")
183 env = self.get("env")
185 # We want to make sure the ccnd is running
186 # before the experiment starts.
187 # Run the command as a bash script in background,
188 # in the host ( but wait until the command has
189 # finished to continue )
190 env = self.replace_paths(env)
191 command = self.replace_paths(command)
193 shfile = os.path.join(self.app_home, "start.sh")
194 self.node.upload_command(command,
200 self._run_in_background()
203 if self.has_changed("simulatorImplementationType"):
204 simu_type = self.get("simulatorImplementationType")
205 stype = self.create("StringValue", simu_type)
206 self.invoke(GLOBAL_VALUE_UUID, "Bind", "SimulatorImplementationType", stype)
208 if self.has_changed("checksumEnabled"):
209 check_sum = self.get("checksumEnabled")
210 btrue = self.create("BooleanValue", check_sum)
211 self.invoke(GLOBAL_VALUE_UUID, "Bind", "ChecksumEnabled", btrue)
213 if self.has_changed("schedulerType"):
214 sched_type = self.get("schedulerType")
215 stype = self.create("StringValue", sched_type)
216 self.invoke(GLOBAL_VALUE_UUID, "Bind", "SchedulerType", btrue)
219 if not self.node or self.node.state < ResourceState.READY:
220 self.debug("---- RESCHEDULING DEPLOY ---- node state %s " % self.node.state )
222 # ccnd needs to wait until node is deployed and running
223 self.ec.schedule(reschedule_delay, self.deploy)
225 if not self.get("command"):
226 self.set("command", self._start_command)
228 if not self.get("depends"):
229 self.set("depends", self._dependencies)
231 if self.get("sources"):
232 sources = self.get("sources")
233 source = sources.split(" ")[0]
234 basename = os.path.basename(source)
235 version = ( basename.strip().replace(".tar.gz", "")
238 .replace(".zip","") )
240 self.set("ns3Version", version)
241 self.set("sources", source)
243 if not self.get("build"):
244 self.set("build", self._build)
246 if not self.get("install"):
247 self.set("install", self._install)
249 if not self.get("env"):
250 self.set("env", self._environment)
256 self._client = LinuxNS3Client(self)
263 """ Starts simulation execution
266 self.info("Starting")
268 if self.state == ResourceState.READY:
269 if self.get("populateRoutingTables") == True:
270 self.invoke(IPV4_GLOBAL_ROUTING_HELPER_UUID, "PopulateRoutingTables")
274 # Wait until the Simulation is actually started...
276 for i in xrange(1000):
277 is_running = self.invoke(SIMULATOR_UUID, "isRunning")
285 msg = " Simulation did not start"
291 msg = " Failed to execute command '%s'" % command
292 self.error(msg, out, err)
293 raise RuntimeError, msg
296 """ Stops simulation execution
299 if self.state == ResourceState.STARTED:
303 def do_release(self):
304 self.info("Releasing resource")
306 tear_down = self.get("tearDown")
308 self.node.execute(tear_down)
311 self._client.shutdown()
312 LinuxApplication.do_stop(self)
314 super(LinuxApplication, self).do_release()
317 def enable_dce(self):
318 if self._enable_dce is None:
319 from nepi.resources.ns3.ns3dceapplication import NS3BaseDceApplication
320 rclass = ResourceFactory.get_resource_type(
321 NS3BaseDceApplication.get_rtype())
323 self._enable_dce = False
324 for guid in self.ec.resources:
325 rm = self.ec.get_resource(guid)
326 if isinstance(rm, rclass):
327 self._enable_dce = True
330 return self._enable_dce
333 def _start_command(self):
336 command.append("PYTHONPATH=$PYTHONPATH:${SRC}/ns3wrapper/")
338 command.append("python ${SRC}/ns3wrapper/ns3server.py -S %s" % \
339 os.path.basename(self.remote_socket) )
341 ns_log = self.get("nsLog")
343 command.append("-L '%s'" % ns_log)
345 if self.get("verbose"):
348 command = " ".join(command)
352 def _dependencies(self):
353 if self.node.use_rpm:
354 return ( " gcc gcc-c++ python python-devel mercurial bzr tcpdump socat gccxml unzip")
355 elif self.node.use_deb:
356 return ( " gcc g++ python python-dev mercurial bzr tcpdump socat gccxml python-pygccxml unzip")
361 return "http://code.nsnam.org"
364 def pygccxml_version(self):
365 return "pygccxml-1.0.0"
369 return "http://code.nsnam.org/ns-3-dce"
370 #eturn "http://code.nsnam.org/epmancini/ns-3-dce"
374 # If the user defined local sources for ns-3, we uncompress the sources
375 # on the remote sources directory. Else we clone ns-3 from the official repo.
376 source = self.get("sources")
378 clone_ns3_cmd = "hg clone %(ns3_repo)s/%(ns3_version)s ${SRC}/ns-3/%(ns3_version)s" \
380 'ns3_version': self.get("ns3Version"),
381 'ns3_repo': self.ns3_repo,
384 if source.find(".tar.gz") > -1:
386 "tar xzf ${SRC}/ns-3/%(basename)s "
387 " --strip-components=1 -C ${SRC}/ns-3/%(ns3_version)s "
389 'basename': os.path.basename(source),
390 'ns3_version': self.get("ns3Version"),
392 elif source.find(".tar") > -1:
394 "tar xf ${SRC}/ns-3/%(basename)s "
395 " --strip-components=1 -C ${SRC}/ns-3/%(ns3_version)s "
397 'basename': os.path.basename(source),
398 'ns3_version': self.get("ns3Version"),
400 elif source.find(".zip") > -1:
401 basename = os.path.basename(source)
402 bare_basename = basename.replace(".zip", "") \
403 .replace(".tar", "") \
404 .replace(".tar.gz", "")
407 "unzip ${SRC}/ns-3/%(basename)s && "
408 "mv ${SRC}/ns-3/%(bare_basename)s ${SRC}/ns-3/%(ns3_version)s "
410 'bare_basename': basename_name,
411 'basename': basename,
412 'ns3_version': self.get("ns3Version"),
415 clone_dce_cmd = " echo 'DCE will not be built' "
419 # Test if dce is alredy installed
422 " ( test -d ${SRC}/dce/ns-3-dce ) "
423 " && echo 'dce binaries found, nothing to do'"
427 # Get dce source code
429 " mkdir -p ${SRC}/dce && "
430 " hg clone %(dce_repo)s ${SRC}/dce/ns-3-dce"
433 'dce_repo': self.dce_repo
440 # Test if ns-3 is alredy installed
441 " ((( test -d ${SRC}/ns-3/%(ns3_version)s ) || "
442 " ( test -d ${NS3BINDINGS:='None'} && test -d ${NS3LIBRARIES:='None'})) "
443 " && echo 'ns-3 binaries found, nothing to do' )"
446 # If not, install ns-3 and its dependencies
451 " python -c 'import pygccxml' && "
452 " echo 'pygccxml not found' "
456 " tar xf ${SRC}/%(pygccxml_version)s.tar.gz -C ${SRC} && "
457 " cd ${SRC}/%(pygccxml_version)s && "
458 " python setup.py build && "
459 " sudo -S python setup.py install "
466 " test -d ${SRC}/pybindgen/%(pybindgen_version)s && "
467 " echo 'binaries found, nothing to do' "
470 # If not, clone and build
472 " mkdir -p ${SRC}/pybindgen && "
473 " bzr checkout lp:pybindgen -r %(pybindgen_version)s ${SRC}/pybindgen/%(pybindgen_version)s && "
474 " cd ${SRC}/pybindgen/%(pybindgen_version)s && "
475 " ./waf configure && "
480 # Get ns-3 source code
482 " mkdir -p ${SRC}/ns-3/%(ns3_version)s && "
483 " %(clone_ns3_cmd)s "
489 " %(clone_dce_cmd)s "
492 'ns3_version': self.get("ns3Version"),
493 'pybindgen_version': self.get("pybindgenVersion"),
494 'pygccxml_version': self.pygccxml_version,
495 'clone_ns3_cmd': clone_ns3_cmd,
496 'clone_dce_cmd': clone_dce_cmd,
501 install_dce_cmd = " echo 'DCE will not be installed' "
505 " ((test -d %(ns3_build_home)s/bin_dce ) && "
506 " echo 'dce binaries found, nothing to do' )"
510 # If not, copy ns-3 build to bin
511 " cd ${SRC}/dce/ns-3-dce && "
512 " rm -rf ${SRC}/dce/ns-3-dce/build && "
513 " ./waf configure %(enable_opt)s --with-pybindgen=${SRC}/pybindgen/%(pybindgen_version)s "
514 " --prefix=%(ns3_build_home)s --with-ns3=%(ns3_build_home)s && "
517 " mv %(ns3_build_home)s/lib*/python*/site-packages/ns/dce.so %(ns3_build_home)s/lib/python/site-packages/ns/ "
520 'ns3_version': self.get("ns3Version"),
521 'pybindgen_version': self.get("pybindgenVersion"),
522 'ns3_build_home': self.ns3_build_home,
523 'build_mode': self.get("buildMode"),
524 'enable_opt': "--enable-opt" if self.get("buildMode") == "optimized" else ""
528 # Test if ns-3 is alredy installed
531 " ( ( (test -d %(ns3_build_home)s/lib ) || "
532 " (test -d ${NS3BINDINGS:='None'} && test -d ${NS3LIBRARIES:='None'}) ) && "
533 " echo 'binaries found, nothing to do' )"
537 # If not, copy ns-3 build to bin
538 " mkdir -p %(ns3_build_home)s && "
539 " cd ${SRC}/ns-3/%(ns3_version)s && "
540 " rm -rf ${SRC}/ns-3/%(ns3_version)s/build && "
541 " ./waf configure -d %(build_mode)s --with-pybindgen=${SRC}/pybindgen/%(pybindgen_version)s "
542 " --prefix=%(ns3_build_home)s && "
545 " mv %(ns3_build_home)s/lib*/python* %(ns3_build_home)s/lib/python "
550 " %(install_dce_cmd)s "
553 'ns3_version': self.get("ns3Version"),
554 'pybindgen_version': self.get("pybindgenVersion"),
555 'build_mode': self.get("buildMode"),
556 'ns3_build_home': self.ns3_build_home,
557 'install_dce_cmd': install_dce_cmd
561 def _environment(self):
563 env.append("PYTHONPATH=$PYTHONPATH:${NS3BINDINGS:=%(ns3_build_home)s/lib/python/site-packages}" % {
564 'ns3_build_home': self.ns3_build_home
566 # If NS3LIBRARIES is defined and not empty, assign its value,
567 # if not assign ns3_build_home/lib/ to NS3LIBRARIES and LD_LIBARY_PATH
568 env.append("LD_LIBRARY_PATH=${NS3LIBRARIES:=%(ns3_build_home)s/lib}" % {
569 'ns3_build_home': self.ns3_build_home
571 env.append("DCE_PATH=$NS3LIBRARIES/../bin_dce")
572 env.append("DCE_ROOT=$NS3LIBRARIES/..")
576 def replace_paths(self, command):
578 Replace all special path tags with shell-escaped actual paths.
581 .replace("${USR}", self.node.usr_dir)
582 .replace("${LIB}", self.node.lib_dir)
583 .replace("${BIN}", self.node.bin_dir)
584 .replace("${SRC}", self.node.src_dir)
585 .replace("${SHARE}", self.node.share_dir)
586 .replace("${EXP}", self.node.exp_dir)
587 .replace("${EXP_HOME}", self.node.exp_home)
588 .replace("${APP_HOME}", self.app_home)
589 .replace("${RUN_HOME}", self.run_home)
590 .replace("${NODE_HOME}", self.node.node_home)
591 .replace("${HOME}", self.node.home_dir)
592 # If NS3LIBRARIES is defined and not empty, use that value,
593 # if not use ns3_build_home/lib/
594 .replace("${BIN_DCE}", "${NS3LIBRARIES-%s/lib}/../bin_dce" % \
598 def valid_connection(self, guid):