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 TESTBED_STATUS_CREATED
12 class TestbedController(testbed_impl.TestbedController):
13 def __init__(self, testbed_version):
14 super(TestbedController, self).__init__(TESTBED_ID, testbed_version)
16 self._home_directory = None
18 self._simulator_thread = None
19 self._condition = None
22 def home_directory(self):
23 return self._home_directory
30 self._home_directory = self._attributes.\
31 get_attribute_value("homeDirectory")
32 self._ns3 = self._load_ns3_module()
33 super(TestbedController, self).do_setup()
36 super(TestbedController, self).start()
37 self._condition = threading.Condition()
38 self._simulator_thread = threading.Thread(target = self._simulator_run,
39 args = [self._condition])
40 self._simulator_thread.start()
42 def set(self, time, guid, name, value):
43 super(TestbedController, self).set(time, guid, name, value)
44 # TODO: take on account schedule time for the task
45 if self._status < TESTBED_STATUS_CREATED or \
46 factory.box_attributes.is_attribute_design_only(name):
48 element = self._elements[guid]
49 ns3_value = self._to_ns3_value(guid, name, value)
50 element.SetAttribute(name, ns3_value)
52 def get(self, time, guid, name):
53 # TODO: take on account schedule time for the task
54 TypeId = self.ns3.TypeId()
55 typeid = TypeId.LookupByName(factory_id)
56 info = TypeId.AttributeInfo()
57 if not typeid or not typeid.LookupAttributeByName(name, info):
59 # Try design-time attributes
60 return self.box_get(time, guid, name)
61 except KeyError, AttributeError:
63 checker = info.checker
64 ns3_value = checker.Create()
65 element = self._elements[guid]
66 element.GetAttribute(name, ns3_value)
67 value = ns3_value.SerializeToString(checker)
68 factory_id = self._create[guid]
69 factory = self._factories[factory_id]
70 attr_type = factory.box_attributes.get_attribute_type(name)
71 if attr_type == Attribute.INTEGER:
73 if attr_type == Attribute.DOUBLE:
75 if attr_type == Attribute.BOOL:
76 return value == "true"
79 def get_route(self, guid, index, attribute):
80 # TODO: fetch real data from ns3
82 return self.box_get_route(guid, int(index), attribute)
83 except KeyError, AttributeError:
86 def get_address(self, guid, index, attribute='Address'):
87 # TODO: fetch real data from ns3
89 return self.box_get_address(guid, int(index), attribute)
90 except KeyError, AttributeError:
94 def action(self, time, guid, action):
95 raise NotImplementedError
97 def trace_filename(self, guid, trace_id):
98 # TODO: Need to be defined inside a home!!!! with and experiment id_code
99 filename = self._traces[guid][trace_id]
100 return os.path.join(self.home_directory, filename)
102 def follow_trace(self, guid, trace_id, filename):
103 if guid not in self._traces:
104 self._traces[guid] = dict()
105 self._traces[guid][trace_id] = filename
108 for element in self._elements.values():
111 def _simulator_run(self, condition):
113 self.ns3.Simulator.Run()
114 # Signal condition on simulation end to notify waiting threads
116 condition.notifyAll()
119 def _schedule_event(self, condition, func, *args):
120 """Schedules event on running experiment"""
121 def execute_event(condition, has_event_occurred, func, *args):
125 has_event_occurred[0] = True
126 # notify condition indicating attribute was set
128 condition.notifyAll()
131 # contextId is defined as general context
132 contextId = long(0xffffffff)
133 # delay 0 means that the event is expected to execute inmediately
134 delay = self.ns3.Seconds(0)
135 # flag to indicate that the event occured
136 # because bool is an inmutable object in python, in order to create a
137 # bool flag, a list is used as wrapper
138 has_event_occurred = [False]
140 if not self.ns3.Simulator.IsFinished():
141 self.ns3.Simulator.ScheduleWithContext(contextId, delay, execute_event,
142 condition, has_event_occurred, func, *args)
143 while not has_event_occurred[0] and not self.ns3.Simulator.IsFinished():
146 if not has_event_occurred[0]:
147 raise RuntimeError('Event could not be scheduled : %s %s ' \
148 % (repr(func), repr(args)))
150 def _to_ns3_value(self, guid, name, value):
151 factory_id = self._create[guid]
152 TypeId = self.ns3.TypeId()
153 typeid = TypeId.LookupByName(factory_id)
154 info = TypeId.AttributeInfo()
155 if not typeid.LookupAttributeByName(name, info):
156 raise RuntimeError("Attribute %s doesn't belong to element %s" \
157 % (name, factory_id))
158 str_value = str(value)
159 if isinstance(value, bool):
160 str_value = str_value.lower()
161 checker = info.checker
162 ns3_value = checker.Create()
163 ns3_value.DeserializeFromString(str_value, checker)
166 def _load_ns3_module(self):
170 simu_impl_type = self._attributes.get_attribute_value(
171 "SimulatorImplementationType")
172 checksum = self._attributes.get_attribute_value("ChecksumEnabled")
174 bindings = os.environ["NEPI_NS3BINDINGS"] \
175 if "NEPI_NS3BINDINGS" in os.environ else None
176 libfile = os.environ["NEPI_NS3LIBRARY"] \
177 if "NEPI_NS3LIBRARY" in os.environ else None
180 ctypes.CDLL(libfile, ctypes.RTLD_GLOBAL)
182 path = [ os.path.dirname(__file__) ] + sys.path
184 path = [ bindings ] + path
186 module = imp.find_module ('ns3', path)
187 mod = imp.load_module ('ns3', *module)
190 value = mod.StringValue(simu_impl_type)
191 mod.GlobalValue.Bind ("SimulatorImplementationType", value)
193 value = mod.BooleanValue(checksum)
194 mod.GlobalValue.Bind ("ChecksumEnabled", value)
197 def _get_construct_parameters(self, guid):
198 params = self._get_parameters(guid)
199 construct_params = dict()
200 factory_id = self._create[guid]
201 TypeId = self.ns3.TypeId()
202 typeid = TypeId.LookupByName(factory_id)
203 for name, value in params.iteritems():
204 info = self.ns3.TypeId.AttributeInfo()
205 found = typeid.LookupAttributeByName(name, info)
207 (info.flags & TypeId.ATTR_CONSTRUCT == TypeId.ATTR_CONSTRUCT):
208 construct_params[name] = value
209 return construct_params