minor changes to examples
[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
12 class TestbedController(testbed_impl.TestbedController):
13     def __init__(self, testbed_version):
14         super(TestbedController, self).__init__(TESTBED_ID, testbed_version)
15         self._ns3 = None
16         self._home_directory = None
17         self._traces = dict()
18         self._simulator_thread = None
19         self._condition = None
20
21     @property
22     def home_directory(self):
23         return self._home_directory
24
25     @property
26     def ns3(self):
27         return self._ns3
28
29     def do_setup(self):
30         self._home_directory = self._attributes.\
31             get_attribute_value("homeDirectory")
32         self._ns3 = self._load_ns3_module()
33         super(TestbedController, self).do_setup()
34
35     def start(self):
36         super(TestbedController, self).start()
37         self._condition = threading.Condition()
38         self._simulator_thread = threading.Thread(target = self._simulator_run,
39                 args = [self._condition])
40         self._simulator_thread.start()
41
42     def set(self, guid, name, value, time = TIME_NOW):
43         super(TestbedController, self).set(guid, name, value, time)
44         # TODO: take on account schedule time for the task
45         factory_id = self._create[guid]
46         factory = self._factories[factory_id]
47         if factory.box_attributes.is_attribute_design_only(name) or \
48                 factory.box_attributes.is_attribute_invisible(name):
49             return
50         element = self._elements[guid]
51         ns3_value = self._to_ns3_value(guid, name, value) 
52         element.SetAttribute(name, ns3_value)
53
54     def get(self, guid, name, time = TIME_NOW):
55         value = super(TestbedController, self).get(guid, name, time)
56         # TODO: take on account schedule time for the task
57         factory_id = self._create[guid]
58         factory = self._factories[factory_id]
59         if factory.box_attributes.is_attribute_design_only(name) or \
60                 factory.box_attributes.is_attribute_invisible(name):
61             return value
62         TypeId = self.ns3.TypeId()
63         typeid = TypeId.LookupByName(factory_id)
64         info = TypeId.AttributeInfo()
65         if not typeid or not typeid.LookupAttributeByName(name, info):
66             raise AttributeError("Invalid attribute %s for element type %d" % \
67                 (name, guid))
68         checker = info.checker
69         ns3_value = checker.Create() 
70         element = self._elements[guid]
71         element.GetAttribute(name, ns3_value)
72         value = ns3_value.SerializeToString(checker)
73         attr_type = factory.box_attributes.get_attribute_type(name)
74         if attr_type == Attribute.INTEGER:
75             return int(value)
76         if attr_type == Attribute.DOUBLE:
77             return float(value)
78         if attr_type == Attribute.BOOL:
79             return value == "true"
80         return value
81
82     def action(self, time, guid, action):
83         raise NotImplementedError
84
85     def trace_filename(self, guid, trace_id):
86         # TODO: Need to be defined inside a home!!!! with and experiment id_code
87         filename = self._traces[guid][trace_id]
88         return os.path.join(self.home_directory, filename)
89
90     def follow_trace(self, guid, trace_id, filename):
91         if guid not in self._traces:
92             self._traces[guid] = dict()
93         self._traces[guid][trace_id] = filename
94
95     def shutdown(self):
96         for element in self._elements.values():
97             element = None
98
99     def _simulator_run(self, condition):
100         # Run simulation
101         self.ns3.Simulator.Run()
102         # Signal condition on simulation end to notify waiting threads
103         condition.acquire()
104         condition.notifyAll()
105         condition.release()
106
107     def _schedule_event(self, condition, func, *args):
108         """Schedules event on running experiment"""
109         def execute_event(condition, has_event_occurred, func, *args):
110             # exec func
111             func(*args)
112             # flag event occured
113             has_event_occurred[0] = True
114             # notify condition indicating attribute was set
115             condition.acquire()
116             condition.notifyAll()
117             condition.release()
118
119         # contextId is defined as general context
120         contextId = long(0xffffffff)
121         # delay 0 means that the event is expected to execute inmediately
122         delay = self.ns3.Seconds(0)
123         # flag to indicate that the event occured
124         # because bool is an inmutable object in python, in order to create a
125         # bool flag, a list is used as wrapper
126         has_event_occurred = [False]
127         condition.acquire()
128         if not self.ns3.Simulator.IsFinished():
129             self.ns3.Simulator.ScheduleWithContext(contextId, delay, execute_event,
130                  condition, has_event_occurred, func, *args)
131             while not has_event_occurred[0] and not self.ns3.Simulator.IsFinished():
132                 condition.wait()
133                 condition.release()
134                 if not has_event_occurred[0]:
135                     raise RuntimeError('Event could not be scheduled : %s %s ' \
136                     % (repr(func), repr(args)))
137
138     def _to_ns3_value(self, guid, name, value):
139         factory_id = self._create[guid]
140         TypeId = self.ns3.TypeId()
141         typeid = TypeId.LookupByName(factory_id)
142         info = TypeId.AttributeInfo()
143         if not typeid.LookupAttributeByName(name, info):
144             raise RuntimeError("Attribute %s doesn't belong to element %s" \
145                    % (name, factory_id))
146         str_value = str(value)
147         if isinstance(value, bool):
148             str_value = str_value.lower()
149         checker = info.checker
150         ns3_value = checker.Create()
151         ns3_value.DeserializeFromString(str_value, checker)
152         return ns3_value
153
154     def _load_ns3_module(self):
155         import ctypes
156         import imp
157
158         simu_impl_type = self._attributes.get_attribute_value(
159                 "SimulatorImplementationType")
160         checksum = self._attributes.get_attribute_value("ChecksumEnabled")
161
162         bindings = os.environ["NEPI_NS3BINDINGS"] \
163                 if "NEPI_NS3BINDINGS" in os.environ else None
164         libfile = os.environ["NEPI_NS3LIBRARY"] \
165                 if "NEPI_NS3LIBRARY" in os.environ else None
166
167         if libfile:
168             ctypes.CDLL(libfile, ctypes.RTLD_GLOBAL)
169
170         path = [ os.path.dirname(__file__) ] + sys.path
171         if bindings:
172             path = [ bindings ] + path
173
174         module = imp.find_module ('ns3', path)
175         mod = imp.load_module ('ns3', *module)
176     
177         if simu_impl_type:
178             value = mod.StringValue(simu_impl_type)
179             mod.GlobalValue.Bind ("SimulatorImplementationType", value)
180         if checksum:
181             value = mod.BooleanValue(checksum)
182             mod.GlobalValue.Bind ("ChecksumEnabled", value)
183         return mod
184
185     def _get_construct_parameters(self, guid):
186         params = self._get_parameters(guid)
187         construct_params = dict()
188         factory_id = self._create[guid]
189         TypeId = self.ns3.TypeId()
190         typeid = TypeId.LookupByName(factory_id)
191         for name, value in params.iteritems():
192             info = self.ns3.TypeId.AttributeInfo()
193             found = typeid.LookupAttributeByName(name, info)
194             if found and \
195                 (info.flags & TypeId.ATTR_CONSTRUCT == TypeId.ATTR_CONSTRUCT):
196                 construct_params[name] = value
197         return construct_params
198