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