1 # Copyright (c) 2012 Nicira Networks
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at:
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
28 Message = ovs.jsonrpc.Message
29 vlog = ovs.vlog.Vlog("unixctl")
31 strtypes = types.StringTypes
34 class _UnixctlCommand(object):
35 def __init__(self, usage, min_args, max_args, callback, aux):
37 self.min_args = min_args
38 self.max_args = max_args
39 self.callback = callback
43 def _unixctl_help(conn, unused_argv, unused_aux):
44 assert isinstance(conn, UnixctlConnection)
45 reply = "The available commands are:\n"
46 command_names = sorted(commands.keys())
47 for name in command_names:
49 usage = commands[name].usage
51 reply += "%-23s %s" % (name, usage)
58 def _unixctl_version(conn, unused_argv, unused_aux):
59 assert isinstance(conn, UnixctlConnection)
60 version = "%s (Open vSwitch) %s" % (ovs.util.PROGRAM_NAME,
65 def command_register(name, usage, min_args, max_args, callback, aux):
66 """ Registers a command with the given 'name' to be exposed by the
67 UnixctlServer. 'usage' describes the arguments to the command; it is used
68 only for presentation to the user in "help" output.
70 'callback' is called when the command is received. It is passed a
71 UnixctlConnection object, the list of arguments as unicode strings, and
72 'aux'. Normally 'callback' should reply by calling
73 UnixctlConnection.reply() or UnixctlConnection.reply_error() before it
74 returns, but if the command cannot be handled immediately, then it can
75 defer the reply until later. A given connection can only process a single
76 request at a time, so a reply must be made eventually to avoid blocking
79 assert isinstance(name, strtypes)
80 assert isinstance(usage, strtypes)
81 assert isinstance(min_args, int)
82 assert isinstance(max_args, int)
83 assert isinstance(callback, types.FunctionType)
85 if name not in commands:
86 commands[name] = _UnixctlCommand(usage, min_args, max_args, callback,
90 def socket_name_from_target(target):
91 assert isinstance(target, strtypes)
93 if target.startswith("/"):
96 pidfile_name = "%s/%s.pid" % (ovs.dirs.RUNDIR, target)
97 pid = ovs.daemon.read_pidfile(pidfile_name)
99 return -pid, "cannot read pidfile \"%s\"" % pidfile_name
101 return 0, "%s/%s.%d.ctl" % (ovs.dirs.RUNDIR, target, pid)
104 class UnixctlConnection(object):
105 def __init__(self, rpc):
106 assert isinstance(rpc, ovs.jsonrpc.Connection)
108 self._request_id = None
112 error = self._rpc.get_status()
113 if error or self._rpc.get_backlog():
117 if error or self._request_id:
120 error, msg = self._rpc.recv()
122 if msg.type == Message.T_REQUEST:
123 self._process_command(msg)
126 vlog.warn("%s: received unexpected %s message"
128 Message.type_to_string(msg.type)))
132 error = self._rpc.get_status()
136 def reply(self, body):
137 self._reply_impl(True, body)
139 def reply_error(self, body):
140 self._reply_impl(False, body)
142 # Called only by unixctl classes.
145 self._request_id = None
147 def _wait(self, poller):
148 self._rpc.wait(poller)
149 if not self._rpc.get_backlog():
150 self._rpc.recv_wait(poller)
152 def _reply_impl(self, success, body):
153 assert isinstance(success, bool)
154 assert body is None or isinstance(body, strtypes)
156 assert self._request_id is not None
161 if body and not body.endswith("\n"):
165 reply = Message.create_reply(body, self._request_id)
167 reply = Message.create_error(body, self._request_id)
169 self._rpc.send(reply)
170 self._request_id = None
172 def _process_command(self, request):
173 assert isinstance(request, ovs.jsonrpc.Message)
174 assert request.type == ovs.jsonrpc.Message.T_REQUEST
176 self._request_id = request.id
179 params = request.params
180 method = request.method
181 command = commands.get(method)
183 error = '"%s" is not a valid command' % method
184 elif len(params) < command.min_args:
185 error = '"%s" command requires at least %d arguments' \
186 % (method, command.min_args)
187 elif len(params) > command.max_args:
188 error = '"%s" command takes at most %d arguments' \
189 % (method, command.max_args)
192 if not isinstance(param, strtypes):
193 error = '"%s" command has non-string argument' % method
197 unicode_params = [unicode(p) for p in params]
198 command.callback(self, unicode_params, command.aux)
201 self.reply_error(error)
204 class UnixctlServer(object):
205 def __init__(self, listener):
206 assert isinstance(listener, ovs.stream.PassiveStream)
207 self._listener = listener
212 error, stream = self._listener.accept()
214 rpc = ovs.jsonrpc.Connection(stream)
215 self._conns.append(UnixctlConnection(rpc))
216 elif error == errno.EAGAIN:
220 vlog.warn("%s: accept failed: %s" % (self._listener.name,
223 for conn in copy.copy(self._conns):
225 if error and error != errno.EAGAIN:
227 self._conns.remove(conn)
229 def wait(self, poller):
230 self._listener.wait(poller)
231 for conn in self._conns:
235 for conn in self._conns:
239 self._listener.close()
240 self._listener = None
244 assert path is None or isinstance(path, strtypes)
247 path = "punix:%s" % ovs.util.abs_file_name(ovs.dirs.RUNDIR, path)
249 path = "punix:%s/%s.%d.ctl" % (ovs.dirs.RUNDIR,
250 ovs.util.PROGRAM_NAME, os.getpid())
252 error, listener = ovs.stream.PassiveStream.open(path)
254 ovs.util.ovs_error(error, "could not initialize control socket %s"
258 command_register("help", "", 0, 0, _unixctl_help, None)
259 command_register("version", "", 0, 0, _unixctl_version, None)
261 return 0, UnixctlServer(listener)
264 class UnixctlClient(object):
265 def __init__(self, conn):
266 assert isinstance(conn, ovs.jsonrpc.Connection)
269 def transact(self, command, argv):
270 assert isinstance(command, strtypes)
271 assert isinstance(argv, list)
273 assert isinstance(arg, strtypes)
275 request = Message.create_request(command, argv)
276 error, reply = self._conn.transact_block(request)
279 vlog.warn("error communicating with %s: %s"
280 % (self._conn.name, os.strerror(error)))
281 return error, None, None
283 if reply.error is not None:
284 return 0, str(reply.error), None
286 assert reply.result is not None
287 return 0, None, str(reply.result)
295 assert isinstance(path, str)
297 unix = "unix:%s" % ovs.util.abs_file_name(ovs.dirs.RUNDIR, path)
298 error, stream = ovs.stream.Stream.open_block(
299 ovs.stream.Stream.open(unix))
302 vlog.warn("failed to connect to %s" % path)
305 return 0, UnixctlClient(ovs.jsonrpc.Connection(stream))