Ns3 linux example
[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         IPV4_GLOBAL_ROUTING_HELPER_UUID
29 from nepi.resources.linux.ns3.ns3client import LinuxNS3Client
30
31 import os
32 import time
33
34 @clsinit_copy
35 class LinuxNS3Simulation(LinuxApplication, NS3Simulation):
36     _rtype = "LinuxNS3Simulation"
37
38     @classmethod
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,
45             flags = Flags.Design)
46
47         sched_type = Attribute("schedulerType",
48                 "The object class to use as the scheduler implementation",
49                 allowed = ["ns3::MapScheduler",
50                             "ns3::ListScheduler",
51                             "ns3::HeapScheduler",
52                             "ns3::MapScheduler",
53                             "ns3::CalendarScheduler"
54                     ],
55             default = "ns3::MapScheduler",
56             type = Types.Enumerate,
57             flags = Flags.Design)
58
59         check_sum = Attribute("checksumEnabled",
60                 "A global switch to enable all checksums for all protocols",
61             default = False,
62             type = Types.Bool,
63             flags = Flags.Design)
64
65         ns_log = Attribute("nsLog",
66             "NS_LOG environment variable. " \
67                     " Will only generate output if ns-3 is compiled in DEBUG mode. ",
68             flags = Flags.Design)
69
70         verbose = Attribute("verbose",
71             "True to output debugging info from the ns3 client-server communication",
72             type = Types.Bool,
73             flags = Flags.Design)
74
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,
80             flags = Flags.Design)
81
82         ns3_version = Attribute("ns3Version",
83             "Version of ns-3 to install from nsam repo",
84             default = "ns-3.19", 
85             flags = Flags.Design)
86
87         enable_dce = Attribute("enableDCE",
88             "Install DCE source code",
89             default = False, 
90             type = Types.Bool,
91             flags = Flags.Design)
92
93         pybindgen_version = Attribute("pybindgenVersion",
94             "Version of pybindgen to install from bazar repo",
95             default = "834", 
96             flags = Flags.Design)
97
98         populate_routing_tables = Attribute("populateRoutingTables",
99             "Invokes  Ipv4GlobalRoutingHelper.PopulateRoutingTables() ",
100             default = False,
101             type = Types.Bool,
102             flags = Flags.Design)
103
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)
114
115     def __init__(self, ec, guid):
116         LinuxApplication.__init__(self, ec, guid)
117         NS3Simulation.__init__(self)
118
119         self._client = None
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
124
125     @property
126     def socket_name(self):
127         return self._socket_name
128
129     @property
130     def remote_socket(self):
131         return os.path.join(self.run_home, self.socket_name)
132
133     @property
134     def dce_helper_uuid(self):
135         return self._dce_helper_uuid
136
137     @property
138     def dce_application_helper_uuid(self):
139         return self._dce_application_helper_uuid
140
141     @property
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")
145
146     def trace(self, name, attr = TraceAttr.ALL, block = 512, offset = 0):
147         self._client.flush() 
148         return LinuxApplication.trace(self, name, attr, block, offset)
149
150     def upload_sources(self):
151         self.node.mkdir(os.path.join(self.node.src_dir, "ns3wrapper"))
152
153         # upload ns3 wrapper python script
154         ns3_wrapper = os.path.join(os.path.dirname(__file__), "..", "..", "ns3", 
155                 "ns3wrapper.py")
156
157         self.node.upload(ns3_wrapper,
158                 os.path.join(self.node.src_dir, "ns3wrapper", "ns3wrapper.py"),
159                 overwrite = False)
160
161         # upload ns3_server python script
162         ns3_server = os.path.join(os.path.dirname(__file__), "..", "..", "ns3",
163                 "ns3server.py")
164
165         self.node.upload(ns3_server,
166                 os.path.join(self.node.src_dir, "ns3wrapper", "ns3server.py"),
167                 overwrite = False)
168
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)
173
174             self.node.upload(pygccxml_tar,
175                     os.path.join(self.node.src_dir, "%s.tar.gz" % self.pygccxml_version),
176                     overwrite = False)
177
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")
181
182         super(LinuxNS3Simulation, self).upload_sources(src_dir = src_dir)
183
184     def upload_start_command(self):
185         command = self.get("command")
186         env = self.get("env")
187
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)
195
196         shfile = os.path.join(self.app_home, "start.sh")
197         self.node.upload_command(command, 
198                     shfile = shfile,
199                     env = env,
200                     overwrite = True)
201
202         # Run the ns3wrapper 
203         self._run_in_background()
204
205     def configure(self):
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)
210
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)
215         
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)
220         
221         if self.get("enableDCE"):
222             self._dce_helper_uuid = self.create("DceManagerHelper")
223             self._dce_application_helper_uuid = self.create("DceApplicationHelper")
224
225     def do_deploy(self):
226         if not self.node or self.node.state < ResourceState.READY:
227             self.debug("---- RESCHEDULING DEPLOY ---- node state %s " % self.node.state )
228             
229             # ccnd needs to wait until node is deployed and running
230             self.ec.schedule(reschedule_delay, self.deploy)
231         else:
232             if not self.get("command"):
233                 self.set("command", self._start_command)
234             
235             if not self.get("depends"):
236                 self.set("depends", self._dependencies)
237
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", "")
243                     .replace(".tar","")
244                     .replace(".gz","")
245                     .replace(".zip","") )
246
247                 self.set("ns3Version", version)
248                 self.set("sources", source)
249
250             if not self.get("build"):
251                 self.set("build", self._build)
252
253             if not self.get("install"):
254                 self.set("install", self._install)
255
256             if not self.get("env"):
257                 self.set("env", self._environment)
258
259             self.do_discover()
260             self.do_provision()
261
262             # Create client
263             self._client = LinuxNS3Client(self)
264
265             self.configure()
266             
267             self.set_ready()
268
269     def do_start(self):
270         """ Starts simulation execution
271
272         """
273         self.info("Starting")
274
275         if self.state == ResourceState.READY:
276             if self.get("populateRoutingTables") == True:
277                 self.invoke(IPV4_GLOBAL_ROUTING_HELPER_UUID, "PopulateRoutingTables")
278
279             self._client.start() 
280
281             self.set_started()
282         else:
283             msg = " Failed to execute command '%s'" % command
284             self.error(msg, out, err)
285             raise RuntimeError, msg
286
287     def do_stop(self):
288         """ Stops simulation execution
289
290         """
291         if self.state == ResourceState.STARTED:
292             self._client.stop() 
293             self.set_stopped()
294
295     def do_release(self):
296         self.info("Releasing resource")
297
298         tear_down = self.get("tearDown")
299         if tear_down:
300             self.node.execute(tear_down)
301
302         self.do_stop()
303         self._client.shutdown()
304         LinuxApplication.do_stop(self)
305         
306         super(LinuxApplication, self).do_release()
307
308     @property
309     def _start_command(self):
310         command = [] 
311
312         command.append("PYTHONPATH=$PYTHONPATH:${SRC}/ns3wrapper/")
313         
314         command.append("python ${SRC}/ns3wrapper/ns3server.py -S %s" % \
315                 os.path.basename(self.remote_socket) )
316
317         ns_log = self.get("nsLog")
318         if ns_log:
319             command.append("-L '%s'" % ns_log)
320
321         if self.get("verbose"):
322             command.append("-v")
323
324         command = " ".join(command)
325         return command
326
327     @property
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")
333         return ""
334
335     @property
336     def ns3_repo(self):
337         return "http://code.nsnam.org"
338
339     @property
340     def pygccxml_version(self):
341         return "pygccxml-1.0.0"
342
343     @property
344     def dce_repo(self):
345         #return "http://code.nsnam.org/ns-3-dce"
346         return "http://code.nsnam.org/epmancini/ns-3-dce"
347
348     @property
349     def _build(self):
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")
353         if not source:
354             clone_ns3_cmd = "hg clone %(ns3_repo)s/%(ns3_version)s ${SRC}/ns-3/%(ns3_version)s" \
355                     % {
356                         'ns3_version': self.get("ns3Version"),
357                         'ns3_repo':  self.ns3_repo,       
358                       }
359         else:
360             if source.find(".tar.gz") > -1:
361                 clone_ns3_cmd = ( 
362                             "tar xzf ${SRC}/ns-3/%(basename)s " 
363                             " --strip-components=1 -C ${SRC}/ns-3/%(ns3_version)s "
364                             ) % {
365                                 'basename': os.path.basename(source),
366                                 'ns3_version': self.get("ns3Version"),
367                                 }
368             elif source.find(".tar") > -1:
369                 clone_ns3_cmd = ( 
370                             "tar xf ${SRC}/ns-3/%(basename)s " 
371                             " --strip-components=1 -C ${SRC}/ns-3/%(ns3_version)s "
372                             ) % {
373                                 'basename': os.path.basename(source),
374                                 'ns3_version': self.get("ns3Version"),
375                                 }
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", "")
381
382                 clone_ns3_cmd = ( 
383                             "unzip ${SRC}/ns-3/%(basename)s && "
384                             "mv ${SRC}/ns-3/%(bare_basename)s ${SRC}/ns-3/%(ns3_version)s "
385                             ) % {
386                                 'bare_basename': basename_name,
387                                 'basename': basename,
388                                 'ns3_version': self.get("ns3Version"),
389                                 }
390
391         clone_dce_cmd = " echo 'DCE will not be built' "
392         if self.get("enableDCE"):
393             clone_dce_cmd = (
394                         # DCE installation
395                         # Test if dce is alredy installed
396                         " ( "
397                         "  ( "
398                         "    ( test -d ${SRC}/dce/ns-3-dce ) "
399                         "   && echo 'dce binaries found, nothing to do'"
400                         "  ) "
401                         " ) "
402                         "  || " 
403                         # Get dce source code
404                         " ( "
405                         "   mkdir -p ${SRC}/dce && "
406                         "   hg clone %(dce_repo)s ${SRC}/dce/ns-3-dce"
407                         " ) "
408                      ) % {
409                             'dce_repo': self.dce_repo
410                          }
411
412
413         return (
414                 # NS3 installation
415                 "( "
416                 " ( "
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' )"
421                 " ) "
422                 "  || " 
423                 # If not, install ns-3 and its dependencies
424                 " (   "
425                 # Install pygccxml
426                 "   (   "
427                 "     ( "
428                 "       python -c 'import pygccxml' && "
429                 "       echo 'pygccxml not found' "
430                 "     ) "
431                 "      || "
432                 "     ( "
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 "
437                 "     ) "
438                 "   ) " 
439                 # Install pybindgen
440                 "  && "
441                 "   (   "
442                 "     ( "
443                 "       test -d ${SRC}/pybindgen/%(pybindgen_version)s && "
444                 "       echo 'binaries found, nothing to do' "
445                 "     ) "
446                 "      || "
447                 # If not, clone and build
448                 "      ( cd ${SRC} && "
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 && "
453                 "        ./waf "
454                 "      ) "
455                 "   ) " 
456                 " && "
457                 # Get ns-3 source code
458                 "  ( "
459                 "     mkdir -p ${SRC}/ns-3/%(ns3_version)s && "
460                 "     %(clone_ns3_cmd)s "
461                 "  ) "
462                 " ) "
463                 ") "
464                 " && "
465                 "( "
466                 "   %(clone_dce_cmd)s "
467                 ") "
468              ) % { 
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,
474                  }
475
476     @property
477     def _install(self):
478         install_dce_cmd = " echo 'DCE will not be installed' "
479         if self.get("enableDCE"):
480             install_dce_cmd = (
481                         " ( "
482                         "   ((test -d %(ns3_build_home)s/bin_dce ) && "
483                         "    echo 'dce binaries found, nothing to do' )"
484                         " ) "
485                         " ||" 
486                         " (   "
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 && "
491                         "  ./waf build && "
492                         "  ./waf install && "
493                         "  mv %(ns3_build_home)s/lib/python*/site-packages/ns/dce.so %(ns3_build_home)s/lib/python/site-packages/ns/ "
494                         " )"
495                 ) % { 
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 ""
501                     }
502
503         return (
504                  # Test if ns-3 is alredy installed
505                 "("
506                 " ( "
507                 "  ( ( (test -d %(ns3_build_home)s/lib ) || "
508                 "    (test -d ${NS3BINDINGS:='None'} && test -d ${NS3LIBRARIES:='None'}) ) && "
509                 "    echo 'binaries found, nothing to do' )"
510                 " ) "
511                 " ||" 
512                 " (   "
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 && "
518                 "  ./waf build && "
519                 "  ./waf install && "
520                 "  mv %(ns3_build_home)s/lib/python* %(ns3_build_home)s/lib/python "
521                 " )"
522                 ") "
523                 " && "
524                 "( "
525                 "   %(install_dce_cmd)s "
526                 ") "
527               ) % { 
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
533                  }
534
535     @property
536     def _environment(self):
537         env = []
538         env.append("PYTHONPATH=$PYTHONPATH:${NS3BINDINGS:=%(ns3_build_home)s/lib/python/site-packages}" % { 
539                     'ns3_build_home': self.ns3_build_home
540                  })
541         env.append("LD_LIBRARY_PATH=${NS3LIBRARIES:=%(ns3_build_home)s/lib/}" % { 
542                     'ns3_build_home': self.ns3_build_home
543                  })
544         env.append("DCE_PATH=$PATH:$NS3LIBRARIES/../bin_dce")
545         env.append("DCE_ROOT=$PATH:$NS3LIBRARIES/..")
546
547         return " ".join(env) 
548
549     def valid_connection(self, guid):
550         # TODO: Validate!
551         return True
552