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