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