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