Adding DCE version and checking the ns3server socket is created before finishing...
[nepi.git] / src / nepi / resources / linux / ns3 / ns3simulation.py
index 69cdf18..2703246 100644 (file)
@@ -20,7 +20,7 @@
 from nepi.execution.attribute import Attribute, Flags, Types
 from nepi.execution.trace import Trace, TraceAttr
 from nepi.execution.resource import ResourceManager, clsinit_copy, \
-        ResourceState, reschedule_delay
+        ResourceState, ResourceFactory, reschedule_delay
 from nepi.resources.linux.application import LinuxApplication
 from nepi.util.timefuncs import tnow, tdiffsec
 from nepi.resources.ns3.ns3simulation import NS3Simulation
@@ -30,6 +30,10 @@ from nepi.resources.linux.ns3.ns3client import LinuxNS3Client
 
 import os
 import time
+import threading
+
+## TODO: Clean up DCE part. All that is DCE specific should go
+##       in the linux ns3dceapplication.py
 
 @clsinit_copy
 class LinuxNS3Simulation(LinuxApplication, NS3Simulation):
@@ -72,6 +76,13 @@ class LinuxNS3Simulation(LinuxApplication, NS3Simulation):
             type = Types.Bool,
             flags = Flags.Design)
 
+        enable_dump = Attribute("enableDump",
+            "Enable dumping the remote executed ns-3 commands to a script "
+            "in order to later reproduce and debug the experiment",
+            type = Types.Bool,
+            default = False,
+            flags = Flags.Design)
+
         build_mode = Attribute("buildMode",
             "Mode used to build ns-3 with waf. One if: debug, release, oprimized ",
             default = "optimized", 
@@ -81,18 +92,22 @@ class LinuxNS3Simulation(LinuxApplication, NS3Simulation):
 
         ns3_version = Attribute("ns3Version",
             "Version of ns-3 to install from nsam repo",
-            default = "ns-3.19", 
-            flags = Flags.Design)
-
-        enable_dce = Attribute("enableDCE",
-            "Install DCE source code",
-            default = False, 
-            type = Types.Bool,
+            #default = "ns-3.19", 
+            default = "ns-3.20", 
+            #default = "ns-3-dev", 
             flags = Flags.Design)
 
         pybindgen_version = Attribute("pybindgenVersion",
             "Version of pybindgen to install from bazar repo",
-            default = "834", 
+            #default = "864", 
+            default = "868", 
+            #default = "876", 
+            flags = Flags.Design)
+
+        dce_version = Attribute("dceVersion",
+            "Version of dce to install from nsam repo (tag branch for repo)",
+            default = "dce-1.3", 
+            #default = "dce-dev", 
             flags = Flags.Design)
 
         populate_routing_tables = Attribute("populateRoutingTables",
@@ -101,16 +116,22 @@ class LinuxNS3Simulation(LinuxApplication, NS3Simulation):
             type = Types.Bool,
             flags = Flags.Design)
 
+        stoptime = Attribute("stopTime",
+            "Time at which the simulation will stop",
+            flags = Flags.Design)
+
         cls._register_attribute(impl_type)
         cls._register_attribute(sched_type)
         cls._register_attribute(check_sum)
         cls._register_attribute(ns_log)
+        cls._register_attribute(enable_dump)
         cls._register_attribute(verbose)
         cls._register_attribute(build_mode)
         cls._register_attribute(ns3_version)
         cls._register_attribute(pybindgen_version)
+        cls._register_attribute(dce_version)
         cls._register_attribute(populate_routing_tables)
-        cls._register_attribute(enable_dce)
+        cls._register_attribute(stoptime)
 
     def __init__(self, ec, guid):
         LinuxApplication.__init__(self, ec, guid)
@@ -119,8 +140,9 @@ class LinuxNS3Simulation(LinuxApplication, NS3Simulation):
         self._client = None
         self._home = "ns3-simu-%s" % self.guid
         self._socket_name = "ns3-%s.sock" % os.urandom(4).encode('hex')
-        self._dce_helper_uuid = None
+        self._dce_manager_helper_uuid = None
         self._dce_application_helper_uuid = None
+        self._enable_dce = None
 
     @property
     def socket_name(self):
@@ -130,21 +152,24 @@ class LinuxNS3Simulation(LinuxApplication, NS3Simulation):
     def remote_socket(self):
         return os.path.join(self.run_home, self.socket_name)
 
-    @property
-    def dce_helper_uuid(self):
-        return self._dce_helper_uuid
-
-    @property
-    def dce_application_helper_uuid(self):
-        return self._dce_application_helper_uuid
-
     @property
     def ns3_build_home(self):
         return os.path.join(self.node.bin_dir, "ns-3", self.get("ns3Version"), 
                 self.get("buildMode"), "build")
 
     def trace(self, name, attr = TraceAttr.ALL, block = 512, offset = 0):
-        self._client.flush() 
+        # stout needs to get flushed on the ns-3 server side, else we will 
+        # get an empty stream. We try twice to retrieve the stream
+        # if we get empty stdout since the stream might not be
+        # flushed immediately.
+        if name.endswith("stdout"):
+            self._client.flush() 
+            result = LinuxApplication.trace(self, name, attr, block, offset)
+            if result:
+                return result
+            # Let the stream be flushed
+            time.sleep(1)
+
         return LinuxApplication.trace(self, name, attr, block, offset)
 
     def upload_sources(self):
@@ -158,6 +183,14 @@ class LinuxNS3Simulation(LinuxApplication, NS3Simulation):
                 os.path.join(self.node.src_dir, "ns3wrapper", "ns3wrapper.py"),
                 overwrite = False)
 
+        # upload ns3 wrapper debug python script
+        ns3_wrapper_debug = os.path.join(os.path.dirname(__file__), "..", "..", "ns3", 
+                "ns3wrapper_debug.py")
+
+        self.node.upload(ns3_wrapper_debug,
+                os.path.join(self.node.src_dir, "ns3wrapper", "ns3wrapper_debug.py"),
+                overwrite = False)
+
         # upload ns3_server python script
         ns3_server = os.path.join(os.path.dirname(__file__), "..", "..", "ns3",
                 "ns3server.py")
@@ -180,6 +213,11 @@ class LinuxNS3Simulation(LinuxApplication, NS3Simulation):
         src_dir = os.path.join(self.node.src_dir, "ns-3")
 
         super(LinuxNS3Simulation, self).upload_sources(src_dir = src_dir)
+    
+    def upload_extra_sources(self, sources = None, src_dir = None):
+        return super(LinuxNS3Simulation, self).upload_sources(
+                sources = sources, 
+                src_dir = src_dir)
 
     def upload_start_command(self):
         command = self.get("command")
@@ -202,6 +240,9 @@ class LinuxNS3Simulation(LinuxApplication, NS3Simulation):
         # Run the ns3wrapper 
         self._run_in_background()
 
+        # Wait until the remote socket is created
+        self.wait_remote_socket()
+
     def configure(self):
         if self.has_changed("simulatorImplementationType"):
             simu_type = self.get("simulatorImplementationType")
@@ -218,10 +259,6 @@ class LinuxNS3Simulation(LinuxApplication, NS3Simulation):
             stype = self.create("StringValue", sched_type)
             self.invoke(GLOBAL_VALUE_UUID, "Bind", "SchedulerType", btrue)
         
-        if self.get("enableDCE"):
-            self._dce_helper_uuid = self.create("DceManagerHelper")
-            self._dce_application_helper_uuid = self.create("DceApplicationHelper")
-
     def do_deploy(self):
         if not self.node or self.node.state < ResourceState.READY:
             self.debug("---- RESCHEDULING DEPLOY ---- node state %s " % self.node.state )
@@ -276,8 +313,26 @@ class LinuxNS3Simulation(LinuxApplication, NS3Simulation):
             if self.get("populateRoutingTables") == True:
                 self.invoke(IPV4_GLOBAL_ROUTING_HELPER_UUID, "PopulateRoutingTables")
 
-            self._client.start() 
+            self._client.start()
 
+            """
+            # XXX: IS THIS REALLY NEEDED??!!!
+            # Wait until the Simulation is actually started... 
+            is_running = False
+            for i in xrange(1000):
+                is_running = self.invoke(SIMULATOR_UUID, "isRunning")
+                is_finished = self.invoke(SIMULATOR_UUID, "isFinished")
+            
+                if is_running or is_finished:
+                    break
+                else:
+                    time.sleep(1)
+            else:
+                if not is_running:
+                    msg = " Simulation did not start"
+                    self.error(msg)
+                    raise RuntimeError
+            """
             self.set_started()
         else:
             msg = " Failed to execute command '%s'" % command
@@ -289,7 +344,11 @@ class LinuxNS3Simulation(LinuxApplication, NS3Simulation):
 
         """
         if self.state == ResourceState.STARTED:
-            self._client.stop() 
+            time = None
+            if self.get("stopTime"):
+                time = self.get("stopTime")
+
+            self._client.stop(time=time) 
             self.set_stopped()
 
     def do_release(self):
@@ -305,6 +364,22 @@ class LinuxNS3Simulation(LinuxApplication, NS3Simulation):
         
         super(LinuxApplication, self).do_release()
 
+    @property
+    def enable_dce(self):
+        if self._enable_dce is None:
+            from nepi.resources.ns3.ns3dceapplication import NS3BaseDceApplication
+            rclass = ResourceFactory.get_resource_type(
+                    NS3BaseDceApplication.get_rtype())
+            
+            self._enable_dce = False
+            for guid in self.ec.resources:
+                rm = self.ec.get_resource(guid)
+                if isinstance(rm, rclass):
+                    self._enable_dce = True
+                    break
+
+        return self._enable_dce
+
     @property
     def _start_command(self):
         command = [] 
@@ -318,6 +393,9 @@ class LinuxNS3Simulation(LinuxApplication, NS3Simulation):
         if ns_log:
             command.append("-L '%s'" % ns_log)
 
+        if self.get("enableDump"):
+            command.append("-D")
+
         if self.get("verbose"):
             command.append("-v")
 
@@ -342,8 +420,13 @@ class LinuxNS3Simulation(LinuxApplication, NS3Simulation):
 
     @property
     def dce_repo(self):
-        #return "http://code.nsnam.org/ns-3-dce"
-        return "http://code.nsnam.org/epmancini/ns-3-dce"
+        return "http://code.nsnam.org/ns-3-dce"
+        #eturn "http://code.nsnam.org/epmancini/ns-3-dce"
+
+    @property
+    def dce_version(self):
+        dce_version = self.get("dceVersion")
+        return dce_version or "dce-dev"
 
     @property
     def _build(self):
@@ -389,27 +472,33 @@ class LinuxNS3Simulation(LinuxApplication, NS3Simulation):
                                 }
 
         clone_dce_cmd = " echo 'DCE will not be built' "
-        if self.get("enableDCE"):
+        if self.enable_dce:
+            dce_version = self.dce_version
+            dce_tag = ""
+            if dce_version != "dce-dev":
+                dce_tag = "-r %s" % dce_version
+
             clone_dce_cmd = (
                         # DCE installation
                         # Test if dce is alredy installed
                         " ( "
                         "  ( "
-                        "    ( test -d ${SRC}/dce/ns-3-dce ) "
+                        "    ( test -d ${SRC}/dce/ns-3-dce/%(dce_version)s ) "
                         "   && echo 'dce binaries found, nothing to do'"
                         "  ) "
                         " ) "
                         "  || " 
                         # Get dce source code
                         " ( "
-                        "   mkdir -p ${SRC}/dce && "
-                        "   hg clone %(dce_repo)s ${SRC}/dce/ns-3-dce"
+                        "   mkdir -p ${SRC}/dce/%(dce_version)s && "
+                        "   hg clone %(dce_repo)s %(dce_tag)s ${SRC}/dce/ns-3-dce/%(dce_version)s"
                         " ) "
                      ) % {
-                            'dce_repo': self.dce_repo
+                            "dce_repo": self.dce_repo,
+                            "dce_tag": dce_tag,
+                            "dce_version":  dce_version,
                          }
 
-
         return (
                 # NS3 installation
                 "( "
@@ -476,28 +565,30 @@ class LinuxNS3Simulation(LinuxApplication, NS3Simulation):
     @property
     def _install(self):
         install_dce_cmd = " echo 'DCE will not be installed' "
-        if self.get("enableDCE"):
+        if self.enable_dce:
             install_dce_cmd = (
                         " ( "
-                        "   ((test -d %(ns3_build_home)s/bin_dce ) && "
+                        "   ((test -d %(ns3_build_home)s/bin_dce/%(dce_version)s ) && "
                         "    echo 'dce binaries found, nothing to do' )"
                         " ) "
                         " ||" 
                         " (   "
                          # If not, copy ns-3 build to bin
-                        "  cd ${SRC}/dce/ns-3-dce && "
+                        "  cd ${SRC}/dce/ns-3-dce/%(dce_version)s && "
+                        "  rm -rf ${SRC}/dce/ns-3-dce/%(dce_version)s/build && "
                         "  ./waf configure %(enable_opt)s --with-pybindgen=${SRC}/pybindgen/%(pybindgen_version)s "
                         "  --prefix=%(ns3_build_home)s --with-ns3=%(ns3_build_home)s && "
                         "  ./waf build && "
                         "  ./waf install && "
-                        "  mv %(ns3_build_home)s/lib/python*/site-packages/ns/dce.so %(ns3_build_home)s/lib/python/site-packages/ns/ "
+                        "  mv %(ns3_build_home)s/lib*/python*/site-packages/ns/dce.so %(ns3_build_home)s/lib/python/site-packages/ns/ "
                         " )"
                 ) % { 
-                    'ns3_version': self.get("ns3Version"),
-                    'pybindgen_version': self.get("pybindgenVersion"),
-                    'ns3_build_home': self.ns3_build_home,
-                    'build_mode': self.get("buildMode"),
-                    'enable_opt': "--enable-opt" if  self.get("buildMode") == "optimized" else ""
+                    "ns3_version": self.get("ns3Version"),
+                    "pybindgen_version": self.get("pybindgenVersion"),
+                    "ns3_build_home": self.ns3_build_home,
+                    "build_mode": self.get("buildMode"),
+                    "enable_opt": "--enable-opt" if  self.get("buildMode") == "optimized" else "",
+                    "dce_version": self.dce_version,
                     }
 
         return (
@@ -513,11 +604,12 @@ class LinuxNS3Simulation(LinuxApplication, NS3Simulation):
                  # If not, copy ns-3 build to bin
                 "  mkdir -p %(ns3_build_home)s && "
                 "  cd ${SRC}/ns-3/%(ns3_version)s && "
+                "  rm -rf ${SRC}/ns-3/%(ns3_version)s/build && "
                 "  ./waf configure -d %(build_mode)s --with-pybindgen=${SRC}/pybindgen/%(pybindgen_version)s "
-                "  --prefix=%(ns3_build_home)s --includedir=%(ns3_build_home)s && "
+                "  --prefix=%(ns3_build_home)s && "
                 "  ./waf build && "
                 "  ./waf install && "
-                "  mv %(ns3_build_home)s/lib/python* %(ns3_build_home)s/lib/python "
+                "  mv %(ns3_build_home)s/lib*/python* %(ns3_build_home)s/lib/python "
                 " )"
                 ") "
                 " && "
@@ -538,15 +630,55 @@ class LinuxNS3Simulation(LinuxApplication, NS3Simulation):
         env.append("PYTHONPATH=$PYTHONPATH:${NS3BINDINGS:=%(ns3_build_home)s/lib/python/site-packages}" % { 
                     'ns3_build_home': self.ns3_build_home
                  })
-        env.append("LD_LIBRARY_PATH=${NS3LIBRARIES:=%(ns3_build_home)s/lib/}" % { 
+        # If NS3LIBRARIES is defined and not empty, assign its value, 
+        # if not assign ns3_build_home/lib/ to NS3LIBRARIES and LD_LIBARY_PATH
+        env.append("LD_LIBRARY_PATH=${NS3LIBRARIES:=%(ns3_build_home)s/lib}" % { 
                     'ns3_build_home': self.ns3_build_home
                  })
-        env.append("DCE_PATH=$PATH:$NS3LIBRARIES/../bin_dce")
-        env.append("DCE_ROOT=$PATH:$NS3LIBRARIES/..")
+        env.append("DCE_PATH=$NS3LIBRARIES/../bin_dce")
+        env.append("DCE_ROOT=$NS3LIBRARIES/..")
 
         return " ".join(env) 
 
+    def replace_paths(self, command):
+        """
+        Replace all special path tags with shell-escaped actual paths.
+        """
+        return ( command
+            .replace("${USR}", self.node.usr_dir)
+            .replace("${LIB}", self.node.lib_dir)
+            .replace("${BIN}", self.node.bin_dir)
+            .replace("${SRC}", self.node.src_dir)
+            .replace("${SHARE}", self.node.share_dir)
+            .replace("${EXP}", self.node.exp_dir)
+            .replace("${EXP_HOME}", self.node.exp_home)
+            .replace("${APP_HOME}", self.app_home)
+            .replace("${RUN_HOME}", self.run_home)
+            .replace("${NODE_HOME}", self.node.node_home)
+            .replace("${HOME}", self.node.home_dir)
+            # If NS3LIBRARIES is defined and not empty, use that value, 
+            # if not use ns3_build_home/lib/
+            .replace("${BIN_DCE}", "${NS3LIBRARIES-%s/lib}/../bin_dce" % \
+                    self.ns3_build_home)
+            )
+
     def valid_connection(self, guid):
         # TODO: Validate!
         return True
 
+    def wait_remote_socket(self):
+        """ Waits until the remote socket is created
+        """
+        command = " [ -e %s ] && echo 'DONE' " % self.remote_socket
+
+        for i in xrange(200):
+            (out, err), proc = self.node.execute(command, retry = 1, 
+                    with_lock = True)
+
+            if out.find("DONE") > -1:
+                break
+        else:
+            raise RuntimeError("Remote socket not found at %s" % \
+                    self.remote_socket)
+    
+