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