timeval: Make time_init() static and remove calls to it.
[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
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     vlog_init();
78     parse_options(argc, argv);
79     signal(SIGPIPE, SIG_IGN);
80     run_command(argc - optind, argv + optind, all_commands);
81     return 0;
82 }
83
84 static void
85 parse_options(int argc, char *argv[])
86 {
87     enum {
88         OPT_BOOTSTRAP_CA_CERT = UCHAR_MAX + 1
89     };
90     static struct option long_options[] = {
91         {"format", required_argument, 0, 'f'},
92         {"data", required_argument, 0, 'd'},
93         {"no-headings", no_argument, &output_headings, 0},
94         {"pretty", no_argument, &json_flags, JSSF_PRETTY | JSSF_SORT},
95         {"verbose", optional_argument, 0, 'v'},
96         {"help", no_argument, 0, 'h'},
97         {"version", no_argument, 0, 'V'},
98         DAEMON_LONG_OPTIONS,
99 #ifdef HAVE_OPENSSL
100         {"bootstrap-ca-cert", required_argument, 0, OPT_BOOTSTRAP_CA_CERT},
101         STREAM_SSL_LONG_OPTIONS
102 #endif
103         {0, 0, 0, 0},
104     };
105     char *short_options = long_options_to_short_options(long_options);
106
107     for (;;) {
108         int c;
109
110         c = getopt_long(argc, argv, short_options, long_options, NULL);
111         if (c == -1) {
112             break;
113         }
114
115         switch (c) {
116         case 'f':
117             if (!strcmp(optarg, "table")) {
118                 output_format = FMT_TABLE;
119             } else if (!strcmp(optarg, "html")) {
120                 output_format = FMT_HTML;
121             } else if (!strcmp(optarg, "csv")) {
122                 output_format = FMT_CSV;
123             } else {
124                 ovs_fatal(0, "unknown output format \"%s\"", optarg);
125             }
126             break;
127
128         case 'd':
129             if (!strcmp(optarg, "string")) {
130                 data_format = DF_STRING;
131             } else if (!strcmp(optarg, "json")) {
132                 data_format = DF_JSON;
133             } else {
134                 ovs_fatal(0, "unknown data format \"%s\"", optarg);
135             }
136             break;
137
138         case 'h':
139             usage();
140
141         case 'V':
142             OVS_PRINT_VERSION(0, 0);
143             exit(EXIT_SUCCESS);
144
145         case 'v':
146             vlog_set_verbosity(optarg);
147             break;
148
149         DAEMON_OPTION_HANDLERS
150
151 #ifdef HAVE_OPENSSL
152         STREAM_SSL_OPTION_HANDLERS
153
154         case OPT_BOOTSTRAP_CA_CERT:
155             stream_ssl_set_ca_cert_file(optarg, true);
156             break;
157 #endif
158
159         case '?':
160             exit(EXIT_FAILURE);
161
162         case 0:
163             /* getopt_long() already set the value for us. */
164             break;
165
166         default:
167             abort();
168         }
169     }
170     free(short_options);
171 }
172
173 static void
174 usage(void)
175 {
176     printf("%s: Open vSwitch database JSON-RPC client\n"
177            "usage: %s [OPTIONS] COMMAND [ARG...]\n"
178            "\nValid commands are:\n"
179            "\n  list-dbs SERVER\n"
180            "    list databases available on SERVER\n"
181            "\n  get-schema SERVER DATABASE\n"
182            "    retrieve schema for DATABASE from SERVER\n"
183            "\n  list-tables SERVER DATABASE\n"
184            "    list tables for DATABASE on SERVER\n"
185            "\n  list-columns SERVER DATABASE [TABLE]\n"
186            "    list columns in TABLE (or all tables) in DATABASE on SERVER\n"
187            "\n  transact SERVER TRANSACTION\n"
188            "    run TRANSACTION (a JSON array of operations) on SERVER\n"
189            "    and print the results as JSON on stdout\n"
190            "\n  monitor SERVER DATABASE TABLE [COLUMN,...]...\n"
191            "    monitor contents of COLUMNs in TABLE in DATABASE on SERVER.\n"
192            "    COLUMNs may include !initial, !insert, !delete, !modify\n"
193            "    to avoid seeing the specified kinds of changes.\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(jsonrpc_stream_open(server, &stream), &stream);
228     if (error == EAFNOSUPPORT) {
229         struct pstream *pstream;
230
231         error = jsonrpc_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     static int n = 0;
438     struct ds line = DS_EMPTY_INITIALIZER;
439     size_t x, y;
440
441     if (n++ > 0) {
442         putchar('\n');
443     }
444
445     if (output_headings) {
446         for (x = 0; x < table->n_columns; x++) {
447             const struct column *column = &table->columns[x];
448             if (x) {
449                 ds_put_char(&line, ' ');
450             }
451             ds_put_format(&line, "%-*s", column->width, column->heading);
452         }
453         table_print_table_line__(&line);
454
455         for (x = 0; x < table->n_columns; x++) {
456             const struct column *column = &table->columns[x];
457             int i;
458
459             if (x) {
460                 ds_put_char(&line, ' ');
461             }
462             for (i = 0; i < column->width; i++) {
463                 ds_put_char(&line, '-');
464             }
465         }
466         table_print_table_line__(&line);
467     }
468
469     for (y = 0; y < table->n_rows; y++) {
470         for (x = 0; x < table->n_columns; x++) {
471             const char *cell = *table_cell__(table, y, x);
472             if (x) {
473                 ds_put_char(&line, ' ');
474             }
475             ds_put_format(&line, "%-*s", table->columns[x].width, cell);
476         }
477         table_print_table_line__(&line);
478     }
479
480     ds_destroy(&line);
481 }
482
483 static void
484 table_escape_html_text__(const char *s, size_t n)
485 {
486     size_t i;
487
488     for (i = 0; i < n; i++) {
489         char c = s[i];
490
491         switch (c) {
492         case '&':
493             fputs("&amp;", stdout);
494             break;
495         case '<':
496             fputs("&lt;", stdout);
497             break;
498         case '>':
499             fputs("&gt;", stdout);
500             break;
501         case '"':
502             fputs("&quot;", stdout);
503             break;
504         default:
505             putchar(c);
506             break;
507         }
508     }
509 }
510
511 static void
512 table_print_html_cell__(const char *element, const char *content)
513 {
514     const char *p;
515
516     printf("    <%s>", element);
517     for (p = content; *p; ) {
518         struct uuid uuid;
519
520         if (uuid_from_string_prefix(&uuid, p)) {
521             printf("<a href=\"#%.*s\">%.*s</a>", UUID_LEN, p, 8, p);
522             p += UUID_LEN;
523         } else {
524             table_escape_html_text__(p, 1);
525             p++;
526         }
527     }
528     printf("</%s>\n", element);
529 }
530
531 static void
532 table_print_html__(const struct table *table)
533 {
534     size_t x, y;
535
536     fputs("<table border=1>\n", stdout);
537
538     if (table->caption) {
539         table_print_html_cell__("caption", table->caption);
540     }
541
542     if (output_headings) {
543         fputs("  <tr>\n", stdout);
544         for (x = 0; x < table->n_columns; x++) {
545             const struct column *column = &table->columns[x];
546             table_print_html_cell__("th", column->heading);
547         }
548         fputs("  </tr>\n", stdout);
549     }
550
551     for (y = 0; y < table->n_rows; y++) {
552         fputs("  <tr>\n", stdout);
553         for (x = 0; x < table->n_columns; x++) {
554             const char *content = *table_cell__(table, y, x);
555
556             if (!strcmp(table->columns[x].heading, "_uuid")) {
557                 fputs("    <td><a name=\"", stdout);
558                 table_escape_html_text__(content, strlen(content));
559                 fputs("\">", stdout);
560                 table_escape_html_text__(content, 8);
561                 fputs("</a></td>\n", stdout);
562             } else {
563                 table_print_html_cell__("td", content);
564             }
565         }
566         fputs("  </tr>\n", stdout);
567     }
568
569     fputs("</table>\n", stdout);
570 }
571
572 static void
573 table_print_csv_cell__(const char *content)
574 {
575     const char *p;
576
577     if (!strpbrk(content, "\n\",")) {
578         fputs(content, stdout);
579     } else {
580         putchar('"');
581         for (p = content; *p != '\0'; p++) {
582             switch (*p) {
583             case '"':
584                 fputs("\"\"", stdout);
585                 break;
586             default:
587                 putchar(*p);
588                 break;
589             }
590         }
591         putchar('"');
592     }
593 }
594
595 static void
596 table_print_csv__(const struct table *table)
597 {
598     static int n = 0;
599     size_t x, y;
600
601     if (n++ > 0) {
602         putchar('\n');
603     }
604
605     if (table->caption) {
606         puts(table->caption);
607     }
608
609     if (output_headings) {
610         for (x = 0; x < table->n_columns; x++) {
611             const struct column *column = &table->columns[x];
612             if (x) {
613                 putchar(',');
614             }
615             table_print_csv_cell__(column->heading);
616         }
617         putchar('\n');
618     }
619
620     for (y = 0; y < table->n_rows; y++) {
621         for (x = 0; x < table->n_columns; x++) {
622             if (x) {
623                 putchar(',');
624             }
625             table_print_csv_cell__(*table_cell__(table, y, x));
626         }
627         putchar('\n');
628     }
629 }
630
631 static void
632 table_print(const struct table *table)
633 {
634     switch (output_format) {
635     case FMT_TABLE:
636         table_print_table__(table);
637         break;
638
639     case FMT_HTML:
640         table_print_html__(table);
641         break;
642
643     case FMT_CSV:
644         table_print_csv__(table);
645         break;
646     }
647 }
648 \f
649 static void
650 do_list_dbs(int argc OVS_UNUSED, char *argv[])
651 {
652     struct jsonrpc_msg *request, *reply;
653     struct jsonrpc *rpc;
654     int error;
655     size_t i;
656
657     rpc = open_jsonrpc(argv[1]);
658     request = jsonrpc_create_request("list_dbs", json_array_create_empty(),
659                                      NULL);
660     error = jsonrpc_transact_block(rpc, request, &reply);
661     if (error) {
662         ovs_fatal(error, "transaction failed");
663     }
664
665     if (reply->result->type != JSON_ARRAY) {
666         ovs_fatal(0, "list_dbs response is not array");
667     }
668
669     for (i = 0; i < reply->result->u.array.n; i++) {
670         const struct json *name = reply->result->u.array.elems[i];
671
672         if (name->type != JSON_STRING) {
673             ovs_fatal(0, "list_dbs response %zu is not string", i);
674         }
675         puts(name->u.string);
676     }
677     jsonrpc_msg_destroy(reply);
678 }
679
680 static void
681 do_get_schema(int argc OVS_UNUSED, char *argv[])
682 {
683     struct ovsdb_schema *schema = fetch_schema(argv[1], argv[2]);
684     print_and_free_json(ovsdb_schema_to_json(schema));
685     ovsdb_schema_destroy(schema);
686 }
687
688 static void
689 do_list_tables(int argc OVS_UNUSED, char *argv[])
690 {
691     struct ovsdb_schema *schema;
692     struct shash_node *node;
693     struct table t;
694
695     schema = fetch_schema(argv[1], argv[2]);
696     table_init(&t);
697     table_add_column(&t, "Table");
698     SHASH_FOR_EACH (node, &schema->tables) {
699         struct ovsdb_table_schema *ts = node->data;
700
701         table_add_row(&t);
702         table_add_cell(&t, ts->name);
703     }
704     ovsdb_schema_destroy(schema);
705     table_print(&t);
706 }
707
708 static void
709 do_list_columns(int argc OVS_UNUSED, char *argv[])
710 {
711     const char *table_name = argv[3];
712     struct ovsdb_schema *schema;
713     struct shash_node *table_node;
714     struct table t;
715
716     schema = fetch_schema(argv[1], argv[2]);
717     table_init(&t);
718     if (!table_name) {
719         table_add_column(&t, "Table");
720     }
721     table_add_column(&t, "Column");
722     table_add_column(&t, "Type");
723     SHASH_FOR_EACH (table_node, &schema->tables) {
724         struct ovsdb_table_schema *ts = table_node->data;
725
726         if (!table_name || !strcmp(table_name, ts->name)) {
727             struct shash_node *column_node;
728
729             SHASH_FOR_EACH (column_node, &ts->columns) {
730                 const struct ovsdb_column *column = column_node->data;
731                 struct json *type = ovsdb_type_to_json(&column->type);
732
733                 table_add_row(&t);
734                 if (!table_name) {
735                     table_add_cell(&t, ts->name);
736                 }
737                 table_add_cell(&t, column->name);
738                 table_add_cell_nocopy(&t, json_to_string(type, JSSF_SORT));
739
740                 json_destroy(type);
741             }
742         }
743     }
744     ovsdb_schema_destroy(schema);
745     table_print(&t);
746 }
747
748 static void
749 do_transact(int argc OVS_UNUSED, char *argv[])
750 {
751     struct jsonrpc_msg *request, *reply;
752     struct json *transaction;
753     struct jsonrpc *rpc;
754     int error;
755
756     transaction = parse_json(argv[2]);
757
758     rpc = open_jsonrpc(argv[1]);
759     request = jsonrpc_create_request("transact", transaction, NULL);
760     error = jsonrpc_transact_block(rpc, request, &reply);
761     if (error) {
762         ovs_fatal(error, "transaction failed");
763     }
764     if (reply->error) {
765         ovs_fatal(error, "transaction returned error: %s",
766                   json_to_string(reply->error, json_flags));
767     }
768     print_json(reply->result);
769     putchar('\n');
770     jsonrpc_msg_destroy(reply);
771     jsonrpc_close(rpc);
772 }
773
774 static char *
775 format_json(const struct json *json, const struct ovsdb_type *type)
776 {
777     if (data_format == DF_JSON) {
778         return json_to_string(json, JSSF_SORT);
779     } else if (data_format == DF_STRING) {
780         struct ovsdb_datum datum;
781         struct ovsdb_error *error;
782         struct ds s;
783
784         error = ovsdb_datum_from_json(&datum, type, json, NULL);
785         if (error) {
786             return json_to_string(json, JSSF_SORT);
787         }
788
789         ds_init(&s);
790         ovsdb_datum_to_string(&datum, type, &s);
791         ovsdb_datum_destroy(&datum, type);
792         return ds_steal_cstr(&s);
793     } else {
794         NOT_REACHED();
795     }
796 }
797
798 static void
799 monitor_print_row(struct json *row, const char *type, const char *uuid,
800                   const struct ovsdb_column_set *columns, struct table *t)
801 {
802     size_t i;
803
804     if (!row) {
805         ovs_error(0, "missing %s row", type);
806         return;
807     } else if (row->type != JSON_OBJECT) {
808         ovs_error(0, "<row> is not object");
809         return;
810     }
811
812     table_add_row(t);
813     table_add_cell(t, uuid);
814     table_add_cell(t, type);
815     for (i = 0; i < columns->n_columns; i++) {
816         const struct ovsdb_column *column = columns->columns[i];
817         struct json *value = shash_find_data(json_object(row), column->name);
818         if (value) {
819             table_add_cell_nocopy(t, format_json(value, &column->type));
820         } else {
821             table_add_cell(t, "");
822         }
823     }
824 }
825
826 static void
827 monitor_print(struct json *table_updates,
828               const struct ovsdb_table_schema *table,
829               const struct ovsdb_column_set *columns, bool initial)
830 {
831     struct json *table_update;
832     struct shash_node *node;
833     struct table t;
834     size_t i;
835
836     table_init(&t);
837
838     if (table_updates->type != JSON_OBJECT) {
839         ovs_error(0, "<table-updates> is not object");
840         return;
841     }
842     table_update = shash_find_data(json_object(table_updates), table->name);
843     if (!table_update) {
844         return;
845     }
846     if (table_update->type != JSON_OBJECT) {
847         ovs_error(0, "<table-update> is not object");
848         return;
849     }
850
851     table_add_column(&t, "row");
852     table_add_column(&t, "action");
853     for (i = 0; i < columns->n_columns; i++) {
854         table_add_column(&t, "%s", columns->columns[i]->name);
855     }
856     SHASH_FOR_EACH (node, json_object(table_update)) {
857         struct json *row_update = node->data;
858         struct json *old, *new;
859
860         if (row_update->type != JSON_OBJECT) {
861             ovs_error(0, "<row-update> is not object");
862             continue;
863         }
864         old = shash_find_data(json_object(row_update), "old");
865         new = shash_find_data(json_object(row_update), "new");
866         if (initial) {
867             monitor_print_row(new, "initial", node->name, columns, &t);
868         } else if (!old) {
869             monitor_print_row(new, "insert", node->name, columns, &t);
870         } else if (!new) {
871             monitor_print_row(old, "delete", node->name, columns, &t);
872         } else {
873             monitor_print_row(old, "old", node->name, columns, &t);
874             monitor_print_row(new, "new", "", columns, &t);
875         }
876     }
877     table_print(&t);
878     table_destroy(&t);
879 }
880
881 static void
882 add_column(const char *server, const struct ovsdb_column *column,
883            struct ovsdb_column_set *columns, struct json *columns_json)
884 {
885     if (ovsdb_column_set_contains(columns, column->index)) {
886         ovs_fatal(0, "%s: column \"%s\" mentioned multiple times",
887                   server, column->name);
888     }
889     ovsdb_column_set_add(columns, column);
890     json_array_add(columns_json, json_string_create(column->name));
891 }
892
893 static struct json *
894 parse_monitor_columns(char *arg, const char *server, const char *database,
895                       const struct ovsdb_table_schema *table,
896                       struct ovsdb_column_set *columns)
897 {
898     bool initial, insert, delete, modify;
899     struct json *mr, *columns_json;
900     char *save_ptr = NULL;
901     char *token;
902
903     mr = json_object_create();
904     columns_json = json_array_create_empty();
905     json_object_put(mr, "columns", columns_json);
906
907     initial = insert = delete = modify = true;
908     for (token = strtok_r(arg, ",", &save_ptr); token != NULL;
909          token = strtok_r(NULL, ",", &save_ptr)) {
910         if (!strcmp(token, "!initial")) {
911             initial = false;
912         } else if (!strcmp(token, "!insert")) {
913             insert = false;
914         } else if (!strcmp(token, "!delete")) {
915             delete = false;
916         } else if (!strcmp(token, "!modify")) {
917             modify = false;
918         } else {
919             const struct ovsdb_column *column;
920
921             column = ovsdb_table_schema_get_column(table, token);
922             if (!column) {
923                 ovs_fatal(0, "%s: table \"%s\" in %s does not have a "
924                           "column named \"%s\"",
925                           server, table->name, database, token);
926             }
927             add_column(server, column, columns, columns_json);
928         }
929     }
930
931     if (columns_json->u.array.n == 0) {
932         const struct shash_node **nodes;
933         size_t i, n;
934
935         n = shash_count(&table->columns);
936         nodes = shash_sort(&table->columns);
937         for (i = 0; i < n; i++) {
938             const struct ovsdb_column *column = nodes[i]->data;
939             if (column->index != OVSDB_COL_UUID
940                 && column->index != OVSDB_COL_VERSION) {
941                 add_column(server, column, columns, columns_json);
942             }
943         }
944         free(nodes);
945
946         add_column(server, ovsdb_table_schema_get_column(table,"_version"),
947                    columns, columns_json);
948     }
949
950     if (!initial || !insert || !delete || !modify) {
951         struct json *select = json_object_create();
952         json_object_put(select, "initial", json_boolean_create(initial));
953         json_object_put(select, "insert", json_boolean_create(insert));
954         json_object_put(select, "delete", json_boolean_create(delete));
955         json_object_put(select, "modify", json_boolean_create(modify));
956         json_object_put(mr, "select", select);
957     }
958
959     return mr;
960 }
961
962 static void
963 do_monitor(int argc, char *argv[])
964 {
965     const char *server = argv[1];
966     const char *database = argv[2];
967     const char *table_name = argv[3];
968     struct ovsdb_column_set columns = OVSDB_COLUMN_SET_INITIALIZER;
969     struct ovsdb_table_schema *table;
970     struct ovsdb_schema *schema;
971     struct jsonrpc_msg *request;
972     struct jsonrpc *rpc;
973     struct json *monitor, *monitor_request_array,
974         *monitor_requests, *request_id;
975
976     rpc = open_jsonrpc(server);
977
978     schema = fetch_schema_from_rpc(rpc, database);
979     table = shash_find_data(&schema->tables, table_name);
980     if (!table) {
981         ovs_fatal(0, "%s: %s does not have a table named \"%s\"",
982                   server, database, table_name);
983     }
984
985     monitor_request_array = json_array_create_empty();
986     if (argc > 4) {
987         int i;
988
989         for (i = 4; i < argc; i++) {
990             json_array_add(
991                 monitor_request_array,
992                 parse_monitor_columns(argv[i], server, database, table,
993                                       &columns));
994         }
995     } else {
996         /* Allocate a writable empty string since parse_monitor_columns() is
997          * going to strtok() it and that's risky with literal "". */
998         char empty[] = "";
999         json_array_add(
1000             monitor_request_array,
1001             parse_monitor_columns(empty, server, database, table, &columns));
1002     }
1003
1004     monitor_requests = json_object_create();
1005     json_object_put(monitor_requests, table_name, monitor_request_array);
1006
1007     monitor = json_array_create_3(json_string_create(database),
1008                                   json_null_create(), monitor_requests);
1009     request = jsonrpc_create_request("monitor", monitor, NULL);
1010     request_id = json_clone(request->id);
1011     jsonrpc_send(rpc, request);
1012     for (;;) {
1013         struct jsonrpc_msg *msg;
1014         int error;
1015
1016         error = jsonrpc_recv_block(rpc, &msg);
1017         if (error) {
1018             ovsdb_schema_destroy(schema);
1019             ovs_fatal(error, "%s: receive failed", server);
1020         }
1021
1022         if (msg->type == JSONRPC_REQUEST && !strcmp(msg->method, "echo")) {
1023             jsonrpc_send(rpc, jsonrpc_create_reply(json_clone(msg->params),
1024                                                    msg->id));
1025         } else if (msg->type == JSONRPC_REPLY
1026                    && json_equal(msg->id, request_id)) {
1027             monitor_print(msg->result, table, &columns, true);
1028             fflush(stdout);
1029             if (get_detach()) {
1030                 /* daemonize() closes the standard file descriptors.  We output
1031                  * to stdout, so we need to save and restore STDOUT_FILENO. */
1032                 int fd = dup(STDOUT_FILENO);
1033                 daemonize();
1034                 dup2(fd, STDOUT_FILENO);
1035                 close(fd);
1036             }
1037         } else if (msg->type == JSONRPC_NOTIFY
1038                    && !strcmp(msg->method, "update")) {
1039             struct json *params = msg->params;
1040             if (params->type == JSON_ARRAY
1041                 && params->u.array.n == 2
1042                 && params->u.array.elems[0]->type == JSON_NULL) {
1043                 monitor_print(params->u.array.elems[1],
1044                               table, &columns, false);
1045                 fflush(stdout);
1046             }
1047         }
1048         jsonrpc_msg_destroy(msg);
1049     }
1050 }
1051
1052 struct dump_table_aux {
1053     struct ovsdb_datum **data;
1054     const struct ovsdb_column **columns;
1055     size_t n_columns;
1056 };
1057
1058 static int
1059 compare_data(size_t a_y, size_t b_y, size_t x,
1060              const struct dump_table_aux *aux)
1061 {
1062     return ovsdb_datum_compare_3way(&aux->data[a_y][x],
1063                                     &aux->data[b_y][x],
1064                                     &aux->columns[x]->type);
1065 }
1066
1067 static int
1068 compare_rows(size_t a_y, size_t b_y, void *aux_)
1069 {
1070     struct dump_table_aux *aux = aux_;
1071     size_t x;
1072
1073     /* Skip UUID columns on the first pass, since their values tend to be
1074      * random and make our results less reproducible. */
1075     for (x = 0; x < aux->n_columns; x++) {
1076         if (aux->columns[x]->type.key.type != OVSDB_TYPE_UUID) {
1077             int cmp = compare_data(a_y, b_y, x, aux);
1078             if (cmp) {
1079                 return cmp;
1080             }
1081         }
1082     }
1083
1084     /* Use UUID columns as tie-breakers. */
1085     for (x = 0; x < aux->n_columns; x++) {
1086         if (aux->columns[x]->type.key.type == OVSDB_TYPE_UUID) {
1087             int cmp = compare_data(a_y, b_y, x, aux);
1088             if (cmp) {
1089                 return cmp;
1090             }
1091         }
1092     }
1093
1094     return 0;
1095 }
1096
1097 static void
1098 swap_rows(size_t a_y, size_t b_y, void *aux_)
1099 {
1100     struct dump_table_aux *aux = aux_;
1101     struct ovsdb_datum *tmp = aux->data[a_y];
1102     aux->data[a_y] = aux->data[b_y];
1103     aux->data[b_y] = tmp;
1104 }
1105
1106 static char *
1107 format_data(const struct ovsdb_datum *datum, const struct ovsdb_type *type)
1108 {
1109     if (data_format == DF_JSON) {
1110         struct json *json = ovsdb_datum_to_json(datum, type);
1111         char *s = json_to_string(json, JSSF_SORT);
1112         json_destroy(json);
1113         return s;
1114     } else if (data_format == DF_STRING) {
1115         struct ds s;
1116
1117         ds_init(&s);
1118         ovsdb_datum_to_string(datum, type, &s);
1119         return ds_steal_cstr(&s);
1120     } else {
1121         NOT_REACHED();
1122     }
1123 }
1124
1125 static int
1126 compare_columns(const void *a_, const void *b_)
1127 {
1128     const struct ovsdb_column *const *ap = a_;
1129     const struct ovsdb_column *const *bp = b_;
1130     const struct ovsdb_column *a = *ap;
1131     const struct ovsdb_column *b = *bp;
1132
1133     return strcmp(a->name, b->name);
1134 }
1135
1136 static void
1137 dump_table(const struct ovsdb_table_schema *ts, struct json_array *rows)
1138 {
1139     const struct ovsdb_column **columns;
1140     size_t n_columns;
1141
1142     struct ovsdb_datum **data;
1143
1144     struct dump_table_aux aux;
1145     struct shash_node *node;
1146     struct table t;
1147     size_t x, y;
1148
1149     /* Sort columns by name, for reproducibility. */
1150     columns = xmalloc(shash_count(&ts->columns) * sizeof *columns);
1151     n_columns = 0;
1152     SHASH_FOR_EACH (node, &ts->columns) {
1153         struct ovsdb_column *column = node->data;
1154         if (strcmp(column->name, "_version")) {
1155             columns[n_columns++] = column;
1156         }
1157     }
1158     qsort(columns, n_columns, sizeof *columns, compare_columns);
1159
1160     /* Extract data from table. */
1161     data = xmalloc(rows->n * sizeof *data);
1162     for (y = 0; y < rows->n; y++) {
1163         struct shash *row;
1164
1165         if (rows->elems[y]->type != JSON_OBJECT) {
1166             ovs_fatal(0,  "row %zu in table %s response is not a JSON object: "
1167                       "%s", y, ts->name, json_to_string(rows->elems[y], 0));
1168         }
1169         row = json_object(rows->elems[y]);
1170
1171         data[y] = xmalloc(n_columns * sizeof **data);
1172         for (x = 0; x < n_columns; x++) {
1173             const struct json *json = shash_find_data(row, columns[x]->name);
1174             if (!json) {
1175                 ovs_fatal(0, "row %zu in table %s response lacks %s column",
1176                           y, ts->name, columns[x]->name);
1177             }
1178
1179             check_ovsdb_error(ovsdb_datum_from_json(&data[y][x],
1180                                                     &columns[x]->type,
1181                                                     json, NULL));
1182         }
1183     }
1184
1185     /* Sort rows by column values, for reproducibility. */
1186     aux.data = data;
1187     aux.columns = columns;
1188     aux.n_columns = n_columns;
1189     sort(rows->n, compare_rows, swap_rows, &aux);
1190
1191     /* Add column headings. */
1192     table_init(&t);
1193     table_set_caption(&t, xasprintf("%s table", ts->name));
1194     for (x = 0; x < n_columns; x++) {
1195         table_add_column(&t, "%s", columns[x]->name);
1196     }
1197
1198     /* Print rows. */
1199     for (y = 0; y < rows->n; y++) {
1200         table_add_row(&t);
1201         for (x = 0; x < n_columns; x++) {
1202             table_add_cell_nocopy(&t, format_data(&data[y][x],
1203                                                   &columns[x]->type));
1204         }
1205     }
1206     table_print(&t);
1207     table_destroy(&t);
1208 }
1209
1210 static void
1211 do_dump(int argc OVS_UNUSED, char *argv[])
1212 {
1213     const char *server = argv[1];
1214     const char *database = argv[2];
1215
1216     struct jsonrpc_msg *request, *reply;
1217     struct ovsdb_schema *schema;
1218     struct json *transaction;
1219     struct jsonrpc *rpc;
1220     int error;
1221
1222     const struct shash_node **tables;
1223     size_t n_tables;
1224
1225     size_t i;
1226
1227     rpc = open_jsonrpc(server);
1228
1229     schema = fetch_schema_from_rpc(rpc, database);
1230     tables = shash_sort(&schema->tables);
1231     n_tables = shash_count(&schema->tables);
1232
1233     /* Construct transaction to retrieve entire database. */
1234     transaction = json_array_create_1(json_string_create(database));
1235     for (i = 0; i < n_tables; i++) {
1236         const struct ovsdb_table_schema *ts = tables[i]->data;
1237         struct json *op, *columns;
1238         struct shash_node *node;
1239
1240         columns = json_array_create_empty();
1241         SHASH_FOR_EACH (node, &ts->columns) {
1242             const struct ovsdb_column *column = node->data;
1243
1244             if (strcmp(column->name, "_version")) {
1245                 json_array_add(columns, json_string_create(column->name));
1246             }
1247         }
1248
1249         op = json_object_create();
1250         json_object_put_string(op, "op", "select");
1251         json_object_put_string(op, "table", tables[i]->name);
1252         json_object_put(op, "where", json_array_create_empty());
1253         json_object_put(op, "columns", columns);
1254         json_array_add(transaction, op);
1255     }
1256
1257     /* Send request, get reply. */
1258     request = jsonrpc_create_request("transact", transaction, NULL);
1259     error = jsonrpc_transact_block(rpc, request, &reply);
1260     if (error) {
1261         ovs_fatal(error, "transaction failed");
1262     }
1263
1264     /* Print database contents. */
1265     if (reply->result->type != JSON_ARRAY
1266         || reply->result->u.array.n != n_tables) {
1267         ovs_fatal(0, "reply is not array of %zu elements: %s",
1268                   n_tables, json_to_string(reply->result, 0));
1269     }
1270     for (i = 0; i < n_tables; i++) {
1271         const struct ovsdb_table_schema *ts = tables[i]->data;
1272         const struct json *op_result = reply->result->u.array.elems[i];
1273         struct json *rows;
1274
1275         if (op_result->type != JSON_OBJECT
1276             || !(rows = shash_find_data(json_object(op_result), "rows"))
1277             || rows->type != JSON_ARRAY) {
1278             ovs_fatal(0, "%s table reply is not an object with a \"rows\" "
1279                       "member array: %s",
1280                       ts->name, json_to_string(op_result, 0));
1281         }
1282
1283         dump_table(ts, &rows->u.array);
1284     }
1285 }
1286
1287 static void
1288 do_help(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
1289 {
1290     usage();
1291 }
1292
1293 static const struct command all_commands[] = {
1294     { "list-dbs", 1, 1, do_list_dbs },
1295     { "get-schema", 2, 2, do_get_schema },
1296     { "list-tables", 2, 2, do_list_tables },
1297     { "list-columns", 2, 3, do_list_columns },
1298     { "transact", 2, 2, do_transact },
1299     { "monitor", 3, INT_MAX, do_monitor },
1300     { "dump", 2, 2, do_dump },
1301     { "help", 0, INT_MAX, do_help },
1302     { NULL, 0, 0, NULL },
1303 };