ovsdb-client: Refactor table code to save original json during formatting.
[cascardo/ovs.git] / ovsdb / ovsdb-client.c
1 /*
2  * Copyright (c) 2009, 2010 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 <assert.h>
20 #include <errno.h>
21 #include <getopt.h>
22 #include <limits.h>
23 #include <signal.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <unistd.h>
27
28 #include "command-line.h"
29 #include "column.h"
30 #include "compiler.h"
31 #include "daemon.h"
32 #include "dynamic-string.h"
33 #include "json.h"
34 #include "jsonrpc.h"
35 #include "ovsdb.h"
36 #include "ovsdb-data.h"
37 #include "ovsdb-error.h"
38 #include "sort.h"
39 #include "stream.h"
40 #include "stream-ssl.h"
41 #include "table.h"
42 #include "timeval.h"
43 #include "util.h"
44 #include "vlog.h"
45
46 VLOG_DEFINE_THIS_MODULE(ovsdb_client);
47
48 /* --format: Output formatting. */
49 static enum {
50     FMT_TABLE,                  /* Textual table. */
51     FMT_HTML,                   /* HTML table. */
52     FMT_CSV                     /* Comma-separated lines. */
53 } output_format;
54
55 /* --no-headings: Whether table output should include headings. */
56 static int output_headings = true;
57
58 /* --pretty: Flags to pass to json_to_string(). */
59 static int json_flags = JSSF_SORT;
60
61 /* --data: Format of data in output tables. */
62 static enum {
63     DF_STRING,                  /* String format. */
64     DF_JSON,                    /* JSON. */
65 } data_format;
66
67 static const struct command all_commands[];
68
69 static void usage(void) NO_RETURN;
70 static void parse_options(int argc, char *argv[]);
71
72 int
73 main(int argc, char *argv[])
74 {
75     proctitle_init(argc, argv);
76     set_program_name(argv[0]);
77     parse_options(argc, argv);
78     signal(SIGPIPE, SIG_IGN);
79     run_command(argc - optind, argv + optind, all_commands);
80     return 0;
81 }
82
83 static void
84 parse_options(int argc, char *argv[])
85 {
86     enum {
87         OPT_BOOTSTRAP_CA_CERT = UCHAR_MAX + 1
88     };
89     static struct option long_options[] = {
90         {"format", required_argument, 0, 'f'},
91         {"data", required_argument, 0, 'd'},
92         {"no-headings", no_argument, &output_headings, 0},
93         {"pretty", no_argument, &json_flags, JSSF_PRETTY | JSSF_SORT},
94         {"verbose", optional_argument, 0, 'v'},
95         {"help", no_argument, 0, 'h'},
96         {"version", no_argument, 0, 'V'},
97         DAEMON_LONG_OPTIONS,
98 #ifdef HAVE_OPENSSL
99         {"bootstrap-ca-cert", required_argument, 0, OPT_BOOTSTRAP_CA_CERT},
100         STREAM_SSL_LONG_OPTIONS
101 #endif
102         {0, 0, 0, 0},
103     };
104     char *short_options = long_options_to_short_options(long_options);
105
106     for (;;) {
107         int c;
108
109         c = getopt_long(argc, argv, short_options, long_options, NULL);
110         if (c == -1) {
111             break;
112         }
113
114         switch (c) {
115         case 'f':
116             if (!strcmp(optarg, "table")) {
117                 output_format = FMT_TABLE;
118             } else if (!strcmp(optarg, "html")) {
119                 output_format = FMT_HTML;
120             } else if (!strcmp(optarg, "csv")) {
121                 output_format = FMT_CSV;
122             } else {
123                 ovs_fatal(0, "unknown output format \"%s\"", optarg);
124             }
125             break;
126
127         case 'd':
128             if (!strcmp(optarg, "string")) {
129                 data_format = DF_STRING;
130             } else if (!strcmp(optarg, "json")) {
131                 data_format = DF_JSON;
132             } else {
133                 ovs_fatal(0, "unknown data format \"%s\"", optarg);
134             }
135             break;
136
137         case 'h':
138             usage();
139
140         case 'V':
141             OVS_PRINT_VERSION(0, 0);
142             exit(EXIT_SUCCESS);
143
144         case 'v':
145             vlog_set_verbosity(optarg);
146             break;
147
148         DAEMON_OPTION_HANDLERS
149
150 #ifdef HAVE_OPENSSL
151         STREAM_SSL_OPTION_HANDLERS
152
153         case OPT_BOOTSTRAP_CA_CERT:
154             stream_ssl_set_ca_cert_file(optarg, true);
155             break;
156 #endif
157
158         case '?':
159             exit(EXIT_FAILURE);
160
161         case 0:
162             /* getopt_long() already set the value for us. */
163             break;
164
165         default:
166             abort();
167         }
168     }
169     free(short_options);
170 }
171
172 static void
173 usage(void)
174 {
175     printf("%s: Open vSwitch database JSON-RPC client\n"
176            "usage: %s [OPTIONS] COMMAND [ARG...]\n"
177            "\nValid commands are:\n"
178            "\n  list-dbs SERVER\n"
179            "    list databases available on SERVER\n"
180            "\n  get-schema SERVER DATABASE\n"
181            "    retrieve schema for DATABASE from SERVER\n"
182            "\n  list-tables SERVER DATABASE\n"
183            "    list tables for DATABASE on SERVER\n"
184            "\n  list-columns SERVER DATABASE [TABLE]\n"
185            "    list columns in TABLE (or all tables) in DATABASE on SERVER\n"
186            "\n  transact SERVER TRANSACTION\n"
187            "    run TRANSACTION (a JSON array of operations) on SERVER\n"
188            "    and print the results as JSON on stdout\n"
189            "\n  monitor SERVER DATABASE TABLE [COLUMN,...]...\n"
190            "    monitor contents of COLUMNs in TABLE in DATABASE on SERVER.\n"
191            "    COLUMNs may include !initial, !insert, !delete, !modify\n"
192            "    to avoid seeing the specified kinds of changes.\n"
193            "\n  dump SERVER DATABASE\n"
194            "    dump contents of DATABASE on SERVER to stdout\n",
195            program_name, program_name);
196     stream_usage("SERVER", true, true, true);
197     printf("\nOutput formatting options:\n"
198            "  -f, --format=FORMAT         set output formatting to FORMAT\n"
199            "                              (\"table\", \"html\", or \"csv\"\n"
200            "  --no-headings               omit table heading row\n"
201            "  --pretty                    pretty-print JSON in output");
202     daemon_usage();
203     vlog_usage();
204     printf("\nOther options:\n"
205            "  -h, --help                  display this help message\n"
206            "  -V, --version               display version information\n");
207     exit(EXIT_SUCCESS);
208 }
209 \f
210 static struct json *
211 parse_json(const char *s)
212 {
213     struct json *json = json_from_string(s);
214     if (json->type == JSON_STRING) {
215         ovs_fatal(0, "\"%s\": %s", s, json->u.string);
216     }
217     return json;
218 }
219
220 static struct jsonrpc *
221 open_jsonrpc(const char *server)
222 {
223     struct stream *stream;
224     int error;
225
226     error = stream_open_block(jsonrpc_stream_open(server, &stream), &stream);
227     if (error == EAFNOSUPPORT) {
228         struct pstream *pstream;
229
230         error = jsonrpc_pstream_open(server, &pstream);
231         if (error) {
232             ovs_fatal(error, "failed to connect or listen to \"%s\"", server);
233         }
234
235         VLOG_INFO("%s: waiting for connection...", server);
236         error = pstream_accept_block(pstream, &stream);
237         if (error) {
238             ovs_fatal(error, "failed to accept connection on \"%s\"", server);
239         }
240
241         pstream_close(pstream);
242     } else if (error) {
243         ovs_fatal(error, "failed to connect to \"%s\"", server);
244     }
245
246     return jsonrpc_open(stream);
247 }
248
249 static void
250 print_json(struct json *json)
251 {
252     char *string = json_to_string(json, json_flags);
253     fputs(string, stdout);
254     free(string);
255 }
256
257 static void
258 print_and_free_json(struct json *json)
259 {
260     print_json(json);
261     json_destroy(json);
262 }
263
264 static void
265 check_ovsdb_error(struct ovsdb_error *error)
266 {
267     if (error) {
268         ovs_fatal(0, "%s", ovsdb_error_to_string(error));
269     }
270 }
271
272 static struct ovsdb_schema *
273 fetch_schema_from_rpc(struct jsonrpc *rpc, const char *database)
274 {
275     struct jsonrpc_msg *request, *reply;
276     struct ovsdb_schema *schema;
277     int error;
278
279     request = jsonrpc_create_request("get_schema",
280                                      json_array_create_1(
281                                          json_string_create(database)),
282                                      NULL);
283     error = jsonrpc_transact_block(rpc, request, &reply);
284     if (error) {
285         ovs_fatal(error, "transaction failed");
286     }
287     check_ovsdb_error(ovsdb_schema_from_json(reply->result, &schema));
288     jsonrpc_msg_destroy(reply);
289
290     return schema;
291 }
292
293 static struct ovsdb_schema *
294 fetch_schema(const char *server, const char *database)
295 {
296     struct ovsdb_schema *schema;
297     struct jsonrpc *rpc;
298
299     rpc = open_jsonrpc(server);
300     schema = fetch_schema_from_rpc(rpc, database);
301     jsonrpc_close(rpc);
302
303     return schema;
304 }
305 \f
306 struct column {
307     char *heading;
308 };
309
310 struct cell {
311     /* Literal text. */
312     char *text;
313
314     /* JSON. */
315     struct json *json;
316     const struct ovsdb_type *type;
317 };
318
319 static const char *
320 cell_to_text(const struct cell *cell_)
321 {
322     struct cell *cell = (struct cell *) cell_;
323     if (!cell->text) {
324         if (cell->json) {
325             if (data_format == DF_JSON || !cell->type) {
326                 cell->text = json_to_string(cell->json, JSSF_SORT);
327             } else if (data_format == DF_STRING) {
328                 struct ovsdb_datum datum;
329                 struct ovsdb_error *error;
330                 struct ds s;
331
332                 error = ovsdb_datum_from_json(&datum, cell->type, cell->json,
333                                               NULL);
334                 if (!error) {
335                     ds_init(&s);
336                     ovsdb_datum_to_string(&datum, cell->type, &s);
337                     ovsdb_datum_destroy(&datum, cell->type);
338                     cell->text = ds_steal_cstr(&s);
339                 } else {
340                     cell->text = json_to_string(cell->json, JSSF_SORT);
341                 }
342             } else {
343                 NOT_REACHED();
344             }
345         } else {
346             cell->text = xstrdup("");
347         }
348     }
349
350     return cell->text;
351 }
352
353 static void
354 cell_destroy(struct cell *cell)
355 {
356     free(cell->text);
357     json_destroy(cell->json);
358 }
359
360 struct table {
361     struct cell *cells;
362     struct column *columns;
363     size_t n_columns, allocated_columns;
364     size_t n_rows, allocated_rows;
365     size_t current_column;
366     char *caption;
367 };
368
369 static void
370 table_init(struct table *table)
371 {
372     memset(table, 0, sizeof *table);
373 }
374
375 static void
376 table_destroy(struct table *table)
377 {
378     size_t i;
379
380     for (i = 0; i < table->n_columns; i++) {
381         free(table->columns[i].heading);
382     }
383     free(table->columns);
384
385     for (i = 0; i < table->n_columns * table->n_rows; i++) {
386         cell_destroy(&table->cells[i]);
387     }
388     free(table->cells);
389
390     free(table->caption);
391 }
392
393 static void
394 table_set_caption(struct table *table, char *caption)
395 {
396     free(table->caption);
397     table->caption = caption;
398 }
399
400 static void
401 table_add_column(struct table *table, const char *heading, ...)
402     PRINTF_FORMAT(2, 3);
403
404 static void
405 table_add_column(struct table *table, const char *heading, ...)
406 {
407     struct column *column;
408     va_list args;
409
410     assert(!table->n_rows);
411     if (table->n_columns >= table->allocated_columns) {
412         table->columns = x2nrealloc(table->columns, &table->allocated_columns,
413                                     sizeof *table->columns);
414     }
415     column = &table->columns[table->n_columns++];
416
417     va_start(args, heading);
418     column->heading = xvasprintf(heading, args);
419     va_end(args);
420 }
421
422 static struct cell *
423 table_cell__(const struct table *table, size_t row, size_t column)
424 {
425     return &table->cells[column + row * table->n_columns];
426 }
427
428 static void
429 table_add_row(struct table *table)
430 {
431     size_t x, y;
432
433     if (table->n_rows >= table->allocated_rows) {
434         table->cells = x2nrealloc(table->cells, &table->allocated_rows,
435                                   table->n_columns * sizeof *table->cells);
436     }
437
438     y = table->n_rows++;
439     table->current_column = 0;
440     for (x = 0; x < table->n_columns; x++) {
441         struct cell *cell = table_cell__(table, y, x);
442         memset(cell, 0, sizeof *cell);
443     }
444 }
445
446 static struct cell *
447 table_add_cell(struct table *table)
448 {
449     size_t x, y;
450
451     assert(table->n_rows > 0);
452     assert(table->current_column < table->n_columns);
453
454     x = table->current_column++;
455     y = table->n_rows - 1;
456
457     return table_cell__(table, y, x);
458 }
459
460 static void
461 table_print_table_line__(struct ds *line)
462 {
463     puts(ds_cstr(line));
464     ds_clear(line);
465 }
466
467 static void
468 table_print_table__(const struct table *table)
469 {
470     static int n = 0;
471     struct ds line = DS_EMPTY_INITIALIZER;
472     int *widths;
473     size_t x, y;
474
475     if (n++ > 0) {
476         putchar('\n');
477     }
478
479     if (table->caption) {
480         puts(table->caption);
481     }
482
483     widths = xmalloc(table->n_columns * sizeof *widths);
484     for (x = 0; x < table->n_columns; x++) {
485         const struct column *column = &table->columns[x];
486
487         widths[x] = strlen(column->heading);
488         for (y = 0; y < table->n_rows; y++) {
489             const char *text = cell_to_text(table_cell__(table, y, x));
490             size_t length = strlen(text);
491
492             if (length > widths[x])
493                 widths[x] = length;
494         }
495     }
496
497     if (output_headings) {
498         for (x = 0; x < table->n_columns; x++) {
499             const struct column *column = &table->columns[x];
500             if (x) {
501                 ds_put_char(&line, ' ');
502             }
503             ds_put_format(&line, "%-*s", widths[x], column->heading);
504         }
505         table_print_table_line__(&line);
506
507         for (x = 0; x < table->n_columns; x++) {
508             if (x) {
509                 ds_put_char(&line, ' ');
510             }
511             ds_put_char_multiple(&line, '-', widths[x]);
512         }
513         table_print_table_line__(&line);
514     }
515
516     for (y = 0; y < table->n_rows; y++) {
517         for (x = 0; x < table->n_columns; x++) {
518             const char *text = cell_to_text(table_cell__(table, y, x));
519             if (x) {
520                 ds_put_char(&line, ' ');
521             }
522             ds_put_format(&line, "%-*s", widths[x], text);
523         }
524         table_print_table_line__(&line);
525     }
526
527     ds_destroy(&line);
528     free(widths);
529 }
530
531 static void
532 table_escape_html_text__(const char *s, size_t n)
533 {
534     size_t i;
535
536     for (i = 0; i < n; i++) {
537         char c = s[i];
538
539         switch (c) {
540         case '&':
541             fputs("&amp;", stdout);
542             break;
543         case '<':
544             fputs("&lt;", stdout);
545             break;
546         case '>':
547             fputs("&gt;", stdout);
548             break;
549         case '"':
550             fputs("&quot;", stdout);
551             break;
552         default:
553             putchar(c);
554             break;
555         }
556     }
557 }
558
559 static void
560 table_print_html_cell__(const char *element, const char *content)
561 {
562     const char *p;
563
564     printf("    <%s>", element);
565     for (p = content; *p; ) {
566         struct uuid uuid;
567
568         if (uuid_from_string_prefix(&uuid, p)) {
569             printf("<a href=\"#%.*s\">%.*s</a>", UUID_LEN, p, 8, p);
570             p += UUID_LEN;
571         } else {
572             table_escape_html_text__(p, 1);
573             p++;
574         }
575     }
576     printf("</%s>\n", element);
577 }
578
579 static void
580 table_print_html__(const struct table *table)
581 {
582     size_t x, y;
583
584     fputs("<table border=1>\n", stdout);
585
586     if (table->caption) {
587         table_print_html_cell__("caption", table->caption);
588     }
589
590     if (output_headings) {
591         fputs("  <tr>\n", stdout);
592         for (x = 0; x < table->n_columns; x++) {
593             const struct column *column = &table->columns[x];
594             table_print_html_cell__("th", column->heading);
595         }
596         fputs("  </tr>\n", stdout);
597     }
598
599     for (y = 0; y < table->n_rows; y++) {
600         fputs("  <tr>\n", stdout);
601         for (x = 0; x < table->n_columns; x++) {
602             const char *content = cell_to_text(table_cell__(table, y, x));
603
604             if (!strcmp(table->columns[x].heading, "_uuid")) {
605                 fputs("    <td><a name=\"", stdout);
606                 table_escape_html_text__(content, strlen(content));
607                 fputs("\">", stdout);
608                 table_escape_html_text__(content, 8);
609                 fputs("</a></td>\n", stdout);
610             } else {
611                 table_print_html_cell__("td", content);
612             }
613         }
614         fputs("  </tr>\n", stdout);
615     }
616
617     fputs("</table>\n", stdout);
618 }
619
620 static void
621 table_print_csv_cell__(const char *content)
622 {
623     const char *p;
624
625     if (!strpbrk(content, "\n\",")) {
626         fputs(content, stdout);
627     } else {
628         putchar('"');
629         for (p = content; *p != '\0'; p++) {
630             switch (*p) {
631             case '"':
632                 fputs("\"\"", stdout);
633                 break;
634             default:
635                 putchar(*p);
636                 break;
637             }
638         }
639         putchar('"');
640     }
641 }
642
643 static void
644 table_print_csv__(const struct table *table)
645 {
646     static int n = 0;
647     size_t x, y;
648
649     if (n++ > 0) {
650         putchar('\n');
651     }
652
653     if (table->caption) {
654         puts(table->caption);
655     }
656
657     if (output_headings) {
658         for (x = 0; x < table->n_columns; x++) {
659             const struct column *column = &table->columns[x];
660             if (x) {
661                 putchar(',');
662             }
663             table_print_csv_cell__(column->heading);
664         }
665         putchar('\n');
666     }
667
668     for (y = 0; y < table->n_rows; y++) {
669         for (x = 0; x < table->n_columns; x++) {
670             if (x) {
671                 putchar(',');
672             }
673             table_print_csv_cell__(cell_to_text(table_cell__(table, y, x)));
674         }
675         putchar('\n');
676     }
677 }
678
679 static void
680 table_print(const struct table *table)
681 {
682     switch (output_format) {
683     case FMT_TABLE:
684         table_print_table__(table);
685         break;
686
687     case FMT_HTML:
688         table_print_html__(table);
689         break;
690
691     case FMT_CSV:
692         table_print_csv__(table);
693         break;
694     }
695 }
696 \f
697 static void
698 do_list_dbs(int argc OVS_UNUSED, char *argv[])
699 {
700     struct jsonrpc_msg *request, *reply;
701     struct jsonrpc *rpc;
702     int error;
703     size_t i;
704
705     rpc = open_jsonrpc(argv[1]);
706     request = jsonrpc_create_request("list_dbs", json_array_create_empty(),
707                                      NULL);
708     error = jsonrpc_transact_block(rpc, request, &reply);
709     if (error) {
710         ovs_fatal(error, "transaction failed");
711     }
712
713     if (reply->result->type != JSON_ARRAY) {
714         ovs_fatal(0, "list_dbs response is not array");
715     }
716
717     for (i = 0; i < reply->result->u.array.n; i++) {
718         const struct json *name = reply->result->u.array.elems[i];
719
720         if (name->type != JSON_STRING) {
721             ovs_fatal(0, "list_dbs response %zu is not string", i);
722         }
723         puts(name->u.string);
724     }
725     jsonrpc_msg_destroy(reply);
726 }
727
728 static void
729 do_get_schema(int argc OVS_UNUSED, char *argv[])
730 {
731     struct ovsdb_schema *schema = fetch_schema(argv[1], argv[2]);
732     print_and_free_json(ovsdb_schema_to_json(schema));
733     ovsdb_schema_destroy(schema);
734 }
735
736 static void
737 do_list_tables(int argc OVS_UNUSED, char *argv[])
738 {
739     struct ovsdb_schema *schema;
740     struct shash_node *node;
741     struct table t;
742
743     schema = fetch_schema(argv[1], argv[2]);
744     table_init(&t);
745     table_add_column(&t, "Table");
746     SHASH_FOR_EACH (node, &schema->tables) {
747         struct ovsdb_table_schema *ts = node->data;
748
749         table_add_row(&t);
750         table_add_cell(&t)->text = xstrdup(ts->name);
751     }
752     ovsdb_schema_destroy(schema);
753     table_print(&t);
754 }
755
756 static void
757 do_list_columns(int argc OVS_UNUSED, char *argv[])
758 {
759     const char *table_name = argv[3];
760     struct ovsdb_schema *schema;
761     struct shash_node *table_node;
762     struct table t;
763
764     schema = fetch_schema(argv[1], argv[2]);
765     table_init(&t);
766     if (!table_name) {
767         table_add_column(&t, "Table");
768     }
769     table_add_column(&t, "Column");
770     table_add_column(&t, "Type");
771     SHASH_FOR_EACH (table_node, &schema->tables) {
772         struct ovsdb_table_schema *ts = table_node->data;
773
774         if (!table_name || !strcmp(table_name, ts->name)) {
775             struct shash_node *column_node;
776
777             SHASH_FOR_EACH (column_node, &ts->columns) {
778                 const struct ovsdb_column *column = column_node->data;
779
780                 table_add_row(&t);
781                 if (!table_name) {
782                     table_add_cell(&t)->text = xstrdup(ts->name);
783                 }
784                 table_add_cell(&t)->text = xstrdup(column->name);
785                 table_add_cell(&t)->json = ovsdb_type_to_json(&column->type);
786             }
787         }
788     }
789     ovsdb_schema_destroy(schema);
790     table_print(&t);
791 }
792
793 static void
794 do_transact(int argc OVS_UNUSED, char *argv[])
795 {
796     struct jsonrpc_msg *request, *reply;
797     struct json *transaction;
798     struct jsonrpc *rpc;
799     int error;
800
801     transaction = parse_json(argv[2]);
802
803     rpc = open_jsonrpc(argv[1]);
804     request = jsonrpc_create_request("transact", transaction, NULL);
805     error = jsonrpc_transact_block(rpc, request, &reply);
806     if (error) {
807         ovs_fatal(error, "transaction failed");
808     }
809     if (reply->error) {
810         ovs_fatal(error, "transaction returned error: %s",
811                   json_to_string(reply->error, json_flags));
812     }
813     print_json(reply->result);
814     putchar('\n');
815     jsonrpc_msg_destroy(reply);
816     jsonrpc_close(rpc);
817 }
818
819 static void
820 monitor_print_row(struct json *row, const char *type, const char *uuid,
821                   const struct ovsdb_column_set *columns, struct table *t)
822 {
823     size_t i;
824
825     if (!row) {
826         ovs_error(0, "missing %s row", type);
827         return;
828     } else if (row->type != JSON_OBJECT) {
829         ovs_error(0, "<row> is not object");
830         return;
831     }
832
833     table_add_row(t);
834     table_add_cell(t)->text = xstrdup(uuid);
835     table_add_cell(t)->text = xstrdup(type);
836     for (i = 0; i < columns->n_columns; i++) {
837         const struct ovsdb_column *column = columns->columns[i];
838         struct json *value = shash_find_data(json_object(row), column->name);
839         struct cell *cell = table_add_cell(t);
840         if (value) {
841             cell->json = json_clone(value);
842             cell->type = &column->type;
843         }
844     }
845 }
846
847 static void
848 monitor_print(struct json *table_updates,
849               const struct ovsdb_table_schema *table,
850               const struct ovsdb_column_set *columns, bool initial)
851 {
852     struct json *table_update;
853     struct shash_node *node;
854     struct table t;
855     size_t i;
856
857     table_init(&t);
858
859     if (table_updates->type != JSON_OBJECT) {
860         ovs_error(0, "<table-updates> is not object");
861         return;
862     }
863     table_update = shash_find_data(json_object(table_updates), table->name);
864     if (!table_update) {
865         return;
866     }
867     if (table_update->type != JSON_OBJECT) {
868         ovs_error(0, "<table-update> is not object");
869         return;
870     }
871
872     table_add_column(&t, "row");
873     table_add_column(&t, "action");
874     for (i = 0; i < columns->n_columns; i++) {
875         table_add_column(&t, "%s", columns->columns[i]->name);
876     }
877     SHASH_FOR_EACH (node, json_object(table_update)) {
878         struct json *row_update = node->data;
879         struct json *old, *new;
880
881         if (row_update->type != JSON_OBJECT) {
882             ovs_error(0, "<row-update> is not object");
883             continue;
884         }
885         old = shash_find_data(json_object(row_update), "old");
886         new = shash_find_data(json_object(row_update), "new");
887         if (initial) {
888             monitor_print_row(new, "initial", node->name, columns, &t);
889         } else if (!old) {
890             monitor_print_row(new, "insert", node->name, columns, &t);
891         } else if (!new) {
892             monitor_print_row(old, "delete", node->name, columns, &t);
893         } else {
894             monitor_print_row(old, "old", node->name, columns, &t);
895             monitor_print_row(new, "new", "", columns, &t);
896         }
897     }
898     table_print(&t);
899     table_destroy(&t);
900 }
901
902 static void
903 add_column(const char *server, const struct ovsdb_column *column,
904            struct ovsdb_column_set *columns, struct json *columns_json)
905 {
906     if (ovsdb_column_set_contains(columns, column->index)) {
907         ovs_fatal(0, "%s: column \"%s\" mentioned multiple times",
908                   server, column->name);
909     }
910     ovsdb_column_set_add(columns, column);
911     json_array_add(columns_json, json_string_create(column->name));
912 }
913
914 static struct json *
915 parse_monitor_columns(char *arg, const char *server, const char *database,
916                       const struct ovsdb_table_schema *table,
917                       struct ovsdb_column_set *columns)
918 {
919     bool initial, insert, delete, modify;
920     struct json *mr, *columns_json;
921     char *save_ptr = NULL;
922     char *token;
923
924     mr = json_object_create();
925     columns_json = json_array_create_empty();
926     json_object_put(mr, "columns", columns_json);
927
928     initial = insert = delete = modify = true;
929     for (token = strtok_r(arg, ",", &save_ptr); token != NULL;
930          token = strtok_r(NULL, ",", &save_ptr)) {
931         if (!strcmp(token, "!initial")) {
932             initial = false;
933         } else if (!strcmp(token, "!insert")) {
934             insert = false;
935         } else if (!strcmp(token, "!delete")) {
936             delete = false;
937         } else if (!strcmp(token, "!modify")) {
938             modify = false;
939         } else {
940             const struct ovsdb_column *column;
941
942             column = ovsdb_table_schema_get_column(table, token);
943             if (!column) {
944                 ovs_fatal(0, "%s: table \"%s\" in %s does not have a "
945                           "column named \"%s\"",
946                           server, table->name, database, token);
947             }
948             add_column(server, column, columns, columns_json);
949         }
950     }
951
952     if (columns_json->u.array.n == 0) {
953         const struct shash_node **nodes;
954         size_t i, n;
955
956         n = shash_count(&table->columns);
957         nodes = shash_sort(&table->columns);
958         for (i = 0; i < n; i++) {
959             const struct ovsdb_column *column = nodes[i]->data;
960             if (column->index != OVSDB_COL_UUID
961                 && column->index != OVSDB_COL_VERSION) {
962                 add_column(server, column, columns, columns_json);
963             }
964         }
965         free(nodes);
966
967         add_column(server, ovsdb_table_schema_get_column(table,"_version"),
968                    columns, columns_json);
969     }
970
971     if (!initial || !insert || !delete || !modify) {
972         struct json *select = json_object_create();
973         json_object_put(select, "initial", json_boolean_create(initial));
974         json_object_put(select, "insert", json_boolean_create(insert));
975         json_object_put(select, "delete", json_boolean_create(delete));
976         json_object_put(select, "modify", json_boolean_create(modify));
977         json_object_put(mr, "select", select);
978     }
979
980     return mr;
981 }
982
983 static void
984 do_monitor(int argc, char *argv[])
985 {
986     const char *server = argv[1];
987     const char *database = argv[2];
988     const char *table_name = argv[3];
989     struct ovsdb_column_set columns = OVSDB_COLUMN_SET_INITIALIZER;
990     struct ovsdb_table_schema *table;
991     struct ovsdb_schema *schema;
992     struct jsonrpc_msg *request;
993     struct jsonrpc *rpc;
994     struct json *monitor, *monitor_request_array,
995         *monitor_requests, *request_id;
996
997     rpc = open_jsonrpc(server);
998
999     schema = fetch_schema_from_rpc(rpc, database);
1000     table = shash_find_data(&schema->tables, table_name);
1001     if (!table) {
1002         ovs_fatal(0, "%s: %s does not have a table named \"%s\"",
1003                   server, database, table_name);
1004     }
1005
1006     monitor_request_array = json_array_create_empty();
1007     if (argc > 4) {
1008         int i;
1009
1010         for (i = 4; i < argc; i++) {
1011             json_array_add(
1012                 monitor_request_array,
1013                 parse_monitor_columns(argv[i], server, database, table,
1014                                       &columns));
1015         }
1016     } else {
1017         /* Allocate a writable empty string since parse_monitor_columns() is
1018          * going to strtok() it and that's risky with literal "". */
1019         char empty[] = "";
1020         json_array_add(
1021             monitor_request_array,
1022             parse_monitor_columns(empty, server, database, table, &columns));
1023     }
1024
1025     monitor_requests = json_object_create();
1026     json_object_put(monitor_requests, table_name, monitor_request_array);
1027
1028     monitor = json_array_create_3(json_string_create(database),
1029                                   json_null_create(), monitor_requests);
1030     request = jsonrpc_create_request("monitor", monitor, NULL);
1031     request_id = json_clone(request->id);
1032     jsonrpc_send(rpc, request);
1033     for (;;) {
1034         struct jsonrpc_msg *msg;
1035         int error;
1036
1037         error = jsonrpc_recv_block(rpc, &msg);
1038         if (error) {
1039             ovsdb_schema_destroy(schema);
1040             ovs_fatal(error, "%s: receive failed", server);
1041         }
1042
1043         if (msg->type == JSONRPC_REQUEST && !strcmp(msg->method, "echo")) {
1044             jsonrpc_send(rpc, jsonrpc_create_reply(json_clone(msg->params),
1045                                                    msg->id));
1046         } else if (msg->type == JSONRPC_REPLY
1047                    && json_equal(msg->id, request_id)) {
1048             monitor_print(msg->result, table, &columns, true);
1049             fflush(stdout);
1050             if (get_detach()) {
1051                 /* daemonize() closes the standard file descriptors.  We output
1052                  * to stdout, so we need to save and restore STDOUT_FILENO. */
1053                 int fd = dup(STDOUT_FILENO);
1054                 daemonize();
1055                 dup2(fd, STDOUT_FILENO);
1056                 close(fd);
1057             }
1058         } else if (msg->type == JSONRPC_NOTIFY
1059                    && !strcmp(msg->method, "update")) {
1060             struct json *params = msg->params;
1061             if (params->type == JSON_ARRAY
1062                 && params->u.array.n == 2
1063                 && params->u.array.elems[0]->type == JSON_NULL) {
1064                 monitor_print(params->u.array.elems[1],
1065                               table, &columns, false);
1066                 fflush(stdout);
1067             }
1068         }
1069         jsonrpc_msg_destroy(msg);
1070     }
1071 }
1072
1073 struct dump_table_aux {
1074     struct ovsdb_datum **data;
1075     const struct ovsdb_column **columns;
1076     size_t n_columns;
1077 };
1078
1079 static int
1080 compare_data(size_t a_y, size_t b_y, size_t x,
1081              const struct dump_table_aux *aux)
1082 {
1083     return ovsdb_datum_compare_3way(&aux->data[a_y][x],
1084                                     &aux->data[b_y][x],
1085                                     &aux->columns[x]->type);
1086 }
1087
1088 static int
1089 compare_rows(size_t a_y, size_t b_y, void *aux_)
1090 {
1091     struct dump_table_aux *aux = aux_;
1092     size_t x;
1093
1094     /* Skip UUID columns on the first pass, since their values tend to be
1095      * random and make our results less reproducible. */
1096     for (x = 0; x < aux->n_columns; x++) {
1097         if (aux->columns[x]->type.key.type != OVSDB_TYPE_UUID) {
1098             int cmp = compare_data(a_y, b_y, x, aux);
1099             if (cmp) {
1100                 return cmp;
1101             }
1102         }
1103     }
1104
1105     /* Use UUID columns as tie-breakers. */
1106     for (x = 0; x < aux->n_columns; x++) {
1107         if (aux->columns[x]->type.key.type == OVSDB_TYPE_UUID) {
1108             int cmp = compare_data(a_y, b_y, x, aux);
1109             if (cmp) {
1110                 return cmp;
1111             }
1112         }
1113     }
1114
1115     return 0;
1116 }
1117
1118 static void
1119 swap_rows(size_t a_y, size_t b_y, void *aux_)
1120 {
1121     struct dump_table_aux *aux = aux_;
1122     struct ovsdb_datum *tmp = aux->data[a_y];
1123     aux->data[a_y] = aux->data[b_y];
1124     aux->data[b_y] = tmp;
1125 }
1126
1127 static int
1128 compare_columns(const void *a_, const void *b_)
1129 {
1130     const struct ovsdb_column *const *ap = a_;
1131     const struct ovsdb_column *const *bp = b_;
1132     const struct ovsdb_column *a = *ap;
1133     const struct ovsdb_column *b = *bp;
1134
1135     return strcmp(a->name, b->name);
1136 }
1137
1138 static void
1139 dump_table(const struct ovsdb_table_schema *ts, struct json_array *rows)
1140 {
1141     const struct ovsdb_column **columns;
1142     size_t n_columns;
1143
1144     struct ovsdb_datum **data;
1145
1146     struct dump_table_aux aux;
1147     struct shash_node *node;
1148     struct table t;
1149     size_t x, y;
1150
1151     /* Sort columns by name, for reproducibility. */
1152     columns = xmalloc(shash_count(&ts->columns) * sizeof *columns);
1153     n_columns = 0;
1154     SHASH_FOR_EACH (node, &ts->columns) {
1155         struct ovsdb_column *column = node->data;
1156         if (strcmp(column->name, "_version")) {
1157             columns[n_columns++] = column;
1158         }
1159     }
1160     qsort(columns, n_columns, sizeof *columns, compare_columns);
1161
1162     /* Extract data from table. */
1163     data = xmalloc(rows->n * sizeof *data);
1164     for (y = 0; y < rows->n; y++) {
1165         struct shash *row;
1166
1167         if (rows->elems[y]->type != JSON_OBJECT) {
1168             ovs_fatal(0,  "row %zu in table %s response is not a JSON object: "
1169                       "%s", y, ts->name, json_to_string(rows->elems[y], 0));
1170         }
1171         row = json_object(rows->elems[y]);
1172
1173         data[y] = xmalloc(n_columns * sizeof **data);
1174         for (x = 0; x < n_columns; x++) {
1175             const struct json *json = shash_find_data(row, columns[x]->name);
1176             if (!json) {
1177                 ovs_fatal(0, "row %zu in table %s response lacks %s column",
1178                           y, ts->name, columns[x]->name);
1179             }
1180
1181             check_ovsdb_error(ovsdb_datum_from_json(&data[y][x],
1182                                                     &columns[x]->type,
1183                                                     json, NULL));
1184         }
1185     }
1186
1187     /* Sort rows by column values, for reproducibility. */
1188     aux.data = data;
1189     aux.columns = columns;
1190     aux.n_columns = n_columns;
1191     sort(rows->n, compare_rows, swap_rows, &aux);
1192
1193     /* Add column headings. */
1194     table_init(&t);
1195     table_set_caption(&t, xasprintf("%s table", ts->name));
1196     for (x = 0; x < n_columns; x++) {
1197         table_add_column(&t, "%s", columns[x]->name);
1198     }
1199
1200     /* Print rows. */
1201     for (y = 0; y < rows->n; y++) {
1202         table_add_row(&t);
1203         for (x = 0; x < n_columns; x++) {
1204             struct cell *cell = table_add_cell(&t);
1205             cell->json = ovsdb_datum_to_json(&data[y][x], &columns[x]->type);
1206             cell->type = &columns[x]->type;
1207         }
1208     }
1209     table_print(&t);
1210     table_destroy(&t);
1211 }
1212
1213 static void
1214 do_dump(int argc OVS_UNUSED, char *argv[])
1215 {
1216     const char *server = argv[1];
1217     const char *database = argv[2];
1218
1219     struct jsonrpc_msg *request, *reply;
1220     struct ovsdb_schema *schema;
1221     struct json *transaction;
1222     struct jsonrpc *rpc;
1223     int error;
1224
1225     const struct shash_node **tables;
1226     size_t n_tables;
1227
1228     size_t i;
1229
1230     rpc = open_jsonrpc(server);
1231
1232     schema = fetch_schema_from_rpc(rpc, database);
1233     tables = shash_sort(&schema->tables);
1234     n_tables = shash_count(&schema->tables);
1235
1236     /* Construct transaction to retrieve entire database. */
1237     transaction = json_array_create_1(json_string_create(database));
1238     for (i = 0; i < n_tables; i++) {
1239         const struct ovsdb_table_schema *ts = tables[i]->data;
1240         struct json *op, *columns;
1241         struct shash_node *node;
1242
1243         columns = json_array_create_empty();
1244         SHASH_FOR_EACH (node, &ts->columns) {
1245             const struct ovsdb_column *column = node->data;
1246
1247             if (strcmp(column->name, "_version")) {
1248                 json_array_add(columns, json_string_create(column->name));
1249             }
1250         }
1251
1252         op = json_object_create();
1253         json_object_put_string(op, "op", "select");
1254         json_object_put_string(op, "table", tables[i]->name);
1255         json_object_put(op, "where", json_array_create_empty());
1256         json_object_put(op, "columns", columns);
1257         json_array_add(transaction, op);
1258     }
1259
1260     /* Send request, get reply. */
1261     request = jsonrpc_create_request("transact", transaction, NULL);
1262     error = jsonrpc_transact_block(rpc, request, &reply);
1263     if (error) {
1264         ovs_fatal(error, "transaction failed");
1265     }
1266
1267     /* Print database contents. */
1268     if (reply->result->type != JSON_ARRAY
1269         || reply->result->u.array.n != n_tables) {
1270         ovs_fatal(0, "reply is not array of %zu elements: %s",
1271                   n_tables, json_to_string(reply->result, 0));
1272     }
1273     for (i = 0; i < n_tables; i++) {
1274         const struct ovsdb_table_schema *ts = tables[i]->data;
1275         const struct json *op_result = reply->result->u.array.elems[i];
1276         struct json *rows;
1277
1278         if (op_result->type != JSON_OBJECT
1279             || !(rows = shash_find_data(json_object(op_result), "rows"))
1280             || rows->type != JSON_ARRAY) {
1281             ovs_fatal(0, "%s table reply is not an object with a \"rows\" "
1282                       "member array: %s",
1283                       ts->name, json_to_string(op_result, 0));
1284         }
1285
1286         dump_table(ts, &rows->u.array);
1287     }
1288 }
1289
1290 static void
1291 do_help(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
1292 {
1293     usage();
1294 }
1295
1296 static const struct command all_commands[] = {
1297     { "list-dbs", 1, 1, do_list_dbs },
1298     { "get-schema", 2, 2, do_get_schema },
1299     { "list-tables", 2, 2, do_list_tables },
1300     { "list-columns", 2, 3, do_list_columns },
1301     { "transact", 2, 2, do_transact },
1302     { "monitor", 3, INT_MAX, do_monitor },
1303     { "dump", 2, 2, do_dump },
1304     { "help", 0, INT_MAX, do_help },
1305     { NULL, 0, 0, NULL },
1306 };