3350d77b7b24ec427496238ca2d740b82be80fa9
[nepi.git] / src / nepi / resources / ns3 / resource_manager_generator.py
1 #
2 #    NEPI, a framework to manage network experiments
3 #    Copyright (C) 2013 INRIA
4 #
5 #    This program is free software: you can redistribute it and/or modify
6 #    it under the terms of the GNU General Public License version 2 as
7 #    published by the Free Software Foundation;
8 #
9 #    This program is distributed in the hope that it will be useful,
10 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
11 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 #    GNU General Public License for more details.
13 #
14 #    You should have received a copy of the GNU General Public License
15 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
16 #
17 # Author: Alina Quereilhac <alina.quereilhac@inria.fr>
18
19 #
20 # Instructions to automatically generate ns-3 ResourceManagers
21
22 # Configure the ns-3 enviorment (e.g.):
23 #
24 #  export PYTHONPATH=~/.nepi/nepi-usr/bin/ns-3/ns-3.20/optimized/build/lib/python/site-packages
25 #  export LD_LIBRARY_PATH=~/.nepi/nepi-usr/bin/ns-3/ns-3.20/optimized/build/lib
26 #
27 # Run the RM generator:
28 #
29 #  PYTHONPATH=$PYTHONPATH:~/repos/nepi/src python src/nepi/resources/ns3/resource_manager_generator.py
30 #
31
32 # Force the load of ns3 libraries
33 from nepi.resources.ns3.ns3wrapper import load_ns3_module
34
35 import os
36 import re
37
38 adapted_types = ["ns3::Node",
39         "ns3::Icmpv4L4Protocol",
40         "ns3::ArpL3Protocol",
41         "ns3::Ipv4L3Protocol",
42         "ns3::PropagationLossModel",
43         "ns3::MobilityModel",
44         "ns3::PropagationDelayModel",
45         "ns3::WifiRemoteStationManager",
46         "ns3::WifiNetDevice",
47         "ns3::WifiChannel",
48         "ns3::WifiPhy",
49         "ns3::WifiMac",
50         "ns3::ErrorModel",
51         "ns3::ErrorRateModel",
52         "ns3::Application", 
53         "ns3::FdNetDevice",
54         #"ns3::DceApplication", 
55         "ns3::NetDevice",
56         "ns3::Channel",
57         "ns3::Queue"]
58
59 base_types = ["ns3::IpL4Protocol"]
60
61 def select_base_class(ns3, tid): 
62     base_class_import = None
63     base_class = None
64    
65     rtype = tid.GetName()
66
67     type_id = ns3.TypeId()
68
69     for type_name in adapted_types:
70         tid_base = type_id.LookupByName(type_name)
71         if type_name == rtype or tid.IsChildOf(tid_base):
72             base_class = "NS3Base" + type_name.replace("ns3::", "")
73             base_module = "ns3" + type_name.replace("ns3::", "").lower()
74             base_class_import = "from nepi.resources.ns3.%s import %s " % (
75                     base_module, base_class)
76             return (base_class_import, base_class)
77
78     base_class_import = "from nepi.resources.ns3.ns3base import NS3Base"
79     base_class = "NS3Base"
80
81     for type_name in base_types:
82         tid_base = type_id.LookupByName(type_name)
83         if type_name == rtype or tid.IsChildOf(tid_base):
84             return (base_class_import, base_class)
85
86     return (None, None)
87
88 def create_ns3_rms():
89     ns3 = load_ns3_module()
90
91     type_id = ns3.TypeId()
92     
93     tid_count = type_id.GetRegisteredN()
94     base = type_id.LookupByName("ns3::Object")
95
96     # Create a .py file using the ns-3 RM template for each ns-3 TypeId
97     for i in xrange(tid_count):
98         tid = type_id.GetRegistered(i)
99         
100         (base_class_import, base_class) = select_base_class(ns3, tid)
101         if not base_class:
102             continue
103         
104         if tid.MustHideFromDocumentation() or \
105                 not tid.HasConstructor() or \
106                 not tid.IsChildOf(base): 
107             continue
108        
109         attributes = template_attributes(ns3, tid)
110         traces = template_traces(ns3, tid)
111         ptid = tid
112         while ptid.HasParent():
113             ptid = ptid.GetParent()
114             attributes += template_attributes(ns3, ptid)
115             traces += template_traces(ns3, ptid)
116
117         attributes = "\n" + attributes if attributes else "pass"
118         traces = "\n" + traces if traces else "pass"
119
120         category = tid.GetGroupName()
121
122         rtype = tid.GetName()
123         classname = rtype.replace("ns3::", "NS3").replace("::","")
124         uncamm_rtype = re.sub('([a-z])([A-Z])', r'\1-\2', rtype).lower()
125         short_rtype = uncamm_rtype.replace("::","-")
126
127         d = os.path.dirname(os.path.realpath(__file__))
128         ftemp = open(os.path.join(d, "templates", "resource_manager_template.txt"), "r")
129         template = ftemp.read()
130         ftemp.close()
131
132         template = template. \
133                 replace("<CLASS_NAME>", classname). \
134                 replace("<RTYPE>", rtype). \
135                 replace("<ATTRIBUTES>", attributes). \
136                 replace("<TRACES>", traces). \
137                 replace("<BASE_CLASS_IMPORT>", base_class_import). \
138                 replace("<BASE_CLASS>", base_class). \
139                 replace("<SHORT-RTYPE>", short_rtype)
140
141         fname = uncamm_rtype.replace('ns3::', ''). \
142                 replace('::', ''). \
143                 replace("-","_").lower() + ".py"
144
145         f = open(os.path.join(d, "classes", fname), "w")
146         print os.path.join(d, fname)
147         print template
148         f.write(template)
149         f.close()
150
151 def template_attributes(ns3, tid): 
152     d = os.path.dirname(os.path.realpath(__file__))
153     ftemp = open(os.path.join(d, "templates", "attribute_template.txt"), "r")
154     template = ftemp.read()
155     ftemp.close()
156
157     attributes = ""
158
159     attr_count = tid.GetAttributeN()
160     for i in xrange(attr_count):
161         attr_info = tid.GetAttribute(i)
162         if not attr_info.accessor.HasGetter():
163             continue
164
165         attr_flags = "Flags.Reserved"
166         flags = attr_info.flags
167         if (flags & ns3.TypeId.ATTR_CONSTRUCT) == ns3.TypeId.ATTR_CONSTRUCT:
168             attr_flags += " | Flags.Construct"
169         else:
170             if (flags & ns3.TypeId.ATTR_GET) != ns3.TypeId.ATTR_GET:
171                 attr_flags += " | Flags.NoRead"
172             elif (flags & ns3.TypeId.ATTR_SET) != ns3.TypeId.ATTR_SET:
173                 attr_flags += " | Flags.NoWrite"
174
175         attr_name = attr_info.name
176         checker = attr_info.checker
177         attr_help = attr_info.help.replace('"', '\\"').replace("'", "\\'")
178         value = attr_info.initialValue
179         attr_value = value.SerializeToString(checker)
180         attr_allowed = "None"
181         attr_range = "None"
182         attr_type = "Types.String"
183
184         if isinstance(value, ns3.ObjectVectorValue):
185             continue
186         elif isinstance(value, ns3.PointerValue):
187             continue
188         elif isinstance(value, ns3.WaypointValue):
189             continue
190         elif isinstance(value, ns3.BooleanValue):
191             attr_type = "Types.Bool"
192             attr_value = "True" if attr_value == "true" else "False"
193         elif isinstance(value, ns3.EnumValue):
194             attr_type = "Types.Enumerate"
195             allowed = checker.GetUnderlyingTypeInformation().split("|")
196             attr_allowed = "[%s]" % ",".join(map(lambda x: "\"%s\"" % x, allowed))
197         elif isinstance(value, ns3.DoubleValue):
198             attr_type = "Types.Double"
199             # TODO: range
200         elif isinstance(value, ns3.UintegerValue):
201             attr_type = "Types.Integer"
202             # TODO: range
203
204         attr_id = "attr_" + attr_name.lower().replace("-", "_")
205         attributes += template.replace("<ATTR_ID>", attr_id) \
206                 .replace("<ATTR_NAME>", attr_name) \
207                 .replace("<ATTR_HELP>", attr_help) \
208                 .replace("<ATTR_TYPE>", attr_type) \
209                 .replace("<ATTR_DEFAULT>", attr_value) \
210                 .replace("<ATTR_ALLOWED>", attr_allowed) \
211                 .replace("<ATTR_RANGE>", attr_range) \
212                 .replace("<ATTR_FLAGS>", attr_flags) 
213
214     return attributes
215
216 def template_traces(ns3, tid): 
217     d = os.path.dirname(os.path.realpath(__file__))
218     ftemp = open(os.path.join(d, "templates", "trace_template.txt"), "r")
219     template = ftemp.read()
220     ftemp.close()
221
222     traces = ""
223
224     trace_count = tid.GetTraceSourceN()
225     for i in xrange(trace_count):
226         trace_info = tid.GetTraceSource(i)
227         trace_name = trace_info.name
228         trace_help = trace_info.help.replace('"', '\\"').replace("'", "\\'")
229
230         trace_id = trace_name.lower()
231         traces += template.replace("<TRACE_ID>", trace_id) \
232                 .replace("<TRACE_NAME>", trace_name) \
233                 .replace("<TRACE_HELP>", trace_help) 
234
235     return traces
236
237 if __name__ == "__main__":
238     create_ns3_rms()