0e95a2bd62e8eeab1dea20cc23264a0a809dff0a
[nepi.git] / src / nepi / resources / ns3 / ns3wrapper.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 as published by
7 #    the Free Software Foundation, either version 3 of the License, or
8 #    (at your option) any later version.
9 #
10 #    This program is distributed in the hope that it will be useful,
11 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
12 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 #    GNU General Public License for more details.
14 #
15 #    You should have received a copy of the GNU General Public License
16 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 #
18 # Author: Alina Quereilhac <alina.quereilhac@inria.fr>
19
20 import logging
21 import os
22 import sys
23 import threading
24 import time
25 import uuid
26
27 SINGLETON = "singleton::"
28 SIMULATOR_UUID = "singleton::Simulator"
29 CONFIG_UUID = "singleton::Config"
30 GLOBAL_VALUE_UUID = "singleton::GlobalValue"
31 IPV4_GLOBAL_ROUTING_HELPER_UUID = "singleton::Ipv4GlobalRoutingHelper"
32
33 def load_ns3_libraries():
34     import ctypes
35     import re
36
37     libdir = os.environ.get("NS3LIBRARIES")
38
39     # Load the ns-3 modules shared libraries
40     if libdir:
41         files = os.listdir(libdir)
42         regex = re.compile("(.*\.so)$")
43         libs = [m.group(1) for filename in files for m in [regex.search(filename)] if m]
44
45         initial_size = len(libs)
46         # Try to load the libraries in the right order by trial and error.
47         # Loop until all libraries are loaded.
48         while len(libs) > 0:
49             for lib in libs:
50                 libfile = os.path.join(libdir, lib)
51                 try:
52                     ctypes.CDLL(libfile, ctypes.RTLD_GLOBAL)
53                     libs.remove(lib)
54                 except:
55                     #import traceback
56                     #err = traceback.format_exc()
57                     #print err
58                     pass
59
60             # if did not load any libraries in the last iteration break
61             # to prevent infinit loop
62             if initial_size == len(libs):
63                 raise RuntimeError("Imposible to load shared libraries %s" % str(libs))
64             initial_size = len(libs)
65
66 def load_ns3_module():
67     load_ns3_libraries()
68
69     # import the python bindings for the ns-3 modules
70     bindings = os.environ.get("NS3BINDINGS")
71     if bindings:
72         sys.path.append(bindings)
73
74     import pkgutil
75     import imp
76     import ns
77
78     # create a Python module to add all ns3 classes
79     ns3mod = imp.new_module("ns3")
80     sys.modules["ns3"] = ns3mod
81
82     for importer, modname, ispkg in pkgutil.iter_modules(ns.__path__):
83         if modname in [ "visualizer" ]:
84             continue
85
86         fullmodname = "ns.%s" % modname
87         module = __import__(fullmodname, globals(), locals(), ['*'])
88
89         for sattr in dir(module):
90             if sattr.startswith("_"):
91                 continue
92
93             attr = getattr(module, sattr)
94
95             # netanim.Config and lte.Config singleton overrides ns3::Config
96             if sattr == "Config" and modname in ['netanim', 'lte']:
97                 sattr = "%s.%s" % (modname, sattr)
98
99             setattr(ns3mod, sattr, attr)
100
101     return ns3mod
102
103 class NS3Wrapper(object):
104     def __init__(self, loglevel = logging.INFO, enable_dump = False):
105         super(NS3Wrapper, self).__init__()
106         # Thread used to run the simulation
107         self._simulation_thread = None
108         self._condition = None
109
110         # True if Simulator::Run was invoked
111         self._started = False
112
113         # holds reference to all C++ objects and variables in the simulation
114         self._objects = dict()
115
116         # Logging
117         self._logger = logging.getLogger("ns3wrapper")
118         self._logger.setLevel(loglevel)
119
120         ## NOTE that the reason to create a handler to the ns3 module,
121         # that is re-loaded each time a ns-3 wrapper is instantiated,
122         # is that else each unit test for the ns3wrapper class would need
123         # a separate file. Several ns3wrappers would be created in the 
124         # same unit test (single process), leading to inchorences in the 
125         # state of ns-3 global objects
126         #
127         # Handler to ns3 classes
128         self._ns3 = None
129
130         # Collection of allowed ns3 classes
131         self._allowed_types = None
132
133         # Object to dump instructions to reproduce and debug experiment
134         from ns3wrapper_debug import NS3WrapperDebuger
135         self._debuger = NS3WrapperDebuger(enabled = enable_dump)
136
137     @property
138     def debuger(self):
139         return self._debuger
140
141     @property
142     def ns3(self):
143         if not self._ns3:
144             # load ns-3 libraries and bindings
145             self._ns3 = load_ns3_module()
146
147         return self._ns3
148
149     @property
150     def allowed_types(self):
151         if not self._allowed_types:
152             self._allowed_types = set()
153             type_id = self.ns3.TypeId()
154             
155             tid_count = type_id.GetRegisteredN()
156             base = type_id.LookupByName("ns3::Object")
157
158             for i in xrange(tid_count):
159                 tid = type_id.GetRegistered(i)
160                 
161                 if tid.MustHideFromDocumentation() or \
162                         not tid.HasConstructor() or \
163                         not tid.IsChildOf(base): 
164                     continue
165
166                 type_name = tid.GetName()
167                 self._allowed_types.add(type_name)
168         
169         return self._allowed_types
170
171     @property
172     def logger(self):
173         return self._logger
174
175     @property
176     def is_running(self):
177         return self._started and self.ns3.Simulator.IsFinished()
178
179     def make_uuid(self):
180         return "uuid%s" % uuid.uuid4()
181
182     def get_object(self, uuid):
183         return self._objects.get(uuid)
184
185     def factory(self, type_name, **kwargs):
186         """ This method should be used to construct ns-3 objects
187         that have a TypeId and related introspection information """
188
189         if type_name not in self.allowed_types:
190             msg = "Type %s not supported" % (type_name) 
191             self.logger.error(msg)
192
193         uuid = self.make_uuid()
194         
195         ### DEBUG
196         self.logger.debug("FACTORY %s( %s )" % (type_name, str(kwargs)))
197         
198         self.debuger.dump_factory(uuid, type_name, kwargs)
199         ########
200
201         factory = self.ns3.ObjectFactory()
202         factory.SetTypeId(type_name)
203
204         for name, value in kwargs.iteritems():
205             ns3_value = self._attr_from_string_to_ns3_value(type_name, name, value)
206             factory.Set(name, ns3_value)
207
208         obj = factory.Create()
209
210         self._objects[uuid] = obj
211
212         ### DEBUG
213         self.logger.debug("RET FACTORY ( uuid %s ) %s = %s( %s )" % (
214             str(uuid), str(obj), type_name, str(kwargs)))
215         ########
216  
217         return uuid
218
219     def create(self, clazzname, *args):
220         """ This method should be used to construct ns-3 objects that
221         do not have a TypeId (e.g. Values) """
222
223         if not hasattr(self.ns3, clazzname):
224             msg = "Type %s not supported" % (clazzname) 
225             self.logger.error(msg)
226
227         uuid = self.make_uuid()
228         
229         ### DEBUG
230         self.logger.debug("CREATE %s( %s )" % (clazzname, str(args)))
231     
232         self.debuger.dump_create(uuid, clazzname, args)
233         ########
234
235         clazz = getattr(self.ns3, clazzname)
236  
237         # arguments starting with 'uuid' identify ns-3 C++
238         # objects and must be replaced by the actual object
239         realargs = self.replace_args(args)
240        
241         obj = clazz(*realargs)
242         
243         self._objects[uuid] = obj
244
245         ### DEBUG
246         self.logger.debug("RET CREATE ( uuid %s ) %s = %s( %s )" % (str(uuid), 
247             str(obj), clazzname, str(args)))
248         ########
249
250         return uuid
251
252     def invoke(self, uuid, operation, *args, **kwargs):
253         ### DEBUG
254         self.logger.debug("INVOKE %s -> %s( %s, %s ) " % (
255             uuid, operation, str(args), str(kwargs)))
256         ########
257
258         result = None
259         newuuid = None
260
261         if operation == "isRunning":
262             result = self.is_running
263         elif operation == "isAppRunning":
264             result = self._is_app_running(uuid)
265         elif operation == "addStaticRoute":
266             ### DEBUG
267             self.debuger.dump_add_static_route(uuid, args)
268             ########
269
270             result = self._add_static_route(uuid, *args)
271         else:
272             newuuid = self.make_uuid()
273
274             ### DEBUG
275             self.debuger.dump_invoke(newuuid, uuid, operation, args, kwargs)
276             ########
277
278             if uuid.startswith(SINGLETON):
279                 obj = self._singleton(uuid)
280             else:
281                 obj = self.get_object(uuid)
282             
283             method = getattr(obj, operation)
284
285             # arguments starting with 'uuid' identify ns-3 C++
286             # objects and must be replaced by the actual object
287             realargs = self.replace_args(args)
288             realkwargs = self.replace_kwargs(kwargs)
289
290             result = method(*realargs, **realkwargs)
291
292             # If the result is an object (not a base value),
293             # then keep track of the object a return the object
294             # reference (newuuid)
295             if not (result is None or type(result) in [
296                     bool, float, long, str, int]):
297                 self._objects[newuuid] = result
298                 result = newuuid
299
300         ### DEBUG
301         self.logger.debug("RET INVOKE %s%s = %s -> %s(%s, %s) " % (
302             "(uuid %s) " % str(newuuid) if newuuid else "", str(result), uuid, 
303             operation, str(args), str(kwargs)))
304         ########
305
306         return result
307
308     def _set_attr(self, obj, name, ns3_value):
309         obj.SetAttribute(name, ns3_value)
310
311     def set(self, uuid, name, value):
312         ### DEBUG
313         self.logger.debug("SET %s %s %s" % (uuid, name, str(value)))
314     
315         self.debuger.dump_set(uuid, name, value)
316         ########
317
318         obj = self.get_object(uuid)
319         type_name = obj.GetInstanceTypeId().GetName()
320         ns3_value = self._attr_from_string_to_ns3_value(type_name, name, value)
321
322         # If the Simulation thread is not running,
323         # then there will be no thread-safety problems
324         # in changing the value of an attribute directly.
325         # However, if the simulation is running we need
326         # to set the value by scheduling an event, else
327         # we risk to corrupt the state of the
328         # simulation.
329         
330         event_executed = [False]
331
332         if self.is_running:
333             # schedule the event in the Simulator
334             self._schedule_event(self._condition, event_executed, 
335                     self._set_attr, obj, name, ns3_value)
336
337         if not event_executed[0]:
338             self._set_attr(obj, name, ns3_value)
339
340         ### DEBUG
341         self.logger.debug("RET SET %s = %s -> set(%s, %s)" % (str(value), uuid, name, 
342             str(value)))
343         ########
344
345         return value
346
347     def _get_attr(self, obj, name, ns3_value):
348         obj.GetAttribute(name, ns3_value)
349
350     def get(self, uuid, name):
351         ### DEBUG
352         self.logger.debug("GET %s %s" % (uuid, name))
353         
354         self.debuger.dump_get(uuid, name)
355         ########
356
357         obj = self.get_object(uuid)
358         type_name = obj.GetInstanceTypeId().GetName()
359         ns3_value = self._create_attr_ns3_value(type_name, name)
360
361         event_executed = [False]
362
363         if self.is_running:
364             # schedule the event in the Simulator
365             self._schedule_event(self._condition, event_executed,
366                     self._get_attr, obj, name, ns3_value)
367
368         if not event_executed[0]:
369             self._get_attr(obj, name, ns3_value)
370
371         result = self._attr_from_ns3_value_to_string(type_name, name, ns3_value)
372
373         ### DEBUG
374         self.logger.debug("RET GET %s = %s -> get(%s)" % (str(result), uuid, name))
375         ########
376
377         return result
378
379     def start(self):
380         ### DEBUG
381         self.debuger.dump_start()
382         ########
383
384         # Launch the simulator thread and Start the
385         # simulator in that thread
386         self._condition = threading.Condition()
387         self._simulator_thread = threading.Thread(
388                 target = self._simulator_run,
389                 args = [self._condition])
390         self._simulator_thread.setDaemon(True)
391         self._simulator_thread.start()
392         self._started = True
393
394         ### DEBUG
395         self.logger.debug("START")
396         ########
397
398     def stop(self, time = None):
399         ### DEBUG
400         self.debuger.dump_stop(time=time)
401         ########
402         
403         if time is None:
404             self.ns3.Simulator.Stop()
405         else:
406             self.ns3.Simulator.Stop(self.ns3.Time(time))
407
408         ### DEBUG
409         self.logger.debug("STOP time=%s" % str(time))
410         ########
411
412     def shutdown(self):
413         ### DEBUG
414         self.debuger.dump_shutdown()
415         ########
416
417         while not self.ns3.Simulator.IsFinished():
418             #self.logger.debug("Waiting for simulation to finish")
419             time.sleep(0.5)
420         
421         if self._simulator_thread:
422             self._simulator_thread.join()
423        
424         self.ns3.Simulator.Destroy()
425         
426         # Remove all references to ns-3 objects
427         self._objects.clear()
428         
429         sys.stdout.flush()
430         sys.stderr.flush()
431
432         ### DEBUG
433         self.logger.debug("SHUTDOWN")
434         ########
435
436     def _simulator_run(self, condition):
437         # Run simulation
438         self.ns3.Simulator.Run()
439         # Signal condition to indicate simulation ended and
440         # notify waiting threads
441         condition.acquire()
442         condition.notifyAll()
443         condition.release()
444
445     def _schedule_event(self, condition, event_executed, func, *args):
446         """ Schedules event on running simulation, and wait until
447             event is executed"""
448
449         def execute_event(contextId, condition, event_executed, func, *args):
450             try:
451                 func(*args)
452                 event_executed[0] = True
453             finally:
454                 # notify condition indicating event was executed
455                 condition.acquire()
456                 condition.notifyAll()
457                 condition.release()
458
459         # contextId is defined as general context
460         contextId = long(0xffffffff)
461
462         # delay 0 means that the event is expected to execute inmediately
463         delay = self.ns3.Seconds(0)
464     
465         # Mark event as not executed
466         event_executed[0] = False
467
468         condition.acquire()
469         try:
470             self.ns3.Simulator.ScheduleWithContext(contextId, delay, execute_event, 
471                     condition, event_executed, func, *args)
472             if not self.ns3.Simulator.IsFinished():
473                 condition.wait()
474         finally:
475             condition.release()
476
477     def _create_attr_ns3_value(self, type_name, name):
478         TypeId = self.ns3.TypeId()
479         tid = TypeId.LookupByName(type_name)
480         info = TypeId.AttributeInformation()
481         if not tid.LookupAttributeByName(name, info):
482             msg = "TypeId %s has no attribute %s" % (type_name, name) 
483             self.logger.error(msg)
484
485         checker = info.checker
486         ns3_value = checker.Create() 
487         return ns3_value
488
489     def _attr_from_ns3_value_to_string(self, type_name, name, ns3_value):
490         TypeId = self.ns3.TypeId()
491         tid = TypeId.LookupByName(type_name)
492         info = TypeId.AttributeInformation()
493         if not tid.LookupAttributeByName(name, info):
494             msg = "TypeId %s has no attribute %s" % (type_name, name) 
495             self.logger.error(msg)
496
497         checker = info.checker
498         value = ns3_value.SerializeToString(checker)
499
500         type_name = checker.GetValueTypeName()
501         if type_name in ["ns3::UintegerValue", "ns3::IntegerValue"]:
502             return int(value)
503         if type_name == "ns3::DoubleValue":
504             return float(value)
505         if type_name == "ns3::BooleanValue":
506             return value == "true"
507
508         return value
509
510     def _attr_from_string_to_ns3_value(self, type_name, name, value):
511         TypeId = self.ns3.TypeId()
512         tid = TypeId.LookupByName(type_name)
513         info = TypeId.AttributeInformation()
514         if not tid.LookupAttributeByName(name, info):
515             msg = "TypeId %s has no attribute %s" % (type_name, name) 
516             self.logger.error(msg)
517
518         str_value = str(value)
519         if isinstance(value, bool):
520             str_value = str_value.lower()
521
522         checker = info.checker
523         ns3_value = checker.Create()
524         ns3_value.DeserializeFromString(str_value, checker)
525         return ns3_value
526
527     # singletons are identified as "ns3::ClassName"
528     def _singleton(self, ident):
529         if not ident.startswith(SINGLETON):
530             return None
531
532         clazzname = ident[ident.find("::")+2:]
533         if not hasattr(self.ns3, clazzname):
534             msg = "Type %s not supported" % (clazzname)
535             self.logger.error(msg)
536
537         return getattr(self.ns3, clazzname)
538
539     # replace uuids and singleton references for the real objects
540     def replace_args(self, args):
541         realargs = [self.get_object(arg) if \
542                 str(arg).startswith("uuid") else arg for arg in args]
543  
544         realargs = [self._singleton(arg) if \
545                 str(arg).startswith(SINGLETON) else arg for arg in realargs]
546
547         return realargs
548
549     # replace uuids and singleton references for the real objects
550     def replace_kwargs(self, kwargs):
551         realkwargs = dict([(k, self.get_object(v) \
552                 if str(v).startswith("uuid") else v) \
553                 for k,v in kwargs.iteritems()])
554  
555         realkwargs = dict([(k, self._singleton(v) \
556                 if str(v).startswith(SINGLETON) else v )\
557                 for k, v in realkwargs.iteritems()])
558
559         return realkwargs
560
561     def _is_app_running(self, uuid): 
562         now = self.ns3.Simulator.Now()
563         if now.IsZero():
564             return False
565
566         app = self.get_object(uuid)
567         stop_time_value = self.ns3.TimeValue()
568         app.GetAttribute("StopTime", stop_time_value)
569         stop_time = stop_time_value.Get()
570
571         start_time_value = self.ns3.TimeValue()
572         app.GetAttribute("StartTime", start_time_value)
573         start_time = start_time_value.Get()
574         
575         if now.Compare(start_time) >= 0 and now.Compare(stop_time) < 0:
576             return True
577
578         return False
579
580     def _add_static_route(self, ipv4_uuid, network, prefix, nexthop):
581         ipv4 = self.get_object(ipv4_uuid)
582
583         list_routing = ipv4.GetRoutingProtocol()
584         (static_routing, priority) = list_routing.GetRoutingProtocol(0)
585
586         ifindex = self._find_ifindex(ipv4, nexthop)
587         if ifindex == -1:
588             return False
589         
590         nexthop = self.ns3.Ipv4Address(nexthop)
591
592         if network in ["0.0.0.0", "0", None]:
593             # Default route: 0.0.0.0/0
594             static_routing.SetDefaultRoute(nexthop, ifindex)
595         else:
596             mask = self.ns3.Ipv4Mask("/%s" % prefix) 
597             network = self.ns3.Ipv4Address(network)
598
599             if prefix == 32:
600                 # Host route: x.y.z.w/32
601                 static_routing.AddHostRouteTo(network, nexthop, ifindex)
602             else:
603                 # Network route: x.y.z.w/n
604                 static_routing.AddNetworkRouteTo(network, mask, nexthop, 
605                         ifindex) 
606         return True
607
608     def _find_ifindex(self, ipv4, nexthop):
609         ifindex = -1
610
611         nexthop = self.ns3.Ipv4Address(nexthop)
612
613         # For all the interfaces registered with the ipv4 object, find
614         # the one that matches the network of the nexthop
615         nifaces = ipv4.GetNInterfaces()
616         for ifidx in xrange(nifaces):
617             iface = ipv4.GetInterface(ifidx)
618             naddress = iface.GetNAddresses()
619             for addridx in xrange(naddress):
620                 ifaddr = iface.GetAddress(addridx)
621                 ifmask = ifaddr.GetMask()
622                 
623                 ifindex = ipv4.GetInterfaceForPrefix(nexthop, ifmask)
624
625                 if ifindex == ifidx:
626                     return ifindex
627         return ifindex
628