ovsdb-client: Support listening for incoming connections too.
[cascardo/ovs.git] / ovsdb / ovsdb-client.c
1 /*
2  * Copyright (c) 2009 Nicira Networks.
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
19 #include <errno.h>
20 #include <getopt.h>
21 #include <limits.h>
22 #include <signal.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <unistd.h>
26
27 #include "command-line.h"
28 #include "column.h"
29 #include "compiler.h"
30 #include "dynamic-string.h"
31 #include "json.h"
32 #include "jsonrpc.h"
33 #include "ovsdb.h"
34 #include "ovsdb-error.h"
35 #include "stream.h"
36 #include "table.h"
37 #include "timeval.h"
38 #include "util.h"
39
40 #include "vlog.h"
41 #define THIS_MODULE VLM_ovsdb_client
42
43 /* --format: Output formatting. */
44 static enum {
45     FMT_TABLE,                  /* Textual table. */
46     FMT_HTML,                   /* HTML table. */
47     FMT_CSV                     /* Comma-separated lines. */
48 } output_format;
49
50 /* --wide: For --format=table, the maximum output width. */
51 static int output_width;
52
53 /* --no-headings: Whether table output should include headings. */
54 static int output_headings = true;
55
56 static const struct command all_commands[];
57
58 static void usage(void) NO_RETURN;
59 static void parse_options(int argc, char *argv[]);
60
61 int
62 main(int argc, char *argv[])
63 {
64     set_program_name(argv[0]);
65     time_init();
66     vlog_init();
67     parse_options(argc, argv);
68     signal(SIGPIPE, SIG_IGN);
69     run_command(argc - optind, argv + optind, all_commands);
70     return 0;
71 }
72
73 static void
74 parse_options(int argc, char *argv[])
75 {
76     static struct option long_options[] = {
77         {"wide", no_argument, &output_width, INT_MAX},
78         {"format", required_argument, 0, 'f'},
79             {"no-headings", no_argument, &output_headings, 0},
80         {"verbose", optional_argument, 0, 'v'},
81         {"help", no_argument, 0, 'h'},
82         {"version", no_argument, 0, 'V'},
83         {0, 0, 0, 0},
84     };
85     char *short_options = long_options_to_short_options(long_options);
86
87     output_width = isatty(fileno(stdout)) ? 79 : INT_MAX;
88     for (;;) {
89         int c;
90
91         c = getopt_long(argc, argv, short_options, long_options, NULL);
92         if (c == -1) {
93             break;
94         }
95
96         switch (c) {
97         case 'f':
98             if (!strcmp(optarg, "table")) {
99                 output_format = FMT_TABLE;
100             } else if (!strcmp(optarg, "html")) {
101                 output_format = FMT_HTML;
102             } else if (!strcmp(optarg, "csv")) {
103                 output_format = FMT_CSV;
104             } else {
105                 ovs_fatal(0, "unknown output format \"%s\"", optarg);
106             }
107             break;
108
109         case 'w':
110             output_width = INT_MAX;
111             break;
112
113         case 'h':
114             usage();
115
116         case 'V':
117             OVS_PRINT_VERSION(0, 0);
118             exit(EXIT_SUCCESS);
119
120         case 'v':
121             vlog_set_verbosity(optarg);
122             break;
123
124         case '?':
125             exit(EXIT_FAILURE);
126
127         case 0:
128             /* getopt_long() already set the value for us. */
129             break;
130
131         default:
132             abort();
133         }
134     }
135     free(short_options);
136 }
137
138 static void
139 usage(void)
140 {
141     printf("%s: Open vSwitch database JSON-RPC client\n"
142            "usage: %s [OPTIONS] COMMAND [ARG...]\n"
143            "\nValid commands are:\n"
144            "\n  get-schema SERVER\n"
145            "    retrieve schema from SERVER\n"
146            "\n  list-tables SERVER\n"
147            "    list SERVER's tables\n"
148            "\n  list-columns SERVER [TABLE]\n"
149            "    list columns in TABLE (or all tables) on SERVER\n",
150            program_name, program_name);
151     stream_usage("SERVER", true, true);
152     printf("\nOutput formatting options:\n"
153            "  -f, --format=FORMAT         set output formatting to FORMAT\n"
154            "                              (\"table\", \"html\", or \"csv\"\n"
155            "  --wide                      don't limit TTY lines to 79 bytes\n"
156            "  --no-headings               omit table heading row\n");
157     vlog_usage();
158     printf("\nOther options:\n"
159            "  -h, --help                  display this help message\n"
160            "  -V, --version               display version information\n");
161     exit(EXIT_SUCCESS);
162 }
163 \f
164 static struct jsonrpc *
165 open_jsonrpc(const char *server)
166 {
167     struct stream *stream;
168     int error;
169
170     error = stream_open_block(server, &stream);
171     if (error == EAFNOSUPPORT) {
172         struct pstream *pstream;
173
174         error = pstream_open(server, &pstream);
175         if (error) {
176             ovs_fatal(error, "failed to connect or listen to \"%s\"", server);
177         }
178
179         VLOG_INFO("%s: waiting for connection...", server);
180         error = pstream_accept_block(pstream, &stream);
181         if (error) {
182             ovs_fatal(error, "failed to accept connection on \"%s\"", server);
183         }
184
185         pstream_close(pstream);
186     } else if (error) {
187         ovs_fatal(error, "failed to connect to \"%s\"", server);
188     }
189
190     return jsonrpc_open(stream);
191 }
192
193 static void
194 print_json(struct json *json)
195 {
196     char *string = json_to_string(json, JSSF_SORT);
197     fputs(string, stdout);
198     free(string);
199 }
200
201 static void
202 print_and_free_json(struct json *json)
203 {
204     print_json(json);
205     json_destroy(json);
206 }
207
208 static void
209 check_ovsdb_error(struct ovsdb_error *error)
210 {
211     if (error) {
212         ovs_fatal(0, "%s", ovsdb_error_to_string(error));
213     }
214 }
215
216 static struct ovsdb_schema *
217 fetch_schema(const char *server)
218 {
219     struct jsonrpc_msg *request, *reply;
220     struct ovsdb_schema *schema;
221     struct jsonrpc *rpc;
222     int error;
223
224     rpc = open_jsonrpc(server);
225     request = jsonrpc_create_request("get_schema", json_array_create_empty());
226     error = jsonrpc_transact_block(rpc, request, &reply);
227     if (error) {
228         ovs_fatal(error, "transaction failed");
229     }
230     check_ovsdb_error(ovsdb_schema_from_json(reply->result, &schema));
231     jsonrpc_msg_destroy(reply);
232     jsonrpc_close(rpc);
233
234     return schema;
235 }
236 \f
237 struct column {
238     char *heading;
239     int width;
240 };
241
242 struct table {
243     char **cells;
244     struct column *columns;
245     size_t n_columns, allocated_columns;
246     size_t n_rows, allocated_rows;
247     size_t current_column;
248 };
249
250 static void
251 table_init(struct table *table)
252 {
253     memset(table, 0, sizeof *table);
254 }
255
256 static void
257 table_add_column(struct table *table, const char *heading, ...)
258     PRINTF_FORMAT(2, 3);
259
260 static void
261 table_add_column(struct table *table, const char *heading, ...)
262 {
263     struct column *column;
264     va_list args;
265
266     assert(!table->n_rows);
267     if (table->n_columns >= table->allocated_columns) {
268         table->columns = x2nrealloc(table->columns, &table->allocated_columns,
269                                     sizeof *table->columns);
270     }
271     column = &table->columns[table->n_columns++];
272
273     va_start(args, heading);
274     column->heading = xvasprintf(heading, args);
275     column->width = strlen(column->heading);
276     va_end(args);
277 }
278
279 static char **
280 table_cell__(const struct table *table, size_t row, size_t column)
281 {
282     return &table->cells[column + row * table->n_columns];
283 }
284
285 static void
286 table_add_row(struct table *table)
287 {
288     size_t x, y;
289
290     if (table->n_rows >= table->allocated_rows) {
291         table->cells = x2nrealloc(table->cells, &table->allocated_rows,
292                                   table->n_columns * sizeof *table->cells);
293     }
294
295     y = table->n_rows++;
296     table->current_column = 0;
297     for (x = 0; x < table->n_columns; x++) {
298         *table_cell__(table, y, x) = NULL;
299     }
300 }
301
302 static void
303 table_add_cell_nocopy(struct table *table, char *s)
304 {
305     size_t x, y;
306     int length;
307
308     assert(table->n_rows > 0);
309     assert(table->current_column < table->n_columns);
310
311     x = table->current_column++;
312     y = table->n_rows - 1;
313     *table_cell__(table, y, x) = s;
314
315     length = strlen(s);
316     if (length > table->columns[x].width) {
317         table->columns[x].width = length;
318     }
319 }
320
321 static void
322 table_add_cell(struct table *table, const char *format, ...)
323 {
324     va_list args;
325
326     va_start(args, format);
327     table_add_cell_nocopy(table, xvasprintf(format, args));
328     va_end(args);
329 }
330
331 static void
332 table_print_table_line__(struct ds *line, size_t max_width)
333 {
334     ds_truncate(line, max_width);
335     puts(ds_cstr(line));
336     ds_clear(line);
337 }
338
339 static void
340 table_print_table__(const struct table *table)
341 {
342     struct ds line = DS_EMPTY_INITIALIZER;
343     size_t x, y;
344
345     if (output_headings) {
346         for (x = 0; x < table->n_columns; x++) {
347             const struct column *column = &table->columns[x];
348             if (x) {
349                 ds_put_char(&line, ' ');
350             }
351             ds_put_format(&line, "%-*s", column->width, column->heading);
352         }
353         table_print_table_line__(&line, output_width);
354
355         for (x = 0; x < table->n_columns; x++) {
356             const struct column *column = &table->columns[x];
357             int i;
358
359             if (x) {
360                 ds_put_char(&line, ' ');
361             }
362             for (i = 0; i < column->width; i++) {
363                 ds_put_char(&line, '-');
364             }
365         }
366         table_print_table_line__(&line, output_width);
367     }
368
369     for (y = 0; y < table->n_rows; y++) {
370         for (x = 0; x < table->n_columns; x++) {
371             const char *cell = *table_cell__(table, y, x);
372             if (x) {
373                 ds_put_char(&line, ' ');
374             }
375             ds_put_format(&line, "%-*s", table->columns[x].width, cell);
376         }
377         table_print_table_line__(&line, output_width);
378     }
379
380     ds_destroy(&line);
381 }
382
383 static void
384 table_print_html_cell__(const char *element, const char *content)
385 {
386     const char *p;
387
388     printf("    <%s>", element);
389     for (p = content; *p != '\0'; p++) {
390         switch (*p) {
391         case '&':
392             fputs("&amp;", stdout);
393             break;
394         case '<':
395             fputs("&lt;", stdout);
396             break;
397         case '>':
398             fputs("&gt;", stdout);
399             break;
400         default:
401             putchar(*p);
402             break;
403         }
404     }
405     printf("</%s>\n", element);
406 }
407
408 static void
409 table_print_html__(const struct table *table)
410 {
411     size_t x, y;
412
413     fputs("<table>\n", stdout);
414
415     if (output_headings) {
416         fputs("  <tr>\n", stdout);
417         for (x = 0; x < table->n_columns; x++) {
418             const struct column *column = &table->columns[x];
419             table_print_html_cell__("th", column->heading);
420         }
421         fputs("  </tr>\n", stdout);
422     }
423
424     for (y = 0; y < table->n_rows; y++) {
425         fputs("  <tr>\n", stdout);
426         for (x = 0; x < table->n_columns; x++) {
427             table_print_html_cell__("td", *table_cell__(table, y, x));
428         }
429         fputs("  </tr>\n", stdout);
430     }
431
432     fputs("</table>\n", stdout);
433 }
434
435 static void
436 table_print_csv_cell__(const char *content)
437 {
438     const char *p;
439
440     if (!strpbrk(content, "\n\",")) {
441         fputs(content, stdout);
442     } else {
443         putchar('"');
444         for (p = content; *p != '\0'; p++) {
445             switch (*p) {
446             case '"':
447                 fputs("\"\"", stdout);
448                 break;
449             default:
450                 putchar(*p);
451                 break;
452             }
453         }
454         putchar('"');
455     }
456 }
457
458 static void
459 table_print_csv__(const struct table *table)
460 {
461     size_t x, y;
462
463     if (output_headings) {
464         for (x = 0; x < table->n_columns; x++) {
465             const struct column *column = &table->columns[x];
466             if (x) {
467                 putchar(',');
468             }
469             table_print_csv_cell__(column->heading);
470         }
471         putchar('\n');
472     }
473
474     for (y = 0; y < table->n_rows; y++) {
475         for (x = 0; x < table->n_columns; x++) {
476             if (x) {
477                 putchar(',');
478             }
479             table_print_csv_cell__(*table_cell__(table, y, x));
480         }
481         putchar('\n');
482     }
483 }
484
485 static void
486 table_print(const struct table *table)
487 {
488     switch (output_format) {
489     case FMT_TABLE:
490         table_print_table__(table);
491         break;
492
493     case FMT_HTML:
494         table_print_html__(table);
495         break;
496
497     case FMT_CSV:
498         table_print_csv__(table);
499         break;
500     }
501 }
502 \f
503 static void
504 do_get_schema(int argc UNUSED, char *argv[])
505 {
506     struct ovsdb_schema *schema = fetch_schema(argv[1]);
507     print_and_free_json(ovsdb_schema_to_json(schema));
508     ovsdb_schema_destroy(schema);
509 }
510
511 static void
512 do_list_tables(int argc UNUSED, char *argv[])
513 {
514     struct ovsdb_schema *schema;
515     struct shash_node *node;
516     struct table t;
517
518     schema = fetch_schema(argv[1]);
519     table_init(&t);
520     table_add_column(&t, "Table");
521     table_add_column(&t, "Comment");
522     SHASH_FOR_EACH (node, &schema->tables) {
523         struct ovsdb_table_schema *ts = node->data;
524
525         table_add_row(&t);
526         table_add_cell(&t, ts->name);
527         if (ts->comment) {
528             table_add_cell(&t, ts->comment);
529         }
530     }
531     ovsdb_schema_destroy(schema);
532     table_print(&t);
533 }
534
535 static void
536 do_list_columns(int argc UNUSED, char *argv[])
537 {
538     const char *table_name = argv[2];
539     struct ovsdb_schema *schema;
540     struct shash_node *table_node;
541     struct table t;
542
543     schema = fetch_schema(argv[1]);
544     table_init(&t);
545     if (!table_name) {
546         table_add_column(&t, "Table");
547     }
548     table_add_column(&t, "Column");
549     table_add_column(&t, "Type");
550     table_add_column(&t, "Comment");
551     SHASH_FOR_EACH (table_node, &schema->tables) {
552         struct ovsdb_table_schema *ts = table_node->data;
553
554         if (!table_name || !strcmp(table_name, ts->name)) {
555             struct shash_node *column_node;
556
557             SHASH_FOR_EACH (column_node, &ts->columns) {
558                 struct ovsdb_column *column = column_node->data;
559                 struct json *type = ovsdb_type_to_json(&column->type);
560
561                 table_add_row(&t);
562                 if (!table_name) {
563                     table_add_cell(&t, ts->name);
564                 }
565                 table_add_cell(&t, column->name);
566                 table_add_cell_nocopy(&t, json_to_string(type, JSSF_SORT));
567                 if (column->comment) {
568                     table_add_cell(&t, column->comment);
569                 }
570
571                 json_destroy(type);
572             }
573         }
574     }
575     ovsdb_schema_destroy(schema);
576     table_print(&t);
577 }
578
579 static void
580 do_help(int argc UNUSED, char *argv[] UNUSED)
581 {
582     usage();
583 }
584
585 static const struct command all_commands[] = {
586     { "get-schema", 1, 1, do_get_schema },
587     { "list-tables", 1, 1, do_list_tables },
588     { "list-columns", 1, 2, do_list_columns },
589     { "help", 0, INT_MAX, do_help },
590     { NULL, 0, 0, NULL },
591 };