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