2 # -*- coding: utf-8 -*-
4 from constants import TESTBED_ID
5 from nepi.core import testbed_impl
6 from nepi.core.attributes import Attribute
7 from nepi.util.constants import TIME_NOW
15 from nepi.util.tunchannel import TunChannel
17 class TestbedController(testbed_impl.TestbedController):
19 'ns3::Nepi::TunChannel' : TunChannel,
22 def __init__(self, testbed_version):
23 super(TestbedController, self).__init__(TESTBED_ID, testbed_version)
25 self._home_directory = None
27 self._simulator_thread = None
28 self._condition = None
31 self.TunChannel = TunChannel
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 set(self, guid, name, value, time = TIME_NOW):
61 super(TestbedController, self).set(guid, name, value, time)
62 # TODO: take on account schedule time for the task
63 factory_id = self._create[guid]
64 factory = self._factories[factory_id]
65 if factory.box_attributes.is_attribute_design_only(name) or \
66 factory.box_attributes.is_attribute_invisible(name):
68 element = self._elements[guid]
69 if factory_id in self.LOCAL_FACTORIES:
70 setattr(element, name, value)
72 ns3_value = self._to_ns3_value(guid, name, value)
73 element.SetAttribute(name, ns3_value)
75 def get(self, guid, name, time = TIME_NOW):
76 value = super(TestbedController, self).get(guid, name, time)
77 # TODO: take on account schedule time for the task
78 factory_id = self._create[guid]
79 factory = self._factories[factory_id]
80 if factory.box_attributes.is_attribute_design_only(name) or \
81 factory.box_attributes.is_attribute_invisible(name):
83 if factory_id in self.LOCAL_FACTORIES:
84 return getattr(element, name)
85 TypeId = self.ns3.TypeId()
86 typeid = TypeId.LookupByName(factory_id)
87 info = TypeId.AttributeInfo()
88 if not typeid or not typeid.LookupAttributeByName(name, info):
89 raise AttributeError("Invalid attribute %s for element type %d" % \
91 checker = info.checker
92 ns3_value = checker.Create()
93 element = self._elements[guid]
94 element.GetAttribute(name, ns3_value)
95 value = ns3_value.SerializeToString(checker)
96 attr_type = factory.box_attributes.get_attribute_type(name)
97 if attr_type == Attribute.INTEGER:
99 if attr_type == Attribute.DOUBLE:
101 if attr_type == Attribute.BOOL:
102 return value == "true"
105 def action(self, time, guid, action):
106 raise NotImplementedError
108 def trace_filename(self, guid, trace_id):
109 # TODO: Need to be defined inside a home!!!! with and experiment id_code
110 filename = self._traces[guid][trace_id]
111 return os.path.join(self.home_directory, filename)
113 def follow_trace(self, guid, trace_id, filename):
114 if guid not in self._traces:
115 self._traces[guid] = dict()
116 self._traces[guid][trace_id] = filename
119 for element in self._elements.values():
122 def _simulator_run(self, condition):
124 self.ns3.Simulator.Run()
125 # Signal condition on simulation end to notify waiting threads
127 condition.notifyAll()
130 def _schedule_event(self, condition, func, *args):
131 """Schedules event on running experiment"""
132 def execute_event(condition, has_event_occurred, func, *args):
136 has_event_occurred[0] = True
137 # notify condition indicating attribute was set
139 condition.notifyAll()
142 # contextId is defined as general context
143 contextId = long(0xffffffff)
144 # delay 0 means that the event is expected to execute inmediately
145 delay = self.ns3.Seconds(0)
146 # flag to indicate that the event occured
147 # because bool is an inmutable object in python, in order to create a
148 # bool flag, a list is used as wrapper
149 has_event_occurred = [False]
151 if not self.ns3.Simulator.IsFinished():
152 self.ns3.Simulator.ScheduleWithContext(contextId, delay, execute_event,
153 condition, has_event_occurred, func, *args)
154 while not has_event_occurred[0] and not self.ns3.Simulator.IsFinished():
157 if not has_event_occurred[0]:
158 raise RuntimeError('Event could not be scheduled : %s %s ' \
159 % (repr(func), repr(args)))
161 def _to_ns3_value(self, guid, name, value):
162 factory_id = self._create[guid]
163 TypeId = self.ns3.TypeId()
164 typeid = TypeId.LookupByName(factory_id)
165 info = TypeId.AttributeInfo()
166 if not typeid.LookupAttributeByName(name, info):
167 raise RuntimeError("Attribute %s doesn't belong to element %s" \
168 % (name, factory_id))
169 str_value = str(value)
170 if isinstance(value, bool):
171 str_value = str_value.lower()
172 checker = info.checker
173 ns3_value = checker.Create()
174 ns3_value.DeserializeFromString(str_value, checker)
177 def _load_ns3_module(self):
181 simu_impl_type = self._attributes.get_attribute_value(
182 "SimulatorImplementationType")
183 checksum = self._attributes.get_attribute_value("ChecksumEnabled")
185 bindings = os.environ["NEPI_NS3BINDINGS"] \
186 if "NEPI_NS3BINDINGS" in os.environ else None
187 libfile = os.environ["NEPI_NS3LIBRARY"] \
188 if "NEPI_NS3LIBRARY" in os.environ else None
191 ctypes.CDLL(libfile, ctypes.RTLD_GLOBAL)
193 path = [ os.path.dirname(__file__) ] + sys.path
195 path = [ bindings ] + path
198 module = imp.find_module ('ns3', path)
199 mod = imp.load_module ('ns3', *module)
201 # In some environments, ns3 per-se does not exist,
202 # only the low-level _ns3
203 module = imp.find_module ('_ns3', path)
204 mod = imp.load_module ('_ns3', *module)
205 sys.modules["ns3"] = mod # install it as ns3 too
207 # When using _ns3, we have to make sure we destroy
208 # the simulator when the process finishes
210 atexit.register(mod.Simulator.Destroy)
213 value = mod.StringValue(simu_impl_type)
214 mod.GlobalValue.Bind ("SimulatorImplementationType", value)
216 value = mod.BooleanValue(checksum)
217 mod.GlobalValue.Bind ("ChecksumEnabled", value)
220 def _get_construct_parameters(self, guid):
221 params = self._get_parameters(guid)
222 construct_params = dict()
223 factory_id = self._create[guid]
224 TypeId = self.ns3.TypeId()
225 typeid = TypeId.LookupByName(factory_id)
226 for name, value in params.iteritems():
227 info = self.ns3.TypeId.AttributeInfo()
228 found = typeid.LookupAttributeByName(name, info)
230 (info.flags & TypeId.ATTR_CONSTRUCT == TypeId.ATTR_CONSTRUCT):
231 construct_params[name] = value
232 return construct_params