bug fixing: addresses and routes
[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.isDaemon()
59         self._simulator_thread.start()
60
61     def stop(self, time = TIME_NOW):
62         super(TestbedController, self).stop(time)
63         # BUG!!!!
64         # TODO!! This is not working!!!
65         self.ns3.Simulator.Stop()
66         #self._stop_simulation(time)
67
68     def set(self, guid, name, value, time = TIME_NOW):
69         super(TestbedController, self).set(guid, name, value, time)
70         # TODO: take on account schedule time for the task
71         factory_id = self._create[guid]
72         factory = self._factories[factory_id]
73         if factory.box_attributes.is_attribute_design_only(name):
74             return
75         element = self._elements[guid]
76         if factory_id in self.LOCAL_FACTORIES:
77             setattr(element, name, value)
78         elif factory.box_attributes.is_attribute_invisible(name):
79             return
80         else:
81             ns3_value = self._to_ns3_value(guid, name, value)
82             self._set_attribute(name, ns3_value, element)
83
84     def get(self, guid, name, time = TIME_NOW):
85         value = super(TestbedController, self).get(guid, name, time)
86         # TODO: take on account schedule time for the task
87         factory_id = self._create[guid]
88         factory = self._factories[factory_id]
89         element = self._elements[guid]
90         if factory_id in self.LOCAL_FACTORIES:
91             if hasattr(element, name):
92                 return getattr(element, name)
93             else:
94                 return value
95         if factory.box_attributes.is_attribute_design_only(name) or \
96                 factory.box_attributes.is_attribute_invisible(name):
97             return value
98         TypeId = self.ns3.TypeId()
99         typeid = TypeId.LookupByName(factory_id)
100         info = TypeId.AttributeInfo()
101         if not typeid or not typeid.LookupAttributeByName(name, info):
102             raise AttributeError("Invalid attribute %s for element type %d" % \
103                 (name, guid))
104         checker = info.checker
105         ns3_value = checker.Create() 
106         self._get_attribute(name, ns3_value, element)
107         value = ns3_value.SerializeToString(checker)
108         attr_type = factory.box_attributes.get_attribute_type(name)
109         if attr_type == Attribute.INTEGER:
110             return int(value)
111         if attr_type == Attribute.DOUBLE:
112             return float(value)
113         if attr_type == Attribute.BOOL:
114             return value == "true"
115         return value
116
117     def action(self, time, guid, action):
118         raise NotImplementedError
119
120     def trace_filename(self, guid, trace_id):
121         # TODO: Need to be defined inside a home!!!! with and experiment id_code
122         filename = self._traces[guid][trace_id]
123         return os.path.join(self.home_directory, filename)
124
125     def follow_trace(self, guid, trace_id, filename):
126         if guid not in self._traces:
127             self._traces[guid] = dict()
128         self._traces[guid][trace_id] = filename
129
130     def shutdown(self):
131         for element in self._elements.itervalues():
132             if isinstance(element, self.LOCAL_TYPES):
133                 # graceful shutdown of locally-implemented objects
134                 element.Cleanup()
135         self._elements.clear()
136         if self.ns3:
137             self.ns3.Simulator.Stop()
138             # BUG!!!!
139             # TODO!! This is not working!!! NEVER STOPS THE SIMULATION!!!
140             #self._stop_simulation("0s")
141             #if self._simulator_thread:
142             #    print "Joining thread"
143             #    self._simulator_thread.join()
144             #print "destroying"
145             self.ns3.Simulator.Destroy()
146         self._ns3 = None
147         sys.stdout.flush()
148         sys.stderr.flush()
149
150     def _simulator_run(self, condition):
151         # Run simulation
152         self.ns3.Simulator.Run()
153         # Signal condition on simulation end to notify waiting threads
154         condition.acquire()
155         condition.notifyAll()
156         condition.release()
157
158     def _schedule_event(self, condition, func, *args):
159         """Schedules event on running experiment"""
160         def execute_event(condition, has_event_occurred, func, *args):
161             # exec func
162             try:
163                 func(*args)
164             finally:
165                 # flag event occured
166                 has_event_occurred[0] = True
167                 # notify condition indicating attribute was set
168                 condition.acquire()
169                 condition.notifyAll()
170                 condition.release()
171
172         # contextId is defined as general context
173         contextId = long(0xffffffff)
174         # delay 0 means that the event is expected to execute inmediately
175         delay = self.ns3.Seconds(0)
176         # flag to indicate that the event occured
177         # because bool is an inmutable object in python, in order to create a
178         # bool flag, a list is used as wrapper
179         has_event_occurred = [False]
180         condition.acquire()
181         if not self.ns3.Simulator.IsFinished():
182             self.ns3.Simulator.ScheduleWithContext(contextId, delay, execute_event,
183                  condition, has_event_occurred, func, *args)
184             while not has_event_occurred[0] and not self.ns3.Simulator.IsFinished():
185                 condition.wait()
186                 condition.release()
187
188     def _set_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._set_ns3_attribute, 
192                     name, ns3_value, element)
193         else:
194             self._set_ns3_attribute(name, ns3_value, element)
195
196     def _get_attribute(self, name, ns3_value, element):
197         if self.status() == TESTBED_STATUS_STARTED:
198             # schedule the event in the Simulator
199             self._schedule_event(self._condition, self._get_ns3_attribute, 
200                     name, ns3_value, element)
201         else:
202             self._get_ns3_attribute(name, ns3_value, element)
203
204     def _set_ns3_attribute(self, name, ns3_value, element):
205         element.SetAttribute(name, ns3_value)
206
207     def _get_ns3_attribute(self, name, ns3_value, element):
208         element.GetAttribute(name, ns3_value)
209
210     def _stop_simulation(self, time):
211         if self.status() == TESTBED_STATUS_STARTED:
212             # schedule the event in the Simulator
213             self._schedule_event(self._condition, self._stop_ns3_simulation, 
214                     time)
215         else:
216             self._stop_ns3_simulation(time)
217
218     def _stop_simulation(self, time = TIME_NOW):
219         if not self.ns3:
220             return
221         if time == TIME_NOW:
222             self.ns3.Simulator.Stop()
223         else:
224             self.ns3.Simulator.Stop(self.ns3.Time(time))
225
226     def _to_ns3_value(self, guid, name, value):
227         factory_id = self._create[guid]
228         TypeId = self.ns3.TypeId()
229         typeid = TypeId.LookupByName(factory_id)
230         info = TypeId.AttributeInfo()
231         if not typeid.LookupAttributeByName(name, info):
232             raise RuntimeError("Attribute %s doesn't belong to element %s" \
233                    % (name, factory_id))
234         str_value = str(value)
235         if isinstance(value, bool):
236             str_value = str_value.lower()
237         checker = info.checker
238         ns3_value = checker.Create()
239         ns3_value.DeserializeFromString(str_value, checker)
240         return ns3_value
241
242     def _load_ns3_module(self):
243         import ctypes
244         import imp
245
246         simu_impl_type = self._attributes.get_attribute_value(
247                 "SimulatorImplementationType")
248         checksum = self._attributes.get_attribute_value("ChecksumEnabled")
249         stop_time = self._attributes.get_attribute_value("StopTime")
250
251         bindings = os.environ["NEPI_NS3BINDINGS"] \
252                 if "NEPI_NS3BINDINGS" in os.environ else None
253         libfile = os.environ["NEPI_NS3LIBRARY"] \
254                 if "NEPI_NS3LIBRARY" in os.environ else None
255
256         if libfile:
257             ctypes.CDLL(libfile, ctypes.RTLD_GLOBAL)
258
259         path = [ os.path.dirname(__file__) ] + sys.path
260         if bindings:
261             path = [ bindings ] + path
262
263         try:
264             module = imp.find_module ('ns3', path)
265             mod = imp.load_module ('ns3', *module)
266         except ImportError:
267             # In some environments, ns3 per-se does not exist,
268             # only the low-level _ns3
269             module = imp.find_module ('_ns3', path)
270             mod = imp.load_module ('_ns3', *module)
271             sys.modules["ns3"] = mod # install it as ns3 too
272             
273             # When using _ns3, we have to make sure we destroy
274             # the simulator when the process finishes
275             import atexit
276             atexit.register(mod.Simulator.Destroy)
277     
278         if simu_impl_type:
279             value = mod.StringValue(simu_impl_type)
280             mod.GlobalValue.Bind ("SimulatorImplementationType", value)
281         if checksum:
282             value = mod.BooleanValue(checksum)
283             mod.GlobalValue.Bind ("ChecksumEnabled", value)
284         if stop_time:
285             value = mod.Time(stop_time)
286             mod.Simulator.Stop (value)
287         return mod
288
289     def _get_construct_parameters(self, guid):
290         params = self._get_parameters(guid)
291         construct_params = dict()
292         factory_id = self._create[guid]
293         TypeId = self.ns3.TypeId()
294         typeid = TypeId.LookupByName(factory_id)
295         for name, value in params.iteritems():
296             info = self.ns3.TypeId.AttributeInfo()
297             found = typeid.LookupAttributeByName(name, info)
298             if found and \
299                 (info.flags & TypeId.ATTR_CONSTRUCT == TypeId.ATTR_CONSTRUCT):
300                 construct_params[name] = value
301         return construct_params
302
303
304