754c2067c82d858e8c2a63a2969793718125408e
[nepi.git] / src / nepi / testbeds / ns3 / execute.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 from nepi.core import testbed_impl
5 from nepi.core.attributes import Attribute
6 from constants import TESTBED_ID
7 from nepi.util.constants import TIME_NOW, \
8     TESTBED_STATUS_STARTED
9 import os
10 import sys
11 import threading
12 import random
13 import socket
14 import weakref
15
16 class TestbedController(testbed_impl.TestbedController):
17     from nepi.util.tunchannel_impl import TunChannel
18     
19     LOCAL_FACTORIES = {
20         'ns3::Nepi::TunChannel' : TunChannel,
21     }
22     
23     LOCAL_TYPES = tuple(LOCAL_FACTORIES.values())
24
25     def __init__(self, testbed_version):
26         super(TestbedController, self).__init__(TESTBED_ID, testbed_version)
27         self._ns3 = None
28         self._home_directory = None
29         self._traces = dict()
30         self._simulator_thread = None
31         self._condition = None
32
33     @property
34     def home_directory(self):
35         return self._home_directory
36
37     @property
38     def ns3(self):
39         return self._ns3
40
41     def do_setup(self):
42         self._home_directory = self._attributes.\
43             get_attribute_value("homeDirectory")
44         self._ns3 = self._load_ns3_module()
45         
46         # create home...
47         home = os.path.normpath(self.home_directory)
48         if not os.path.exists(home):
49             os.makedirs(home, 0755)
50         
51         super(TestbedController, self).do_setup()
52
53     def start(self):
54         super(TestbedController, self).start()
55         self._condition = threading.Condition()
56         self._simulator_thread = threading.Thread(target = self._simulator_run,
57                 args = [self._condition])
58         self._simulator_thread.start()
59
60     def stop(self, time = TIME_NOW):
61         super(TestbedController, self).stop(time)
62         #self.ns3.Simulator.Stop()
63         self._stop_simulation(time)
64
65     def set(self, guid, name, value, time = TIME_NOW):
66         super(TestbedController, self).set(guid, name, value, time)
67         # TODO: take on account schedule time for the task
68         factory_id = self._create[guid]
69         factory = self._factories[factory_id]
70         if factory.box_attributes.is_attribute_design_only(name):
71             return
72         element = self._elements[guid]
73         if factory_id in self.LOCAL_FACTORIES:
74             setattr(element, name, value)
75         elif factory.box_attributes.is_attribute_invisible(name):
76             return
77         else:
78             ns3_value = self._to_ns3_value(guid, name, value)
79             self._set_attribute(name, ns3_value, element)
80
81     def get(self, guid, name, time = TIME_NOW):
82         value = super(TestbedController, self).get(guid, name, time)
83         # TODO: take on account schedule time for the task
84         factory_id = self._create[guid]
85         factory = self._factories[factory_id]
86         element = self._elements[guid]
87         if factory_id in self.LOCAL_FACTORIES:
88             if hasattr(element, name):
89                 return getattr(element, name)
90             else:
91                 return value
92         if factory.box_attributes.is_attribute_design_only(name) or \
93                 factory.box_attributes.is_attribute_invisible(name):
94             return value
95         TypeId = self.ns3.TypeId()
96         typeid = TypeId.LookupByName(factory_id)
97         info = TypeId.AttributeInfo()
98         if not typeid or not typeid.LookupAttributeByName(name, info):
99             raise AttributeError("Invalid attribute %s for element type %d" % \
100                 (name, guid))
101         checker = info.checker
102         ns3_value = checker.Create() 
103         self._get_attribute(name, ns3_value, element)
104         value = ns3_value.SerializeToString(checker)
105         attr_type = factory.box_attributes.get_attribute_type(name)
106         if attr_type == Attribute.INTEGER:
107             return int(value)
108         if attr_type == Attribute.DOUBLE:
109             return float(value)
110         if attr_type == Attribute.BOOL:
111             return value == "true"
112         return value
113
114     def action(self, time, guid, action):
115         raise NotImplementedError
116
117     def trace_filepath(self, guid, trace_id):
118         filename = self._traces[guid][trace_id]
119         return os.path.join(self.home_directory, filename)
120
121     def follow_trace(self, guid, trace_id, filename):
122         if not guid in self._traces:
123             self._traces[guid] = dict()
124         self._traces[guid][trace_id] = filename
125
126     def shutdown(self):
127         for element in self._elements.itervalues():
128             if isinstance(element, self.LOCAL_TYPES):
129                 # graceful shutdown of locally-implemented objects
130                 element.Cleanup()
131         self._elements.clear()
132         if self.ns3:
133             #self.ns3.Simulator.Stop()
134             self._stop_simulation("0s")
135             if self._simulator_thread:
136                 self._simulator_thread.join()
137             self.ns3.Simulator.Destroy()
138         self._ns3 = None
139         sys.stdout.flush()
140         sys.stderr.flush()
141
142     def _simulator_run(self, condition):
143         # Run simulation
144         self.ns3.Simulator.Run()
145         # Signal condition on simulation end to notify waiting threads
146         condition.acquire()
147         condition.notifyAll()
148         condition.release()
149
150     def _schedule_event(self, condition, func, *args):
151         """Schedules event on running experiment"""
152         def execute_event(condition, has_event_occurred, func, *args):
153             # exec func
154             try:
155                 func(*args)
156             finally:
157                 # flag event occured
158                 has_event_occurred[0] = True
159                 # notify condition indicating attribute was set
160                 condition.acquire()
161                 condition.notifyAll()
162                 condition.release()
163
164         # contextId is defined as general context
165         contextId = long(0xffffffff)
166         # delay 0 means that the event is expected to execute inmediately
167         delay = self.ns3.Seconds(0)
168         # flag to indicate that the event occured
169         # because bool is an inmutable object in python, in order to create a
170         # bool flag, a list is used as wrapper
171         has_event_occurred = [False]
172         condition.acquire()
173         if not self.ns3.Simulator.IsFinished():
174             self.ns3.Simulator.ScheduleWithContext(contextId, delay, execute_event,
175                  condition, has_event_occurred, func, *args)
176             while not has_event_occurred[0] and not self.ns3.Simulator.IsFinished():
177                 condition.wait()
178                 condition.release()
179
180     def _set_attribute(self, name, ns3_value, element):
181         if self.status() == TESTBED_STATUS_STARTED:
182             # schedule the event in the Simulator
183             self._schedule_event(self._condition, self._set_ns3_attribute, 
184                     name, ns3_value, element)
185         else:
186             self._set_ns3_attribute(name, ns3_value, element)
187
188     def _get_attribute(self, name, ns3_value, element):
189         if self.status() == TESTBED_STATUS_STARTED:
190             # schedule the event in the Simulator
191             self._schedule_event(self._condition, self._get_ns3_attribute, 
192                     name, ns3_value, element)
193         else:
194             self._get_ns3_attribute(name, ns3_value, element)
195
196     def _set_ns3_attribute(self, name, ns3_value, element):
197         element.SetAttribute(name, ns3_value)
198
199     def _get_ns3_attribute(self, name, ns3_value, element):
200         element.GetAttribute(name, ns3_value)
201
202     def _stop_simulation(self, time):
203         if self.status() == TESTBED_STATUS_STARTED:
204             # schedule the event in the Simulator
205             self._schedule_event(self._condition, self._stop_ns3_simulation, 
206                     time)
207         else:
208             self._stop_ns3_simulation(time)
209
210     def _stop_simulation(self, time = TIME_NOW):
211         if not self.ns3:
212             return
213         if time == TIME_NOW:
214             self.ns3.Simulator.Stop()
215         else:
216             self.ns3.Simulator.Stop(self.ns3.Time(time))
217
218     def _to_ns3_value(self, guid, name, value):
219         factory_id = self._create[guid]
220         TypeId = self.ns3.TypeId()
221         typeid = TypeId.LookupByName(factory_id)
222         info = TypeId.AttributeInfo()
223         if not typeid.LookupAttributeByName(name, info):
224             raise RuntimeError("Attribute %s doesn't belong to element %s" \
225                    % (name, factory_id))
226         str_value = str(value)
227         if isinstance(value, bool):
228             str_value = str_value.lower()
229         checker = info.checker
230         ns3_value = checker.Create()
231         ns3_value.DeserializeFromString(str_value, checker)
232         return ns3_value
233
234     def _load_ns3_module(self):
235         import ctypes
236         import imp
237
238         simu_impl_type = self._attributes.get_attribute_value(
239                 "SimulatorImplementationType")
240         checksum = self._attributes.get_attribute_value("ChecksumEnabled")
241         stop_time = self._attributes.get_attribute_value("StopTime")
242
243         bindings = os.environ["NEPI_NS3BINDINGS"] \
244                 if "NEPI_NS3BINDINGS" in os.environ else None
245         libfile = os.environ["NEPI_NS3LIBRARY"] \
246                 if "NEPI_NS3LIBRARY" in os.environ else None
247
248         if libfile:
249             ctypes.CDLL(libfile, ctypes.RTLD_GLOBAL)
250
251         path = [ os.path.dirname(__file__) ] + sys.path
252         if bindings:
253             path = [ bindings ] + path
254
255         try:
256             module = imp.find_module ('ns3', path)
257             mod = imp.load_module ('ns3', *module)
258         except ImportError:
259             # In some environments, ns3 per-se does not exist,
260             # only the low-level _ns3
261             module = imp.find_module ('_ns3', path)
262             mod = imp.load_module ('_ns3', *module)
263             sys.modules["ns3"] = mod # install it as ns3 too
264             
265             # When using _ns3, we have to make sure we destroy
266             # the simulator when the process finishes
267             import atexit
268             atexit.register(mod.Simulator.Destroy)
269     
270         if simu_impl_type:
271             value = mod.StringValue(simu_impl_type)
272             mod.GlobalValue.Bind ("SimulatorImplementationType", value)
273         if checksum:
274             value = mod.BooleanValue(checksum)
275             mod.GlobalValue.Bind ("ChecksumEnabled", value)
276         if stop_time:
277             value = mod.Time(stop_time)
278             mod.Simulator.Stop (value)
279         return mod
280
281     def _get_construct_parameters(self, guid):
282         params = self._get_parameters(guid)
283         construct_params = dict()
284         factory_id = self._create[guid]
285         TypeId = self.ns3.TypeId()
286         typeid = TypeId.LookupByName(factory_id)
287         for name, value in params.iteritems():
288             info = self.ns3.TypeId.AttributeInfo()
289             found = typeid.LookupAttributeByName(name, info)
290             if found and \
291                 (info.flags & TypeId.ATTR_CONSTRUCT == TypeId.ATTR_CONSTRUCT):
292                 construct_params[name] = value
293         return construct_params
294
295
296