b47f35ad04f72503cbc496f0c74ca712532b37ec
[cascardo/ovs.git] / lib / unixctl.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013, 2014 Nicira, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18 #include "unixctl.h"
19 #include <errno.h>
20 #include <unistd.h>
21 #include "coverage.h"
22 #include "dirs.h"
23 #include "dynamic-string.h"
24 #include "json.h"
25 #include "jsonrpc.h"
26 #include "list.h"
27 #include "poll-loop.h"
28 #include "shash.h"
29 #include "stream.h"
30 #include "stream-provider.h"
31 #include "svec.h"
32 #include "openvswitch/vlog.h"
33
34 VLOG_DEFINE_THIS_MODULE(unixctl);
35
36 COVERAGE_DEFINE(unixctl_received);
37 COVERAGE_DEFINE(unixctl_replied);
38 \f
39 struct unixctl_command {
40     const char *usage;
41     int min_args, max_args;
42     unixctl_cb_func *cb;
43     void *aux;
44 };
45
46 struct unixctl_conn {
47     struct ovs_list node;
48     struct jsonrpc *rpc;
49
50     /* Only one request can be in progress at a time.  While the request is
51      * being processed, 'request_id' is populated, otherwise it is null. */
52     struct json *request_id;   /* ID of the currently active request. */
53 };
54
55 /* Server for control connection. */
56 struct unixctl_server {
57     struct pstream *listener;
58     struct ovs_list conns;
59 };
60
61 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 5);
62
63 static struct shash commands = SHASH_INITIALIZER(&commands);
64
65 static void
66 unixctl_list_commands(struct unixctl_conn *conn, int argc OVS_UNUSED,
67                       const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
68 {
69     struct ds ds = DS_EMPTY_INITIALIZER;
70     const struct shash_node **nodes = shash_sort(&commands);
71     size_t i;
72
73     ds_put_cstr(&ds, "The available commands are:\n");
74
75     for (i = 0; i < shash_count(&commands); i++) {
76         const struct shash_node *node = nodes[i];
77         const struct unixctl_command *command = node->data;
78
79         ds_put_format(&ds, "  %-23s %s\n", node->name, command->usage);
80     }
81     free(nodes);
82
83     unixctl_command_reply(conn, ds_cstr(&ds));
84     ds_destroy(&ds);
85 }
86
87 static void
88 unixctl_version(struct unixctl_conn *conn, int argc OVS_UNUSED,
89                 const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
90 {
91     unixctl_command_reply(conn, ovs_get_program_version());
92 }
93
94 /* Registers a unixctl command with the given 'name'.  'usage' describes the
95  * arguments to the command; it is used only for presentation to the user in
96  * "list-commands" output.
97  *
98  * 'cb' is called when the command is received.  It is passed an array
99  * containing the command name and arguments, plus a copy of 'aux'.  Normally
100  * 'cb' should reply by calling unixctl_command_reply() or
101  * unixctl_command_reply_error() before it returns, but if the command cannot
102  * be handled immediately then it can defer the reply until later.  A given
103  * connection can only process a single request at a time, so a reply must be
104  * made eventually to avoid blocking that connection. */
105 void
106 unixctl_command_register(const char *name, const char *usage,
107                          int min_args, int max_args,
108                          unixctl_cb_func *cb, void *aux)
109 {
110     struct unixctl_command *command;
111     struct unixctl_command *lookup = shash_find_data(&commands, name);
112
113     ovs_assert(!lookup || lookup->cb == cb);
114
115     if (lookup) {
116         return;
117     }
118
119     command = xmalloc(sizeof *command);
120     command->usage = usage;
121     command->min_args = min_args;
122     command->max_args = max_args;
123     command->cb = cb;
124     command->aux = aux;
125     shash_add(&commands, name, command);
126 }
127
128 static void
129 unixctl_command_reply__(struct unixctl_conn *conn,
130                         bool success, const char *body)
131 {
132     struct json *body_json;
133     struct jsonrpc_msg *reply;
134
135     COVERAGE_INC(unixctl_replied);
136     ovs_assert(conn->request_id);
137
138     if (!body) {
139         body = "";
140     }
141
142     if (body[0] && body[strlen(body) - 1] != '\n') {
143         body_json = json_string_create_nocopy(xasprintf("%s\n", body));
144     } else {
145         body_json = json_string_create(body);
146     }
147
148     if (success) {
149         reply = jsonrpc_create_reply(body_json, conn->request_id);
150     } else {
151         reply = jsonrpc_create_error(body_json, conn->request_id);
152     }
153
154     /* If jsonrpc_send() returns an error, the run loop will take care of the
155      * problem eventually. */
156     jsonrpc_send(conn->rpc, reply);
157     json_destroy(conn->request_id);
158     conn->request_id = NULL;
159 }
160
161 /* Replies to the active unixctl connection 'conn'.  'result' is sent to the
162  * client indicating the command was processed successfully.  Only one call to
163  * unixctl_command_reply() or unixctl_command_reply_error() may be made per
164  * request. */
165 void
166 unixctl_command_reply(struct unixctl_conn *conn, const char *result)
167 {
168     unixctl_command_reply__(conn, true, result);
169 }
170
171 /* Replies to the active unixctl connection 'conn'. 'error' is sent to the
172  * client indicating an error occurred processing the command.  Only one call to
173  * unixctl_command_reply() or unixctl_command_reply_error() may be made per
174  * request. */
175 void
176 unixctl_command_reply_error(struct unixctl_conn *conn, const char *error)
177 {
178     unixctl_command_reply__(conn, false, error);
179 }
180
181 /* Creates a unixctl server listening on 'path', which for POSIX may be:
182  *
183  *      - NULL, in which case <rundir>/<program>.<pid>.ctl is used.
184  *
185  *      - A name that does not start with '/', in which case it is put in
186  *        <rundir>.
187  *
188  *      - An absolute path (starting with '/') that gives the exact name of
189  *        the Unix domain socket to listen on.
190  *
191  * For Windows, a kernel assigned TCP port is used and written in 'path'
192  * which may be:
193  *
194  *      - NULL, in which case <rundir>/<program>.ctl is used.
195  *
196  *      - An absolute path that gives the name of the file.
197  *
198  * For both POSIX and Windows, if the path is "none", the function will
199  * return successfully but no socket will actually be created.
200  *
201  * A program that (optionally) daemonizes itself should call this function
202  * *after* daemonization, so that the socket name contains the pid of the
203  * daemon instead of the pid of the program that exited.  (Otherwise,
204  * "ovs-appctl --target=<program>" will fail.)
205  *
206  * Returns 0 if successful, otherwise a positive errno value.  If successful,
207  * sets '*serverp' to the new unixctl_server (or to NULL if 'path' was "none"),
208  * otherwise to NULL. */
209 int
210 unixctl_server_create(const char *path, struct unixctl_server **serverp)
211 {
212     struct unixctl_server *server;
213     struct pstream *listener;
214     char *punix_path;
215     int error;
216
217     *serverp = NULL;
218     if (path && !strcmp(path, "none")) {
219         return 0;
220     }
221
222     if (path) {
223         char *abs_path;
224 #ifndef _WIN32
225         abs_path = abs_file_name(ovs_rundir(), path);
226 #else
227         abs_path = xstrdup(path);
228 #endif
229         punix_path = xasprintf("punix:%s", abs_path);
230         free(abs_path);
231     } else {
232 #ifndef _WIN32
233         punix_path = xasprintf("punix:%s/%s.%ld.ctl", ovs_rundir(),
234                                program_name, (long int) getpid());
235 #else
236         punix_path = xasprintf("punix:%s/%s.ctl", ovs_rundir(), program_name);
237 #endif
238     }
239
240     error = pstream_open(punix_path, &listener, 0);
241     if (error) {
242         ovs_error(error, "could not initialize control socket %s", punix_path);
243         goto exit;
244     }
245
246     unixctl_command_register("list-commands", "", 0, 0, unixctl_list_commands,
247                              NULL);
248     unixctl_command_register("version", "", 0, 0, unixctl_version, NULL);
249
250     server = xmalloc(sizeof *server);
251     server->listener = listener;
252     list_init(&server->conns);
253     *serverp = server;
254
255 exit:
256     free(punix_path);
257     return error;
258 }
259
260 static void
261 process_command(struct unixctl_conn *conn, struct jsonrpc_msg *request)
262 {
263     char *error = NULL;
264
265     struct unixctl_command *command;
266     struct json_array *params;
267
268     COVERAGE_INC(unixctl_received);
269     conn->request_id = json_clone(request->id);
270
271     params = json_array(request->params);
272     command = shash_find_data(&commands, request->method);
273     if (!command) {
274         error = xasprintf("\"%s\" is not a valid command", request->method);
275     } else if (params->n < command->min_args) {
276         error = xasprintf("\"%s\" command requires at least %d arguments",
277                           request->method, command->min_args);
278     } else if (params->n > command->max_args) {
279         error = xasprintf("\"%s\" command takes at most %d arguments",
280                           request->method, command->max_args);
281     } else {
282         struct svec argv = SVEC_EMPTY_INITIALIZER;
283         int  i;
284
285         svec_add(&argv, request->method);
286         for (i = 0; i < params->n; i++) {
287             if (params->elems[i]->type != JSON_STRING) {
288                 error = xasprintf("\"%s\" command has non-string argument",
289                                   request->method);
290                 break;
291             }
292             svec_add(&argv, json_string(params->elems[i]));
293         }
294         svec_terminate(&argv);
295
296         if (!error) {
297             command->cb(conn, argv.n, (const char **) argv.names,
298                         command->aux);
299         }
300
301         svec_destroy(&argv);
302     }
303
304     if (error) {
305         unixctl_command_reply_error(conn, error);
306         free(error);
307     }
308 }
309
310 static int
311 run_connection(struct unixctl_conn *conn)
312 {
313     int error, i;
314
315     jsonrpc_run(conn->rpc);
316     error = jsonrpc_get_status(conn->rpc);
317     if (error || jsonrpc_get_backlog(conn->rpc)) {
318         return error;
319     }
320
321     for (i = 0; i < 10; i++) {
322         struct jsonrpc_msg *msg;
323
324         if (error || conn->request_id) {
325             break;
326         }
327
328         jsonrpc_recv(conn->rpc, &msg);
329         if (msg) {
330             if (msg->type == JSONRPC_REQUEST) {
331                 process_command(conn, msg);
332             } else {
333                 VLOG_WARN_RL(&rl, "%s: received unexpected %s message",
334                              jsonrpc_get_name(conn->rpc),
335                              jsonrpc_msg_type_to_string(msg->type));
336                 error = EINVAL;
337             }
338             jsonrpc_msg_destroy(msg);
339         }
340         error = error ? error : jsonrpc_get_status(conn->rpc);
341     }
342
343     return error;
344 }
345
346 static void
347 kill_connection(struct unixctl_conn *conn)
348 {
349     list_remove(&conn->node);
350     jsonrpc_close(conn->rpc);
351     json_destroy(conn->request_id);
352     free(conn);
353 }
354
355 void
356 unixctl_server_run(struct unixctl_server *server)
357 {
358     struct unixctl_conn *conn, *next;
359     int i;
360
361     if (!server) {
362         return;
363     }
364
365     for (i = 0; i < 10; i++) {
366         struct stream *stream;
367         int error;
368
369         error = pstream_accept(server->listener, &stream);
370         if (!error) {
371             struct unixctl_conn *conn = xzalloc(sizeof *conn);
372             list_push_back(&server->conns, &conn->node);
373             conn->rpc = jsonrpc_open(stream);
374         } else if (error == EAGAIN) {
375             break;
376         } else {
377             VLOG_WARN_RL(&rl, "%s: accept failed: %s",
378                          pstream_get_name(server->listener),
379                          ovs_strerror(error));
380         }
381     }
382
383     LIST_FOR_EACH_SAFE (conn, next, node, &server->conns) {
384         int error = run_connection(conn);
385         if (error && error != EAGAIN) {
386             kill_connection(conn);
387         }
388     }
389 }
390
391 void
392 unixctl_server_wait(struct unixctl_server *server)
393 {
394     struct unixctl_conn *conn;
395
396     if (!server) {
397         return;
398     }
399
400     pstream_wait(server->listener);
401     LIST_FOR_EACH (conn, node, &server->conns) {
402         jsonrpc_wait(conn->rpc);
403         if (!jsonrpc_get_backlog(conn->rpc)) {
404             jsonrpc_recv_wait(conn->rpc);
405         }
406     }
407 }
408
409 /* Destroys 'server' and stops listening for connections. */
410 void
411 unixctl_server_destroy(struct unixctl_server *server)
412 {
413     if (server) {
414         struct unixctl_conn *conn, *next;
415
416         LIST_FOR_EACH_SAFE (conn, next, node, &server->conns) {
417             kill_connection(conn);
418         }
419
420         pstream_close(server->listener);
421         free(server);
422     }
423 }
424 \f
425 /* On POSIX based systems, connects to a unixctl server socket.  'path' should
426  * be the name of a unixctl server socket.  If it does not start with '/', it
427  * will be prefixed with the rundir (e.g. /usr/local/var/run/openvswitch).
428  *
429  * On Windows, connects to a localhost TCP port as written inside 'path'.
430  * 'path' should be an absolute path of the file.
431  *
432  * Returns 0 if successful, otherwise a positive errno value.  If successful,
433  * sets '*client' to the new jsonrpc, otherwise to NULL. */
434 int
435 unixctl_client_create(const char *path, struct jsonrpc **client)
436 {
437     char *abs_path, *unix_path;
438     struct stream *stream;
439     int error;
440
441 #ifdef _WIN32
442     abs_path = xstrdup(path);
443 #else
444     abs_path = abs_file_name(ovs_rundir(), path);
445 #endif
446     unix_path = xasprintf("unix:%s", abs_path);
447
448     *client = NULL;
449
450     error = stream_open_block(stream_open(unix_path, &stream, DSCP_DEFAULT),
451                               &stream);
452     free(unix_path);
453     free(abs_path);
454
455     if (error) {
456         VLOG_WARN("failed to connect to %s", path);
457         return error;
458     }
459
460     *client = jsonrpc_open(stream);
461     return 0;
462 }
463
464 /* Executes 'command' on the server with an argument vector 'argv' containing
465  * 'argc' elements.  If successfully communicated with the server, returns 0
466  * and sets '*result', or '*err' (not both) to the result or error the server
467  * returned.  Otherwise, sets '*result' and '*err' to NULL and returns a
468  * positive errno value.  The caller is responsible for freeing '*result' or
469  * '*err' if not NULL. */
470 int
471 unixctl_client_transact(struct jsonrpc *client, const char *command, int argc,
472                         char *argv[], char **result, char **err)
473 {
474     struct jsonrpc_msg *request, *reply;
475     struct json **json_args, *params;
476     int error, i;
477
478     *result = NULL;
479     *err = NULL;
480
481     json_args = xmalloc(argc * sizeof *json_args);
482     for (i = 0; i < argc; i++) {
483         json_args[i] = json_string_create(argv[i]);
484     }
485     params = json_array_create(json_args, argc);
486     request = jsonrpc_create_request(command, params, NULL);
487
488     error = jsonrpc_transact_block(client, request, &reply);
489     if (error) {
490         VLOG_WARN("error communicating with %s: %s", jsonrpc_get_name(client),
491                   ovs_retval_to_string(error));
492         return error;
493     }
494
495     if (reply->error) {
496         if (reply->error->type == JSON_STRING) {
497             *err = xstrdup(json_string(reply->error));
498         } else {
499             VLOG_WARN("%s: unexpected error type in JSON RPC reply: %s",
500                       jsonrpc_get_name(client),
501                       json_type_to_string(reply->error->type));
502             error = EINVAL;
503         }
504     } else if (reply->result) {
505         if (reply->result->type == JSON_STRING) {
506             *result = xstrdup(json_string(reply->result));
507         } else {
508             VLOG_WARN("%s: unexpected result type in JSON rpc reply: %s",
509                       jsonrpc_get_name(client),
510                       json_type_to_string(reply->result->type));
511             error = EINVAL;
512         }
513     }
514
515     jsonrpc_msg_destroy(reply);
516     return error;
517 }