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 element = self._elements[guid]
107 if factory_id in self.LOCAL_FACTORIES:
108 setattr(element, name, value)
109 elif not factory.box_attributes.is_attribute_metadata(name):
110 ns3_value = self._to_ns3_value(guid, name, value)
111 self._set_attribute(name, ns3_value, element)
113 def get(self, guid, name, time = TIME_NOW):
114 value = super(TestbedController, self).get(guid, name, time)
115 # TODO: take on account schedule time for the task
116 factory_id = self._create[guid]
117 factory = self._factories[factory_id]
118 element = self._elements[guid]
119 if factory_id in self.LOCAL_FACTORIES:
120 if hasattr(element, name):
121 return getattr(element, name)
124 if factory.box_attributes.is_attribute_metadata(name):
127 TypeId = self.ns3.TypeId()
128 typeid = TypeId.LookupByName(factory_id)
129 info = TypeId.AttributeInfo()
130 if not typeid or not typeid.LookupAttributeByName(name, info):
131 raise AttributeError("Invalid attribute %s for element type %d" % \
133 checker = info.checker
134 ns3_value = checker.Create()
135 self._get_attribute(name, ns3_value, element)
136 value = ns3_value.SerializeToString(checker)
137 attr_type = factory.box_attributes.get_attribute_type(name)
138 if attr_type == Attribute.INTEGER:
140 if attr_type == Attribute.DOUBLE:
142 if attr_type == Attribute.BOOL:
143 return value == "true"
146 def action(self, time, guid, action):
147 raise NotImplementedError
149 def trace_filepath(self, guid, trace_id):
150 filename = self._traces[guid][trace_id]
151 return os.path.join(self.home_directory, filename)
153 def follow_trace(self, guid, trace_id, filename):
154 if not guid in self._traces:
155 self._traces[guid] = dict()
156 self._traces[guid][trace_id] = filename
159 for element in self._elements.itervalues():
160 if isinstance(element, self.LOCAL_TYPES):
161 # graceful shutdown of locally-implemented objects
164 self.ns3.Simulator.Stop()
166 # Wait for it to stop, with a 30s timeout
167 for i in xrange(300):
168 if self.ns3.Simulator.IsFinished():
171 #self._stop_simulation("0s")
173 self._elements.clear()
176 # TODO!!!! SHOULD WAIT UNTIL THE THREAD FINISHES
177 # if self._simulator_thread:
178 # self._simulator_thread.join()
179 self.ns3.Simulator.Destroy()
185 def _simulator_run(self, condition):
187 self.ns3.Simulator.Run()
188 # Signal condition on simulation end to notify waiting threads
190 condition.notifyAll()
193 def _schedule_event(self, condition, func, *args):
194 """Schedules event on running experiment"""
195 def execute_event(condition, has_event_occurred, func, *args):
201 has_event_occurred[0] = True
202 # notify condition indicating attribute was set
204 condition.notifyAll()
207 # contextId is defined as general context
208 contextId = long(0xffffffff)
209 # delay 0 means that the event is expected to execute inmediately
210 delay = self.ns3.Seconds(0)
211 # flag to indicate that the event occured
212 # because bool is an inmutable object in python, in order to create a
213 # bool flag, a list is used as wrapper
214 has_event_occurred = [False]
216 if not self.ns3.Simulator.IsFinished():
217 self.ns3.Simulator.ScheduleWithContext(contextId, delay, execute_event,
218 condition, has_event_occurred, func, *args)
219 while not has_event_occurred[0] and not self.ns3.Simulator.IsFinished():
223 def _set_attribute(self, name, ns3_value, element):
224 if self.status() == TS.STATUS_STARTED:
225 # schedule the event in the Simulator
226 self._schedule_event(self._condition, self._set_ns3_attribute,
227 name, ns3_value, element)
229 self._set_ns3_attribute(name, ns3_value, element)
231 def _get_attribute(self, name, ns3_value, element):
232 if self.status() == TS.STATUS_STARTED:
233 # schedule the event in the Simulator
234 self._schedule_event(self._condition, self._get_ns3_attribute,
235 name, ns3_value, element)
237 self._get_ns3_attribute(name, ns3_value, element)
239 def _set_ns3_attribute(self, name, ns3_value, element):
240 element.SetAttribute(name, ns3_value)
242 def _get_ns3_attribute(self, name, ns3_value, element):
243 element.GetAttribute(name, ns3_value)
245 def _stop_simulation(self, time):
246 if self.status() == TS.STATUS_STARTED:
247 # schedule the event in the Simulator
248 self._schedule_event(self._condition, self._stop_ns3_simulation,
251 self._stop_ns3_simulation(time)
253 def _stop_ns3_simulation(self, time = TIME_NOW):
257 self.ns3.Simulator.Stop()
259 self.ns3.Simulator.Stop(self.ns3.Time(time))
261 def _to_ns3_value(self, guid, name, value):
262 factory_id = self._create[guid]
263 TypeId = self.ns3.TypeId()
264 typeid = TypeId.LookupByName(factory_id)
265 info = TypeId.AttributeInfo()
266 if not typeid.LookupAttributeByName(name, info):
267 raise RuntimeError("Attribute %s doesn't belong to element %s" \
268 % (name, factory_id))
269 str_value = str(value)
270 if isinstance(value, bool):
271 str_value = str_value.lower()
272 checker = info.checker
273 ns3_value = checker.Create()
274 ns3_value.DeserializeFromString(str_value, checker)
277 def _load_ns3_module(self):
278 simu_impl_type = self._attributes.get_attribute_value(
279 "SimulatorImplementationType")
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.BooleanValue(checksum)
292 mod.GlobalValue.Bind ("ChecksumEnabled", value)
294 value = mod.Time(stop_time)
295 mod.Simulator.Stop (value)
298 def _get_construct_parameters(self, guid):
299 params = self._get_parameters(guid)
300 construct_params = dict()
301 factory_id = self._create[guid]
302 TypeId = self.ns3.TypeId()
303 typeid = TypeId.LookupByName(factory_id)
304 for name, value in params.iteritems():
305 info = self.ns3.TypeId.AttributeInfo()
306 found = typeid.LookupAttributeByName(name, info)
308 (info.flags & TypeId.ATTR_CONSTRUCT == TypeId.ATTR_CONSTRUCT):
309 construct_params[name] = value
310 return construct_params