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) or \
65 factory.box_attributes.is_attribute_invisible(name):
67 element = self._elements[guid]
68 if factory_id in self.LOCAL_FACTORIES:
69 setattr(element, name, value)
71 ns3_value = self._to_ns3_value(guid, name, value)
72 element.SetAttribute(name, ns3_value)
74 def get(self, guid, name, time = TIME_NOW):
75 value = super(TestbedController, self).get(guid, name, time)
76 # TODO: take on account schedule time for the task
77 factory_id = self._create[guid]
78 factory = self._factories[factory_id]
79 if factory.box_attributes.is_attribute_design_only(name) or \
80 factory.box_attributes.is_attribute_invisible(name):
82 if factory_id in self.LOCAL_FACTORIES:
83 return getattr(element, name)
84 TypeId = self.ns3.TypeId()
85 typeid = TypeId.LookupByName(factory_id)
86 info = TypeId.AttributeInfo()
87 if not typeid or not typeid.LookupAttributeByName(name, info):
88 raise AttributeError("Invalid attribute %s for element type %d" % \
90 checker = info.checker
91 ns3_value = checker.Create()
92 element = self._elements[guid]
93 element.GetAttribute(name, ns3_value)
94 value = ns3_value.SerializeToString(checker)
95 attr_type = factory.box_attributes.get_attribute_type(name)
96 if attr_type == Attribute.INTEGER:
98 if attr_type == Attribute.DOUBLE:
100 if attr_type == Attribute.BOOL:
101 return value == "true"
104 def action(self, time, guid, action):
105 raise NotImplementedError
107 def trace_filename(self, guid, trace_id):
108 # TODO: Need to be defined inside a home!!!! with and experiment id_code
109 filename = self._traces[guid][trace_id]
110 return os.path.join(self.home_directory, filename)
112 def follow_trace(self, guid, trace_id, filename):
113 if guid not in self._traces:
114 self._traces[guid] = dict()
115 self._traces[guid][trace_id] = filename
118 for element in self._elements.values():
119 if isinstance(element, self.LOCAL_TYPES):
120 # graceful shutdown of locally-implemented objects
124 def _simulator_run(self, condition):
126 self.ns3.Simulator.Run()
127 # Signal condition on simulation end to notify waiting threads
129 condition.notifyAll()
132 def _schedule_event(self, condition, func, *args):
133 """Schedules event on running experiment"""
134 def execute_event(condition, has_event_occurred, func, *args):
138 has_event_occurred[0] = True
139 # notify condition indicating attribute was set
141 condition.notifyAll()
144 # contextId is defined as general context
145 contextId = long(0xffffffff)
146 # delay 0 means that the event is expected to execute inmediately
147 delay = self.ns3.Seconds(0)
148 # flag to indicate that the event occured
149 # because bool is an inmutable object in python, in order to create a
150 # bool flag, a list is used as wrapper
151 has_event_occurred = [False]
153 if not self.ns3.Simulator.IsFinished():
154 self.ns3.Simulator.ScheduleWithContext(contextId, delay, execute_event,
155 condition, has_event_occurred, func, *args)
156 while not has_event_occurred[0] and not self.ns3.Simulator.IsFinished():
159 if not has_event_occurred[0]:
160 raise RuntimeError('Event could not be scheduled : %s %s ' \
161 % (repr(func), repr(args)))
163 def _to_ns3_value(self, guid, name, value):
164 factory_id = self._create[guid]
165 TypeId = self.ns3.TypeId()
166 typeid = TypeId.LookupByName(factory_id)
167 info = TypeId.AttributeInfo()
168 if not typeid.LookupAttributeByName(name, info):
169 raise RuntimeError("Attribute %s doesn't belong to element %s" \
170 % (name, factory_id))
171 str_value = str(value)
172 if isinstance(value, bool):
173 str_value = str_value.lower()
174 checker = info.checker
175 ns3_value = checker.Create()
176 ns3_value.DeserializeFromString(str_value, checker)
179 def _load_ns3_module(self):
183 simu_impl_type = self._attributes.get_attribute_value(
184 "SimulatorImplementationType")
185 checksum = self._attributes.get_attribute_value("ChecksumEnabled")
187 bindings = os.environ["NEPI_NS3BINDINGS"] \
188 if "NEPI_NS3BINDINGS" in os.environ else None
189 libfile = os.environ["NEPI_NS3LIBRARY"] \
190 if "NEPI_NS3LIBRARY" in os.environ else None
193 ctypes.CDLL(libfile, ctypes.RTLD_GLOBAL)
195 path = [ os.path.dirname(__file__) ] + sys.path
197 path = [ bindings ] + path
200 module = imp.find_module ('ns3', path)
201 mod = imp.load_module ('ns3', *module)
203 # In some environments, ns3 per-se does not exist,
204 # only the low-level _ns3
205 module = imp.find_module ('_ns3', path)
206 mod = imp.load_module ('_ns3', *module)
207 sys.modules["ns3"] = mod # install it as ns3 too
209 # When using _ns3, we have to make sure we destroy
210 # the simulator when the process finishes
212 atexit.register(mod.Simulator.Destroy)
215 value = mod.StringValue(simu_impl_type)
216 mod.GlobalValue.Bind ("SimulatorImplementationType", value)
218 value = mod.BooleanValue(checksum)
219 mod.GlobalValue.Bind ("ChecksumEnabled", value)
222 def _get_construct_parameters(self, guid):
223 params = self._get_parameters(guid)
224 construct_params = dict()
225 factory_id = self._create[guid]
226 TypeId = self.ns3.TypeId()
227 typeid = TypeId.LookupByName(factory_id)
228 for name, value in params.iteritems():
229 info = self.ns3.TypeId.AttributeInfo()
230 found = typeid.LookupAttributeByName(name, info)
232 (info.flags & TypeId.ATTR_CONSTRUCT == TypeId.ATTR_CONSTRUCT):
233 construct_params[name] = value
234 return construct_params