2 # -*- coding: utf-8 -*-
4 from nepi.core import testbed_impl
5 from nepi.core.attributes import Attribute
6 from constants import TESTBED_ID, TESTBED_VERSION
7 from nepi.util.constants import TIME_NOW, TestbedStatus as TS
15 def load_ns3_module():
17 if 'ns3' in sys.modules:
24 bindings = os.environ["NEPI_NS3BINDINGS"] \
25 if "NEPI_NS3BINDINGS" in os.environ else None
26 libdir = os.environ["NEPI_NS3LIBRARY"] \
27 if "NEPI_NS3LIBRARY" in os.environ else None
30 files = os.listdir(libdir)
31 regex = re.compile("(.*\.so)$")
32 libs = [m.group(1) for filename in files for m in [regex.search(filename)] if m]
37 libfile = os.path.join(libdir, lib)
39 ctypes.CDLL(libfile, ctypes.RTLD_GLOBAL)
43 # if did not load any libraries in the last iteration
44 if len(libscp) == len(libs):
45 raise RuntimeError("Imposible to load shared libraries %s" % str(libs))
49 sys.path.append(bindings)
51 import ns3_bindings_import as mod
52 sys.modules["ns3"] = mod
54 class TestbedController(testbed_impl.TestbedController):
55 from nepi.util.tunchannel_impl import TunChannel
58 'ns3::Nepi::TunChannel' : TunChannel,
61 LOCAL_TYPES = tuple(LOCAL_FACTORIES.values())
64 super(TestbedController, self).__init__(TESTBED_ID, TESTBED_VERSION)
66 self._home_directory = None
68 self._simulator_thread = None
69 self._condition = None
72 def home_directory(self):
73 return self._home_directory
80 self._home_directory = self._attributes.\
81 get_attribute_value("homeDirectory")
82 self._ns3 = self._configure_ns3_module()
85 home = os.path.normpath(self.home_directory)
86 if not os.path.exists(home):
87 os.makedirs(home, 0755)
89 super(TestbedController, self).do_setup()
92 super(TestbedController, self).start()
93 self._condition = threading.Condition()
94 self._simulator_thread = threading.Thread(target = self._simulator_run,
95 args = [self._condition])
96 self._simulator_thread.setDaemon(True)
97 self._simulator_thread.start()
99 def stop(self, time = TIME_NOW):
100 super(TestbedController, self).stop(time)
101 self._stop_simulation(time)
103 def set(self, guid, name, value, time = TIME_NOW):
104 super(TestbedController, self).set(guid, name, value, time)
105 # TODO: take on account schedule time for the task
106 factory_id = self._create[guid]
107 factory = self._factories[factory_id]
108 element = self._elements[guid]
109 if factory_id in self.LOCAL_FACTORIES:
110 setattr(element, name, value)
111 elif not factory.box_attributes.is_attribute_metadata(name):
112 ns3_value = self._to_ns3_value(guid, name, value)
113 self._set_attribute(name, ns3_value, element)
115 def get(self, guid, name, time = TIME_NOW):
116 value = super(TestbedController, self).get(guid, name, time)
117 # TODO: take on account schedule time for the task
118 factory_id = self._create[guid]
119 factory = self._factories[factory_id]
120 element = self._elements[guid]
121 if factory_id in self.LOCAL_FACTORIES:
122 if hasattr(element, name):
123 return getattr(element, name)
126 if factory.box_attributes.is_attribute_metadata(name):
129 TypeId = self.ns3.TypeId()
130 typeid = TypeId.LookupByName(factory_id)
131 info = TypeId.AttributeInfo()
132 if not typeid or not typeid.LookupAttributeByName(name, info):
133 raise AttributeError("Invalid attribute %s for element type %d" % \
135 checker = info.checker
136 ns3_value = checker.Create()
137 self._get_attribute(name, ns3_value, element)
138 value = ns3_value.SerializeToString(checker)
139 attr_type = factory.box_attributes.get_attribute_type(name)
140 if attr_type == Attribute.INTEGER:
142 if attr_type == Attribute.DOUBLE:
144 if attr_type == Attribute.BOOL:
145 return value == "true"
148 def action(self, time, guid, action):
149 raise NotImplementedError
151 def trace_filepath(self, guid, trace_id):
152 filename = self._traces[guid][trace_id]
153 return os.path.join(self.home_directory, filename)
155 def follow_trace(self, guid, trace_id, filename):
156 if not guid in self._traces:
157 self._traces[guid] = dict()
158 self._traces[guid][trace_id] = filename
161 for element in self._elements.itervalues():
162 if isinstance(element, self.LOCAL_TYPES):
163 # graceful shutdown of locally-implemented objects
166 if not self.ns3.Simulator.IsFinished():
169 # TODO!!!! SHOULD WAIT UNTIL THE THREAD FINISHES
170 if self._simulator_thread:
171 self._simulator_thread.join()
173 self.ns3.Simulator.Destroy()
175 self._elements.clear()
181 def _simulator_run(self, condition):
183 self.ns3.Simulator.Run()
184 # Signal condition on simulation end to notify waiting threads
186 condition.notifyAll()
189 def _schedule_event(self, condition, func, *args):
190 """Schedules event on running experiment"""
191 def execute_event(condition, has_event_occurred, func, *args):
197 has_event_occurred[0] = True
198 # notify condition indicating attribute was set
200 condition.notifyAll()
203 # contextId is defined as general context
204 contextId = long(0xffffffff)
205 # delay 0 means that the event is expected to execute inmediately
206 delay = self.ns3.Seconds(0)
207 # flag to indicate that the event occured
208 # because bool is an inmutable object in python, in order to create a
209 # bool flag, a list is used as wrapper
210 has_event_occurred = [False]
213 if not self.ns3.Simulator.IsFinished():
214 self.ns3.Simulator.ScheduleWithContext(contextId, delay, execute_event,
215 condition, has_event_occurred, func, *args)
216 while not has_event_occurred[0] and not self.ns3.Simulator.IsFinished():
221 def _set_attribute(self, name, ns3_value, element):
222 if self.status() == TS.STATUS_STARTED:
223 # schedule the event in the Simulator
224 self._schedule_event(self._condition, self._set_ns3_attribute,
225 name, ns3_value, element)
227 self._set_ns3_attribute(name, ns3_value, element)
229 def _get_attribute(self, name, ns3_value, element):
230 if self.status() == TS.STATUS_STARTED:
231 # schedule the event in the Simulator
232 self._schedule_event(self._condition, self._get_ns3_attribute,
233 name, ns3_value, element)
235 self._get_ns3_attribute(name, ns3_value, element)
237 def _set_ns3_attribute(self, name, ns3_value, element):
238 element.SetAttribute(name, ns3_value)
240 def _get_ns3_attribute(self, name, ns3_value, element):
241 element.GetAttribute(name, ns3_value)
243 def _stop_simulation(self, time):
244 if self.status() == TS.STATUS_STARTED:
245 # schedule the event in the Simulator
246 self._schedule_event(self._condition, self._stop_ns3_simulation,
249 self._stop_ns3_simulation(time)
251 def _stop_ns3_simulation(self, time = TIME_NOW):
255 self.ns3.Simulator.Stop()
257 self.ns3.Simulator.Stop(self.ns3.Time(time))
259 def _to_ns3_value(self, guid, name, value):
260 factory_id = self._create[guid]
261 TypeId = self.ns3.TypeId()
262 typeid = TypeId.LookupByName(factory_id)
263 info = TypeId.AttributeInfo()
264 if not typeid.LookupAttributeByName(name, info):
265 raise RuntimeError("Attribute %s doesn't belong to element %s" \
266 % (name, factory_id))
267 str_value = str(value)
268 if isinstance(value, bool):
269 str_value = str_value.lower()
270 checker = info.checker
271 ns3_value = checker.Create()
272 ns3_value.DeserializeFromString(str_value, checker)
275 def _configure_ns3_module(self):
276 simu_impl_type = self._attributes.get_attribute_value(
277 "SimulatorImplementationType")
278 sched_impl_type = self._attributes.get_attribute_value(
280 checksum = self._attributes.get_attribute_value("ChecksumEnabled")
281 stop_time = self._attributes.get_attribute_value("StopTime")
288 value = mod.StringValue(simu_impl_type)
289 mod.GlobalValue.Bind ("SimulatorImplementationType", value)
291 value = mod.StringValue(sched_impl_type)
292 mod.GlobalValue.Bind ("SchedulerType", value)
294 value = mod.BooleanValue(checksum)
295 mod.GlobalValue.Bind ("ChecksumEnabled", value)
297 value = mod.Time(stop_time)
298 mod.Simulator.Stop (value)
301 def _get_construct_parameters(self, guid):
302 params = self._get_parameters(guid)
303 construct_params = dict()
304 factory_id = self._create[guid]
305 TypeId = self.ns3.TypeId()
306 typeid = TypeId.LookupByName(factory_id)
307 for name, value in params.iteritems():
308 info = self.ns3.TypeId.AttributeInfo()
309 found = typeid.LookupAttributeByName(name, info)
311 (info.flags & TypeId.ATTR_CONSTRUCT == TypeId.ATTR_CONSTRUCT):
312 construct_params[name] = value
313 return construct_params