Ignoring error on NETNSWrapper when NETNS is not instaled
[nepi.git] / src / nepi / resources / netns / netnswrapper.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 time
22 import os
23 import sys
24 import uuid
25
26 try:
27     import netns
28 except ImportError:
29     pass
30
31 class NetNSWrapper(object):
32     def __init__(self, loglevel = logging.INFO, enable_dump = False):
33         super(NetNSWrapper, self).__init__()
34         # holds reference to all C++ objects and variables in the simulation
35         self._objects = dict()
36
37         # Logging
38         self._logger = logging.getLogger("netnswrapper")
39         self._logger.setLevel(loglevel)
40
41         # Object to dump instructions to reproduce and debug experiment
42         from netnswrapper_debug import NetNSWrapperDebuger
43         self._debuger = NetNSWrapperDebuger(enabled = enable_dump)
44
45     @property
46     def debuger(self):
47         return self._debuger
48
49     @property
50     def logger(self):
51         return self._logger
52
53     def make_uuid(self):
54         return "uuid%s" % uuid.uuid4()
55
56     def get_object(self, uuid):
57         return self._objects.get(uuid)
58  
59     def create(self, clazzname, *args):
60         """ This method should be used to construct netns objects """
61
62         if clazzname not in ['open'] and not hasattr(netns, clazzname):
63             msg = "Type %s not supported" % (clazzname) 
64             self.logger.error(msg)
65
66         uuid = self.make_uuid()
67         
68         ### DEBUG
69         self.logger.debug("CREATE %s( %s )" % (clazzname, str(args)))
70     
71         self.debuger.dump_create(uuid, clazzname, args)
72         ########
73
74         if clazzname == "open":
75             path = args[0] 
76             mode = args[1] 
77             obj = open(path, mode)
78         else:
79             clazz = getattr(netns, clazzname)
80      
81             # arguments starting with 'uuid' identify ns-3 C++
82             # objects and must be replaced by the actual object
83             realargs = self.replace_args(args)
84            
85             obj = clazz(*realargs)
86             
87         self._objects[uuid] = obj
88
89         ### DEBUG
90         self.logger.debug("RET CREATE ( uuid %s ) %s = %s( %s )" % (str(uuid), 
91             str(obj), clazzname, str(args)))
92         ########
93
94         return uuid
95
96     def invoke(self, uuid, operation, *args, **kwargs):
97         newuuid = self.make_uuid()
98         
99         ### DEBUG
100         self.logger.debug("INVOKE %s -> %s( %s, %s ) " % (
101             uuid, operation, str(args), str(kwargs)))
102             
103         self.debuger.dump_invoke(newuuid, uuid, operation, args, kwargs)
104         ########
105
106         obj = self.get_object(uuid)
107         
108         method = getattr(obj, operation)
109
110         # arguments starting with 'uuid' identify netns
111         # objects and must be replaced by the actual object
112         realargs = self.replace_args(args)
113         realkwargs = self.replace_kwargs(kwargs)
114
115         result = method(*realargs, **realkwargs)
116
117         # If the result is an object (not a base value),
118         # then keep track of the object a return the object
119         # reference (newuuid)
120         if not (result is None or type(result) in [
121                 bool, float, long, str, int]):
122             self._objects[newuuid] = result
123             result = newuuid
124
125         ### DEBUG
126         self.logger.debug("RET INVOKE %s%s = %s -> %s(%s, %s) " % (
127             "(uuid %s) " % str(newuuid) if newuuid else "", str(result), uuid, 
128             operation, str(args), str(kwargs)))
129         ########
130
131         return result
132
133     def set(self, uuid, name, value):
134         ### DEBUG
135         self.logger.debug("SET %s %s %s" % (uuid, name, str(value)))
136     
137         self.debuger.dump_set(uuid, name, value)
138         ########
139
140         obj = self.get_object(uuid)
141         setattr(obj, name, value)
142
143         ### DEBUG
144         self.logger.debug("RET SET %s = %s -> set(%s, %s)" % (str(value), uuid, name, 
145             str(value)))
146         ########
147
148         return value
149
150     def get(self, uuid, name):
151         ### DEBUG
152         self.logger.debug("GET %s %s" % (uuid, name))
153         
154         self.debuger.dump_get(uuid, name)
155         ########
156
157         obj = self.get_object(uuid)
158         result = getattr(obj, name)
159
160         ### DEBUG
161         self.logger.debug("RET GET %s = %s -> get(%s)" % (str(result), uuid, name))
162         ########
163
164         return result
165
166     def shutdown(self):
167         ### DEBUG
168         self.debuger.dump_shutdown()
169         ########
170
171         sys.stdout.flush()
172         sys.stderr.flush()
173
174         ### DEBUG
175         self.logger.debug("SHUTDOWN")
176         ########
177
178     def replace_args(self, args):
179         realargs = [self.get_object(arg) if \
180                 str(arg).startswith("uuid") else arg for arg in args]
181  
182         return realargs
183
184     def replace_kwargs(self, kwargs):
185         realkwargs = dict([(k, self.get_object(v) \
186                 if str(v).startswith("uuid") else v) \
187                 for k,v in kwargs.iteritems()])
188  
189         return realkwargs
190