2 # -*- coding: utf-8 -*-
4 from nepi.core import testbed_impl
5 from nepi.core.attributes import Attribute
6 from constants import TESTBED_ID
7 from nepi.util.constants import TIME_NOW, TestbedStatus as TS
16 if 'ns3' in sys.modules:
22 bindings = os.environ["NEPI_NS3BINDINGS"] \
23 if "NEPI_NS3BINDINGS" in os.environ else None
24 libfile = os.environ["NEPI_NS3LIBRARY"] \
25 if "NEPI_NS3LIBRARY" in os.environ else None
28 ctypes.CDLL(libfile, ctypes.RTLD_GLOBAL)
30 path = [ os.path.dirname(__file__) ] + sys.path
32 path = [ bindings ] + path
35 module = imp.find_module ('ns3', path)
36 mod = imp.load_module ('ns3', *module)
38 # In some environments, ns3 per-se does not exist,
39 # only the low-level _ns3
40 module = imp.find_module ('_ns3', path)
41 mod = imp.load_module ('_ns3', *module)
42 sys.modules["ns3"] = mod # install it as ns3 too
44 # When using _ns3, we have to make sure we destroy
45 # the simulator when the process finishes
47 atexit.register(mod.Simulator.Destroy)
51 class TestbedController(testbed_impl.TestbedController):
52 from nepi.util.tunchannel_impl import TunChannel
55 'ns3::Nepi::TunChannel' : TunChannel,
58 LOCAL_TYPES = tuple(LOCAL_FACTORIES.values())
60 def __init__(self, testbed_version):
61 super(TestbedController, self).__init__(TESTBED_ID, testbed_version)
63 self._home_directory = None
65 self._simulator_thread = None
66 self._condition = None
69 def home_directory(self):
70 return self._home_directory
77 self._home_directory = self._attributes.\
78 get_attribute_value("homeDirectory")
79 self._ns3 = self._load_ns3_module()
82 home = os.path.normpath(self.home_directory)
83 if not os.path.exists(home):
84 os.makedirs(home, 0755)
86 super(TestbedController, self).do_setup()
89 super(TestbedController, self).start()
90 self._condition = threading.Condition()
91 self._simulator_thread = threading.Thread(target = self._simulator_run,
92 args = [self._condition])
93 self._simulator_thread.setDaemon(True)
94 self._simulator_thread.start()
96 def stop(self, time = TIME_NOW):
97 super(TestbedController, self).stop(time)
98 #self.ns3.Simulator.Stop()
99 self._stop_simulation(time)
101 def set(self, guid, name, value, time = TIME_NOW):
102 super(TestbedController, self).set(guid, name, value, time)
103 # TODO: take on account schedule time for the task
104 factory_id = self._create[guid]
105 factory = self._factories[factory_id]
106 if factory.box_attributes.is_attribute_design_only(name):
108 element = self._elements[guid]
109 if factory_id in self.LOCAL_FACTORIES:
110 setattr(element, name, value)
111 elif factory.box_attributes.is_attribute_invisible(name):
114 ns3_value = self._to_ns3_value(guid, name, value)
115 self._set_attribute(name, ns3_value, element)
117 def get(self, guid, name, time = TIME_NOW):
118 value = super(TestbedController, self).get(guid, name, time)
119 # TODO: take on account schedule time for the task
120 factory_id = self._create[guid]
121 factory = self._factories[factory_id]
122 element = self._elements[guid]
123 if factory_id in self.LOCAL_FACTORIES:
124 if hasattr(element, name):
125 return getattr(element, name)
128 if factory.box_attributes.is_attribute_design_only(name) or \
129 factory.box_attributes.is_attribute_invisible(name):
131 TypeId = self.ns3.TypeId()
132 typeid = TypeId.LookupByName(factory_id)
133 info = TypeId.AttributeInfo()
134 if not typeid or not typeid.LookupAttributeByName(name, info):
135 raise AttributeError("Invalid attribute %s for element type %d" % \
137 checker = info.checker
138 ns3_value = checker.Create()
139 self._get_attribute(name, ns3_value, element)
140 value = ns3_value.SerializeToString(checker)
141 attr_type = factory.box_attributes.get_attribute_type(name)
142 if attr_type == Attribute.INTEGER:
144 if attr_type == Attribute.DOUBLE:
146 if attr_type == Attribute.BOOL:
147 return value == "true"
150 def action(self, time, guid, action):
151 raise NotImplementedError
153 def trace_filepath(self, guid, trace_id):
154 filename = self._traces[guid][trace_id]
155 return os.path.join(self.home_directory, filename)
157 def follow_trace(self, guid, trace_id, filename):
158 if not guid in self._traces:
159 self._traces[guid] = dict()
160 self._traces[guid][trace_id] = filename
163 for element in self._elements.itervalues():
164 if isinstance(element, self.LOCAL_TYPES):
165 # graceful shutdown of locally-implemented objects
168 self.ns3.Simulator.Stop()
170 # Wait for it to stop, with a 30s timeout
171 for i in xrange(300):
172 if self.ns3.Simulator.IsFinished():
175 #self._stop_simulation("0s")
177 self._elements.clear()
180 # TODO!!!! SHOULD WAIT UNTIL THE THREAD FINISHES
181 # if self._simulator_thread:
182 # self._simulator_thread.join()
183 self.ns3.Simulator.Destroy()
189 def _simulator_run(self, condition):
191 self.ns3.Simulator.Run()
192 # Signal condition on simulation end to notify waiting threads
194 condition.notifyAll()
197 def _schedule_event(self, condition, func, *args):
198 """Schedules event on running experiment"""
199 def execute_event(condition, has_event_occurred, func, *args):
205 has_event_occurred[0] = True
206 # notify condition indicating attribute was set
208 condition.notifyAll()
211 # contextId is defined as general context
212 contextId = long(0xffffffff)
213 # delay 0 means that the event is expected to execute inmediately
214 delay = self.ns3.Seconds(0)
215 # flag to indicate that the event occured
216 # because bool is an inmutable object in python, in order to create a
217 # bool flag, a list is used as wrapper
218 has_event_occurred = [False]
220 if not self.ns3.Simulator.IsFinished():
221 self.ns3.Simulator.ScheduleWithContext(contextId, delay, execute_event,
222 condition, has_event_occurred, func, *args)
223 while not has_event_occurred[0] and not self.ns3.Simulator.IsFinished():
227 def _set_attribute(self, name, ns3_value, element):
228 if self.status() == TS.STATUS_STARTED:
229 # schedule the event in the Simulator
230 self._schedule_event(self._condition, self._set_ns3_attribute,
231 name, ns3_value, element)
233 self._set_ns3_attribute(name, ns3_value, element)
235 def _get_attribute(self, name, ns3_value, element):
236 if self.status() == TS.STATUS_STARTED:
237 # schedule the event in the Simulator
238 self._schedule_event(self._condition, self._get_ns3_attribute,
239 name, ns3_value, element)
241 self._get_ns3_attribute(name, ns3_value, element)
243 def _set_ns3_attribute(self, name, ns3_value, element):
244 element.SetAttribute(name, ns3_value)
246 def _get_ns3_attribute(self, name, ns3_value, element):
247 element.GetAttribute(name, ns3_value)
249 def _stop_simulation(self, time):
250 if self.status() == TS.STATUS_STARTED:
251 # schedule the event in the Simulator
252 self._schedule_event(self._condition, self._stop_ns3_simulation,
255 self._stop_ns3_simulation(time)
257 def _stop_ns3_simulation(self, time = TIME_NOW):
261 self.ns3.Simulator.Stop()
263 self.ns3.Simulator.Stop(self.ns3.Time(time))
265 def _to_ns3_value(self, guid, name, value):
266 factory_id = self._create[guid]
267 TypeId = self.ns3.TypeId()
268 typeid = TypeId.LookupByName(factory_id)
269 info = TypeId.AttributeInfo()
270 if not typeid.LookupAttributeByName(name, info):
271 raise RuntimeError("Attribute %s doesn't belong to element %s" \
272 % (name, factory_id))
273 str_value = str(value)
274 if isinstance(value, bool):
275 str_value = str_value.lower()
276 checker = info.checker
277 ns3_value = checker.Create()
278 ns3_value.DeserializeFromString(str_value, checker)
281 def _load_ns3_module(self):
282 simu_impl_type = self._attributes.get_attribute_value(
283 "SimulatorImplementationType")
284 checksum = self._attributes.get_attribute_value("ChecksumEnabled")
285 stop_time = self._attributes.get_attribute_value("StopTime")
292 value = mod.StringValue(simu_impl_type)
293 mod.GlobalValue.Bind ("SimulatorImplementationType", value)
295 value = mod.BooleanValue(checksum)
296 mod.GlobalValue.Bind ("ChecksumEnabled", value)
298 value = mod.Time(stop_time)
299 mod.Simulator.Stop (value)
302 def _get_construct_parameters(self, guid):
303 params = self._get_parameters(guid)
304 construct_params = dict()
305 factory_id = self._create[guid]
306 TypeId = self.ns3.TypeId()
307 typeid = TypeId.LookupByName(factory_id)
308 for name, value in params.iteritems():
309 info = self.ns3.TypeId.AttributeInfo()
310 found = typeid.LookupAttributeByName(name, info)
312 (info.flags & TypeId.ATTR_CONSTRUCT == TypeId.ATTR_CONSTRUCT):
313 construct_params[name] = value
314 return construct_params