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