Fix invisible attribute implementation: they should be both queriable and settable.
[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
128     def _simulator_run(self, condition):
129         # Run simulation
130         self.ns3.Simulator.Run()
131         # Signal condition on simulation end to notify waiting threads
132         condition.acquire()
133         condition.notifyAll()
134         condition.release()
135
136     def _schedule_event(self, condition, func, *args):
137         """Schedules event on running experiment"""
138         def execute_event(condition, has_event_occurred, func, *args):
139             # exec func
140             func(*args)
141             # flag event occured
142             has_event_occurred[0] = True
143             # notify condition indicating attribute was set
144             condition.acquire()
145             condition.notifyAll()
146             condition.release()
147
148         # contextId is defined as general context
149         contextId = long(0xffffffff)
150         # delay 0 means that the event is expected to execute inmediately
151         delay = self.ns3.Seconds(0)
152         # flag to indicate that the event occured
153         # because bool is an inmutable object in python, in order to create a
154         # bool flag, a list is used as wrapper
155         has_event_occurred = [False]
156         condition.acquire()
157         if not self.ns3.Simulator.IsFinished():
158             self.ns3.Simulator.ScheduleWithContext(contextId, delay, execute_event,
159                  condition, has_event_occurred, func, *args)
160             while not has_event_occurred[0] and not self.ns3.Simulator.IsFinished():
161                 condition.wait()
162                 condition.release()
163                 if not has_event_occurred[0]:
164                     raise RuntimeError('Event could not be scheduled : %s %s ' \
165                     % (repr(func), repr(args)))
166
167     def _to_ns3_value(self, guid, name, value):
168         factory_id = self._create[guid]
169         TypeId = self.ns3.TypeId()
170         typeid = TypeId.LookupByName(factory_id)
171         info = TypeId.AttributeInfo()
172         if not typeid.LookupAttributeByName(name, info):
173             raise RuntimeError("Attribute %s doesn't belong to element %s" \
174                    % (name, factory_id))
175         str_value = str(value)
176         if isinstance(value, bool):
177             str_value = str_value.lower()
178         checker = info.checker
179         ns3_value = checker.Create()
180         ns3_value.DeserializeFromString(str_value, checker)
181         return ns3_value
182
183     def _load_ns3_module(self):
184         import ctypes
185         import imp
186
187         simu_impl_type = self._attributes.get_attribute_value(
188                 "SimulatorImplementationType")
189         checksum = self._attributes.get_attribute_value("ChecksumEnabled")
190
191         bindings = os.environ["NEPI_NS3BINDINGS"] \
192                 if "NEPI_NS3BINDINGS" in os.environ else None
193         libfile = os.environ["NEPI_NS3LIBRARY"] \
194                 if "NEPI_NS3LIBRARY" in os.environ else None
195
196         if libfile:
197             ctypes.CDLL(libfile, ctypes.RTLD_GLOBAL)
198
199         path = [ os.path.dirname(__file__) ] + sys.path
200         if bindings:
201             path = [ bindings ] + path
202
203         try:
204             module = imp.find_module ('ns3', path)
205             mod = imp.load_module ('ns3', *module)
206         except ImportError:
207             # In some environments, ns3 per-se does not exist,
208             # only the low-level _ns3
209             module = imp.find_module ('_ns3', path)
210             mod = imp.load_module ('_ns3', *module)
211             sys.modules["ns3"] = mod # install it as ns3 too
212             
213             # When using _ns3, we have to make sure we destroy
214             # the simulator when the process finishes
215             import atexit
216             atexit.register(mod.Simulator.Destroy)
217     
218         if simu_impl_type:
219             value = mod.StringValue(simu_impl_type)
220             mod.GlobalValue.Bind ("SimulatorImplementationType", value)
221         if checksum:
222             value = mod.BooleanValue(checksum)
223             mod.GlobalValue.Bind ("ChecksumEnabled", value)
224         return mod
225
226     def _get_construct_parameters(self, guid):
227         params = self._get_parameters(guid)
228         construct_params = dict()
229         factory_id = self._create[guid]
230         TypeId = self.ns3.TypeId()
231         typeid = TypeId.LookupByName(factory_id)
232         for name, value in params.iteritems():
233             info = self.ns3.TypeId.AttributeInfo()
234             found = typeid.LookupAttributeByName(name, info)
235             if found and \
236                 (info.flags & TypeId.ATTR_CONSTRUCT == TypeId.ATTR_CONSTRUCT):
237                 construct_params[name] = value
238         return construct_params
239
240
241