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 class LinuxNS3Simulation(LinuxApplication, NS3Simulation):
36 _rtype = "LinuxNS3Simulation"
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 build_mode = Attribute("buildMode",
76 "Mode used to build ns-3 with waf. One if: debug, release, oprimized ",
77 default = "optimized",
78 allowed = ["debug", "release", "optimized"],
79 type = Types.Enumerate,
82 ns3_version = Attribute("ns3Version",
83 "Version of ns-3 to install from nsam repo",
87 enable_dce = Attribute("enableDCE",
88 "Install DCE source code",
93 pybindgen_version = Attribute("pybindgenVersion",
94 "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)
113 cls._register_attribute(enable_dce)
115 def __init__(self, ec, guid):
116 LinuxApplication.__init__(self, ec, guid)
117 NS3Simulation.__init__(self)
120 self._home = "ns3-simu-%s" % self.guid
121 self._socket_name = "ns3-%s.sock" % os.urandom(4).encode('hex')
122 self._dce_helper_uuid = None
123 self._dce_application_helper_uuid = 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 dce_helper_uuid(self):
135 return self._dce_helper_uuid
138 def dce_application_helper_uuid(self):
139 return self._dce_application_helper_uuid
142 def ns3_build_home(self):
143 return os.path.join(self.node.bin_dir, "ns-3", self.get("ns3Version"),
144 self.get("buildMode"), "build")
146 def trace(self, name, attr = TraceAttr.ALL, block = 512, offset = 0):
148 return LinuxApplication.trace(self, name, attr, block, offset)
150 def upload_sources(self):
151 self.node.mkdir(os.path.join(self.node.src_dir, "ns3wrapper"))
153 # upload ns3 wrapper python script
154 ns3_wrapper = os.path.join(os.path.dirname(__file__), "..", "..", "ns3",
157 self.node.upload(ns3_wrapper,
158 os.path.join(self.node.src_dir, "ns3wrapper", "ns3wrapper.py"),
161 # upload ns3_server python script
162 ns3_server = os.path.join(os.path.dirname(__file__), "..", "..", "ns3",
165 self.node.upload(ns3_server,
166 os.path.join(self.node.src_dir, "ns3wrapper", "ns3server.py"),
169 if self.node.use_rpm:
170 # upload pygccxml sources
171 pygccxml_tar = os.path.join(os.path.dirname(__file__), "dependencies",
172 "%s.tar.gz" % self.pygccxml_version)
174 self.node.upload(pygccxml_tar,
175 os.path.join(self.node.src_dir, "%s.tar.gz" % self.pygccxml_version),
178 # Upload user defined ns-3 sources
179 self.node.mkdir(os.path.join(self.node.src_dir, "ns-3"))
180 src_dir = os.path.join(self.node.src_dir, "ns-3")
182 super(LinuxNS3Simulation, self).upload_sources(src_dir = src_dir)
184 def upload_start_command(self):
185 command = self.get("command")
186 env = self.get("env")
188 # We want to make sure the ccnd is running
189 # before the experiment starts.
190 # Run the command as a bash script in background,
191 # in the host ( but wait until the command has
192 # finished to continue )
193 env = self.replace_paths(env)
194 command = self.replace_paths(command)
196 shfile = os.path.join(self.app_home, "start.sh")
197 self.node.upload_command(command,
203 self._run_in_background()
206 if self.has_changed("simulatorImplementationType"):
207 simu_type = self.get("simulatorImplementationType")
208 stype = self.create("StringValue", simu_type)
209 self.invoke(GLOBAL_VALUE_UUID, "Bind", "SimulatorImplementationType", stype)
211 if self.has_changed("checksumEnabled"):
212 check_sum = self.get("checksumEnabled")
213 btrue = self.create("BooleanValue", check_sum)
214 self.invoke(GLOBAL_VALUE_UUID, "Bind", "ChecksumEnabled", btrue)
216 if self.has_changed("schedulerType"):
217 sched_type = self.get("schedulerType")
218 stype = self.create("StringValue", sched_type)
219 self.invoke(GLOBAL_VALUE_UUID, "Bind", "SchedulerType", btrue)
221 if self.get("enableDCE"):
222 self._dce_helper_uuid = self.create("DceManagerHelper")
223 self._dce_application_helper_uuid = self.create("DceApplicationHelper")
226 if not self.node or self.node.state < ResourceState.READY:
227 self.debug("---- RESCHEDULING DEPLOY ---- node state %s " % self.node.state )
229 # ccnd needs to wait until node is deployed and running
230 self.ec.schedule(reschedule_delay, self.deploy)
232 if not self.get("command"):
233 self.set("command", self._start_command)
235 if not self.get("depends"):
236 self.set("depends", self._dependencies)
238 if self.get("sources"):
239 sources = self.get("sources")
240 source = sources.split(" ")[0]
241 basename = os.path.basename(source)
242 version = ( basename.strip().replace(".tar.gz", "")
245 .replace(".zip","") )
247 self.set("ns3Version", version)
248 self.set("sources", source)
250 if not self.get("build"):
251 self.set("build", self._build)
253 if not self.get("install"):
254 self.set("install", self._install)
256 if not self.get("env"):
257 self.set("env", self._environment)
263 self._client = LinuxNS3Client(self)
270 """ Starts simulation execution
273 self.info("Starting")
275 if self.state == ResourceState.READY:
276 if self.get("populateRoutingTables") == True:
277 self.invoke(IPV4_GLOBAL_ROUTING_HELPER_UUID, "PopulateRoutingTables")
283 msg = " Failed to execute command '%s'" % command
284 self.error(msg, out, err)
285 raise RuntimeError, msg
288 """ Stops simulation execution
291 if self.state == ResourceState.STARTED:
295 def do_release(self):
296 self.info("Releasing resource")
298 tear_down = self.get("tearDown")
300 self.node.execute(tear_down)
303 self._client.shutdown()
304 LinuxApplication.do_stop(self)
306 super(LinuxApplication, self).do_release()
309 def _start_command(self):
312 command.append("PYTHONPATH=$PYTHONPATH:${SRC}/ns3wrapper/")
314 command.append("python ${SRC}/ns3wrapper/ns3server.py -S %s" % \
315 os.path.basename(self.remote_socket) )
317 ns_log = self.get("nsLog")
319 command.append("-L '%s'" % ns_log)
321 if self.get("verbose"):
324 command = " ".join(command)
328 def _dependencies(self):
329 if self.node.use_rpm:
330 return ( " gcc gcc-c++ python python-devel mercurial bzr tcpdump socat gccxml unzip")
331 elif self.node.use_deb:
332 return ( " gcc g++ python python-dev mercurial bzr tcpdump socat gccxml python-pygccxml unzip")
337 return "http://code.nsnam.org"
340 def pygccxml_version(self):
341 return "pygccxml-1.0.0"
345 #return "http://code.nsnam.org/ns-3-dce"
346 return "http://code.nsnam.org/epmancini/ns-3-dce"
350 # If the user defined local sources for ns-3, we uncompress the sources
351 # on the remote sources directory. Else we clone ns-3 from the official repo.
352 source = self.get("sources")
354 clone_ns3_cmd = "hg clone %(ns3_repo)s/%(ns3_version)s ${SRC}/ns-3/%(ns3_version)s" \
356 'ns3_version': self.get("ns3Version"),
357 'ns3_repo': self.ns3_repo,
360 if source.find(".tar.gz") > -1:
362 "tar xzf ${SRC}/ns-3/%(basename)s "
363 " --strip-components=1 -C ${SRC}/ns-3/%(ns3_version)s "
365 'basename': os.path.basename(source),
366 'ns3_version': self.get("ns3Version"),
368 elif source.find(".tar") > -1:
370 "tar xf ${SRC}/ns-3/%(basename)s "
371 " --strip-components=1 -C ${SRC}/ns-3/%(ns3_version)s "
373 'basename': os.path.basename(source),
374 'ns3_version': self.get("ns3Version"),
376 elif source.find(".zip") > -1:
377 basename = os.path.basename(source)
378 bare_basename = basename.replace(".zip", "") \
379 .replace(".tar", "") \
380 .replace(".tar.gz", "")
383 "unzip ${SRC}/ns-3/%(basename)s && "
384 "mv ${SRC}/ns-3/%(bare_basename)s ${SRC}/ns-3/%(ns3_version)s "
386 'bare_basename': basename_name,
387 'basename': basename,
388 'ns3_version': self.get("ns3Version"),
391 clone_dce_cmd = " echo 'DCE will not be built' "
392 if self.get("enableDCE"):
395 # Test if dce is alredy installed
398 " ( test -d ${SRC}/dce/ns-3-dce ) "
399 " && echo 'dce binaries found, nothing to do'"
403 # Get dce source code
405 " mkdir -p ${SRC}/dce && "
406 " hg clone %(dce_repo)s ${SRC}/dce/ns-3-dce"
409 'dce_repo': self.dce_repo
417 # Test if ns-3 is alredy installed
418 " ((( test -d ${SRC}/ns-3/%(ns3_version)s ) || "
419 " ( test -d ${NS3BINDINGS:='None'} && test -d ${NS3LIBRARIES:='None'})) "
420 " && echo 'ns-3 binaries found, nothing to do' )"
423 # If not, install ns-3 and its dependencies
428 " python -c 'import pygccxml' && "
429 " echo 'pygccxml not found' "
433 " tar xf ${SRC}/%(pygccxml_version)s.tar.gz -C ${SRC} && "
434 " cd ${SRC}/%(pygccxml_version)s && "
435 " python setup.py build && "
436 " sudo -S python setup.py install "
443 " test -d ${SRC}/pybindgen/%(pybindgen_version)s && "
444 " echo 'binaries found, nothing to do' "
447 # If not, clone and build
449 " mkdir -p ${SRC}/pybindgen && "
450 " bzr checkout lp:pybindgen -r %(pybindgen_version)s ${SRC}/pybindgen/%(pybindgen_version)s && "
451 " cd ${SRC}/pybindgen/%(pybindgen_version)s && "
452 " ./waf configure && "
457 # Get ns-3 source code
459 " mkdir -p ${SRC}/ns-3/%(ns3_version)s && "
460 " %(clone_ns3_cmd)s "
466 " %(clone_dce_cmd)s "
469 'ns3_version': self.get("ns3Version"),
470 'pybindgen_version': self.get("pybindgenVersion"),
471 'pygccxml_version': self.pygccxml_version,
472 'clone_ns3_cmd': clone_ns3_cmd,
473 'clone_dce_cmd': clone_dce_cmd,
478 install_dce_cmd = " echo 'DCE will not be installed' "
479 if self.get("enableDCE"):
482 " ((test -d %(ns3_build_home)s/bin_dce ) && "
483 " echo 'dce binaries found, nothing to do' )"
487 # If not, copy ns-3 build to bin
488 " cd ${SRC}/dce/ns-3-dce && "
489 " ./waf configure %(enable_opt)s --with-pybindgen=${SRC}/pybindgen/%(pybindgen_version)s "
490 " --prefix=%(ns3_build_home)s --with-ns3=%(ns3_build_home)s && "
493 " mv %(ns3_build_home)s/lib/python*/site-packages/ns/dce.so %(ns3_build_home)s/lib/python/site-packages/ns/ "
496 'ns3_version': self.get("ns3Version"),
497 'pybindgen_version': self.get("pybindgenVersion"),
498 'ns3_build_home': self.ns3_build_home,
499 'build_mode': self.get("buildMode"),
500 'enable_opt': "--enable-opt" if self.get("buildMode") == "optimized" else ""
504 # Test if ns-3 is alredy installed
507 " ( ( (test -d %(ns3_build_home)s/lib ) || "
508 " (test -d ${NS3BINDINGS:='None'} && test -d ${NS3LIBRARIES:='None'}) ) && "
509 " echo 'binaries found, nothing to do' )"
513 # If not, copy ns-3 build to bin
514 " mkdir -p %(ns3_build_home)s && "
515 " cd ${SRC}/ns-3/%(ns3_version)s && "
516 " ./waf configure -d %(build_mode)s --with-pybindgen=${SRC}/pybindgen/%(pybindgen_version)s "
517 " --prefix=%(ns3_build_home)s --includedir=%(ns3_build_home)s && "
520 " mv %(ns3_build_home)s/lib/python* %(ns3_build_home)s/lib/python "
525 " %(install_dce_cmd)s "
528 'ns3_version': self.get("ns3Version"),
529 'pybindgen_version': self.get("pybindgenVersion"),
530 'build_mode': self.get("buildMode"),
531 'ns3_build_home': self.ns3_build_home,
532 'install_dce_cmd': install_dce_cmd
536 def _environment(self):
538 env.append("PYTHONPATH=$PYTHONPATH:${NS3BINDINGS:=%(ns3_build_home)s/lib/python/site-packages}" % {
539 'ns3_build_home': self.ns3_build_home
541 env.append("LD_LIBRARY_PATH=${NS3LIBRARIES:=%(ns3_build_home)s/lib/}" % {
542 'ns3_build_home': self.ns3_build_home
544 env.append("DCE_PATH=$PATH:$NS3LIBRARIES/../bin_dce")
545 env.append("DCE_ROOT=$PATH:$NS3LIBRARIES/..")
549 def valid_connection(self, guid):