2 # NEPI, a framework to manage network experiments
3 # Copyright (C) 2013 INRIA
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.
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.
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/>.
18 # Author: Alina Quereilhac <alina.quereilhac@inria.fr>
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"
33 def load_ns3_libraries():
37 libdir = os.environ.get("NS3LIBRARIES")
39 # Load the ns-3 modules shared libraries
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]
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.
50 libfile = os.path.join(libdir, lib)
52 ctypes.CDLL(libfile, ctypes.RTLD_GLOBAL)
56 #err = traceback.format_exc()
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)
66 def load_ns3_module():
69 # import the python bindings for the ns-3 modules
70 bindings = os.environ.get("NS3BINDINGS")
72 sys.path.append(bindings)
78 # create a Python module to add all ns3 classes
79 ns3mod = imp.new_module("ns3")
80 sys.modules["ns3"] = ns3mod
82 for importer, modname, ispkg in pkgutil.iter_modules(ns.__path__):
83 if modname in [ "visualizer" ]:
86 fullmodname = "ns.%s" % modname
87 module = __import__(fullmodname, globals(), locals(), ['*'])
89 for sattr in dir(module):
90 if sattr.startswith("_"):
93 attr = getattr(module, sattr)
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)
99 setattr(ns3mod, sattr, attr)
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
110 # True if Simulator::Run was invoked
111 self._started = False
113 # holds reference to all C++ objects and variables in the simulation
114 self._objects = dict()
117 self._logger = logging.getLogger("ns3wrapper")
118 self._logger.setLevel(loglevel)
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
127 # Handler to ns3 classes
130 # Collection of allowed ns3 classes
131 self._allowed_types = None
133 # Object to dump instructions to reproduce and debug experiment
134 from ns3wrapper_debug import NS3WrapperDebuger
135 self._debuger = NS3WrapperDebuger(enabled = enable_dump)
144 # load ns-3 libraries and bindings
145 self._ns3 = load_ns3_module()
150 def allowed_types(self):
151 if not self._allowed_types:
152 self._allowed_types = set()
153 type_id = self.ns3.TypeId()
155 tid_count = type_id.GetRegisteredN()
156 base = type_id.LookupByName("ns3::Object")
158 for i in xrange(tid_count):
159 tid = type_id.GetRegistered(i)
161 if tid.MustHideFromDocumentation() or \
162 not tid.HasConstructor() or \
163 not tid.IsChildOf(base):
166 type_name = tid.GetName()
167 self._allowed_types.add(type_name)
169 return self._allowed_types
176 def is_running(self):
177 return self._started and not self.ns3.Simulator.IsFinished()
180 def is_finished(self):
181 return self.ns3.Simulator.IsFinished()
184 return "uuid%s" % uuid.uuid4()
186 def get_object(self, uuid):
187 return self._objects.get(uuid)
189 def factory(self, type_name, **kwargs):
190 """ This method should be used to construct ns-3 objects
191 that have a TypeId and related introspection information """
193 if type_name not in self.allowed_types:
194 msg = "Type %s not supported" % (type_name)
195 self.logger.error(msg)
197 uuid = self.make_uuid()
200 self.logger.debug("FACTORY %s( %s )" % (type_name, str(kwargs)))
202 self.debuger.dump_factory(uuid, type_name, kwargs)
205 factory = self.ns3.ObjectFactory()
206 factory.SetTypeId(type_name)
208 for name, value in kwargs.iteritems():
209 ns3_value = self._attr_from_string_to_ns3_value(type_name, name, value)
210 factory.Set(name, ns3_value)
212 obj = factory.Create()
214 self._objects[uuid] = obj
217 self.logger.debug("RET FACTORY ( uuid %s ) %s = %s( %s )" % (
218 str(uuid), str(obj), type_name, str(kwargs)))
223 def create(self, clazzname, *args):
224 """ This method should be used to construct ns-3 objects that
225 do not have a TypeId (e.g. Values) """
227 if not hasattr(self.ns3, clazzname):
228 msg = "Type %s not supported" % (clazzname)
229 self.logger.error(msg)
231 uuid = self.make_uuid()
234 self.logger.debug("CREATE %s( %s )" % (clazzname, str(args)))
236 self.debuger.dump_create(uuid, clazzname, args)
239 clazz = getattr(self.ns3, clazzname)
241 # arguments starting with 'uuid' identify ns-3 C++
242 # objects and must be replaced by the actual object
243 realargs = self.replace_args(args)
245 obj = clazz(*realargs)
247 self._objects[uuid] = obj
250 self.logger.debug("RET CREATE ( uuid %s ) %s = %s( %s )" % (str(uuid),
251 str(obj), clazzname, str(args)))
256 def invoke(self, uuid, operation, *args, **kwargs):
258 self.logger.debug("INVOKE %s -> %s( %s, %s ) " % (
259 uuid, operation, str(args), str(kwargs)))
265 if operation == "isRunning":
266 result = self.is_running
267 elif operation == "isFinished":
268 result = self.is_finished
269 elif operation == "isAppRunning":
270 result = self._is_app_running(uuid)
272 newuuid = self.make_uuid()
275 self.debuger.dump_invoke(newuuid, uuid, operation, args, kwargs)
278 if operation == "addStaticRoute":
279 result = self._add_static_route(uuid, *args)
281 elif operation == "retrieveObject":
282 result = self._retrieve_object(uuid, *args, **kwargs)
285 if uuid.startswith(SINGLETON):
286 obj = self._singleton(uuid)
288 obj = self.get_object(uuid)
290 method = getattr(obj, operation)
292 # arguments starting with 'uuid' identify ns-3 C++
293 # objects and must be replaced by the actual object
294 realargs = self.replace_args(args)
295 realkwargs = self.replace_kwargs(kwargs)
297 result = method(*realargs, **realkwargs)
299 # If the result is an object (not a base value),
300 # then keep track of the object a return the object
301 # reference (newuuid)
302 if not (result is None or type(result) in [
303 bool, float, long, str, int]):
304 self._objects[newuuid] = result
308 self.logger.debug("RET INVOKE %s%s = %s -> %s(%s, %s) " % (
309 "(uuid %s) " % str(newuuid) if newuuid else "", str(result), uuid,
310 operation, str(args), str(kwargs)))
315 def _set_attr(self, obj, name, ns3_value):
316 obj.SetAttribute(name, ns3_value)
318 def set(self, uuid, name, value):
320 self.logger.debug("SET %s %s %s" % (uuid, name, str(value)))
322 self.debuger.dump_set(uuid, name, value)
325 obj = self.get_object(uuid)
326 type_name = obj.GetInstanceTypeId().GetName()
327 ns3_value = self._attr_from_string_to_ns3_value(type_name, name, value)
329 # If the Simulation thread is not running,
330 # then there will be no thread-safety problems
331 # in changing the value of an attribute directly.
332 # However, if the simulation is running we need
333 # to set the value by scheduling an event, else
334 # we risk to corrupt the state of the
337 event_executed = [False]
340 # schedule the event in the Simulator
341 self._schedule_event(self._condition, event_executed,
342 self._set_attr, obj, name, ns3_value)
344 if not event_executed[0]:
345 self._set_attr(obj, name, ns3_value)
348 self.logger.debug("RET SET %s = %s -> set(%s, %s)" % (str(value), uuid, name,
354 def _get_attr(self, obj, name, ns3_value):
355 obj.GetAttribute(name, ns3_value)
357 def get(self, uuid, name):
359 self.logger.debug("GET %s %s" % (uuid, name))
361 self.debuger.dump_get(uuid, name)
364 obj = self.get_object(uuid)
365 type_name = obj.GetInstanceTypeId().GetName()
366 ns3_value = self._create_attr_ns3_value(type_name, name)
368 event_executed = [False]
371 # schedule the event in the Simulator
372 self._schedule_event(self._condition, event_executed,
373 self._get_attr, obj, name, ns3_value)
375 if not event_executed[0]:
376 self._get_attr(obj, name, ns3_value)
378 result = self._attr_from_ns3_value_to_string(type_name, name, ns3_value)
381 self.logger.debug("RET GET %s = %s -> get(%s)" % (str(result), uuid, name))
388 self.debuger.dump_start()
391 # Launch the simulator thread and Start the
392 # simulator in that thread
393 self._condition = threading.Condition()
394 self._simulator_thread = threading.Thread(
395 target = self._simulator_run,
396 args = [self._condition])
397 self._simulator_thread.setDaemon(True)
398 self._simulator_thread.start()
402 self.logger.debug("START")
405 def stop(self, time = None):
407 self.debuger.dump_stop(time=time)
411 self.ns3.Simulator.Stop()
413 self.ns3.Simulator.Stop(self.ns3.Time(time))
416 self.logger.debug("STOP time=%s" % str(time))
421 self.debuger.dump_shutdown()
424 while not self.ns3.Simulator.IsFinished():
425 #self.logger.debug("Waiting for simulation to finish")
428 if self._simulator_thread:
429 self._simulator_thread.join()
431 self.ns3.Simulator.Destroy()
433 # Remove all references to ns-3 objects
434 self._objects.clear()
440 self.logger.debug("SHUTDOWN")
443 def _simulator_run(self, condition):
445 self.ns3.Simulator.Run()
446 # Signal condition to indicate simulation ended and
447 # notify waiting threads
449 condition.notifyAll()
452 def _schedule_event(self, condition, event_executed, func, *args):
453 """ Schedules event on running simulation, and wait until
456 def execute_event(contextId, condition, event_executed, func, *args):
459 event_executed[0] = True
461 # notify condition indicating event was executed
463 condition.notifyAll()
466 # contextId is defined as general context
467 contextId = long(0xffffffff)
469 # delay 0 means that the event is expected to execute inmediately
470 delay = self.ns3.Seconds(0)
472 # Mark event as not executed
473 event_executed[0] = False
477 self.ns3.Simulator.ScheduleWithContext(contextId, delay, execute_event,
478 condition, event_executed, func, *args)
479 if not self.ns3.Simulator.IsFinished():
484 def _create_attr_ns3_value(self, type_name, name):
485 TypeId = self.ns3.TypeId()
486 tid = TypeId.LookupByName(type_name)
487 info = TypeId.AttributeInformation()
488 if not tid.LookupAttributeByName(name, info):
489 msg = "TypeId %s has no attribute %s" % (type_name, name)
490 self.logger.error(msg)
492 checker = info.checker
493 ns3_value = checker.Create()
496 def _attr_from_ns3_value_to_string(self, type_name, name, ns3_value):
497 TypeId = self.ns3.TypeId()
498 tid = TypeId.LookupByName(type_name)
499 info = TypeId.AttributeInformation()
500 if not tid.LookupAttributeByName(name, info):
501 msg = "TypeId %s has no attribute %s" % (type_name, name)
502 self.logger.error(msg)
504 checker = info.checker
505 value = ns3_value.SerializeToString(checker)
507 type_name = checker.GetValueTypeName()
508 if type_name in ["ns3::UintegerValue", "ns3::IntegerValue"]:
510 if type_name == "ns3::DoubleValue":
512 if type_name == "ns3::BooleanValue":
513 return value == "true"
517 def _attr_from_string_to_ns3_value(self, type_name, name, value):
518 TypeId = self.ns3.TypeId()
519 tid = TypeId.LookupByName(type_name)
520 info = TypeId.AttributeInformation()
521 if not tid.LookupAttributeByName(name, info):
522 msg = "TypeId %s has no attribute %s" % (type_name, name)
523 self.logger.error(msg)
525 str_value = str(value)
526 if isinstance(value, bool):
527 str_value = str_value.lower()
529 checker = info.checker
530 ns3_value = checker.Create()
531 ns3_value.DeserializeFromString(str_value, checker)
534 # singletons are identified as "ns3::ClassName"
535 def _singleton(self, ident):
536 if not ident.startswith(SINGLETON):
539 clazzname = ident[ident.find("::")+2:]
540 if not hasattr(self.ns3, clazzname):
541 msg = "Type %s not supported" % (clazzname)
542 self.logger.error(msg)
544 return getattr(self.ns3, clazzname)
546 # replace uuids and singleton references for the real objects
547 def replace_args(self, args):
548 realargs = [self.get_object(arg) if \
549 str(arg).startswith("uuid") else arg for arg in args]
551 realargs = [self._singleton(arg) if \
552 str(arg).startswith(SINGLETON) else arg for arg in realargs]
556 # replace uuids and singleton references for the real objects
557 def replace_kwargs(self, kwargs):
558 realkwargs = dict([(k, self.get_object(v) \
559 if str(v).startswith("uuid") else v) \
560 for k,v in kwargs.iteritems()])
562 realkwargs = dict([(k, self._singleton(v) \
563 if str(v).startswith(SINGLETON) else v )\
564 for k, v in realkwargs.iteritems()])
568 def _is_app_running(self, uuid):
569 now = self.ns3.Simulator.Now()
573 app = self.get_object(uuid)
574 stop_time_value = self.ns3.TimeValue()
575 app.GetAttribute("StopTime", stop_time_value)
576 stop_time = stop_time_value.Get()
578 start_time_value = self.ns3.TimeValue()
579 app.GetAttribute("StartTime", start_time_value)
580 start_time = start_time_value.Get()
582 if now.Compare(start_time) >= 0 and now.Compare(stop_time) < 0:
587 def _add_static_route(self, ipv4_uuid, network, prefix, nexthop):
588 ipv4 = self.get_object(ipv4_uuid)
590 list_routing = ipv4.GetRoutingProtocol()
591 (static_routing, priority) = list_routing.GetRoutingProtocol(0)
593 ifindex = self._find_ifindex(ipv4, nexthop)
597 nexthop = self.ns3.Ipv4Address(nexthop)
599 if network in ["0.0.0.0", "0", None]:
600 # Default route: 0.0.0.0/0
601 static_routing.SetDefaultRoute(nexthop, ifindex)
603 mask = self.ns3.Ipv4Mask("/%s" % prefix)
604 network = self.ns3.Ipv4Address(network)
607 # Host route: x.y.z.w/32
608 static_routing.AddHostRouteTo(network, nexthop, ifindex)
610 # Network route: x.y.z.w/n
611 static_routing.AddNetworkRouteTo(network, mask, nexthop,
615 def _find_ifindex(self, ipv4, nexthop):
618 nexthop = self.ns3.Ipv4Address(nexthop)
620 # For all the interfaces registered with the ipv4 object, find
621 # the one that matches the network of the nexthop
622 nifaces = ipv4.GetNInterfaces()
623 for ifidx in xrange(nifaces):
624 iface = ipv4.GetInterface(ifidx)
625 naddress = iface.GetNAddresses()
626 for addridx in xrange(naddress):
627 ifaddr = iface.GetAddress(addridx)
628 ifmask = ifaddr.GetMask()
630 ifindex = ipv4.GetInterfaceForPrefix(nexthop, ifmask)
636 def _retrieve_object(self, uuid, typeid, search = False):
637 obj = self.get_object(uuid)
639 type_id = self.ns3.TypeId()
640 tid = type_id.LookupByName(typeid)
641 nobj = obj.GetObject(tid)
646 for ouuid, oobj in self._objects.iteritems():
651 newuuid = self.make_uuid()
652 self._objects[newuuid] = nobj