#124 - Allow the ns-3 sources to be built in debug mode
[nepi.git] / src / nepi / resources / linux / ns3 / ns3simulation.py
1 #
2 #    NEPI, a framework to manage network experiments
3 #    Copyright (C) 2014 INRIA
4 #
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.
9 #
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.
14 #
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/>.
17 #
18 # Author: Alina Quereilhac <alina.quereilhac@inria.fr>
19
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
29
30 import os
31 import time
32
33 @clsinit_copy
34 class LinuxNS3Simulation(LinuxApplication, NS3Simulation):
35     _rtype = "LinuxNS3Simulation"
36
37     @classmethod
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,
44             flags = Flags.Design)
45
46         sched_type = Attribute("schedulerType",
47                 "The object class to use as the scheduler implementation",
48                 allowed = ["ns3::MapScheduler",
49                             "ns3::ListScheduler",
50                             "ns3::HeapScheduler",
51                             "ns3::MapScheduler",
52                             "ns3::CalendarScheduler"
53                     ],
54             default = "ns3::MapScheduler",
55             type = Types.Enumerate,
56             flags = Flags.Design)
57
58         check_sum = Attribute("checksumEnabled",
59                 "A global switch to enable all checksums for all protocols",
60             default = False,
61             type = Types.Bool,
62             flags = Flags.Design)
63
64         ns_log = Attribute("nsLog",
65             "NS_LOG environment variable. " \
66                     " Will only generate output if ns-3 is compiled in DEBUG mode. ",
67             flags = Flags.Design)
68
69         verbose = Attribute("verbose",
70             "True to output debugging info from the ns3 client-server communication",
71             type = Types.Bool,
72             flags = Flags.Design)
73
74         build_mode = Attribute("buildMode",
75             "Mode used to build ns-3 with waf. One if: debug, release, oprimized ",
76             default = "release", 
77             allowed = ["debug", "release", "optimized"],
78             type = Types.Enumerate,
79             flags = Flags.Design)
80
81         ns3_version = Attribute("ns3Version",
82             "Version of ns-3 to install from nsam repo",
83             default = "ns-3.19", 
84             flags = Flags.Design)
85
86         pybindgen_version = Attribute("pybindgenVersion",
87             "Version of pybindgen to install from bazar repo",
88             default = "834", 
89             flags = Flags.Design)
90
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)
99
100     def __init__(self, ec, guid):
101         LinuxApplication.__init__(self, ec, guid)
102         NS3Simulation.__init__(self)
103
104         self._client = None
105         self._home = "ns3-simu-%s" % self.guid
106         self._socket_name = "ns3simu-%s" % os.urandom(8).encode('hex')
107
108     @property
109     def socket_name(self):
110         return self._socket_name
111
112     @property
113     def remote_socket(self):
114         return os.path.join(self.run_home, self.socket_name)
115
116     @property
117     def local_socket(self):
118         if self.node.get('hostname') in ['localhost', '127.0.0.01']:
119             return self.remote_socket
120
121         return os.path.join("/", "tmp", self.socket_name)
122
123     def trace(self, name, attr = TraceAttr.ALL, block = 512, offset = 0):
124         self._client.flush() 
125         return LinuxApplication.trace(self, name, attr, block, offset)
126
127     def upload_sources(self):
128         self.node.mkdir(os.path.join(self.node.src_dir, "ns3wrapper"))
129
130         # upload ns3 wrapper python script
131         ns3_wrapper = os.path.join(os.path.dirname(__file__), "..", "..", "ns3", 
132                 "ns3wrapper.py")
133
134         self.node.upload(ns3_wrapper,
135                 os.path.join(self.node.src_dir, "ns3wrapper", "ns3wrapper.py"),
136                 overwrite = False)
137
138         # upload ns3_server python script
139         ns3_server = os.path.join(os.path.dirname(__file__), "..", "..", "ns3",
140                 "ns3server.py")
141
142         self.node.upload(ns3_server,
143                 os.path.join(self.node.src_dir, "ns3wrapper", "ns3server.py"),
144                 overwrite = False)
145
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)
150
151             self.node.upload(pygccxml_tar,
152                     os.path.join(self.node.src_dir, "%s.tar.gz" % self.pygccxml_version),
153                     overwrite = False)
154
155     def upload_start_command(self):
156         command = self.get("command")
157         env = self.get("env")
158
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)
166
167         shfile = os.path.join(self.app_home, "start.sh")
168         self.node.upload_command(command, 
169                     shfile = shfile,
170                     env = env,
171                     overwrite = True)
172
173         # Run the ns3wrapper 
174         self._run_in_background()
175
176     def configure(self):
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)
181
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)
186         
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)
191        
192     def do_deploy(self):
193         if not self.node or self.node.state < ResourceState.READY:
194             self.debug("---- RESCHEDULING DEPLOY ---- node state %s " % self.node.state )
195             
196             # ccnd needs to wait until node is deployed and running
197             self.ec.schedule(reschedule_delay, self.deploy)
198         else:
199             if not self.get("command"):
200                 self.set("command", self._start_command)
201             
202             if not self.get("depends"):
203                 self.set("depends", self._dependencies)
204
205             if not self.get("build"):
206                 self.set("build", self._build)
207
208             if not self.get("install"):
209                 self.set("install", self._install)
210
211             if not self.get("env"):
212                 self.set("env", self._environment)
213
214             self.do_discover()
215             self.do_provision()
216
217             # Create client
218             self._client = LinuxNS3Client(self)
219            
220             # Wait until local socket is created
221             for i in [1, 5, 15, 30, 60]:
222                 if os.path.exists(self.local_socket):
223                     break
224                 time.sleep(i)
225
226             if not os.path.exists(self.local_socket):
227                 raise RuntimeError("Problem starting socat")
228
229             self.configure()
230             
231             self.set_ready()
232
233     def do_start(self):
234         """ Starts simulation execution
235
236         """
237         self.info("Starting")
238
239         if self.state == ResourceState.READY:
240             self._client.start() 
241
242             self.set_started()
243         else:
244             msg = " Failed to execute command '%s'" % command
245             self.error(msg, out, err)
246             raise RuntimeError, msg
247
248     def do_stop(self):
249         """ Stops simulation execution
250
251         """
252         if self.state == ResourceState.STARTED:
253             self._client.stop() 
254             self.set_stopped()
255
256     def do_release(self):
257         self.info("Releasing resource")
258
259         tear_down = self.get("tearDown")
260         if tear_down:
261             self.node.execute(tear_down)
262
263         self.do_stop()
264         self._client.shutdown()
265         LinuxApplication.do_stop(self)
266         
267         super(LinuxApplication, self).do_release()
268
269     @property
270     def _start_command(self):
271         command = [] 
272         command.append("PYTHONPATH=$PYTHONPATH:${SRC}/ns3wrapper/")
273
274         command.append("python ${SRC}/ns3wrapper/ns3server.py -S %s" % self.remote_socket )
275
276         ns_log = self.get("nsLog")
277         if ns_log:
278             command.append("-L %s" % ns_log)
279
280         if self.get("verbose"):
281             command.append("-v")
282
283         command = " ".join(command)
284         return command
285
286     @property
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")
292         return ""
293
294     @property
295     def ns3_repo(self):
296         return "http://code.nsnam.org"
297
298     @property
299     def pygccxml_version(self):
300         return "pygccxml-1.0.0"
301
302     @property
303     def _build(self):
304         return (
305                 # Test if ns-3 is alredy installed
306                 " ( "
307                 " (( "
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' )"
311                 " ) "
312                 "  || " 
313                 # If not, install ns-3 and its dependencies
314                 " (   "
315                 # Install pygccxml
316                 "   (   "
317                 "     ( "
318                 "       python -c 'import pygccxml' && "
319                 "       echo 'pygccxml not found' "
320                 "     ) "
321                 "      || "
322                 "     ( "
323                 "       tar xf ${SRC}/%(pygccxml_version)s.tar.gz -C ${SRC} && "
324                 "       cd ${SRC}/%(pygccxml_version)s && "
325                 "       sudo -S python setup.py install "
326                 "     ) "
327                 "   ) " 
328                 # Install pybindgen
329                 "  && "
330                 "   (   "
331                 "     ( "
332                 "       test -d ${BIN}/pybindgen/%(pybindgen_version)s && "
333                 "       echo 'binaries found, nothing to do' "
334                 "     ) "
335                 "      || "
336                 # If not, clone and build
337                 "      ( cd ${SRC} && "
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 && "
342                 "        ./waf "
343                 "      ) "
344                 "   ) " 
345                "  && "
346                 # Clone and build ns-3
347                 "  ( "
348                 "    hg clone %(ns3_repo)s/%(ns3_version)s ${SRC}/ns-3/%(ns3_version)s"
349                "   ) "
350                 " ) "
351              ) % ({ 
352                     'ns3_repo':  self.ns3_repo,       
353                     'ns3_version': self.get("ns3Version"),
354                     'pybindgen_version': self.get("pybindgenVersion"),
355                     'pygccxml_version': self.pygccxml_version,
356                  })
357
358     @property
359     def _install(self):
360         return (
361                  # Test if ns-3 is alredy cloned
362                 " ( "
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' )"
366                 " ) "
367                 " ||" 
368                 " (   "
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 && "
372                 "  ./waf && "
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 "
375                 " )"
376              ) % ({ 
377                     'ns3_version': self.get("ns3Version"),
378                     'pybindgen_version': self.get("pybindgenVersion"),
379                     'build_mode': self.get("buildMode"),
380                  })
381
382     @property
383     def _environment(self):
384         env = []
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")
388                  }))
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")
392                  }))
393
394         return " ".join(env) 
395
396     def valid_connection(self, guid):
397         # TODO: Validate!
398         return True
399