Refactor TunChannel implementation in ns3 to make it common to all testbeds:
[nepi.git] / src / nepi / testbeds / ns3 / execute.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 from constants import TESTBED_ID
5 from nepi.core import testbed_impl
6 from nepi.core.attributes import Attribute
7 from nepi.util.constants import TIME_NOW
8 import os
9 import sys
10 import threading
11 import random
12 import socket
13 import weakref
14
15 from nepi.util.tunchannel import TunChannel
16
17 class TestbedController(testbed_impl.TestbedController):
18     LOCAL_FACTORIES = {
19         'ns3::Nepi::TunChannel' : TunChannel,
20     }
21
22     def __init__(self, testbed_version):
23         super(TestbedController, self).__init__(TESTBED_ID, testbed_version)
24         self._ns3 = None
25         self._home_directory = None
26         self._traces = dict()
27         self._simulator_thread = None
28         self._condition = None
29         
30         # local factories
31         self.TunChannel = TunChannel
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.start()
59
60     def set(self, guid, name, value, time = TIME_NOW):
61         super(TestbedController, self).set(guid, name, value, time)
62         # TODO: take on account schedule time for the task
63         factory_id = self._create[guid]
64         factory = self._factories[factory_id]
65         if factory.box_attributes.is_attribute_design_only(name) or \
66                 factory.box_attributes.is_attribute_invisible(name):
67             return
68         element = self._elements[guid]
69         if factory_id in self.LOCAL_FACTORIES:
70             setattr(element, name, value)
71         else:
72             ns3_value = self._to_ns3_value(guid, name, value) 
73             element.SetAttribute(name, ns3_value)
74
75     def get(self, guid, name, time = TIME_NOW):
76         value = super(TestbedController, self).get(guid, name, time)
77         # TODO: take on account schedule time for the task
78         factory_id = self._create[guid]
79         factory = self._factories[factory_id]
80         if factory.box_attributes.is_attribute_design_only(name) or \
81                 factory.box_attributes.is_attribute_invisible(name):
82             return value
83         if factory_id in self.LOCAL_FACTORIES:
84             return getattr(element, name)
85         TypeId = self.ns3.TypeId()
86         typeid = TypeId.LookupByName(factory_id)
87         info = TypeId.AttributeInfo()
88         if not typeid or not typeid.LookupAttributeByName(name, info):
89             raise AttributeError("Invalid attribute %s for element type %d" % \
90                 (name, guid))
91         checker = info.checker
92         ns3_value = checker.Create() 
93         element = self._elements[guid]
94         element.GetAttribute(name, ns3_value)
95         value = ns3_value.SerializeToString(checker)
96         attr_type = factory.box_attributes.get_attribute_type(name)
97         if attr_type == Attribute.INTEGER:
98             return int(value)
99         if attr_type == Attribute.DOUBLE:
100             return float(value)
101         if attr_type == Attribute.BOOL:
102             return value == "true"
103         return value
104
105     def action(self, time, guid, action):
106         raise NotImplementedError
107
108     def trace_filename(self, guid, trace_id):
109         # TODO: Need to be defined inside a home!!!! with and experiment id_code
110         filename = self._traces[guid][trace_id]
111         return os.path.join(self.home_directory, filename)
112
113     def follow_trace(self, guid, trace_id, filename):
114         if guid not in self._traces:
115             self._traces[guid] = dict()
116         self._traces[guid][trace_id] = filename
117
118     def shutdown(self):
119         for element in self._elements.values():
120             element = None
121
122     def _simulator_run(self, condition):
123         # Run simulation
124         self.ns3.Simulator.Run()
125         # Signal condition on simulation end to notify waiting threads
126         condition.acquire()
127         condition.notifyAll()
128         condition.release()
129
130     def _schedule_event(self, condition, func, *args):
131         """Schedules event on running experiment"""
132         def execute_event(condition, has_event_occurred, func, *args):
133             # exec func
134             func(*args)
135             # flag event occured
136             has_event_occurred[0] = True
137             # notify condition indicating attribute was set
138             condition.acquire()
139             condition.notifyAll()
140             condition.release()
141
142         # contextId is defined as general context
143         contextId = long(0xffffffff)
144         # delay 0 means that the event is expected to execute inmediately
145         delay = self.ns3.Seconds(0)
146         # flag to indicate that the event occured
147         # because bool is an inmutable object in python, in order to create a
148         # bool flag, a list is used as wrapper
149         has_event_occurred = [False]
150         condition.acquire()
151         if not self.ns3.Simulator.IsFinished():
152             self.ns3.Simulator.ScheduleWithContext(contextId, delay, execute_event,
153                  condition, has_event_occurred, func, *args)
154             while not has_event_occurred[0] and not self.ns3.Simulator.IsFinished():
155                 condition.wait()
156                 condition.release()
157                 if not has_event_occurred[0]:
158                     raise RuntimeError('Event could not be scheduled : %s %s ' \
159                     % (repr(func), repr(args)))
160
161     def _to_ns3_value(self, guid, name, value):
162         factory_id = self._create[guid]
163         TypeId = self.ns3.TypeId()
164         typeid = TypeId.LookupByName(factory_id)
165         info = TypeId.AttributeInfo()
166         if not typeid.LookupAttributeByName(name, info):
167             raise RuntimeError("Attribute %s doesn't belong to element %s" \
168                    % (name, factory_id))
169         str_value = str(value)
170         if isinstance(value, bool):
171             str_value = str_value.lower()
172         checker = info.checker
173         ns3_value = checker.Create()
174         ns3_value.DeserializeFromString(str_value, checker)
175         return ns3_value
176
177     def _load_ns3_module(self):
178         import ctypes
179         import imp
180
181         simu_impl_type = self._attributes.get_attribute_value(
182                 "SimulatorImplementationType")
183         checksum = self._attributes.get_attribute_value("ChecksumEnabled")
184
185         bindings = os.environ["NEPI_NS3BINDINGS"] \
186                 if "NEPI_NS3BINDINGS" in os.environ else None
187         libfile = os.environ["NEPI_NS3LIBRARY"] \
188                 if "NEPI_NS3LIBRARY" in os.environ else None
189
190         if libfile:
191             ctypes.CDLL(libfile, ctypes.RTLD_GLOBAL)
192
193         path = [ os.path.dirname(__file__) ] + sys.path
194         if bindings:
195             path = [ bindings ] + path
196
197         try:
198             module = imp.find_module ('ns3', path)
199             mod = imp.load_module ('ns3', *module)
200         except ImportError:
201             # In some environments, ns3 per-se does not exist,
202             # only the low-level _ns3
203             module = imp.find_module ('_ns3', path)
204             mod = imp.load_module ('_ns3', *module)
205             sys.modules["ns3"] = mod # install it as ns3 too
206             
207             # When using _ns3, we have to make sure we destroy
208             # the simulator when the process finishes
209             import atexit
210             atexit.register(mod.Simulator.Destroy)
211     
212         if simu_impl_type:
213             value = mod.StringValue(simu_impl_type)
214             mod.GlobalValue.Bind ("SimulatorImplementationType", value)
215         if checksum:
216             value = mod.BooleanValue(checksum)
217             mod.GlobalValue.Bind ("ChecksumEnabled", value)
218         return mod
219
220     def _get_construct_parameters(self, guid):
221         params = self._get_parameters(guid)
222         construct_params = dict()
223         factory_id = self._create[guid]
224         TypeId = self.ns3.TypeId()
225         typeid = TypeId.LookupByName(factory_id)
226         for name, value in params.iteritems():
227             info = self.ns3.TypeId.AttributeInfo()
228             found = typeid.LookupAttributeByName(name, info)
229             if found and \
230                 (info.flags & TypeId.ATTR_CONSTRUCT == TypeId.ATTR_CONSTRUCT):
231                 construct_params[name] = value
232         return construct_params
233
234
235