Bug fixing Netns emulation
[nepi.git] / src / nepi / resources / netns / netnsserver.py
1 #
2 #    NEPI, a framework to manage network experiments
3 #    Copyright (C) 2014 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 base64
21 import cPickle
22 import errno
23 import logging
24 import os
25 import socket
26 import sys
27
28 from optparse import OptionParser, SUPPRESS_HELP
29
30 from netnswrapper import NetNSWrapper
31
32 class NetNSWrapperMessage:
33     CREATE = "CREATE"
34     INVOKE = "INVOKE"
35     SET = "SET"
36     GET = "GET"
37     FLUSH = "FLUSH"
38     SHUTDOWN = "SHUTDOWN"
39
40 def handle_message(wrapper, msg_type, args, kwargs):
41     if msg_type == NetNSWrapperMessage.SHUTDOWN:
42         wrapper.shutdown()
43
44         return "BYEBYE"
45     
46     if msg_type == NetNSWrapperMessage.CREATE:
47         clazzname = args.pop(0)
48         
49         return wrapper.create(clazzname, *args)
50         
51     if msg_type == NetNSWrapperMessage.INVOKE:
52         uuid = args.pop(0)
53         operation = args.pop(0)
54    
55         return wrapper.invoke(uuid, operation, *args, **kwargs)
56
57     if msg_type == NetNSWrapperMessage.GET:
58         uuid = args.pop(0)
59         name = args.pop(0)
60
61         return wrapper.get(uuid, name)
62         
63     if msg_type == NetNSWrapperMessage.SET:
64         uuid = args.pop(0)
65         name = args.pop(0)
66         value = args.pop(0)
67
68         return wrapper.set(uuid, name, value)
69
70     if msg_type == NetNSWrapperMessage.FLUSH:
71         # Forces flushing output and error streams.
72         # NS-3 output will stay unflushed until the program exits or 
73         # explicit invocation flush is done
74         sys.stdout.flush()
75         sys.stderr.flush()
76
77         wrapper.logger.debug("FLUSHED") 
78         
79         return "FLUSHED"
80
81 def create_socket(socket_name):
82     sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
83     sock.bind(socket_name)
84     return sock
85
86 def recv_msg(conn):
87     msg = []
88     chunk = ''
89
90     while '\n' not in chunk:
91         try:
92             chunk = conn.recv(1024)
93         except (OSError, socket.error), e:
94             if e[0] != errno.EINTR:
95                 raise
96             # Ignore eintr errors
97             continue
98
99         if chunk:
100             msg.append(chunk)
101         else:
102             # empty chunk = EOF
103             break
104  
105     msg = ''.join(msg).strip()
106
107     # The message is formatted as follows:
108     #   MESSAGE_TYPE|args|kwargs
109     #
110     #   where MESSAGE_TYPE, args and kwargs are pickld and enoded in base64
111
112     def decode(item):
113         item = base64.b64decode(item).rstrip()
114         return cPickle.loads(item)
115
116     decoded = map(decode, msg.split("|"))
117
118     # decoded message
119     dmsg_type = decoded.pop(0)
120     dargs = list(decoded.pop(0)) # transforming touple into list
121     dkwargs = decoded.pop(0)
122
123     return (dmsg_type, dargs, dkwargs)
124
125 def send_reply(conn, reply):
126     encoded = base64.b64encode(cPickle.dumps(reply))
127     conn.send("%s\n" % encoded)
128
129 def get_options():
130     usage = ("usage: %prog -S <socket-name> -D <enable-dump> -v ")
131     
132     parser = OptionParser(usage = usage)
133
134     parser.add_option("-S", "--socket-name", dest="socket_name",
135         help = "Name for the unix socket used to interact with this process", 
136         default = "tap.sock", type="str")
137
138     parser.add_option("-D", "--enable-dump", dest="enable_dump",
139         help = "Enable dumping the remote executed commands to a script "
140             "in order to later reproduce and debug the experiment",
141         action = "store_true",
142         default = False)
143
144     parser.add_option("-v", "--verbose",
145         help="Print debug output",
146         action="store_true", 
147         dest="verbose", default=False)
148
149     (options, args) = parser.parse_args()
150     
151     return (options.socket_name, options.verbose, options.enable_dump)
152
153 def run_server(socket_name, level = logging.INFO, 
154         enable_dump = False):
155
156     ###### wrapper instantiation
157     if level == logging.DEBUG:
158         from syslog import LOG_DEBUG
159         import netns
160         netns.environ.set_log_level(LOG_DEBUG)
161
162     wrapper = NetNSWrapper(loglevel=level, enable_dump = enable_dump)
163     
164     wrapper.logger.info("STARTING...")
165
166     # create unix socket to receive instructions
167     sock = create_socket(socket_name)
168     sock.listen(0)
169
170     # wait for messages to arrive and process them
171     stop = False
172
173     while not stop:
174         conn, addr = sock.accept()
175         conn.settimeout(5)
176
177         try:
178             (msg_type, args, kwargs) = recv_msg(conn)
179         except socket.timeout, e:
180             # Ingore time-out
181             continue
182
183         if not msg_type:
184             # Ignore - connection lost
185             break
186
187         if msg_type == NetNSWrapperMessage.SHUTDOWN:
188            stop = True
189   
190         try:
191             reply = handle_message(wrapper, msg_type, args, kwargs)  
192         except:
193             import traceback
194             err = traceback.format_exc()
195             wrapper.logger.error(err) 
196             raise
197
198         try:
199             send_reply(conn, reply)
200         except socket.error:
201             break
202         
203     wrapper.logger.info("EXITING...")
204
205 if __name__ == '__main__':
206             
207     (socket_name, verbose, enable_dump) = get_options()
208
209     ## configure logging
210     FORMAT = "%(asctime)s %(name)s %(levelname)-4s %(message)s"
211     level = logging.DEBUG if verbose else logging.INFO
212     
213     logging.basicConfig(format = FORMAT, level = level)
214
215     ## Run the server
216     run_server(socket_name, level, enable_dump)
217