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