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