2 # -*- coding: utf-8 -*-
4 from constants import TESTBED_ID
5 from nepi.core import testbed_impl
6 from nepi.core.attributes import Attribute
11 class TestbedController(testbed_impl.TestbedController):
12 def __init__(self, testbed_version):
13 super(TestbedController, self).__init__(TESTBED_ID, testbed_version)
15 self._home_directory = None
17 self._simulator_thread = None
18 self._condition = None
21 def home_directory(self):
22 return self._home_directory
29 self._home_directory = self._attributes.\
30 get_attribute_value("homeDirectory")
31 self._ns3 = self._load_ns3_module()
34 super(TestbedController, self).start()
35 self._condition = threading.Condition()
36 self._simulator_thread = threading.Thread(target = self._simulator_run,
37 args = [self._condition])
38 self._simulator_thread.start()
40 def set(self, time, guid, name, value):
41 super(TestbedController, self).set(time, guid, name, value)
42 # TODO: take on account schedule time for the task
43 element = self._elements[guid]
44 ns3_value = self._to_ns3_value(guid, name, value)
45 element.SetAttribute(name, ns3_value)
47 def get(self, time, guid, name):
48 # TODO: take on account schedule time for the task
49 TypeId = self.ns3.TypeId()
50 typeid = TypeId.LookupByName(factory_id)
51 info = TypeId.AttributeInfo()
52 if not typeid or not typeid.LookupAttributeByName(name, info):
54 # Try design-time attributes
55 return self.box_get(time, guid, name)
56 except KeyError, AttributeError:
58 checker = info.checker
59 ns3_value = checker.Create()
60 element = self._elements[guid]
61 element.GetAttribute(name, ns3_value)
62 value = ns3_value.SerializeToString(checker)
63 factory_id = self._create[guid]
64 factory = self._factories[factory_id]
65 attr_type = factory.box_attributes.get_attribute_type(name)
66 if attr_type == Attribute.INTEGER:
68 if attr_type == Attribute.DOUBLE:
70 if attr_type == Attribute.BOOL:
71 return value == "true"
74 def get_route(self, guid, index, attribute):
75 # TODO: fetch real data from ns3
77 return self.box_get_route(guid, int(index), attribute)
78 except KeyError, AttributeError:
81 def get_address(self, guid, index, attribute='Address'):
82 # TODO: fetch real data from ns3
84 return self.box_get_address(guid, int(index), attribute)
85 except KeyError, AttributeError:
89 def action(self, time, guid, action):
90 raise NotImplementedError
92 def trace_filename(self, guid, trace_id):
93 # TODO: Need to be defined inside a home!!!! with and experiment id_code
94 filename = self._traces[guid][trace_id]
95 return os.path.join(self.home_directory, filename)
97 def follow_trace(self, guid, trace_id, filename):
98 if guid not in self._traces:
99 self._traces[guid] = dict()
100 self._traces[guid][trace_id] = filename
103 for element in self._elements.values():
106 def _simulator_run(self, condition):
108 self.ns3.Simulator.Run()
109 # Signal condition on simulation end to notify waiting threads
111 condition.notifyAll()
114 def _schedule_event(self, condition, func, *args):
115 """Schedules event on running experiment"""
116 def execute_event(condition, has_event_occurred, func, *args):
120 has_event_occurred[0] = True
121 # notify condition indicating attribute was set
123 condition.notifyAll()
126 # contextId is defined as general context
127 contextId = long(0xffffffff)
128 # delay 0 means that the event is expected to execute inmediately
129 delay = self.ns3.Seconds(0)
130 # flag to indicate that the event occured
131 # because bool is an inmutable object in python, in order to create a
132 # bool flag, a list is used as wrapper
133 has_event_occurred = [False]
135 if not self.ns3.Simulator.IsFinished():
136 self.ns3.Simulator.ScheduleWithContext(contextId, delay, execute_event,
137 condition, has_event_occurred, func, *args)
138 while not has_event_occurred[0] and not self.ns3.Simulator.IsFinished():
141 if not has_event_occurred[0]:
142 raise RuntimeError('Event could not be scheduled : %s %s ' \
143 % (repr(func), repr(args)))
145 def _to_ns3_value(self, guid, name, value):
146 factory_id = self._create[guid]
147 TypeId = self.ns3.TypeId()
148 typeid = TypeId.LookupByName(factory_id)
149 info = TypeId.AttributeInfo()
150 if not typeid.LookupAttributeByName(name, info):
151 raise RuntimeError("Attribute %s doesn't belong to element %s" \
152 % (name, factory_id))
153 str_value = str(value)
154 if isinstance(value, bool):
155 str_value = str_value.lower()
156 checker = info.checker
157 ns3_value = checker.Create()
158 ns3_value.DeserializeFromString(str_value, checker)
161 def _load_ns3_module(self):
165 simu_impl_type = self._attributes.get_attribute_value(
166 "SimulatorImplementationType")
167 checksum = self._attributes.get_attribute_value("ChecksumEnabled")
169 bindings = os.environ["NEPI_NS3BINDINGS"] \
170 if "NEPI_NS3BINDINGS" in os.environ else None
171 libfile = os.environ["NEPI_NS3LIBRARY"] \
172 if "NEPI_NS3LIBRARY" in os.environ else None
175 ctypes.CDLL(libfile, ctypes.RTLD_GLOBAL)
177 path = [ os.path.dirname(__file__) ] + sys.path
179 path = [ bindings ] + path
181 module = imp.find_module ('ns3', path)
182 mod = imp.load_module ('ns3', *module)
185 value = mod.StringValue(simu_impl_type)
186 mod.GlobalValue.Bind ("SimulatorImplementationType", value)
188 value = mod.BooleanValue(checksum)
189 mod.GlobalValue.Bind ("ChecksumEnabled", value)
192 def _get_construct_parameters(self, guid):
193 params = self._get_parameters(guid)
194 construct_params = dict()
195 factory_id = self._create[guid]
196 TypeId = self.ns3.TypeId()
197 typeid = TypeId.LookupByName(factory_id)
198 for name, value in params.iteritems():
199 info = self.ns3.TypeId.AttributeInfo()
200 typeid.LookupAttributeByName(name, info)
201 if info.flags & TypeId.ATTR_CONSTRUCT == TypeId.ATTR_CONSTRUCT:
202 construct_params[name] = value
203 return construct_params