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