ab34f25e3b06fc471ad1f5311e69cfba1522af8a
[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 class TestbedController(testbed_impl.TestbedController):
16     from nepi.util.tunchannel_impl import TunChannel
17     
18     LOCAL_FACTORIES = {
19         'ns3::Nepi::TunChannel' : TunChannel,
20     }
21     
22     LOCAL_TYPES = tuple(LOCAL_FACTORIES.values())
23
24     def __init__(self, testbed_version):
25         super(TestbedController, self).__init__(TESTBED_ID, testbed_version)
26         self._ns3 = None
27         self._home_directory = None
28         self._traces = dict()
29         self._simulator_thread = None
30         self._condition = None
31
32     @property
33     def home_directory(self):
34         return self._home_directory
35
36     @property
37     def ns3(self):
38         return self._ns3
39
40     def do_setup(self):
41         self._home_directory = self._attributes.\
42             get_attribute_value("homeDirectory")
43         self._ns3 = self._load_ns3_module()
44         
45         # create home...
46         home = os.path.normpath(self.home_directory)
47         if not os.path.exists(home):
48             os.makedirs(home, 0755)
49         
50         super(TestbedController, self).do_setup()
51
52     def start(self):
53         super(TestbedController, self).start()
54         self._condition = threading.Condition()
55         self._simulator_thread = threading.Thread(target = self._simulator_run,
56                 args = [self._condition])
57         self._simulator_thread.start()
58
59     def set(self, guid, name, value, time = TIME_NOW):
60         super(TestbedController, self).set(guid, name, value, time)
61         # TODO: take on account schedule time for the task
62         factory_id = self._create[guid]
63         factory = self._factories[factory_id]
64         if factory.box_attributes.is_attribute_design_only(name):
65             return
66         element = self._elements[guid]
67         if factory_id in self.LOCAL_FACTORIES:
68             setattr(element, name, value)
69         elif factory.box_attributes.is_attribute_invisible(name):
70             return
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         element = self._elements[guid]
81         if factory_id in self.LOCAL_FACTORIES:
82             if hasattr(element, name):
83                 return getattr(element, name)
84             else:
85                 return value
86         if factory.box_attributes.is_attribute_design_only(name) or \
87                 factory.box_attributes.is_attribute_invisible(name):
88             return value
89         TypeId = self.ns3.TypeId()
90         typeid = TypeId.LookupByName(factory_id)
91         info = TypeId.AttributeInfo()
92         if not typeid or not typeid.LookupAttributeByName(name, info):
93             raise AttributeError("Invalid attribute %s for element type %d" % \
94                 (name, guid))
95         checker = info.checker
96         ns3_value = checker.Create() 
97         element.GetAttribute(name, ns3_value)
98         value = ns3_value.SerializeToString(checker)
99         attr_type = factory.box_attributes.get_attribute_type(name)
100         if attr_type == Attribute.INTEGER:
101             return int(value)
102         if attr_type == Attribute.DOUBLE:
103             return float(value)
104         if attr_type == Attribute.BOOL:
105             return value == "true"
106         return value
107
108     def action(self, time, guid, action):
109         raise NotImplementedError
110
111     def trace_filename(self, guid, trace_id):
112         # TODO: Need to be defined inside a home!!!! with and experiment id_code
113         filename = self._traces[guid][trace_id]
114         return os.path.join(self.home_directory, filename)
115
116     def follow_trace(self, guid, trace_id, filename):
117         if guid not in self._traces:
118             self._traces[guid] = dict()
119         self._traces[guid][trace_id] = filename
120
121     def shutdown(self):
122         for element in self._elements.values():
123             if isinstance(element, self.LOCAL_TYPES):
124                 # graceful shutdown of locally-implemented objects
125                 element.Cleanup()
126             element = None
127         sys.stdout.flush()
128         sys.stderr.flush()
129
130     def _simulator_run(self, condition):
131         # Run simulation
132         self.ns3.Simulator.Run()
133         # Signal condition on simulation end to notify waiting threads
134         condition.acquire()
135         condition.notifyAll()
136         condition.release()
137
138     def _schedule_event(self, condition, func, *args):
139         """Schedules event on running experiment"""
140         def execute_event(condition, has_event_occurred, func, *args):
141             # exec func
142             func(*args)
143             # flag event occured
144             has_event_occurred[0] = True
145             # notify condition indicating attribute was set
146             condition.acquire()
147             condition.notifyAll()
148             condition.release()
149
150         # contextId is defined as general context
151         contextId = long(0xffffffff)
152         # delay 0 means that the event is expected to execute inmediately
153         delay = self.ns3.Seconds(0)
154         # flag to indicate that the event occured
155         # because bool is an inmutable object in python, in order to create a
156         # bool flag, a list is used as wrapper
157         has_event_occurred = [False]
158         condition.acquire()
159         if not self.ns3.Simulator.IsFinished():
160             self.ns3.Simulator.ScheduleWithContext(contextId, delay, execute_event,
161                  condition, has_event_occurred, func, *args)
162             while not has_event_occurred[0] and not self.ns3.Simulator.IsFinished():
163                 condition.wait()
164                 condition.release()
165                 if not has_event_occurred[0]:
166                     raise RuntimeError('Event could not be scheduled : %s %s ' \
167                     % (repr(func), repr(args)))
168
169     def _to_ns3_value(self, guid, name, value):
170         factory_id = self._create[guid]
171         TypeId = self.ns3.TypeId()
172         typeid = TypeId.LookupByName(factory_id)
173         info = TypeId.AttributeInfo()
174         if not typeid.LookupAttributeByName(name, info):
175             raise RuntimeError("Attribute %s doesn't belong to element %s" \
176                    % (name, factory_id))
177         str_value = str(value)
178         if isinstance(value, bool):
179             str_value = str_value.lower()
180         checker = info.checker
181         ns3_value = checker.Create()
182         ns3_value.DeserializeFromString(str_value, checker)
183         return ns3_value
184
185     def _load_ns3_module(self):
186         import ctypes
187         import imp
188
189         simu_impl_type = self._attributes.get_attribute_value(
190                 "SimulatorImplementationType")
191         checksum = self._attributes.get_attribute_value("ChecksumEnabled")
192         stop_time = self._attributes.get_attribute_value("StopTime")
193
194         bindings = os.environ["NEPI_NS3BINDINGS"] \
195                 if "NEPI_NS3BINDINGS" in os.environ else None
196         libfile = os.environ["NEPI_NS3LIBRARY"] \
197                 if "NEPI_NS3LIBRARY" in os.environ else None
198
199         if libfile:
200             ctypes.CDLL(libfile, ctypes.RTLD_GLOBAL)
201
202         path = [ os.path.dirname(__file__) ] + sys.path
203         if bindings:
204             path = [ bindings ] + path
205
206         try:
207             module = imp.find_module ('ns3', path)
208             mod = imp.load_module ('ns3', *module)
209         except ImportError:
210             # In some environments, ns3 per-se does not exist,
211             # only the low-level _ns3
212             module = imp.find_module ('_ns3', path)
213             mod = imp.load_module ('_ns3', *module)
214             sys.modules["ns3"] = mod # install it as ns3 too
215             
216             # When using _ns3, we have to make sure we destroy
217             # the simulator when the process finishes
218             import atexit
219             atexit.register(mod.Simulator.Destroy)
220     
221         if simu_impl_type:
222             value = mod.StringValue(simu_impl_type)
223             mod.GlobalValue.Bind ("SimulatorImplementationType", value)
224         if checksum:
225             value = mod.BooleanValue(checksum)
226             mod.GlobalValue.Bind ("ChecksumEnabled", value)
227         if stop_time:
228             value = mod.Time(stop_time)
229             mod.Simulator.Stop (value)
230         return mod
231
232     def _get_construct_parameters(self, guid):
233         params = self._get_parameters(guid)
234         construct_params = dict()
235         factory_id = self._create[guid]
236         TypeId = self.ns3.TypeId()
237         typeid = TypeId.LookupByName(factory_id)
238         for name, value in params.iteritems():
239             info = self.ns3.TypeId.AttributeInfo()
240             found = typeid.LookupAttributeByName(name, info)
241             if found and \
242                 (info.flags & TypeId.ATTR_CONSTRUCT == TypeId.ATTR_CONSTRUCT):
243                 construct_params[name] = value
244         return construct_params
245
246
247