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