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 from nepi.resources.linux.ns3.ns3client import LinuxNS3Client
34 class LinuxNS3Simulation(LinuxApplication, NS3Simulation):
35 _rtype = "LinuxNS3Simulation"
38 def _register_attributes(cls):
39 impl_type = Attribute("simulatorImplementationType",
40 "The object class to use as the simulator implementation",
41 allowed = ["ns3::DefaultSimulatorImpl", "ns3::RealtimeSimulatorImpl"],
42 default = "ns3::DefaultSimulatorImpl",
43 type = Types.Enumerate,
46 sched_type = Attribute("schedulerType",
47 "The object class to use as the scheduler implementation",
48 allowed = ["ns3::MapScheduler",
52 "ns3::CalendarScheduler"
54 default = "ns3::MapScheduler",
55 type = Types.Enumerate,
58 check_sum = Attribute("checksumEnabled",
59 "A global switch to enable all checksums for all protocols",
64 ns_log = Attribute("nsLog",
65 "NS_LOG environment variable. " \
66 " Will only generate output if ns-3 is compiled in DEBUG mode. ",
69 verbose = Attribute("verbose",
70 "True to output debugging info from the ns3 client-server communication",
74 build_mode = Attribute("buildMode",
75 "Mode used to build ns-3 with waf. One if: debug, release, oprimized ",
77 allowed = ["debug", "release", "optimized"],
78 type = Types.Enumerate,
81 ns3_version = Attribute("ns3Version",
82 "Version of ns-3 to install from nsam repo",
86 pybindgen_version = Attribute("pybindgenVersion",
87 "Version of pybindgen to install from bazar repo",
91 cls._register_attribute(impl_type)
92 cls._register_attribute(sched_type)
93 cls._register_attribute(check_sum)
94 cls._register_attribute(ns_log)
95 cls._register_attribute(verbose)
96 cls._register_attribute(build_mode)
97 cls._register_attribute(ns3_version)
98 cls._register_attribute(pybindgen_version)
100 def __init__(self, ec, guid):
101 LinuxApplication.__init__(self, ec, guid)
102 NS3Simulation.__init__(self)
105 self._home = "ns3-simu-%s" % self.guid
106 self._socket_name = "ns3simu-%s" % os.urandom(8).encode('hex')
109 def socket_name(self):
110 return self._socket_name
113 def remote_socket(self):
114 return os.path.join(self.run_home, self.socket_name)
117 def local_socket(self):
118 if self.node.get('hostname') in ['localhost', '127.0.0.01']:
119 return self.remote_socket
121 return os.path.join("/", "tmp", self.socket_name)
123 def trace(self, name, attr = TraceAttr.ALL, block = 512, offset = 0):
125 return LinuxApplication.trace(self, name, attr, block, offset)
127 def upload_sources(self):
128 self.node.mkdir(os.path.join(self.node.src_dir, "ns3wrapper"))
130 # upload ns3 wrapper python script
131 ns3_wrapper = os.path.join(os.path.dirname(__file__), "..", "..", "ns3",
134 self.node.upload(ns3_wrapper,
135 os.path.join(self.node.src_dir, "ns3wrapper", "ns3wrapper.py"),
138 # upload ns3_server python script
139 ns3_server = os.path.join(os.path.dirname(__file__), "..", "..", "ns3",
142 self.node.upload(ns3_server,
143 os.path.join(self.node.src_dir, "ns3wrapper", "ns3server.py"),
146 if self.node.use_rpm:
147 # upload pygccxml sources
148 pygccxml_tar = os.path.join(os.path.dirname(__file__), "dependencies",
149 "%s.tar.gz" % self.pygccxml_version)
151 self.node.upload(pygccxml_tar,
152 os.path.join(self.node.src_dir, "%s.tar.gz" % self.pygccxml_version),
155 def upload_start_command(self):
156 command = self.get("command")
157 env = self.get("env")
159 # We want to make sure the ccnd is running
160 # before the experiment starts.
161 # Run the command as a bash script in background,
162 # in the host ( but wait until the command has
163 # finished to continue )
164 env = self.replace_paths(env)
165 command = self.replace_paths(command)
167 shfile = os.path.join(self.app_home, "start.sh")
168 self.node.upload_command(command,
174 self._run_in_background()
177 if self.has_changed("simulatorImplementationType"):
178 simu_type = self.get("simulatorImplementationType")
179 stype = self.create("StringValue", simu_type)
180 self.invoke(GLOBAL_VALUE_UUID, "Bind", "SimulatorImplementationType", stype)
182 if self.has_changed("checksumEnabled"):
183 check_sum = self.get("checksumEnabled")
184 btrue = self.create("BooleanValue", check_sum)
185 self.invoke(GLOBAL_VALUE_UUID, "Bind", "ChecksumEnabled", btrue)
187 if self.has_changed("schedulerType"):
188 sched_type = self.get("schedulerType")
189 stype = self.create("StringValue", sched_type)
190 self.invoke(GLOBAL_VALUE_UUID, "Bind", "SchedulerType", btrue)
193 if not self.node or self.node.state < ResourceState.READY:
194 self.debug("---- RESCHEDULING DEPLOY ---- node state %s " % self.node.state )
196 # ccnd needs to wait until node is deployed and running
197 self.ec.schedule(reschedule_delay, self.deploy)
199 if not self.get("command"):
200 self.set("command", self._start_command)
202 if not self.get("depends"):
203 self.set("depends", self._dependencies)
205 if not self.get("build"):
206 self.set("build", self._build)
208 if not self.get("install"):
209 self.set("install", self._install)
211 if not self.get("env"):
212 self.set("env", self._environment)
218 self._client = LinuxNS3Client(self)
220 # Wait until local socket is created
221 for i in [1, 5, 15, 30, 60]:
222 if os.path.exists(self.local_socket):
226 if not os.path.exists(self.local_socket):
227 raise RuntimeError("Problem starting socat")
234 """ Starts simulation execution
237 self.info("Starting")
239 if self.state == ResourceState.READY:
244 msg = " Failed to execute command '%s'" % command
245 self.error(msg, out, err)
246 raise RuntimeError, msg
249 """ Stops simulation execution
252 if self.state == ResourceState.STARTED:
256 def do_release(self):
257 self.info("Releasing resource")
259 tear_down = self.get("tearDown")
261 self.node.execute(tear_down)
264 self._client.shutdown()
265 LinuxApplication.do_stop(self)
267 super(LinuxApplication, self).do_release()
270 def _start_command(self):
272 command.append("PYTHONPATH=$PYTHONPATH:${SRC}/ns3wrapper/")
274 command.append("python ${SRC}/ns3wrapper/ns3server.py -S %s" % self.remote_socket )
276 ns_log = self.get("nsLog")
278 command.append("-L %s" % ns_log)
280 if self.get("verbose"):
283 command = " ".join(command)
287 def _dependencies(self):
288 if self.node.use_rpm:
289 return ( " gcc gcc-c++ python python-devel mercurial bzr tcpdump socat gccxml")
290 elif self.node.use_deb:
291 return ( " gcc g++ python python-dev mercurial bzr tcpdump socat gccxml python-pygccxml")
296 return "http://code.nsnam.org"
299 def pygccxml_version(self):
300 return "pygccxml-1.0.0"
305 # Test if ns-3 is alredy installed
308 " ( test -d ${SRC}/ns-3/%(ns3_version)s ) || "
309 " ( test -d ${NS3BINDINGS:='None'} && test -d ${NS3LIBRARIES:='None'}) "
310 " ) && echo 'binaries found, nothing to do' )"
313 # If not, install ns-3 and its dependencies
318 " python -c 'import pygccxml' && "
319 " echo 'pygccxml not found' "
323 " tar xf ${SRC}/%(pygccxml_version)s.tar.gz -C ${SRC} && "
324 " cd ${SRC}/%(pygccxml_version)s && "
325 " sudo -S python setup.py install "
332 " test -d ${BIN}/pybindgen/%(pybindgen_version)s && "
333 " echo 'binaries found, nothing to do' "
336 # If not, clone and build
338 " mkdir -p ${SRC}/pybindgen && "
339 " bzr checkout lp:pybindgen -r %(pybindgen_version)s ${SRC}/pybindgen/%(pybindgen_version)s && "
340 " cd ${SRC}/pybindgen/%(pybindgen_version)s && "
341 " ./waf configure && "
346 # Clone and build ns-3
348 " hg clone %(ns3_repo)s/%(ns3_version)s ${SRC}/ns-3/%(ns3_version)s"
352 'ns3_repo': self.ns3_repo,
353 'ns3_version': self.get("ns3Version"),
354 'pybindgen_version': self.get("pybindgenVersion"),
355 'pygccxml_version': self.pygccxml_version,
361 # Test if ns-3 is alredy cloned
363 " ( ( (test -d ${BIN}/ns-3/%(ns3_version)s/%(build_mode)s/build ) || "
364 " (test -d ${NS3BINDINGS:='None'} && test -d ${NS3LIBRARIES:='None'}) ) && "
365 " echo 'binaries found, nothing to do' )"
369 # If not, copy ns-3 build to bin
370 " cd ${SRC}/ns-3/%(ns3_version)s && "
371 " ./waf configure -d %(build_mode)s --with-pybindgen=${SRC}/pybindgen/%(pybindgen_version)s && "
373 " mkdir -p ${BIN}/ns-3/%(ns3_version)s/%(build_mode)s && "
374 " mv ${SRC}/ns-3/%(ns3_version)s/build ${BIN}/ns-3/%(ns3_version)s/%(build_mode)s/build "
377 'ns3_version': self.get("ns3Version"),
378 'pybindgen_version': self.get("pybindgenVersion"),
379 'build_mode': self.get("buildMode"),
383 def _environment(self):
385 env.append("NS3BINDINGS=${NS3BINDINGS:=${BIN}/ns-3/%(ns3_version)s/%(build_mode)s/build/bindings/python/}" % ({
386 'ns3_version': self.get("ns3Version"),
387 'build_mode': self.get("buildMode")
389 env.append("NS3LIBRARIES=${NS3LIBRARIES:=${BIN}/ns-3/%(ns3_version)s/%(build_mode)s/build/}" % ({
390 'ns3_version': self.get("ns3Version"),
391 'build_mode': self.get("buildMode")
396 def valid_connection(self, guid):