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, \
16 class TestbedController(testbed_impl.TestbedController):
17 from nepi.util.tunchannel_impl import TunChannel
20 'ns3::Nepi::TunChannel' : TunChannel,
23 LOCAL_TYPES = tuple(LOCAL_FACTORIES.values())
25 def __init__(self, testbed_version):
26 super(TestbedController, self).__init__(TESTBED_ID, testbed_version)
28 self._home_directory = None
30 self._simulator_thread = None
31 self._condition = None
34 def home_directory(self):
35 return self._home_directory
42 self._home_directory = self._attributes.\
43 get_attribute_value("homeDirectory")
44 self._ns3 = self._load_ns3_module()
47 home = os.path.normpath(self.home_directory)
48 if not os.path.exists(home):
49 os.makedirs(home, 0755)
51 super(TestbedController, self).do_setup()
54 super(TestbedController, self).start()
55 self._condition = threading.Condition()
56 self._simulator_thread = threading.Thread(target = self._simulator_run,
57 args = [self._condition])
58 self._simulator_thread.start()
60 def stop(self, time = TIME_NOW):
61 super(TestbedController, self).stop(time)
62 #self.ns3.Simulator.Stop()
63 self._stop_simulation(time)
65 def set(self, guid, name, value, time = TIME_NOW):
66 super(TestbedController, self).set(guid, name, value, time)
67 # TODO: take on account schedule time for the task
68 factory_id = self._create[guid]
69 factory = self._factories[factory_id]
70 if factory.box_attributes.is_attribute_design_only(name):
72 element = self._elements[guid]
73 if factory_id in self.LOCAL_FACTORIES:
74 setattr(element, name, value)
75 elif factory.box_attributes.is_attribute_invisible(name):
78 ns3_value = self._to_ns3_value(guid, name, value)
79 self._set_attribute(name, ns3_value, element)
81 def get(self, guid, name, time = TIME_NOW):
82 value = super(TestbedController, self).get(guid, name, time)
83 # TODO: take on account schedule time for the task
84 factory_id = self._create[guid]
85 factory = self._factories[factory_id]
86 element = self._elements[guid]
87 if factory_id in self.LOCAL_FACTORIES:
88 if hasattr(element, name):
89 return getattr(element, name)
92 if factory.box_attributes.is_attribute_design_only(name) or \
93 factory.box_attributes.is_attribute_invisible(name):
95 TypeId = self.ns3.TypeId()
96 typeid = TypeId.LookupByName(factory_id)
97 info = TypeId.AttributeInfo()
98 if not typeid or not typeid.LookupAttributeByName(name, info):
99 raise AttributeError("Invalid attribute %s for element type %d" % \
101 checker = info.checker
102 ns3_value = checker.Create()
103 self._get_attribute(name, ns3_value, element)
104 value = ns3_value.SerializeToString(checker)
105 attr_type = factory.box_attributes.get_attribute_type(name)
106 if attr_type == Attribute.INTEGER:
108 if attr_type == Attribute.DOUBLE:
110 if attr_type == Attribute.BOOL:
111 return value == "true"
114 def action(self, time, guid, action):
115 raise NotImplementedError
117 def trace_filename(self, guid, trace_id):
118 # TODO: Need to be defined inside a home!!!! with and experiment id_code
119 filename = self._traces[guid][trace_id]
120 return os.path.join(self.home_directory, filename)
122 def follow_trace(self, guid, trace_id, filename):
123 if guid not in self._traces:
124 self._traces[guid] = dict()
125 self._traces[guid][trace_id] = filename
128 for element in self._elements.itervalues():
129 if isinstance(element, self.LOCAL_TYPES):
130 # graceful shutdown of locally-implemented objects
132 self._elements.clear()
134 #self.ns3.Simulator.Stop()
135 self._stop_simulation("0s")
136 if self._simulator_thread:
137 self._simulator_thread.join()
138 self.ns3.Simulator.Destroy()
143 def _simulator_run(self, condition):
145 self.ns3.Simulator.Run()
146 # Signal condition on simulation end to notify waiting threads
148 condition.notifyAll()
151 def _schedule_event(self, condition, func, *args):
152 """Schedules event on running experiment"""
153 def execute_event(condition, has_event_occurred, func, *args):
159 has_event_occurred[0] = True
160 # notify condition indicating attribute was set
162 condition.notifyAll()
165 # contextId is defined as general context
166 contextId = long(0xffffffff)
167 # delay 0 means that the event is expected to execute inmediately
168 delay = self.ns3.Seconds(0)
169 # flag to indicate that the event occured
170 # because bool is an inmutable object in python, in order to create a
171 # bool flag, a list is used as wrapper
172 has_event_occurred = [False]
174 if not self.ns3.Simulator.IsFinished():
175 self.ns3.Simulator.ScheduleWithContext(contextId, delay, execute_event,
176 condition, has_event_occurred, func, *args)
177 while not has_event_occurred[0] and not self.ns3.Simulator.IsFinished():
181 def _set_attribute(self, name, ns3_value, element):
182 if self.status() == TESTBED_STATUS_STARTED:
183 # schedule the event in the Simulator
184 self._schedule_event(self._condition, self._set_ns3_attribute,
185 name, ns3_value, element)
187 self._set_ns3_attribute(name, ns3_value, element)
189 def _get_attribute(self, name, ns3_value, element):
190 if self.status() == TESTBED_STATUS_STARTED:
191 # schedule the event in the Simulator
192 self._schedule_event(self._condition, self._get_ns3_attribute,
193 name, ns3_value, element)
195 self._get_ns3_attribute(name, ns3_value, element)
197 def _set_ns3_attribute(self, name, ns3_value, element):
198 element.SetAttribute(name, ns3_value)
200 def _get_ns3_attribute(self, name, ns3_value, element):
201 element.GetAttribute(name, ns3_value)
203 def _stop_simulation(self, time):
204 if self.status() == TESTBED_STATUS_STARTED:
205 # schedule the event in the Simulator
206 self._schedule_event(self._condition, self._stop_ns3_simulation,
209 self._stop_ns3_simulation(time)
211 def _stop_simulation(self, time = TIME_NOW):
215 self.ns3.Simulator.Stop()
217 self.ns3.Simulator.Stop(self.ns3.Time(time))
219 def _to_ns3_value(self, guid, name, value):
220 factory_id = self._create[guid]
221 TypeId = self.ns3.TypeId()
222 typeid = TypeId.LookupByName(factory_id)
223 info = TypeId.AttributeInfo()
224 if not typeid.LookupAttributeByName(name, info):
225 raise RuntimeError("Attribute %s doesn't belong to element %s" \
226 % (name, factory_id))
227 str_value = str(value)
228 if isinstance(value, bool):
229 str_value = str_value.lower()
230 checker = info.checker
231 ns3_value = checker.Create()
232 ns3_value.DeserializeFromString(str_value, checker)
235 def _load_ns3_module(self):
239 simu_impl_type = self._attributes.get_attribute_value(
240 "SimulatorImplementationType")
241 checksum = self._attributes.get_attribute_value("ChecksumEnabled")
242 stop_time = self._attributes.get_attribute_value("StopTime")
244 bindings = os.environ["NEPI_NS3BINDINGS"] \
245 if "NEPI_NS3BINDINGS" in os.environ else None
246 libfile = os.environ["NEPI_NS3LIBRARY"] \
247 if "NEPI_NS3LIBRARY" in os.environ else None
250 ctypes.CDLL(libfile, ctypes.RTLD_GLOBAL)
252 path = [ os.path.dirname(__file__) ] + sys.path
254 path = [ bindings ] + path
257 module = imp.find_module ('ns3', path)
258 mod = imp.load_module ('ns3', *module)
260 # In some environments, ns3 per-se does not exist,
261 # only the low-level _ns3
262 module = imp.find_module ('_ns3', path)
263 mod = imp.load_module ('_ns3', *module)
264 sys.modules["ns3"] = mod # install it as ns3 too
266 # When using _ns3, we have to make sure we destroy
267 # the simulator when the process finishes
269 atexit.register(mod.Simulator.Destroy)
272 value = mod.StringValue(simu_impl_type)
273 mod.GlobalValue.Bind ("SimulatorImplementationType", value)
275 value = mod.BooleanValue(checksum)
276 mod.GlobalValue.Bind ("ChecksumEnabled", value)
278 value = mod.Time(stop_time)
279 mod.Simulator.Stop (value)
282 def _get_construct_parameters(self, guid):
283 params = self._get_parameters(guid)
284 construct_params = dict()
285 factory_id = self._create[guid]
286 TypeId = self.ns3.TypeId()
287 typeid = TypeId.LookupByName(factory_id)
288 for name, value in params.iteritems():
289 info = self.ns3.TypeId.AttributeInfo()
290 found = typeid.LookupAttributeByName(name, info)
292 (info.flags & TypeId.ATTR_CONSTRUCT == TypeId.ATTR_CONSTRUCT):
293 construct_params[name] = value
294 return construct_params