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 TestbedInstance(testbed_impl.TestbedInstance):
12 def __init__(self, testbed_version):
13 super(TestbedInstance, 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(TestbedInstance, 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(TestbedInstance, 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.LookupAttributeByName(name, info):
53 raise RuntimeError("Attribute %s doesn't belong to element %s" \
55 checker = info.checker
56 ns3_value = checker.Create()
57 element = self._elements[guid]
58 element.GetAttribute(name, ns3_value)
59 value = ns3_value.SerializeToString(checker)
60 factory_id = self._create[guid]
61 factory = self._factories[factory_id]
62 attr_type = factory.box_attributes.get_attribute_type(name)
63 if attr_type == Attribute.INTEGER:
65 if attr_type == Attribute.DOUBLE:
67 if attr_type == Attribute.BOOL:
68 return value == "true"
71 def action(self, time, guid, action):
72 raise NotImplementedError
74 def trace(self, guid, trace_id):
75 fd = open("%s" % self.trace_filename(guid, trace_id), "r")
80 def trace_filename(self, guid, trace_id):
81 # TODO: Need to be defined inside a home!!!! with and experiment id_code
82 filename = self._traces[guid][trace_id]
83 return os.path.join(self.home_directory, filename)
85 def follow_trace(self, guid, trace_id, filename):
86 if guid not in self._traces:
87 self._traces[guid] = dict()
88 self._traces[guid][trace_id] = filename
91 for element in self._elements.values():
94 def _simulator_run(self, condition):
96 self.ns3.Simulator.Run()
97 # Signal condition on simulation end to notify waiting threads
102 def _schedule_event(self, condition, func, *args):
103 """Schedules event on running experiment"""
104 def execute_event(condition, has_event_occurred, func, *args):
108 has_event_occurred[0] = True
109 # notify condition indicating attribute was set
111 condition.notifyAll()
114 # contextId is defined as general context
115 contextId = long(0xffffffff)
116 # delay 0 means that the event is expected to execute inmediately
117 delay = self.ns3.Seconds(0)
118 # flag to indicate that the event occured
119 # because bool is an inmutable object in python, in order to create a
120 # bool flag, a list is used as wrapper
121 has_event_occurred = [False]
123 if not self.ns3.Simulator.IsFinished():
124 self.ns3.Simulator.ScheduleWithContext(contextId, delay, execute_event,
125 condition, has_event_occurred, func, *args)
126 while not has_event_occurred[0] and not self.ns3.Simulator.IsFinished():
129 if not has_event_occurred[0]:
130 raise RuntimeError('Event could not be scheduled : %s %s ' \
131 % (repr(func), repr(args)))
133 def _to_ns3_value(self, guid, name, value):
134 factory_id = self._create[guid]
135 TypeId = self.ns3.TypeId()
136 typeid = TypeId.LookupByName(factory_id)
137 info = TypeId.AttributeInfo()
138 if not typeid.LookupAttributeByName(name, info):
139 raise RuntimeError("Attribute %s doesn't belong to element %s" \
140 % (name, factory_id))
141 str_value = str(value)
142 if isinstance(value, bool):
143 str_value = str_value.lower()
144 checker = info.checker
145 ns3_value = checker.Create()
146 ns3_value.DeserializeFromString(str_value, checker)
149 def _load_ns3_module(self):
153 simu_impl_type = self._attributes.get_attribute_value(
154 "SimulatorImplementationType")
155 checksum = self._attributes.get_attribute_value("ChecksumEnabled")
157 bindings = os.environ["NEPI_NS3BINDINGS"] \
158 if "NEPI_NS3BINDINGS" in os.environ else None
159 libfile = os.environ["NEPI_NS3LIBRARY"] \
160 if "NEPI_NS3LIBRARY" in os.environ else None
163 ctypes.CDLL(libfile, ctypes.RTLD_GLOBAL)
165 path = [ os.path.dirname(__file__) ] + sys.path
167 path = [ bindings ] + path
169 module = imp.find_module ('ns3', path)
170 mod = imp.load_module ('ns3', *module)
173 value = mod.StringValue(simu_impl_type)
174 mod.GlobalValue.Bind ("SimulatorImplementationType", value)
176 value = mod.BooleanValue(checksum)
177 mod.GlobalValue.Bind ("ChecksumEnabled", value)
180 def _get_construct_parameters(self, guid):
181 params = self._get_parameters(guid)
182 construct_params = dict()
183 factory_id = self._create[guid]
184 TypeId = self.ns3.TypeId()
185 typeid = TypeId.LookupByName(factory_id)
186 for name, value in params.iteritems():
187 info = self.ns3.TypeId.AttributeInfo()
188 typeid.LookupAttributeByName(name, info)
189 if info.flags & TypeId.ATTR_CONSTRUCT == TypeId.ATTR_CONSTRUCT:
190 construct_params[name] = value
191 return construct_params