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 class TestbedController(testbed_impl.TestbedController):
16 from nepi.util.tunchannel_impl import TunChannel
19 'ns3::Nepi::TunChannel' : TunChannel,
22 LOCAL_TYPES = tuple(LOCAL_FACTORIES.values())
24 def __init__(self, testbed_version):
25 super(TestbedController, self).__init__(TESTBED_ID, testbed_version)
27 self._home_directory = None
29 self._simulator_thread = None
30 self._condition = None
33 def home_directory(self):
34 return self._home_directory
41 self._home_directory = self._attributes.\
42 get_attribute_value("homeDirectory")
43 self._ns3 = self._load_ns3_module()
46 home = os.path.normpath(self.home_directory)
47 if not os.path.exists(home):
48 os.makedirs(home, 0755)
50 super(TestbedController, self).do_setup()
53 super(TestbedController, self).start()
54 self._condition = threading.Condition()
55 self._simulator_thread = threading.Thread(target = self._simulator_run,
56 args = [self._condition])
57 self._simulator_thread.start()
59 def set(self, guid, name, value, time = TIME_NOW):
60 super(TestbedController, self).set(guid, name, value, time)
61 # TODO: take on account schedule time for the task
62 factory_id = self._create[guid]
63 factory = self._factories[factory_id]
64 if factory.box_attributes.is_attribute_design_only(name):
66 element = self._elements[guid]
67 if factory_id in self.LOCAL_FACTORIES:
68 setattr(element, name, value)
69 elif factory.box_attributes.is_attribute_invisible(name):
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 element = self._elements[guid]
81 if factory_id in self.LOCAL_FACTORIES:
82 if hasattr(element, name):
83 return getattr(element, name)
86 if factory.box_attributes.is_attribute_design_only(name) or \
87 factory.box_attributes.is_attribute_invisible(name):
89 TypeId = self.ns3.TypeId()
90 typeid = TypeId.LookupByName(factory_id)
91 info = TypeId.AttributeInfo()
92 if not typeid or not typeid.LookupAttributeByName(name, info):
93 raise AttributeError("Invalid attribute %s for element type %d" % \
95 checker = info.checker
96 ns3_value = checker.Create()
97 element.GetAttribute(name, ns3_value)
98 value = ns3_value.SerializeToString(checker)
99 attr_type = factory.box_attributes.get_attribute_type(name)
100 if attr_type == Attribute.INTEGER:
102 if attr_type == Attribute.DOUBLE:
104 if attr_type == Attribute.BOOL:
105 return value == "true"
108 def action(self, time, guid, action):
109 raise NotImplementedError
111 def trace_filename(self, guid, trace_id):
112 # TODO: Need to be defined inside a home!!!! with and experiment id_code
113 filename = self._traces[guid][trace_id]
114 return os.path.join(self.home_directory, filename)
116 def follow_trace(self, guid, trace_id, filename):
117 if guid not in self._traces:
118 self._traces[guid] = dict()
119 self._traces[guid][trace_id] = filename
122 for element in self._elements.values():
123 if isinstance(element, self.LOCAL_TYPES):
124 # graceful shutdown of locally-implemented objects
128 def _simulator_run(self, condition):
130 self.ns3.Simulator.Run()
131 # Signal condition on simulation end to notify waiting threads
133 condition.notifyAll()
136 def _schedule_event(self, condition, func, *args):
137 """Schedules event on running experiment"""
138 def execute_event(condition, has_event_occurred, func, *args):
142 has_event_occurred[0] = True
143 # notify condition indicating attribute was set
145 condition.notifyAll()
148 # contextId is defined as general context
149 contextId = long(0xffffffff)
150 # delay 0 means that the event is expected to execute inmediately
151 delay = self.ns3.Seconds(0)
152 # flag to indicate that the event occured
153 # because bool is an inmutable object in python, in order to create a
154 # bool flag, a list is used as wrapper
155 has_event_occurred = [False]
157 if not self.ns3.Simulator.IsFinished():
158 self.ns3.Simulator.ScheduleWithContext(contextId, delay, execute_event,
159 condition, has_event_occurred, func, *args)
160 while not has_event_occurred[0] and not self.ns3.Simulator.IsFinished():
163 if not has_event_occurred[0]:
164 raise RuntimeError('Event could not be scheduled : %s %s ' \
165 % (repr(func), repr(args)))
167 def _to_ns3_value(self, guid, name, value):
168 factory_id = self._create[guid]
169 TypeId = self.ns3.TypeId()
170 typeid = TypeId.LookupByName(factory_id)
171 info = TypeId.AttributeInfo()
172 if not typeid.LookupAttributeByName(name, info):
173 raise RuntimeError("Attribute %s doesn't belong to element %s" \
174 % (name, factory_id))
175 str_value = str(value)
176 if isinstance(value, bool):
177 str_value = str_value.lower()
178 checker = info.checker
179 ns3_value = checker.Create()
180 ns3_value.DeserializeFromString(str_value, checker)
183 def _load_ns3_module(self):
187 simu_impl_type = self._attributes.get_attribute_value(
188 "SimulatorImplementationType")
189 checksum = self._attributes.get_attribute_value("ChecksumEnabled")
191 bindings = os.environ["NEPI_NS3BINDINGS"] \
192 if "NEPI_NS3BINDINGS" in os.environ else None
193 libfile = os.environ["NEPI_NS3LIBRARY"] \
194 if "NEPI_NS3LIBRARY" in os.environ else None
197 ctypes.CDLL(libfile, ctypes.RTLD_GLOBAL)
199 path = [ os.path.dirname(__file__) ] + sys.path
201 path = [ bindings ] + path
204 module = imp.find_module ('ns3', path)
205 mod = imp.load_module ('ns3', *module)
207 # In some environments, ns3 per-se does not exist,
208 # only the low-level _ns3
209 module = imp.find_module ('_ns3', path)
210 mod = imp.load_module ('_ns3', *module)
211 sys.modules["ns3"] = mod # install it as ns3 too
213 # When using _ns3, we have to make sure we destroy
214 # the simulator when the process finishes
216 atexit.register(mod.Simulator.Destroy)
219 value = mod.StringValue(simu_impl_type)
220 mod.GlobalValue.Bind ("SimulatorImplementationType", value)
222 value = mod.BooleanValue(checksum)
223 mod.GlobalValue.Bind ("ChecksumEnabled", value)
226 def _get_construct_parameters(self, guid):
227 params = self._get_parameters(guid)
228 construct_params = dict()
229 factory_id = self._create[guid]
230 TypeId = self.ns3.TypeId()
231 typeid = TypeId.LookupByName(factory_id)
232 for name, value in params.iteritems():
233 info = self.ns3.TypeId.AttributeInfo()
234 found = typeid.LookupAttributeByName(name, info)
236 (info.flags & TypeId.ATTR_CONSTRUCT == TypeId.ATTR_CONSTRUCT):
237 construct_params[name] = value
238 return construct_params