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