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