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
130 def _simulator_run(self, condition):
132 self.ns3.Simulator.Run()
133 # Signal condition on simulation end to notify waiting threads
135 condition.notifyAll()
138 def _schedule_event(self, condition, func, *args):
139 """Schedules event on running experiment"""
140 def execute_event(condition, has_event_occurred, func, *args):
144 has_event_occurred[0] = True
145 # notify condition indicating attribute was set
147 condition.notifyAll()
150 # contextId is defined as general context
151 contextId = long(0xffffffff)
152 # delay 0 means that the event is expected to execute inmediately
153 delay = self.ns3.Seconds(0)
154 # flag to indicate that the event occured
155 # because bool is an inmutable object in python, in order to create a
156 # bool flag, a list is used as wrapper
157 has_event_occurred = [False]
159 if not self.ns3.Simulator.IsFinished():
160 self.ns3.Simulator.ScheduleWithContext(contextId, delay, execute_event,
161 condition, has_event_occurred, func, *args)
162 while not has_event_occurred[0] and not self.ns3.Simulator.IsFinished():
165 if not has_event_occurred[0]:
166 raise RuntimeError('Event could not be scheduled : %s %s ' \
167 % (repr(func), repr(args)))
169 def _to_ns3_value(self, guid, name, value):
170 factory_id = self._create[guid]
171 TypeId = self.ns3.TypeId()
172 typeid = TypeId.LookupByName(factory_id)
173 info = TypeId.AttributeInfo()
174 if not typeid.LookupAttributeByName(name, info):
175 raise RuntimeError("Attribute %s doesn't belong to element %s" \
176 % (name, factory_id))
177 str_value = str(value)
178 if isinstance(value, bool):
179 str_value = str_value.lower()
180 checker = info.checker
181 ns3_value = checker.Create()
182 ns3_value.DeserializeFromString(str_value, checker)
185 def _load_ns3_module(self):
189 simu_impl_type = self._attributes.get_attribute_value(
190 "SimulatorImplementationType")
191 checksum = self._attributes.get_attribute_value("ChecksumEnabled")
192 stop_time = self._attributes.get_attribute_value("StopTime")
194 bindings = os.environ["NEPI_NS3BINDINGS"] \
195 if "NEPI_NS3BINDINGS" in os.environ else None
196 libfile = os.environ["NEPI_NS3LIBRARY"] \
197 if "NEPI_NS3LIBRARY" in os.environ else None
200 ctypes.CDLL(libfile, ctypes.RTLD_GLOBAL)
202 path = [ os.path.dirname(__file__) ] + sys.path
204 path = [ bindings ] + path
207 module = imp.find_module ('ns3', path)
208 mod = imp.load_module ('ns3', *module)
210 # In some environments, ns3 per-se does not exist,
211 # only the low-level _ns3
212 module = imp.find_module ('_ns3', path)
213 mod = imp.load_module ('_ns3', *module)
214 sys.modules["ns3"] = mod # install it as ns3 too
216 # When using _ns3, we have to make sure we destroy
217 # the simulator when the process finishes
219 atexit.register(mod.Simulator.Destroy)
222 value = mod.StringValue(simu_impl_type)
223 mod.GlobalValue.Bind ("SimulatorImplementationType", value)
225 value = mod.BooleanValue(checksum)
226 mod.GlobalValue.Bind ("ChecksumEnabled", value)
228 value = mod.Time(stop_time)
229 mod.Simulator.Stop (value)
232 def _get_construct_parameters(self, guid):
233 params = self._get_parameters(guid)
234 construct_params = dict()
235 factory_id = self._create[guid]
236 TypeId = self.ns3.TypeId()
237 typeid = TypeId.LookupByName(factory_id)
238 for name, value in params.iteritems():
239 info = self.ns3.TypeId.AttributeInfo()
240 found = typeid.LookupAttributeByName(name, info)
242 (info.flags & TypeId.ATTR_CONSTRUCT == TypeId.ATTR_CONSTRUCT):
243 construct_params[name] = value
244 return construct_params