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