NEPI DCE integration with CCN 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 import threading
34
35 ## TODO: Clean up DCE part. All that is DCE specific should go
36 ##       in the linux ns3dceapplication.py
37
38 @clsinit_copy
39 class LinuxNS3Simulation(LinuxApplication, NS3Simulation):
40     _rtype = "LinuxNS3Simulation"
41
42     @classmethod
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,
49             flags = Flags.Design)
50
51         sched_type = Attribute("schedulerType",
52                 "The object class to use as the scheduler implementation",
53                 allowed = ["ns3::MapScheduler",
54                             "ns3::ListScheduler",
55                             "ns3::HeapScheduler",
56                             "ns3::MapScheduler",
57                             "ns3::CalendarScheduler"
58                     ],
59             default = "ns3::MapScheduler",
60             type = Types.Enumerate,
61             flags = Flags.Design)
62
63         check_sum = Attribute("checksumEnabled",
64                 "A global switch to enable all checksums for all protocols",
65             default = False,
66             type = Types.Bool,
67             flags = Flags.Design)
68
69         ns_log = Attribute("nsLog",
70             "NS_LOG environment variable. " \
71                     " Will only generate output if ns-3 is compiled in DEBUG mode. ",
72             flags = Flags.Design)
73
74         verbose = Attribute("verbose",
75             "True to output debugging info from the ns3 client-server communication",
76             type = Types.Bool,
77             flags = Flags.Design)
78
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,
84             flags = Flags.Design)
85
86         ns3_version = Attribute("ns3Version",
87             "Version of ns-3 to install from nsam repo",
88             #default = "ns-3.19", 
89             default = "ns-3-dev", 
90             flags = Flags.Design)
91
92         enable_dce = Attribute("enableDCE",
93             "Install DCE source code",
94             default = False, 
95             type = Types.Bool,
96             flags = Flags.Design)
97
98         pybindgen_version = Attribute("pybindgenVersion",
99             "Version of pybindgen to install from bazar repo",
100             default = "868", 
101             flags = Flags.Design)
102
103         populate_routing_tables = Attribute("populateRoutingTables",
104             "Invokes  Ipv4GlobalRoutingHelper.PopulateRoutingTables() ",
105             default = False,
106             type = Types.Bool,
107             flags = Flags.Design)
108
109         cls._register_attribute(impl_type)
110         cls._register_attribute(sched_type)
111         cls._register_attribute(check_sum)
112         cls._register_attribute(ns_log)
113         cls._register_attribute(verbose)
114         cls._register_attribute(build_mode)
115         cls._register_attribute(ns3_version)
116         cls._register_attribute(pybindgen_version)
117         cls._register_attribute(populate_routing_tables)
118         cls._register_attribute(enable_dce)
119
120     def __init__(self, ec, guid):
121         LinuxApplication.__init__(self, ec, guid)
122         NS3Simulation.__init__(self)
123
124         self._client = None
125         self._home = "ns3-simu-%s" % self.guid
126         self._socket_name = "ns3-%s.sock" % os.urandom(4).encode('hex')
127         self._dce_manager_helper_uuid = None
128         self._dce_application_helper_uuid = None
129
130     @property
131     def socket_name(self):
132         return self._socket_name
133
134     @property
135     def remote_socket(self):
136         return os.path.join(self.run_home, self.socket_name)
137
138     @property
139     def ns3_build_home(self):
140         return os.path.join(self.node.bin_dir, "ns-3", self.get("ns3Version"), 
141                 self.get("buildMode"), "build")
142
143     def trace(self, name, attr = TraceAttr.ALL, block = 512, offset = 0):
144         self._client.flush() 
145         return LinuxApplication.trace(self, name, attr, block, offset)
146
147     def upload_sources(self):
148         self.node.mkdir(os.path.join(self.node.src_dir, "ns3wrapper"))
149
150         # upload ns3 wrapper python script
151         ns3_wrapper = os.path.join(os.path.dirname(__file__), "..", "..", "ns3", 
152                 "ns3wrapper.py")
153
154         self.node.upload(ns3_wrapper,
155                 os.path.join(self.node.src_dir, "ns3wrapper", "ns3wrapper.py"),
156                 overwrite = False)
157
158         # upload ns3_server python script
159         ns3_server = os.path.join(os.path.dirname(__file__), "..", "..", "ns3",
160                 "ns3server.py")
161
162         self.node.upload(ns3_server,
163                 os.path.join(self.node.src_dir, "ns3wrapper", "ns3server.py"),
164                 overwrite = False)
165
166         if self.node.use_rpm:
167             # upload pygccxml sources
168             pygccxml_tar = os.path.join(os.path.dirname(__file__), "dependencies",
169                     "%s.tar.gz" % self.pygccxml_version)
170
171             self.node.upload(pygccxml_tar,
172                     os.path.join(self.node.src_dir, "%s.tar.gz" % self.pygccxml_version),
173                     overwrite = False)
174
175         # Upload user defined ns-3 sources
176         self.node.mkdir(os.path.join(self.node.src_dir, "ns-3"))
177         src_dir = os.path.join(self.node.src_dir, "ns-3")
178
179         super(LinuxNS3Simulation, self).upload_sources(src_dir = src_dir)
180     
181     def upload_extra_sources(self, sources = None, src_dir = None):
182         return super(LinuxNS3Simulation, self).upload_sources(
183                 sources = sources, 
184                 src_dir = src_dir)
185
186     def upload_start_command(self):
187         command = self.get("command")
188         env = self.get("env")
189
190         # We want to make sure the ccnd is running
191         # before the experiment starts.
192         # Run the command as a bash script in background,
193         # in the host ( but wait until the command has
194         # finished to continue )
195         env = self.replace_paths(env)
196         command = self.replace_paths(command)
197
198         shfile = os.path.join(self.app_home, "start.sh")
199         self.node.upload_command(command, 
200                     shfile = shfile,
201                     env = env,
202                     overwrite = True)
203
204         # Run the ns3wrapper 
205         self._run_in_background()
206
207     def configure(self):
208         if self.has_changed("simulatorImplementationType"):
209             simu_type = self.get("simulatorImplementationType")
210             stype = self.create("StringValue", simu_type)
211             self.invoke(GLOBAL_VALUE_UUID, "Bind", "SimulatorImplementationType", stype)
212
213         if self.has_changed("checksumEnabled"):
214             check_sum = self.get("checksumEnabled")
215             btrue = self.create("BooleanValue", check_sum)    
216             self.invoke(GLOBAL_VALUE_UUID, "Bind", "ChecksumEnabled", btrue)
217         
218         if self.has_changed("schedulerType"):
219             sched_type = self.get("schedulerType")
220             stype = self.create("StringValue", sched_type)
221             self.invoke(GLOBAL_VALUE_UUID, "Bind", "SchedulerType", btrue)
222         
223     def do_deploy(self):
224         if not self.node or self.node.state < ResourceState.READY:
225             self.debug("---- RESCHEDULING DEPLOY ---- node state %s " % self.node.state )
226             
227             # ccnd needs to wait until node is deployed and running
228             self.ec.schedule(reschedule_delay, self.deploy)
229         else:
230             if not self.get("command"):
231                 self.set("command", self._start_command)
232             
233             if not self.get("depends"):
234                 self.set("depends", self._dependencies)
235
236             if self.get("sources"):
237                 sources = self.get("sources")
238                 source = sources.split(" ")[0]
239                 basename = os.path.basename(source)
240                 version = ( basename.strip().replace(".tar.gz", "")
241                     .replace(".tar","")
242                     .replace(".gz","")
243                     .replace(".zip","") )
244
245                 self.set("ns3Version", version)
246                 self.set("sources", source)
247
248             if not self.get("build"):
249                 self.set("build", self._build)
250
251             if not self.get("install"):
252                 self.set("install", self._install)
253
254             if not self.get("env"):
255                 self.set("env", self._environment)
256
257             self.do_discover()
258             self.do_provision()
259
260             # Create client
261             self._client = LinuxNS3Client(self)
262
263             self.configure()
264             
265             self.set_ready()
266
267     def do_start(self):
268         """ Starts simulation execution
269
270         """
271         self.info("Starting")
272
273         if self.state == ResourceState.READY:
274             if self.get("populateRoutingTables") == True:
275                 self.invoke(IPV4_GLOBAL_ROUTING_HELPER_UUID, "PopulateRoutingTables")
276
277             self._client.start() 
278
279             self.set_started()
280         else:
281             msg = " Failed to execute command '%s'" % command
282             self.error(msg, out, err)
283             raise RuntimeError, msg
284
285     def do_stop(self):
286         """ Stops simulation execution
287
288         """
289         if self.state == ResourceState.STARTED:
290             self._client.stop() 
291             self.set_stopped()
292
293     def do_release(self):
294         self.info("Releasing resource")
295
296         tear_down = self.get("tearDown")
297         if tear_down:
298             self.node.execute(tear_down)
299
300         self.do_stop()
301         self._client.shutdown()
302         LinuxApplication.do_stop(self)
303         
304         super(LinuxApplication, self).do_release()
305
306     @property
307     def _start_command(self):
308         command = [] 
309
310         command.append("PYTHONPATH=$PYTHONPATH:${SRC}/ns3wrapper/")
311         
312         command.append("python ${SRC}/ns3wrapper/ns3server.py -S %s" % \
313                 os.path.basename(self.remote_socket) )
314
315         ns_log = self.get("nsLog")
316         if ns_log:
317             command.append("-L '%s'" % ns_log)
318
319         if self.get("verbose"):
320             command.append("-v")
321
322         command = " ".join(command)
323         return command
324
325     @property
326     def _dependencies(self):
327         if self.node.use_rpm:
328             return ( " gcc gcc-c++ python python-devel mercurial bzr tcpdump socat gccxml unzip")
329         elif self.node.use_deb:
330             return ( " gcc g++ python python-dev mercurial bzr tcpdump socat gccxml python-pygccxml unzip")
331         return ""
332
333     @property
334     def ns3_repo(self):
335         return "http://code.nsnam.org"
336
337     @property
338     def pygccxml_version(self):
339         return "pygccxml-1.0.0"
340
341     @property
342     def dce_repo(self):
343         return "http://code.nsnam.org/ns-3-dce"
344         #eturn "http://code.nsnam.org/epmancini/ns-3-dce"
345
346     @property
347     def _build(self):
348         # If the user defined local sources for ns-3, we uncompress the sources
349         # on the remote sources directory. Else we clone ns-3 from the official repo.
350         source = self.get("sources")
351         if not source:
352             clone_ns3_cmd = "hg clone %(ns3_repo)s/%(ns3_version)s ${SRC}/ns-3/%(ns3_version)s" \
353                     % {
354                         'ns3_version': self.get("ns3Version"),
355                         'ns3_repo':  self.ns3_repo,       
356                       }
357         else:
358             if source.find(".tar.gz") > -1:
359                 clone_ns3_cmd = ( 
360                             "tar xzf ${SRC}/ns-3/%(basename)s " 
361                             " --strip-components=1 -C ${SRC}/ns-3/%(ns3_version)s "
362                             ) % {
363                                 'basename': os.path.basename(source),
364                                 'ns3_version': self.get("ns3Version"),
365                                 }
366             elif source.find(".tar") > -1:
367                 clone_ns3_cmd = ( 
368                             "tar xf ${SRC}/ns-3/%(basename)s " 
369                             " --strip-components=1 -C ${SRC}/ns-3/%(ns3_version)s "
370                             ) % {
371                                 'basename': os.path.basename(source),
372                                 'ns3_version': self.get("ns3Version"),
373                                 }
374             elif source.find(".zip") > -1:
375                 basename = os.path.basename(source)
376                 bare_basename = basename.replace(".zip", "") \
377                         .replace(".tar", "") \
378                         .replace(".tar.gz", "")
379
380                 clone_ns3_cmd = ( 
381                             "unzip ${SRC}/ns-3/%(basename)s && "
382                             "mv ${SRC}/ns-3/%(bare_basename)s ${SRC}/ns-3/%(ns3_version)s "
383                             ) % {
384                                 'bare_basename': basename_name,
385                                 'basename': basename,
386                                 'ns3_version': self.get("ns3Version"),
387                                 }
388
389         clone_dce_cmd = " echo 'DCE will not be built' "
390         if self.get("enableDCE"):
391             clone_dce_cmd = (
392                         # DCE installation
393                         # Test if dce is alredy installed
394                         " ( "
395                         "  ( "
396                         "    ( test -d ${SRC}/dce/ns-3-dce ) "
397                         "   && echo 'dce binaries found, nothing to do'"
398                         "  ) "
399                         " ) "
400                         "  || " 
401                         # Get dce source code
402                         " ( "
403                         "   mkdir -p ${SRC}/dce && "
404                         "   hg clone %(dce_repo)s ${SRC}/dce/ns-3-dce"
405                         " ) "
406                      ) % {
407                             'dce_repo': self.dce_repo
408                          }
409
410
411         return (
412                 # NS3 installation
413                 "( "
414                 " ( "
415                 # Test if ns-3 is alredy installed
416                 "  ((( test -d ${SRC}/ns-3/%(ns3_version)s ) || "
417                 "    ( test -d ${NS3BINDINGS:='None'} && test -d ${NS3LIBRARIES:='None'})) "
418                 "  && echo 'ns-3 binaries found, nothing to do' )"
419                 " ) "
420                 "  || " 
421                 # If not, install ns-3 and its dependencies
422                 " (   "
423                 # Install pygccxml
424                 "   (   "
425                 "     ( "
426                 "       python -c 'import pygccxml' && "
427                 "       echo 'pygccxml not found' "
428                 "     ) "
429                 "      || "
430                 "     ( "
431                 "       tar xf ${SRC}/%(pygccxml_version)s.tar.gz -C ${SRC} && "
432                 "       cd ${SRC}/%(pygccxml_version)s && "
433                 "       python setup.py build && "
434                 "       sudo -S python setup.py install "
435                 "     ) "
436                 "   ) " 
437                 # Install pybindgen
438                 "  && "
439                 "   (   "
440                 "     ( "
441                 "       test -d ${SRC}/pybindgen/%(pybindgen_version)s && "
442                 "       echo 'binaries found, nothing to do' "
443                 "     ) "
444                 "      || "
445                 # If not, clone and build
446                 "      ( cd ${SRC} && "
447                 "        mkdir -p ${SRC}/pybindgen && "
448                 "        bzr checkout lp:pybindgen -r %(pybindgen_version)s ${SRC}/pybindgen/%(pybindgen_version)s && "
449                 "        cd ${SRC}/pybindgen/%(pybindgen_version)s && "
450                 "        ./waf configure && "
451                 "        ./waf "
452                 "      ) "
453                 "   ) " 
454                 " && "
455                 # Get ns-3 source code
456                 "  ( "
457                 "     mkdir -p ${SRC}/ns-3/%(ns3_version)s && "
458                 "     %(clone_ns3_cmd)s "
459                 "  ) "
460                 " ) "
461                 ") "
462                 " && "
463                 "( "
464                 "   %(clone_dce_cmd)s "
465                 ") "
466              ) % { 
467                     'ns3_version': self.get("ns3Version"),
468                     'pybindgen_version': self.get("pybindgenVersion"),
469                     'pygccxml_version': self.pygccxml_version,
470                     'clone_ns3_cmd': clone_ns3_cmd,
471                     'clone_dce_cmd': clone_dce_cmd,
472                  }
473
474     @property
475     def _install(self):
476         install_dce_cmd = " echo 'DCE will not be installed' "
477         if self.get("enableDCE"):
478             install_dce_cmd = (
479                         " ( "
480                         "   ((test -d %(ns3_build_home)s/bin_dce ) && "
481                         "    echo 'dce binaries found, nothing to do' )"
482                         " ) "
483                         " ||" 
484                         " (   "
485                          # If not, copy ns-3 build to bin
486                         "  cd ${SRC}/dce/ns-3-dce && "
487                         "  ./waf configure %(enable_opt)s --with-pybindgen=${SRC}/pybindgen/%(pybindgen_version)s "
488                         "  --prefix=%(ns3_build_home)s --with-ns3=%(ns3_build_home)s && "
489                         "  ./waf build && "
490                         "  ./waf install && "
491                         "  mv %(ns3_build_home)s/lib*/python*/site-packages/ns/dce.so %(ns3_build_home)s/lib/python/site-packages/ns/ "
492                         " )"
493                 ) % { 
494                     'ns3_version': self.get("ns3Version"),
495                     'pybindgen_version': self.get("pybindgenVersion"),
496                     'ns3_build_home': self.ns3_build_home,
497                     'build_mode': self.get("buildMode"),
498                     'enable_opt': "--enable-opt" if  self.get("buildMode") == "optimized" else ""
499                     }
500
501         return (
502                  # Test if ns-3 is alredy installed
503                 "("
504                 " ( "
505                 "  ( ( (test -d %(ns3_build_home)s/lib ) || "
506                 "    (test -d ${NS3BINDINGS:='None'} && test -d ${NS3LIBRARIES:='None'}) ) && "
507                 "    echo 'binaries found, nothing to do' )"
508                 " ) "
509                 " ||" 
510                 " (   "
511                  # If not, copy ns-3 build to bin
512                 "  mkdir -p %(ns3_build_home)s && "
513                 "  cd ${SRC}/ns-3/%(ns3_version)s && "
514                 "  ./waf configure -d %(build_mode)s --with-pybindgen=${SRC}/pybindgen/%(pybindgen_version)s "
515                 "  --prefix=%(ns3_build_home)s && "
516                 "  ./waf build && "
517                 "  ./waf install && "
518                 "  mv %(ns3_build_home)s/lib*/python* %(ns3_build_home)s/lib/python "
519                 " )"
520                 ") "
521                 " && "
522                 "( "
523                 "   %(install_dce_cmd)s "
524                 ") "
525               ) % { 
526                     'ns3_version': self.get("ns3Version"),
527                     'pybindgen_version': self.get("pybindgenVersion"),
528                     'build_mode': self.get("buildMode"),
529                     'ns3_build_home': self.ns3_build_home,
530                     'install_dce_cmd': install_dce_cmd
531                  }
532
533     @property
534     def _environment(self):
535         env = []
536         env.append("PYTHONPATH=$PYTHONPATH:${NS3BINDINGS:=%(ns3_build_home)s/lib/python/site-packages}" % { 
537                     'ns3_build_home': self.ns3_build_home
538                  })
539         # If NS3LIBRARIES is defined and not empty, assign its value, 
540         # if not assign ns3_build_home/lib/ to NS3LIBRARIES and LD_LIBARY_PATH
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=$NS3LIBRARIES/../bin_dce")
545         env.append("DCE_ROOT=$NS3LIBRARIES/..")
546
547         return " ".join(env) 
548
549     def replace_paths(self, command):
550         """
551         Replace all special path tags with shell-escaped actual paths.
552         """
553         return ( command
554             .replace("${USR}", self.node.usr_dir)
555             .replace("${LIB}", self.node.lib_dir)
556             .replace("${BIN}", self.node.bin_dir)
557             .replace("${SRC}", self.node.src_dir)
558             .replace("${SHARE}", self.node.share_dir)
559             .replace("${EXP}", self.node.exp_dir)
560             .replace("${EXP_HOME}", self.node.exp_home)
561             .replace("${APP_HOME}", self.app_home)
562             .replace("${RUN_HOME}", self.run_home)
563             .replace("${NODE_HOME}", self.node.node_home)
564             .replace("${HOME}", self.node.home_dir)
565             # If NS3LIBRARIES is defined and not empty, use that value, 
566             # if not use ns3_build_home/lib/
567             .replace("${BIN_DCE}", "${NS3LIBRARIES-%s/lib}/../bin_dce" % \
568                     self.ns3_build_home)
569             )
570
571     def valid_connection(self, guid):
572         # TODO: Validate!
573         return True
574