bug fixing: addresses and routes
[nepi.git] / src / nepi / testbeds / ns3 / execute.py
index 5befa69..15a8c26 100644 (file)
@@ -1,15 +1,27 @@
 #!/usr/bin/env python
 # -*- coding: utf-8 -*-
 
-from constants import TESTBED_ID
 from nepi.core import testbed_impl
 from nepi.core.attributes import Attribute
-from nepi.util.constants import TIME_NOW
+from constants import TESTBED_ID
+from nepi.util.constants import TIME_NOW, \
+    TESTBED_STATUS_STARTED
 import os
 import sys
 import threading
+import random
+import socket
+import weakref
 
 class TestbedController(testbed_impl.TestbedController):
+    from nepi.util.tunchannel_impl import TunChannel
+    
+    LOCAL_FACTORIES = {
+        'ns3::Nepi::TunChannel' : TunChannel,
+    }
+    
+    LOCAL_TYPES = tuple(LOCAL_FACTORIES.values())
+
     def __init__(self, testbed_version):
         super(TestbedController, self).__init__(TESTBED_ID, testbed_version)
         self._ns3 = None
@@ -30,6 +42,12 @@ class TestbedController(testbed_impl.TestbedController):
         self._home_directory = self._attributes.\
             get_attribute_value("homeDirectory")
         self._ns3 = self._load_ns3_module()
+        
+        # create home...
+        home = os.path.normpath(self.home_directory)
+        if not os.path.exists(home):
+            os.makedirs(home, 0755)
+        
         super(TestbedController, self).do_setup()
 
     def start(self):
@@ -37,25 +55,43 @@ class TestbedController(testbed_impl.TestbedController):
         self._condition = threading.Condition()
         self._simulator_thread = threading.Thread(target = self._simulator_run,
                 args = [self._condition])
+        self._simulator_thread.isDaemon()
         self._simulator_thread.start()
 
+    def stop(self, time = TIME_NOW):
+        super(TestbedController, self).stop(time)
+        # BUG!!!!
+        # TODO!! This is not working!!!
+        self.ns3.Simulator.Stop()
+        #self._stop_simulation(time)
+
     def set(self, guid, name, value, time = TIME_NOW):
         super(TestbedController, self).set(guid, name, value, time)
         # TODO: take on account schedule time for the task
         factory_id = self._create[guid]
         factory = self._factories[factory_id]
-        if factory.box_attributes.is_attribute_design_only(name) or \
-                factory.box_attributes.is_attribute_invisible(name):
+        if factory.box_attributes.is_attribute_design_only(name):
             return
         element = self._elements[guid]
-        ns3_value = self._to_ns3_value(guid, name, value) 
-        element.SetAttribute(name, ns3_value)
+        if factory_id in self.LOCAL_FACTORIES:
+            setattr(element, name, value)
+        elif factory.box_attributes.is_attribute_invisible(name):
+            return
+        else:
+            ns3_value = self._to_ns3_value(guid, name, value)
+            self._set_attribute(name, ns3_value, element)
 
     def get(self, guid, name, time = TIME_NOW):
         value = super(TestbedController, self).get(guid, name, time)
         # TODO: take on account schedule time for the task
         factory_id = self._create[guid]
         factory = self._factories[factory_id]
+        element = self._elements[guid]
+        if factory_id in self.LOCAL_FACTORIES:
+            if hasattr(element, name):
+                return getattr(element, name)
+            else:
+                return value
         if factory.box_attributes.is_attribute_design_only(name) or \
                 factory.box_attributes.is_attribute_invisible(name):
             return value
@@ -67,8 +103,7 @@ class TestbedController(testbed_impl.TestbedController):
                 (name, guid))
         checker = info.checker
         ns3_value = checker.Create() 
-        element = self._elements[guid]
-        element.GetAttribute(name, ns3_value)
+        self._get_attribute(name, ns3_value, element)
         value = ns3_value.SerializeToString(checker)
         attr_type = factory.box_attributes.get_attribute_type(name)
         if attr_type == Attribute.INTEGER:
@@ -93,8 +128,24 @@ class TestbedController(testbed_impl.TestbedController):
         self._traces[guid][trace_id] = filename
 
     def shutdown(self):
-        for element in self._elements.values():
-            element = None
+        for element in self._elements.itervalues():
+            if isinstance(element, self.LOCAL_TYPES):
+                # graceful shutdown of locally-implemented objects
+                element.Cleanup()
+        self._elements.clear()
+        if self.ns3:
+            self.ns3.Simulator.Stop()
+            # BUG!!!!
+            # TODO!! This is not working!!! NEVER STOPS THE SIMULATION!!!
+            #self._stop_simulation("0s")
+            #if self._simulator_thread:
+            #    print "Joining thread"
+            #    self._simulator_thread.join()
+            #print "destroying"
+            self.ns3.Simulator.Destroy()
+        self._ns3 = None
+        sys.stdout.flush()
+        sys.stderr.flush()
 
     def _simulator_run(self, condition):
         # Run simulation
@@ -108,13 +159,15 @@ class TestbedController(testbed_impl.TestbedController):
         """Schedules event on running experiment"""
         def execute_event(condition, has_event_occurred, func, *args):
             # exec func
-            func(*args)
-            # flag event occured
-            has_event_occurred[0] = True
-            # notify condition indicating attribute was set
-            condition.acquire()
-            condition.notifyAll()
-            condition.release()
+            try:
+                func(*args)
+            finally:
+                # flag event occured
+                has_event_occurred[0] = True
+                # notify condition indicating attribute was set
+                condition.acquire()
+                condition.notifyAll()
+                condition.release()
 
         # contextId is defined as general context
         contextId = long(0xffffffff)
@@ -131,9 +184,44 @@ class TestbedController(testbed_impl.TestbedController):
             while not has_event_occurred[0] and not self.ns3.Simulator.IsFinished():
                 condition.wait()
                 condition.release()
-                if not has_event_occurred[0]:
-                    raise RuntimeError('Event could not be scheduled : %s %s ' \
-                    % (repr(func), repr(args)))
+
+    def _set_attribute(self, name, ns3_value, element):
+        if self.status() == TESTBED_STATUS_STARTED:
+            # schedule the event in the Simulator
+            self._schedule_event(self._condition, self._set_ns3_attribute, 
+                    name, ns3_value, element)
+        else:
+            self._set_ns3_attribute(name, ns3_value, element)
+
+    def _get_attribute(self, name, ns3_value, element):
+        if self.status() == TESTBED_STATUS_STARTED:
+            # schedule the event in the Simulator
+            self._schedule_event(self._condition, self._get_ns3_attribute, 
+                    name, ns3_value, element)
+        else:
+            self._get_ns3_attribute(name, ns3_value, element)
+
+    def _set_ns3_attribute(self, name, ns3_value, element):
+        element.SetAttribute(name, ns3_value)
+
+    def _get_ns3_attribute(self, name, ns3_value, element):
+        element.GetAttribute(name, ns3_value)
+
+    def _stop_simulation(self, time):
+        if self.status() == TESTBED_STATUS_STARTED:
+            # schedule the event in the Simulator
+            self._schedule_event(self._condition, self._stop_ns3_simulation, 
+                    time)
+        else:
+            self._stop_ns3_simulation(time)
+
+    def _stop_simulation(self, time = TIME_NOW):
+        if not self.ns3:
+            return
+        if time == TIME_NOW:
+            self.ns3.Simulator.Stop()
+        else:
+            self.ns3.Simulator.Stop(self.ns3.Time(time))
 
     def _to_ns3_value(self, guid, name, value):
         factory_id = self._create[guid]
@@ -158,6 +246,7 @@ class TestbedController(testbed_impl.TestbedController):
         simu_impl_type = self._attributes.get_attribute_value(
                 "SimulatorImplementationType")
         checksum = self._attributes.get_attribute_value("ChecksumEnabled")
+        stop_time = self._attributes.get_attribute_value("StopTime")
 
         bindings = os.environ["NEPI_NS3BINDINGS"] \
                 if "NEPI_NS3BINDINGS" in os.environ else None
@@ -171,8 +260,20 @@ class TestbedController(testbed_impl.TestbedController):
         if bindings:
             path = [ bindings ] + path
 
-        module = imp.find_module ('ns3', path)
-        mod = imp.load_module ('ns3', *module)
+        try:
+            module = imp.find_module ('ns3', path)
+            mod = imp.load_module ('ns3', *module)
+        except ImportError:
+            # In some environments, ns3 per-se does not exist,
+            # only the low-level _ns3
+            module = imp.find_module ('_ns3', path)
+            mod = imp.load_module ('_ns3', *module)
+            sys.modules["ns3"] = mod # install it as ns3 too
+            
+            # When using _ns3, we have to make sure we destroy
+            # the simulator when the process finishes
+            import atexit
+            atexit.register(mod.Simulator.Destroy)
     
         if simu_impl_type:
             value = mod.StringValue(simu_impl_type)
@@ -180,6 +281,9 @@ class TestbedController(testbed_impl.TestbedController):
         if checksum:
             value = mod.BooleanValue(checksum)
             mod.GlobalValue.Bind ("ChecksumEnabled", value)
+        if stop_time:
+            value = mod.Time(stop_time)
+            mod.Simulator.Stop (value)
         return mod
 
     def _get_construct_parameters(self, guid):
@@ -196,3 +300,5 @@ class TestbedController(testbed_impl.TestbedController):
                 construct_params[name] = value
         return construct_params
 
+
+