2 # NEPI, a framework to manage network experiments
3 # Copyright (C) 2014 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>
28 from optparse import OptionParser, SUPPRESS_HELP
30 from netnswrapper import NetNSWrapper
32 class NetNSWrapperMessage:
40 def handle_message(wrapper, msg_type, args, kwargs):
41 if msg_type == NetNSWrapperMessage.SHUTDOWN:
46 if msg_type == NetNSWrapperMessage.CREATE:
47 clazzname = args.pop(0)
49 return wrapper.create(clazzname, *args)
51 if msg_type == NetNSWrapperMessage.INVOKE:
53 operation = args.pop(0)
55 return wrapper.invoke(uuid, operation, *args, **kwargs)
57 if msg_type == NetNSWrapperMessage.GET:
61 return wrapper.get(uuid, name)
63 if msg_type == NetNSWrapperMessage.SET:
68 return wrapper.set(uuid, name, value)
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
77 wrapper.logger.debug("FLUSHED")
81 def create_socket(socket_name):
82 sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
83 sock.bind(socket_name)
90 while '\n' not in chunk:
92 chunk = conn.recv(1024)
93 except (OSError, socket.error), e:
94 if e[0] != errno.EINTR:
105 msg = ''.join(msg).strip()
107 # The message is formatted as follows:
108 # MESSAGE_TYPE|args|kwargs
110 # where MESSAGE_TYPE, args and kwargs are pickld and enoded in base64
113 item = base64.b64decode(item).rstrip()
114 return cPickle.loads(item)
116 decoded = map(decode, msg.split("|"))
119 dmsg_type = decoded.pop(0)
120 dargs = list(decoded.pop(0)) # transforming touple into list
121 dkwargs = decoded.pop(0)
123 return (dmsg_type, dargs, dkwargs)
125 def send_reply(conn, reply):
126 encoded = base64.b64encode(cPickle.dumps(reply))
127 conn.send("%s\n" % encoded)
130 usage = ("usage: %prog -S <socket-name> -L <ns-log> -D <enable-dump> -v ")
132 parser = OptionParser(usage = usage)
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")
138 parser.add_option("-L", "--ns-log", dest="ns_log",
139 help = "NS_LOG environmental variable to be set",
140 default = "", type="str")
142 parser.add_option("-D", "--enable-dump", dest="enable_dump",
143 help = "Enable dumping the remote executed ns-3 commands to a script "
144 "in order to later reproduce and debug the experiment",
145 action = "store_true",
148 parser.add_option("-v", "--verbose",
149 help="Print debug output",
151 dest="verbose", default=False)
153 (options, args) = parser.parse_args()
155 return (options.socket_name, options.verbose, options.ns_log,
158 def run_server(socket_name, level = logging.INFO, ns_log = None,
159 enable_dump = False):
161 # Sets NS_LOG environmental variable for NS debugging
163 os.environ["NS_LOG"] = ns_log
165 ###### ns-3 wrapper instantiation
167 wrapper = NetNSWrapper(loglevel=level, enable_dump = enable_dump)
169 wrapper.logger.info("STARTING...")
171 # create unix socket to receive instructions
172 sock = create_socket(socket_name)
175 # wait for messages to arrive and process them
179 conn, addr = sock.accept()
183 (msg_type, args, kwargs) = recv_msg(conn)
184 except socket.timeout, e:
189 # Ignore - connection lost
192 if msg_type == NetNSWrapperMessage.SHUTDOWN:
196 reply = handle_message(wrapper, msg_type, args, kwargs)
199 err = traceback.format_exc()
200 wrapper.logger.error(err)
204 send_reply(conn, reply)
208 wrapper.logger.info("EXITING...")
210 if __name__ == '__main__':
212 (socket_name, verbose, ns_log, enable_dump) = get_options()
215 FORMAT = "%(asctime)s %(name)s %(levelname)-4s %(message)s"
216 level = logging.DEBUG if verbose else logging.INFO
218 logging.basicConfig(format = FORMAT, level = level)
221 run_server(socket_name, level, ns_log, enable_dump)