TunChannel finalization fix
[nepi.git] / src / nepi / testbeds / ns3 / execute.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 from constants import TESTBED_ID
5 from nepi.core import testbed_impl
6 from nepi.core.attributes import Attribute
7 from nepi.util.constants import TIME_NOW
8 import os
9 import sys
10 import threading
11 import random
12 import socket
13 import weakref
14
15 class TestbedController(testbed_impl.TestbedController):
16     from nepi.util.tunchannel_impl import TunChannel
17     
18     LOCAL_FACTORIES = {
19         'ns3::Nepi::TunChannel' : TunChannel,
20     }
21     
22     LOCAL_TYPES = tuple(LOCAL_FACTORIES.values())
23
24     def __init__(self, testbed_version):
25         super(TestbedController, self).__init__(TESTBED_ID, testbed_version)
26         self._ns3 = None
27         self._home_directory = None
28         self._traces = dict()
29         self._simulator_thread = None
30         self._condition = None
31
32     @property
33     def home_directory(self):
34         return self._home_directory
35
36     @property
37     def ns3(self):
38         return self._ns3
39
40     def do_setup(self):
41         self._home_directory = self._attributes.\
42             get_attribute_value("homeDirectory")
43         self._ns3 = self._load_ns3_module()
44         
45         # create home...
46         home = os.path.normpath(self.home_directory)
47         if not os.path.exists(home):
48             os.makedirs(home, 0755)
49         
50         super(TestbedController, self).do_setup()
51
52     def start(self):
53         super(TestbedController, self).start()
54         self._condition = threading.Condition()
55         self._simulator_thread = threading.Thread(target = self._simulator_run,
56                 args = [self._condition])
57         self._simulator_thread.start()
58
59     def set(self, guid, name, value, time = TIME_NOW):
60         super(TestbedController, self).set(guid, name, value, time)
61         # TODO: take on account schedule time for the task
62         factory_id = self._create[guid]
63         factory = self._factories[factory_id]
64         if factory.box_attributes.is_attribute_design_only(name) or \
65                 factory.box_attributes.is_attribute_invisible(name):
66             return
67         element = self._elements[guid]
68         if factory_id in self.LOCAL_FACTORIES:
69             setattr(element, name, value)
70         else:
71             ns3_value = self._to_ns3_value(guid, name, value) 
72             element.SetAttribute(name, ns3_value)
73
74     def get(self, guid, name, time = TIME_NOW):
75         value = super(TestbedController, self).get(guid, name, time)
76         # TODO: take on account schedule time for the task
77         factory_id = self._create[guid]
78         factory = self._factories[factory_id]
79         if factory.box_attributes.is_attribute_design_only(name) or \
80                 factory.box_attributes.is_attribute_invisible(name):
81             return value
82         if factory_id in self.LOCAL_FACTORIES:
83             return getattr(element, name)
84         TypeId = self.ns3.TypeId()
85         typeid = TypeId.LookupByName(factory_id)
86         info = TypeId.AttributeInfo()
87         if not typeid or not typeid.LookupAttributeByName(name, info):
88             raise AttributeError("Invalid attribute %s for element type %d" % \
89                 (name, guid))
90         checker = info.checker
91         ns3_value = checker.Create() 
92         element = self._elements[guid]
93         element.GetAttribute(name, ns3_value)
94         value = ns3_value.SerializeToString(checker)
95         attr_type = factory.box_attributes.get_attribute_type(name)
96         if attr_type == Attribute.INTEGER:
97             return int(value)
98         if attr_type == Attribute.DOUBLE:
99             return float(value)
100         if attr_type == Attribute.BOOL:
101             return value == "true"
102         return value
103
104     def action(self, time, guid, action):
105         raise NotImplementedError
106
107     def trace_filename(self, guid, trace_id):
108         # TODO: Need to be defined inside a home!!!! with and experiment id_code
109         filename = self._traces[guid][trace_id]
110         return os.path.join(self.home_directory, filename)
111
112     def follow_trace(self, guid, trace_id, filename):
113         if guid not in self._traces:
114             self._traces[guid] = dict()
115         self._traces[guid][trace_id] = filename
116
117     def shutdown(self):
118         for element in self._elements.values():
119             if isinstance(element, self.LOCAL_TYPES):
120                 # graceful shutdown of locally-implemented objects
121                 element.Cleanup()
122             element = None
123
124     def _simulator_run(self, condition):
125         # Run simulation
126         self.ns3.Simulator.Run()
127         # Signal condition on simulation end to notify waiting threads
128         condition.acquire()
129         condition.notifyAll()
130         condition.release()
131
132     def _schedule_event(self, condition, func, *args):
133         """Schedules event on running experiment"""
134         def execute_event(condition, has_event_occurred, func, *args):
135             # exec func
136             func(*args)
137             # flag event occured
138             has_event_occurred[0] = True
139             # notify condition indicating attribute was set
140             condition.acquire()
141             condition.notifyAll()
142             condition.release()
143
144         # contextId is defined as general context
145         contextId = long(0xffffffff)
146         # delay 0 means that the event is expected to execute inmediately
147         delay = self.ns3.Seconds(0)
148         # flag to indicate that the event occured
149         # because bool is an inmutable object in python, in order to create a
150         # bool flag, a list is used as wrapper
151         has_event_occurred = [False]
152         condition.acquire()
153         if not self.ns3.Simulator.IsFinished():
154             self.ns3.Simulator.ScheduleWithContext(contextId, delay, execute_event,
155                  condition, has_event_occurred, func, *args)
156             while not has_event_occurred[0] and not self.ns3.Simulator.IsFinished():
157                 condition.wait()
158                 condition.release()
159                 if not has_event_occurred[0]:
160                     raise RuntimeError('Event could not be scheduled : %s %s ' \
161                     % (repr(func), repr(args)))
162
163     def _to_ns3_value(self, guid, name, value):
164         factory_id = self._create[guid]
165         TypeId = self.ns3.TypeId()
166         typeid = TypeId.LookupByName(factory_id)
167         info = TypeId.AttributeInfo()
168         if not typeid.LookupAttributeByName(name, info):
169             raise RuntimeError("Attribute %s doesn't belong to element %s" \
170                    % (name, factory_id))
171         str_value = str(value)
172         if isinstance(value, bool):
173             str_value = str_value.lower()
174         checker = info.checker
175         ns3_value = checker.Create()
176         ns3_value.DeserializeFromString(str_value, checker)
177         return ns3_value
178
179     def _load_ns3_module(self):
180         import ctypes
181         import imp
182
183         simu_impl_type = self._attributes.get_attribute_value(
184                 "SimulatorImplementationType")
185         checksum = self._attributes.get_attribute_value("ChecksumEnabled")
186
187         bindings = os.environ["NEPI_NS3BINDINGS"] \
188                 if "NEPI_NS3BINDINGS" in os.environ else None
189         libfile = os.environ["NEPI_NS3LIBRARY"] \
190                 if "NEPI_NS3LIBRARY" in os.environ else None
191
192         if libfile:
193             ctypes.CDLL(libfile, ctypes.RTLD_GLOBAL)
194
195         path = [ os.path.dirname(__file__) ] + sys.path
196         if bindings:
197             path = [ bindings ] + path
198
199         try:
200             module = imp.find_module ('ns3', path)
201             mod = imp.load_module ('ns3', *module)
202         except ImportError:
203             # In some environments, ns3 per-se does not exist,
204             # only the low-level _ns3
205             module = imp.find_module ('_ns3', path)
206             mod = imp.load_module ('_ns3', *module)
207             sys.modules["ns3"] = mod # install it as ns3 too
208             
209             # When using _ns3, we have to make sure we destroy
210             # the simulator when the process finishes
211             import atexit
212             atexit.register(mod.Simulator.Destroy)
213     
214         if simu_impl_type:
215             value = mod.StringValue(simu_impl_type)
216             mod.GlobalValue.Bind ("SimulatorImplementationType", value)
217         if checksum:
218             value = mod.BooleanValue(checksum)
219             mod.GlobalValue.Bind ("ChecksumEnabled", value)
220         return mod
221
222     def _get_construct_parameters(self, guid):
223         params = self._get_parameters(guid)
224         construct_params = dict()
225         factory_id = self._create[guid]
226         TypeId = self.ns3.TypeId()
227         typeid = TypeId.LookupByName(factory_id)
228         for name, value in params.iteritems():
229             info = self.ns3.TypeId.AttributeInfo()
230             found = typeid.LookupAttributeByName(name, info)
231             if found and \
232                 (info.flags & TypeId.ATTR_CONSTRUCT == TypeId.ATTR_CONSTRUCT):
233                 construct_params[name] = value
234         return construct_params
235
236
237