box_get removed and replaced for get in testbed_impl
[nepi.git] / src / nepi / testbeds / ns3 / execute.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3
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 TESTBED_STATUS_CREATED
8 import os
9 import sys
10 import threading
11
12 class TestbedController(testbed_impl.TestbedController):
13     def __init__(self, testbed_version):
14         super(TestbedController, self).__init__(TESTBED_ID, testbed_version)
15         self._ns3 = None
16         self._home_directory = None
17         self._traces = dict()
18         self._simulator_thread = None
19         self._condition = None
20
21     @property
22     def home_directory(self):
23         return self._home_directory
24
25     @property
26     def ns3(self):
27         return self._ns3
28
29     def do_setup(self):
30         self._home_directory = self._attributes.\
31             get_attribute_value("homeDirectory")
32         self._ns3 = self._load_ns3_module()
33         super(TestbedController, self).do_setup()
34
35     def start(self):
36         super(TestbedController, self).start()
37         self._condition = threading.Condition()
38         self._simulator_thread = threading.Thread(target = self._simulator_run,
39                 args = [self._condition])
40         self._simulator_thread.start()
41
42     def set(self, time, guid, name, value):
43         super(TestbedController, self).set(time, guid, name, value)
44         # TODO: take on account schedule time for the task
45         factory_id = self._create[guid]
46         factory = self._factories[factory_id]
47         if factory.box_attributes.is_attribute_design_only(name):
48             return
49         element = self._elements[guid]
50         ns3_value = self._to_ns3_value(guid, name, value) 
51         element.SetAttribute(name, ns3_value)
52
53     def get(self, time, guid, name):
54         value = super(TestbedController, self).get(time, guid, name)
55         # TODO: take on account schedule time for the task
56         factory_id = self._create[guid]
57         factory = self._factories[factory_id]
58         if factory.box_attributes.is_attribute_design_only(name):
59             return value
60         TypeId = self.ns3.TypeId()
61         typeid = TypeId.LookupByName(factory_id)
62         info = TypeId.AttributeInfo()
63         if not typeid or not typeid.LookupAttributeByName(name, info):
64             raise AttributeError("Invalid attribute %s for element type %d" % \
65                 (name, guid))
66         checker = info.checker
67         ns3_value = checker.Create() 
68         element = self._elements[guid]
69         element.GetAttribute(name, ns3_value)
70         value = ns3_value.SerializeToString(checker)
71         attr_type = factory.box_attributes.get_attribute_type(name)
72         if attr_type == Attribute.INTEGER:
73             return int(value)
74         if attr_type == Attribute.DOUBLE:
75             return float(value)
76         if attr_type == Attribute.BOOL:
77             return value == "true"
78         return value
79
80     def get_route(self, guid, index, attribute):
81         # TODO: fetch real data from ns3
82         try:
83             return self.box_get_route(guid, int(index), attribute)
84         except KeyError, AttributeError:
85             return None
86
87     def get_address(self, guid, index, attribute='Address'):
88         # TODO: fetch real data from ns3
89         try:
90             return self.box_get_address(guid, int(index), attribute)
91         except KeyError, AttributeError:
92             return None
93
94
95     def action(self, time, guid, action):
96         raise NotImplementedError
97
98     def trace_filename(self, guid, trace_id):
99         # TODO: Need to be defined inside a home!!!! with and experiment id_code
100         filename = self._traces[guid][trace_id]
101         return os.path.join(self.home_directory, filename)
102
103     def follow_trace(self, guid, trace_id, filename):
104         if guid not in self._traces:
105             self._traces[guid] = dict()
106         self._traces[guid][trace_id] = filename
107
108     def shutdown(self):
109         for element in self._elements.values():
110             element = None
111
112     def _simulator_run(self, condition):
113         # Run simulation
114         self.ns3.Simulator.Run()
115         # Signal condition on simulation end to notify waiting threads
116         condition.acquire()
117         condition.notifyAll()
118         condition.release()
119
120     def _schedule_event(self, condition, func, *args):
121         """Schedules event on running experiment"""
122         def execute_event(condition, has_event_occurred, func, *args):
123             # exec func
124             func(*args)
125             # flag event occured
126             has_event_occurred[0] = True
127             # notify condition indicating attribute was set
128             condition.acquire()
129             condition.notifyAll()
130             condition.release()
131
132         # contextId is defined as general context
133         contextId = long(0xffffffff)
134         # delay 0 means that the event is expected to execute inmediately
135         delay = self.ns3.Seconds(0)
136         # flag to indicate that the event occured
137         # because bool is an inmutable object in python, in order to create a
138         # bool flag, a list is used as wrapper
139         has_event_occurred = [False]
140         condition.acquire()
141         if not self.ns3.Simulator.IsFinished():
142             self.ns3.Simulator.ScheduleWithContext(contextId, delay, execute_event,
143                  condition, has_event_occurred, func, *args)
144             while not has_event_occurred[0] and not self.ns3.Simulator.IsFinished():
145                 condition.wait()
146                 condition.release()
147                 if not has_event_occurred[0]:
148                     raise RuntimeError('Event could not be scheduled : %s %s ' \
149                     % (repr(func), repr(args)))
150
151     def _to_ns3_value(self, guid, name, value):
152         factory_id = self._create[guid]
153         TypeId = self.ns3.TypeId()
154         typeid = TypeId.LookupByName(factory_id)
155         info = TypeId.AttributeInfo()
156         if not typeid.LookupAttributeByName(name, info):
157             raise RuntimeError("Attribute %s doesn't belong to element %s" \
158                    % (name, factory_id))
159         str_value = str(value)
160         if isinstance(value, bool):
161             str_value = str_value.lower()
162         checker = info.checker
163         ns3_value = checker.Create()
164         ns3_value.DeserializeFromString(str_value, checker)
165         return ns3_value
166
167     def _load_ns3_module(self):
168         import ctypes
169         import imp
170
171         simu_impl_type = self._attributes.get_attribute_value(
172                 "SimulatorImplementationType")
173         checksum = self._attributes.get_attribute_value("ChecksumEnabled")
174
175         bindings = os.environ["NEPI_NS3BINDINGS"] \
176                 if "NEPI_NS3BINDINGS" in os.environ else None
177         libfile = os.environ["NEPI_NS3LIBRARY"] \
178                 if "NEPI_NS3LIBRARY" in os.environ else None
179
180         if libfile:
181             ctypes.CDLL(libfile, ctypes.RTLD_GLOBAL)
182
183         path = [ os.path.dirname(__file__) ] + sys.path
184         if bindings:
185             path = [ bindings ] + path
186
187         module = imp.find_module ('ns3', path)
188         mod = imp.load_module ('ns3', *module)
189     
190         if simu_impl_type:
191             value = mod.StringValue(simu_impl_type)
192             mod.GlobalValue.Bind ("SimulatorImplementationType", value)
193         if checksum:
194             value = mod.BooleanValue(checksum)
195             mod.GlobalValue.Bind ("ChecksumEnabled", value)
196         return mod
197
198     def _get_construct_parameters(self, guid):
199         params = self._get_parameters(guid)
200         construct_params = dict()
201         factory_id = self._create[guid]
202         TypeId = self.ns3.TypeId()
203         typeid = TypeId.LookupByName(factory_id)
204         for name, value in params.iteritems():
205             info = self.ns3.TypeId.AttributeInfo()
206             found = typeid.LookupAttributeByName(name, info)
207             if found and \
208                 (info.flags & TypeId.ATTR_CONSTRUCT == TypeId.ATTR_CONSTRUCT):
209                 construct_params[name] = value
210         return construct_params
211