0635f2624cab348c607ca3b96c65f0475b29c653
[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._stop_simulation(time)
102
103     def set(self, guid, name, value, time = TIME_NOW):
104         super(TestbedController, self).set(guid, name, value, time)
105         # TODO: take on account schedule time for the task
106         factory_id = self._create[guid]
107         factory = self._factories[factory_id]
108         element = self._elements[guid]
109         if factory_id in self.LOCAL_FACTORIES:
110             setattr(element, name, value)
111         elif not factory.box_attributes.is_attribute_metadata(name):
112             ns3_value = self._to_ns3_value(guid, name, value)
113             self._set_attribute(name, ns3_value, element)
114
115     def get(self, guid, name, time = TIME_NOW):
116         value = super(TestbedController, self).get(guid, name, time)
117         # TODO: take on account schedule time for the task
118         factory_id = self._create[guid]
119         factory = self._factories[factory_id]
120         element = self._elements[guid]
121         if factory_id in self.LOCAL_FACTORIES:
122             if hasattr(element, name):
123                 return getattr(element, name)
124             else:
125                 return value
126         if factory.box_attributes.is_attribute_metadata(name):
127             return value
128
129         TypeId = self.ns3.TypeId()
130         typeid = TypeId.LookupByName(factory_id)
131         info = TypeId.AttributeInfo()
132         if not typeid or not typeid.LookupAttributeByName(name, info):
133             raise AttributeError("Invalid attribute %s for element type %d" % \
134                 (name, guid))
135         checker = info.checker
136         ns3_value = checker.Create() 
137         self._get_attribute(name, ns3_value, element)
138         value = ns3_value.SerializeToString(checker)
139         attr_type = factory.box_attributes.get_attribute_type(name)
140         if attr_type == Attribute.INTEGER:
141             return int(value)
142         if attr_type == Attribute.DOUBLE:
143             return float(value)
144         if attr_type == Attribute.BOOL:
145             return value == "true"
146         return value
147
148     def action(self, time, guid, action):
149         raise NotImplementedError
150
151     def trace_filepath(self, guid, trace_id):
152         filename = self._traces[guid][trace_id]
153         return os.path.join(self.home_directory, filename)
154
155     def trace_filename(self, guid, trace_id):
156         return self._traces[guid][trace_id]
157
158     def follow_trace(self, guid, trace_id, filename):
159         if not guid in self._traces:
160             self._traces[guid] = dict()
161         self._traces[guid][trace_id] = filename
162
163     def shutdown(self):
164         for element in self._elements.itervalues():
165             if isinstance(element, self.LOCAL_TYPES):
166                 # graceful shutdown of locally-implemented objects
167                 element.cleanup()
168         if self.ns3:
169             if not self.ns3.Simulator.IsFinished():
170                 self.stop()
171             
172             # TODO!!!! SHOULD WAIT UNTIL THE THREAD FINISHES
173             if self._simulator_thread:
174                 self._simulator_thread.join()
175             
176             self.ns3.Simulator.Destroy()
177         
178         self._elements.clear()
179         
180         self._ns3 = None
181         sys.stdout.flush()
182         sys.stderr.flush()
183
184     def _simulator_run(self, condition):
185         # Run simulation
186         self.ns3.Simulator.Run()
187         # Signal condition on simulation end to notify waiting threads
188         condition.acquire()
189         condition.notifyAll()
190         condition.release()
191
192     def _schedule_event(self, condition, func, *args):
193         """Schedules event on running experiment"""
194         def execute_event(condition, has_event_occurred, func, *args):
195             # exec func
196             try:
197                 func(*args)
198             finally:
199                 # flag event occured
200                 has_event_occurred[0] = True
201                 # notify condition indicating attribute was set
202                 condition.acquire()
203                 condition.notifyAll()
204                 condition.release()
205
206         # contextId is defined as general context
207         contextId = long(0xffffffff)
208         # delay 0 means that the event is expected to execute inmediately
209         delay = self.ns3.Seconds(0)
210         # flag to indicate that the event occured
211         # because bool is an inmutable object in python, in order to create a
212         # bool flag, a list is used as wrapper
213         has_event_occurred = [False]
214         condition.acquire()
215         try:
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         finally:
222             condition.release()
223
224     def _set_attribute(self, name, ns3_value, element):
225         if self.status() == TS.STATUS_STARTED:
226             # schedule the event in the Simulator
227             self._schedule_event(self._condition, self._set_ns3_attribute, 
228                     name, ns3_value, element)
229         else:
230             self._set_ns3_attribute(name, ns3_value, element)
231
232     def _get_attribute(self, name, ns3_value, element):
233         if self.status() == TS.STATUS_STARTED:
234             # schedule the event in the Simulator
235             self._schedule_event(self._condition, self._get_ns3_attribute, 
236                     name, ns3_value, element)
237         else:
238             self._get_ns3_attribute(name, ns3_value, element)
239
240     def _set_ns3_attribute(self, name, ns3_value, element):
241         element.SetAttribute(name, ns3_value)
242
243     def _get_ns3_attribute(self, name, ns3_value, element):
244         element.GetAttribute(name, ns3_value)
245
246     def _stop_simulation(self, time):
247         if self.status() == TS.STATUS_STARTED:
248             # schedule the event in the Simulator
249             self._schedule_event(self._condition, self._stop_ns3_simulation, 
250                     time)
251         else:
252             self._stop_ns3_simulation(time)
253
254     def _stop_ns3_simulation(self, time = TIME_NOW):
255         if not self.ns3:
256             return
257         if time == TIME_NOW:
258             self.ns3.Simulator.Stop()
259         else:
260             self.ns3.Simulator.Stop(self.ns3.Time(time))
261
262     def _to_ns3_value(self, guid, name, value):
263         factory_id = self._create[guid]
264         TypeId = self.ns3.TypeId()
265         typeid = TypeId.LookupByName(factory_id)
266         info = TypeId.AttributeInfo()
267         if not typeid.LookupAttributeByName(name, info):
268             raise RuntimeError("Attribute %s doesn't belong to element %s" \
269                    % (name, factory_id))
270         str_value = str(value)
271         if isinstance(value, bool):
272             str_value = str_value.lower()
273         checker = info.checker
274         ns3_value = checker.Create()
275         ns3_value.DeserializeFromString(str_value, checker)
276         return ns3_value
277
278     def _configure_ns3_module(self):
279         simu_impl_type = self._attributes.get_attribute_value(
280                 "SimulatorImplementationType")
281         sched_impl_type = self._attributes.get_attribute_value(
282                 "SchedulerType")
283         checksum = self._attributes.get_attribute_value("ChecksumEnabled")
284         stop_time = self._attributes.get_attribute_value("StopTime")
285
286         load_ns3_module()
287
288         import ns3 as mod
289  
290         if simu_impl_type:
291             value = mod.StringValue(simu_impl_type)
292             mod.GlobalValue.Bind ("SimulatorImplementationType", value)
293         if sched_impl_type:
294             value = mod.StringValue(sched_impl_type)
295             mod.GlobalValue.Bind ("SchedulerType", value)
296         if checksum:
297             value = mod.BooleanValue(checksum)
298             mod.GlobalValue.Bind ("ChecksumEnabled", value)
299         if stop_time:
300             value = mod.Time(stop_time)
301             mod.Simulator.Stop (value)
302         return mod
303
304     def _get_construct_parameters(self, guid):
305         params = self._get_parameters(guid)
306         construct_params = dict()
307         factory_id = self._create[guid]
308         TypeId = self.ns3.TypeId()
309         typeid = TypeId.LookupByName(factory_id)
310         for name, value in params.iteritems():
311             info = self.ns3.TypeId.AttributeInfo()
312             found = typeid.LookupAttributeByName(name, info)
313             if found and \
314                 (info.flags & TypeId.ATTR_CONSTRUCT == TypeId.ATTR_CONSTRUCT):
315                 construct_params[name] = value
316         return construct_params
317
318
319