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.setDaemon(True)
59 self._simulator_thread.start()
61 def stop(self, time = TIME_NOW):
62 super(TestbedController, self).stop(time)
63 # BUG!!!! RealtimeSimulatorImpl never stops simulation with Stop()!!!
64 self.ns3.Simulator.Stop()
65 #self._stop_simulation(time)
67 def set(self, guid, name, value, time = TIME_NOW):
68 super(TestbedController, self).set(guid, name, value, time)
69 # TODO: take on account schedule time for the task
70 factory_id = self._create[guid]
71 factory = self._factories[factory_id]
72 if factory.box_attributes.is_attribute_design_only(name):
74 element = self._elements[guid]
75 if factory_id in self.LOCAL_FACTORIES:
76 setattr(element, name, value)
77 elif factory.box_attributes.is_attribute_invisible(name):
80 ns3_value = self._to_ns3_value(guid, name, value)
81 self._set_attribute(name, ns3_value, element)
83 def get(self, guid, name, time = TIME_NOW):
84 value = super(TestbedController, self).get(guid, name, time)
85 # TODO: take on account schedule time for the task
86 factory_id = self._create[guid]
87 factory = self._factories[factory_id]
88 element = self._elements[guid]
89 if factory_id in self.LOCAL_FACTORIES:
90 if hasattr(element, name):
91 return getattr(element, name)
94 if factory.box_attributes.is_attribute_design_only(name) or \
95 factory.box_attributes.is_attribute_invisible(name):
97 TypeId = self.ns3.TypeId()
98 typeid = TypeId.LookupByName(factory_id)
99 info = TypeId.AttributeInfo()
100 if not typeid or not typeid.LookupAttributeByName(name, info):
101 raise AttributeError("Invalid attribute %s for element type %d" % \
103 checker = info.checker
104 ns3_value = checker.Create()
105 self._get_attribute(name, ns3_value, element)
106 value = ns3_value.SerializeToString(checker)
107 attr_type = factory.box_attributes.get_attribute_type(name)
108 if attr_type == Attribute.INTEGER:
110 if attr_type == Attribute.DOUBLE:
112 if attr_type == Attribute.BOOL:
113 return value == "true"
116 def action(self, time, guid, action):
117 raise NotImplementedError
119 def trace_filename(self, guid, trace_id):
120 # TODO: Need to be defined inside a home!!!! with and experiment id_code
121 filename = self._traces[guid][trace_id]
122 return os.path.join(self.home_directory, filename)
124 def follow_trace(self, guid, trace_id, filename):
125 if guid not in self._traces:
126 self._traces[guid] = dict()
127 self._traces[guid][trace_id] = filename
130 for element in self._elements.itervalues():
131 if isinstance(element, self.LOCAL_TYPES):
132 # graceful shutdown of locally-implemented objects
134 self._elements.clear()
136 self.ns3.Simulator.Stop()
137 ##################################################
138 # BUG!!!! RealtimeSimulatorImpl never stops simulation with Stop()!!!
139 # self._stop_simulation("0s")
140 # if self._simulator_thread:
141 # print "Joining thread"
142 # self._simulator_thread.join()
143 #################################################
144 self.ns3.Simulator.Destroy()
149 def _simulator_run(self, condition):
151 self.ns3.Simulator.Run()
152 # Signal condition on simulation end to notify waiting threads
154 condition.notifyAll()
157 def _schedule_event(self, condition, func, *args):
158 """Schedules event on running experiment"""
159 def execute_event(condition, has_event_occurred, func, *args):
165 has_event_occurred[0] = True
166 # notify condition indicating attribute was set
168 condition.notifyAll()
171 # contextId is defined as general context
172 contextId = long(0xffffffff)
173 # delay 0 means that the event is expected to execute inmediately
174 delay = self.ns3.Seconds(0)
175 # flag to indicate that the event occured
176 # because bool is an inmutable object in python, in order to create a
177 # bool flag, a list is used as wrapper
178 has_event_occurred = [False]
180 if not self.ns3.Simulator.IsFinished():
181 self.ns3.Simulator.ScheduleWithContext(contextId, delay, execute_event,
182 condition, has_event_occurred, func, *args)
183 while not has_event_occurred[0] and not self.ns3.Simulator.IsFinished():
187 def _set_attribute(self, name, ns3_value, element):
188 if self.status() == TESTBED_STATUS_STARTED:
189 # schedule the event in the Simulator
190 self._schedule_event(self._condition, self._set_ns3_attribute,
191 name, ns3_value, element)
193 self._set_ns3_attribute(name, ns3_value, element)
195 def _get_attribute(self, name, ns3_value, element):
196 if self.status() == TESTBED_STATUS_STARTED:
197 # schedule the event in the Simulator
198 self._schedule_event(self._condition, self._get_ns3_attribute,
199 name, ns3_value, element)
201 self._get_ns3_attribute(name, ns3_value, element)
203 def _set_ns3_attribute(self, name, ns3_value, element):
204 element.SetAttribute(name, ns3_value)
206 def _get_ns3_attribute(self, name, ns3_value, element):
207 element.GetAttribute(name, ns3_value)
209 def _stop_simulation(self, time):
210 if self.status() == TESTBED_STATUS_STARTED:
211 # schedule the event in the Simulator
212 self._schedule_event(self._condition, self._stop_ns3_simulation,
215 self._stop_ns3_simulation(time)
217 def _stop_simulation(self, time = TIME_NOW):
221 self.ns3.Simulator.Stop()
223 self.ns3.Simulator.Stop(self.ns3.Time(time))
225 def _to_ns3_value(self, guid, name, value):
226 factory_id = self._create[guid]
227 TypeId = self.ns3.TypeId()
228 typeid = TypeId.LookupByName(factory_id)
229 info = TypeId.AttributeInfo()
230 if not typeid.LookupAttributeByName(name, info):
231 raise RuntimeError("Attribute %s doesn't belong to element %s" \
232 % (name, factory_id))
233 str_value = str(value)
234 if isinstance(value, bool):
235 str_value = str_value.lower()
236 checker = info.checker
237 ns3_value = checker.Create()
238 ns3_value.DeserializeFromString(str_value, checker)
241 def _load_ns3_module(self):
245 simu_impl_type = self._attributes.get_attribute_value(
246 "SimulatorImplementationType")
247 checksum = self._attributes.get_attribute_value("ChecksumEnabled")
248 stop_time = self._attributes.get_attribute_value("StopTime")
250 bindings = os.environ["NEPI_NS3BINDINGS"] \
251 if "NEPI_NS3BINDINGS" in os.environ else None
252 libfile = os.environ["NEPI_NS3LIBRARY"] \
253 if "NEPI_NS3LIBRARY" in os.environ else None
256 ctypes.CDLL(libfile, ctypes.RTLD_GLOBAL)
258 path = [ os.path.dirname(__file__) ] + sys.path
260 path = [ bindings ] + path
263 module = imp.find_module ('ns3', path)
264 mod = imp.load_module ('ns3', *module)
266 # In some environments, ns3 per-se does not exist,
267 # only the low-level _ns3
268 module = imp.find_module ('_ns3', path)
269 mod = imp.load_module ('_ns3', *module)
270 sys.modules["ns3"] = mod # install it as ns3 too
272 # When using _ns3, we have to make sure we destroy
273 # the simulator when the process finishes
275 atexit.register(mod.Simulator.Destroy)
278 value = mod.StringValue(simu_impl_type)
279 mod.GlobalValue.Bind ("SimulatorImplementationType", value)
281 value = mod.BooleanValue(checksum)
282 mod.GlobalValue.Bind ("ChecksumEnabled", value)
284 value = mod.Time(stop_time)
285 mod.Simulator.Stop (value)
288 def _get_construct_parameters(self, guid):
289 params = self._get_parameters(guid)
290 construct_params = dict()
291 factory_id = self._create[guid]
292 TypeId = self.ns3.TypeId()
293 typeid = TypeId.LookupByName(factory_id)
294 for name, value in params.iteritems():
295 info = self.ns3.TypeId.AttributeInfo()
296 found = typeid.LookupAttributeByName(name, info)
298 (info.flags & TypeId.ATTR_CONSTRUCT == TypeId.ATTR_CONSTRUCT):
299 construct_params[name] = value
300 return construct_params