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 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 def home_directory(self):
32 return self._home_directory
39 self._home_directory = self._attributes.\
40 get_attribute_value("homeDirectory")
41 self._ns3 = self._load_ns3_module()
44 home = os.path.normpath(self.home_directory)
45 if not os.path.exists(home):
46 os.makedirs(home, 0755)
48 super(TestbedController, self).do_setup()
51 super(TestbedController, self).start()
52 self._condition = threading.Condition()
53 self._simulator_thread = threading.Thread(target = self._simulator_run,
54 args = [self._condition])
55 self._simulator_thread.start()
57 def set(self, guid, name, value, time = TIME_NOW):
58 super(TestbedController, self).set(guid, name, value, time)
59 # TODO: take on account schedule time for the task
60 factory_id = self._create[guid]
61 factory = self._factories[factory_id]
62 if factory.box_attributes.is_attribute_design_only(name) or \
63 factory.box_attributes.is_attribute_invisible(name):
65 element = self._elements[guid]
66 if factory_id in self.LOCAL_FACTORIES:
67 setattr(element, name, value)
69 ns3_value = self._to_ns3_value(guid, name, value)
70 element.SetAttribute(name, ns3_value)
72 def get(self, guid, name, time = TIME_NOW):
73 value = super(TestbedController, self).get(guid, name, time)
74 # TODO: take on account schedule time for the task
75 factory_id = self._create[guid]
76 factory = self._factories[factory_id]
77 if factory.box_attributes.is_attribute_design_only(name) or \
78 factory.box_attributes.is_attribute_invisible(name):
80 if factory_id in self.LOCAL_FACTORIES:
81 return getattr(element, name)
82 TypeId = self.ns3.TypeId()
83 typeid = TypeId.LookupByName(factory_id)
84 info = TypeId.AttributeInfo()
85 if not typeid or not typeid.LookupAttributeByName(name, info):
86 raise AttributeError("Invalid attribute %s for element type %d" % \
88 checker = info.checker
89 ns3_value = checker.Create()
90 element = self._elements[guid]
91 element.GetAttribute(name, ns3_value)
92 value = ns3_value.SerializeToString(checker)
93 attr_type = factory.box_attributes.get_attribute_type(name)
94 if attr_type == Attribute.INTEGER:
96 if attr_type == Attribute.DOUBLE:
98 if attr_type == Attribute.BOOL:
99 return value == "true"
102 def action(self, time, guid, action):
103 raise NotImplementedError
105 def trace_filename(self, guid, trace_id):
106 # TODO: Need to be defined inside a home!!!! with and experiment id_code
107 filename = self._traces[guid][trace_id]
108 return os.path.join(self.home_directory, filename)
110 def follow_trace(self, guid, trace_id, filename):
111 if guid not in self._traces:
112 self._traces[guid] = dict()
113 self._traces[guid][trace_id] = filename
116 for element in self._elements.values():
119 def _simulator_run(self, condition):
121 self.ns3.Simulator.Run()
122 # Signal condition on simulation end to notify waiting threads
124 condition.notifyAll()
127 def _schedule_event(self, condition, func, *args):
128 """Schedules event on running experiment"""
129 def execute_event(condition, has_event_occurred, func, *args):
133 has_event_occurred[0] = True
134 # notify condition indicating attribute was set
136 condition.notifyAll()
139 # contextId is defined as general context
140 contextId = long(0xffffffff)
141 # delay 0 means that the event is expected to execute inmediately
142 delay = self.ns3.Seconds(0)
143 # flag to indicate that the event occured
144 # because bool is an inmutable object in python, in order to create a
145 # bool flag, a list is used as wrapper
146 has_event_occurred = [False]
148 if not self.ns3.Simulator.IsFinished():
149 self.ns3.Simulator.ScheduleWithContext(contextId, delay, execute_event,
150 condition, has_event_occurred, func, *args)
151 while not has_event_occurred[0] and not self.ns3.Simulator.IsFinished():
154 if not has_event_occurred[0]:
155 raise RuntimeError('Event could not be scheduled : %s %s ' \
156 % (repr(func), repr(args)))
158 def _to_ns3_value(self, guid, name, value):
159 factory_id = self._create[guid]
160 TypeId = self.ns3.TypeId()
161 typeid = TypeId.LookupByName(factory_id)
162 info = TypeId.AttributeInfo()
163 if not typeid.LookupAttributeByName(name, info):
164 raise RuntimeError("Attribute %s doesn't belong to element %s" \
165 % (name, factory_id))
166 str_value = str(value)
167 if isinstance(value, bool):
168 str_value = str_value.lower()
169 checker = info.checker
170 ns3_value = checker.Create()
171 ns3_value.DeserializeFromString(str_value, checker)
174 def _load_ns3_module(self):
178 simu_impl_type = self._attributes.get_attribute_value(
179 "SimulatorImplementationType")
180 checksum = self._attributes.get_attribute_value("ChecksumEnabled")
182 bindings = os.environ["NEPI_NS3BINDINGS"] \
183 if "NEPI_NS3BINDINGS" in os.environ else None
184 libfile = os.environ["NEPI_NS3LIBRARY"] \
185 if "NEPI_NS3LIBRARY" in os.environ else None
188 ctypes.CDLL(libfile, ctypes.RTLD_GLOBAL)
190 path = [ os.path.dirname(__file__) ] + sys.path
192 path = [ bindings ] + path
195 module = imp.find_module ('ns3', path)
196 mod = imp.load_module ('ns3', *module)
198 # In some environments, ns3 per-se does not exist,
199 # only the low-level _ns3
200 module = imp.find_module ('_ns3', path)
201 mod = imp.load_module ('_ns3', *module)
202 sys.modules["ns3"] = mod # install it as ns3 too
204 # When using _ns3, we have to make sure we destroy
205 # the simulator when the process finishes
207 atexit.register(mod.Simulator.Destroy)
210 value = mod.StringValue(simu_impl_type)
211 mod.GlobalValue.Bind ("SimulatorImplementationType", value)
213 value = mod.BooleanValue(checksum)
214 mod.GlobalValue.Bind ("ChecksumEnabled", value)
217 def _get_construct_parameters(self, guid):
218 params = self._get_parameters(guid)
219 construct_params = dict()
220 factory_id = self._create[guid]
221 TypeId = self.ns3.TypeId()
222 typeid = TypeId.LookupByName(factory_id)
223 for name, value in params.iteritems():
224 info = self.ns3.TypeId.AttributeInfo()
225 found = typeid.LookupAttributeByName(name, info)
227 (info.flags & TypeId.ATTR_CONSTRUCT == TypeId.ATTR_CONSTRUCT):
228 construct_params[name] = value
229 return construct_params