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