ovsdb-server: Destroy allocated shash.
[cascardo/ovs.git] / ovsdb / ovsdb-client.c
1 /*
2  * Copyright (c) 2009, 2010, 2011, 2012, 2013, 2014, 2015 Nicira, Inc.
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 <ctype.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 "dirs.h"
33 #include "dynamic-string.h"
34 #include "fatal-signal.h"
35 #include "json.h"
36 #include "jsonrpc.h"
37 #include "lib/table.h"
38 #include "ovsdb.h"
39 #include "ovsdb-data.h"
40 #include "ovsdb-error.h"
41 #include "poll-loop.h"
42 #include "sort.h"
43 #include "svec.h"
44 #include "stream.h"
45 #include "stream-ssl.h"
46 #include "table.h"
47 #include "timeval.h"
48 #include "unixctl.h"
49 #include "util.h"
50 #include "openvswitch/vlog.h"
51
52 VLOG_DEFINE_THIS_MODULE(ovsdb_client);
53
54 enum args_needed {
55     NEED_NONE,            /* No JSON-RPC connection or database name needed. */
56     NEED_RPC,             /* JSON-RPC connection needed. */
57     NEED_DATABASE         /* JSON-RPC connection and database name needed. */
58 };
59
60 struct ovsdb_client_command {
61     const char *name;
62     enum args_needed need;
63     int min_args;
64     int max_args;
65     void (*handler)(struct jsonrpc *rpc, const char *database,
66                     int argc, char *argv[]);
67 };
68
69 /* --timestamp: Print a timestamp before each update on "monitor" command? */
70 static bool timestamp;
71
72 /* Format for table output. */
73 static struct table_style table_style = TABLE_STYLE_DEFAULT;
74
75 static const struct ovsdb_client_command *get_all_commands(void);
76
77 OVS_NO_RETURN static void usage(void);
78 static void parse_options(int argc, char *argv[]);
79 static struct jsonrpc *open_jsonrpc(const char *server);
80 static void fetch_dbs(struct jsonrpc *, struct svec *dbs);
81
82 int
83 main(int argc, char *argv[])
84 {
85     const struct ovsdb_client_command *command;
86     const char *database;
87     struct jsonrpc *rpc;
88
89     ovs_cmdl_proctitle_init(argc, argv);
90     set_program_name(argv[0]);
91     parse_options(argc, argv);
92     fatal_ignore_sigpipe();
93
94     daemon_become_new_user(false);
95     if (optind >= argc) {
96         ovs_fatal(0, "missing command name; use --help for help");
97     }
98
99     for (command = get_all_commands(); ; command++) {
100         if (!command->name) {
101             VLOG_FATAL("unknown command '%s'; use --help for help",
102                        argv[optind]);
103         } else if (!strcmp(command->name, argv[optind])) {
104             break;
105         }
106     }
107     optind++;
108
109     if (command->need != NEED_NONE) {
110         if (argc - optind > command->min_args
111             && (isalpha((unsigned char) argv[optind][0])
112                 && strchr(argv[optind], ':'))) {
113             rpc = open_jsonrpc(argv[optind++]);
114         } else {
115             char *sock = xasprintf("unix:%s/db.sock", ovs_rundir());
116             rpc = open_jsonrpc(sock);
117             free(sock);
118         }
119     } else {
120         rpc = NULL;
121     }
122
123     if (command->need == NEED_DATABASE) {
124         struct svec dbs;
125
126         svec_init(&dbs);
127         fetch_dbs(rpc, &dbs);
128         if (argc - optind > command->min_args
129             && svec_contains(&dbs, argv[optind])) {
130             database = argv[optind++];
131         } else if (dbs.n == 1) {
132             database = xstrdup(dbs.names[0]);
133         } else if (svec_contains(&dbs, "Open_vSwitch")) {
134             database = "Open_vSwitch";
135         } else {
136             ovs_fatal(0, "no default database for `%s' command, please "
137                       "specify a database name", command->name);
138         }
139         svec_destroy(&dbs);
140     } else {
141         database = NULL;
142     }
143
144     if (argc - optind < command->min_args ||
145         argc - optind > command->max_args) {
146         VLOG_FATAL("invalid syntax for '%s' (use --help for help)",
147                     command->name);
148     }
149
150     command->handler(rpc, database, argc - optind, argv + optind);
151
152     jsonrpc_close(rpc);
153
154     if (ferror(stdout)) {
155         VLOG_FATAL("write to stdout failed");
156     }
157     if (ferror(stderr)) {
158         VLOG_FATAL("write to stderr failed");
159     }
160
161     return 0;
162 }
163
164 static void
165 parse_options(int argc, char *argv[])
166 {
167     enum {
168         OPT_BOOTSTRAP_CA_CERT = UCHAR_MAX + 1,
169         OPT_TIMESTAMP,
170         VLOG_OPTION_ENUMS,
171         DAEMON_OPTION_ENUMS,
172         TABLE_OPTION_ENUMS
173     };
174     static const struct option long_options[] = {
175         {"help", no_argument, NULL, 'h'},
176         {"version", no_argument, NULL, 'V'},
177         {"timestamp", no_argument, NULL, OPT_TIMESTAMP},
178         VLOG_LONG_OPTIONS,
179         DAEMON_LONG_OPTIONS,
180 #ifdef HAVE_OPENSSL
181         {"bootstrap-ca-cert", required_argument, NULL, OPT_BOOTSTRAP_CA_CERT},
182         STREAM_SSL_LONG_OPTIONS,
183 #endif
184         TABLE_LONG_OPTIONS,
185         {NULL, 0, NULL, 0},
186     };
187     char *short_options = ovs_cmdl_long_options_to_short_options(long_options);
188
189     for (;;) {
190         int c;
191
192         c = getopt_long(argc, argv, short_options, long_options, NULL);
193         if (c == -1) {
194             break;
195         }
196
197         switch (c) {
198         case 'h':
199             usage();
200
201         case 'V':
202             ovs_print_version(0, 0);
203             exit(EXIT_SUCCESS);
204
205         VLOG_OPTION_HANDLERS
206         DAEMON_OPTION_HANDLERS
207         TABLE_OPTION_HANDLERS(&table_style)
208         STREAM_SSL_OPTION_HANDLERS
209
210         case OPT_BOOTSTRAP_CA_CERT:
211             stream_ssl_set_ca_cert_file(optarg, true);
212             break;
213
214         case OPT_TIMESTAMP:
215             timestamp = true;
216             break;
217
218         case '?':
219             exit(EXIT_FAILURE);
220
221         case 0:
222             /* getopt_long() already set the value for us. */
223             break;
224
225         default:
226             abort();
227         }
228     }
229     free(short_options);
230 }
231
232 static void
233 usage(void)
234 {
235     printf("%s: Open vSwitch database JSON-RPC client\n"
236            "usage: %s [OPTIONS] COMMAND [ARG...]\n"
237            "\nValid commands are:\n"
238            "\n  list-dbs [SERVER]\n"
239            "    list databases available on SERVER\n"
240            "\n  get-schema [SERVER] [DATABASE]\n"
241            "    retrieve schema for DATABASE from SERVER\n"
242            "\n  get-schema-version [SERVER] [DATABASE]\n"
243            "    retrieve schema for DATABASE from SERVER and report only its\n"
244            "    version number on stdout\n"
245            "\n  list-tables [SERVER] [DATABASE]\n"
246            "    list tables for DATABASE on SERVER\n"
247            "\n  list-columns [SERVER] [DATABASE] [TABLE]\n"
248            "    list columns in TABLE (or all tables) in DATABASE on SERVER\n"
249            "\n  transact [SERVER] TRANSACTION\n"
250            "    run TRANSACTION (a JSON array of operations) on SERVER\n"
251            "    and print the results as JSON on stdout\n"
252            "\n  monitor [SERVER] [DATABASE] TABLE [COLUMN,...]...\n"
253            "    monitor contents of COLUMNs in TABLE in DATABASE on SERVER.\n"
254            "    COLUMNs may include !initial, !insert, !delete, !modify\n"
255            "    to avoid seeing the specified kinds of changes.\n"
256            "\n  monitor [SERVER] [DATABASE] ALL\n"
257            "    monitor all changes to all columns in all tables\n"
258            "    in DATBASE on SERVER.\n"
259            "\n  dump [SERVER] [DATABASE]\n"
260            "    dump contents of DATABASE on SERVER to stdout\n"
261            "\nThe default SERVER is unix:%s/db.sock.\n"
262            "The default DATABASE is Open_vSwitch.\n",
263            program_name, program_name, ovs_rundir());
264     stream_usage("SERVER", true, true, true);
265     printf("\nOutput formatting options:\n"
266            "  -f, --format=FORMAT         set output formatting to FORMAT\n"
267            "                              (\"table\", \"html\", \"csv\", "
268            "or \"json\")\n"
269            "  --no-headings               omit table heading row\n"
270            "  --pretty                    pretty-print JSON in output\n"
271            "  --timestamp                 timestamp \"monitor\" output");
272     daemon_usage();
273     vlog_usage();
274     printf("\nOther options:\n"
275            "  -h, --help                  display this help message\n"
276            "  -V, --version               display version information\n");
277     exit(EXIT_SUCCESS);
278 }
279 \f
280 static void
281 check_txn(int error, struct jsonrpc_msg **reply_)
282 {
283     struct jsonrpc_msg *reply = *reply_;
284
285     if (error) {
286         ovs_fatal(error, "transaction failed");
287     }
288
289     if (reply->error) {
290         ovs_fatal(error, "transaction returned error: %s",
291                   json_to_string(reply->error, table_style.json_flags));
292     }
293 }
294
295 static struct json *
296 parse_json(const char *s)
297 {
298     struct json *json = json_from_string(s);
299     if (json->type == JSON_STRING) {
300         ovs_fatal(0, "\"%s\": %s", s, json->u.string);
301     }
302     return json;
303 }
304
305 static struct jsonrpc *
306 open_jsonrpc(const char *server)
307 {
308     struct stream *stream;
309     int error;
310
311     error = stream_open_block(jsonrpc_stream_open(server, &stream,
312                               DSCP_DEFAULT), &stream);
313     if (error == EAFNOSUPPORT) {
314         struct pstream *pstream;
315
316         error = jsonrpc_pstream_open(server, &pstream, DSCP_DEFAULT);
317         if (error) {
318             ovs_fatal(error, "failed to connect or listen to \"%s\"", server);
319         }
320
321         VLOG_INFO("%s: waiting for connection...", server);
322         error = pstream_accept_block(pstream, &stream);
323         if (error) {
324             ovs_fatal(error, "failed to accept connection on \"%s\"", server);
325         }
326
327         pstream_close(pstream);
328     } else if (error) {
329         ovs_fatal(error, "failed to connect to \"%s\"", server);
330     }
331
332     return jsonrpc_open(stream);
333 }
334
335 static void
336 print_json(struct json *json)
337 {
338     char *string = json_to_string(json, table_style.json_flags);
339     fputs(string, stdout);
340     free(string);
341 }
342
343 static void
344 print_and_free_json(struct json *json)
345 {
346     print_json(json);
347     json_destroy(json);
348 }
349
350 static void
351 check_ovsdb_error(struct ovsdb_error *error)
352 {
353     if (error) {
354         ovs_fatal(0, "%s", ovsdb_error_to_string(error));
355     }
356 }
357
358 static struct ovsdb_schema *
359 fetch_schema(struct jsonrpc *rpc, const char *database)
360 {
361     struct jsonrpc_msg *request, *reply;
362     struct ovsdb_schema *schema;
363
364     request = jsonrpc_create_request("get_schema",
365                                      json_array_create_1(
366                                          json_string_create(database)),
367                                      NULL);
368     check_txn(jsonrpc_transact_block(rpc, request, &reply), &reply);
369     check_ovsdb_error(ovsdb_schema_from_json(reply->result, &schema));
370     jsonrpc_msg_destroy(reply);
371
372     return schema;
373 }
374
375 static void
376 fetch_dbs(struct jsonrpc *rpc, struct svec *dbs)
377 {
378     struct jsonrpc_msg *request, *reply;
379     size_t i;
380
381     request = jsonrpc_create_request("list_dbs", json_array_create_empty(),
382                                      NULL);
383
384     check_txn(jsonrpc_transact_block(rpc, request, &reply), &reply);
385     if (reply->result->type != JSON_ARRAY) {
386         ovs_fatal(0, "list_dbs response is not array");
387     }
388
389     for (i = 0; i < reply->result->u.array.n; i++) {
390         const struct json *name = reply->result->u.array.elems[i];
391
392         if (name->type != JSON_STRING) {
393             ovs_fatal(0, "list_dbs response %"PRIuSIZE" is not string", i);
394         }
395         svec_add(dbs, name->u.string);
396     }
397     jsonrpc_msg_destroy(reply);
398     svec_sort(dbs);
399 }
400 \f
401 static void
402 do_list_dbs(struct jsonrpc *rpc, const char *database OVS_UNUSED,
403             int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
404 {
405     const char *db_name;
406     struct svec dbs;
407     size_t i;
408
409     svec_init(&dbs);
410     fetch_dbs(rpc, &dbs);
411     SVEC_FOR_EACH (i, db_name, &dbs) {
412         puts(db_name);
413     }
414     svec_destroy(&dbs);
415 }
416
417 static void
418 do_get_schema(struct jsonrpc *rpc, const char *database,
419               int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
420 {
421     struct ovsdb_schema *schema = fetch_schema(rpc, database);
422     print_and_free_json(ovsdb_schema_to_json(schema));
423     ovsdb_schema_destroy(schema);
424 }
425
426 static void
427 do_get_schema_version(struct jsonrpc *rpc, const char *database,
428                       int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
429 {
430     struct ovsdb_schema *schema = fetch_schema(rpc, database);
431     puts(schema->version);
432     ovsdb_schema_destroy(schema);
433 }
434
435 static void
436 do_list_tables(struct jsonrpc *rpc, const char *database,
437                int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
438 {
439     struct ovsdb_schema *schema;
440     struct shash_node *node;
441     struct table t;
442
443     schema = fetch_schema(rpc, database);
444     table_init(&t);
445     table_add_column(&t, "Table");
446     SHASH_FOR_EACH (node, &schema->tables) {
447         struct ovsdb_table_schema *ts = node->data;
448
449         table_add_row(&t);
450         table_add_cell(&t)->text = xstrdup(ts->name);
451     }
452     ovsdb_schema_destroy(schema);
453     table_print(&t, &table_style);
454 }
455
456 static void
457 do_list_columns(struct jsonrpc *rpc, const char *database,
458                 int argc OVS_UNUSED, char *argv[])
459 {
460     const char *table_name = argv[0];
461     struct ovsdb_schema *schema;
462     struct shash_node *table_node;
463     struct table t;
464
465     schema = fetch_schema(rpc, database);
466     table_init(&t);
467     if (!table_name) {
468         table_add_column(&t, "Table");
469     }
470     table_add_column(&t, "Column");
471     table_add_column(&t, "Type");
472     SHASH_FOR_EACH (table_node, &schema->tables) {
473         struct ovsdb_table_schema *ts = table_node->data;
474
475         if (!table_name || !strcmp(table_name, ts->name)) {
476             struct shash_node *column_node;
477
478             SHASH_FOR_EACH (column_node, &ts->columns) {
479                 const struct ovsdb_column *column = column_node->data;
480
481                 table_add_row(&t);
482                 if (!table_name) {
483                     table_add_cell(&t)->text = xstrdup(ts->name);
484                 }
485                 table_add_cell(&t)->text = xstrdup(column->name);
486                 table_add_cell(&t)->json = ovsdb_type_to_json(&column->type);
487             }
488         }
489     }
490     ovsdb_schema_destroy(schema);
491     table_print(&t, &table_style);
492 }
493
494 static void
495 do_transact(struct jsonrpc *rpc, const char *database OVS_UNUSED,
496             int argc OVS_UNUSED, char *argv[])
497 {
498     struct jsonrpc_msg *request, *reply;
499     struct json *transaction;
500
501     transaction = parse_json(argv[0]);
502
503     request = jsonrpc_create_request("transact", transaction, NULL);
504     check_txn(jsonrpc_transact_block(rpc, request, &reply), &reply);
505     print_json(reply->result);
506     putchar('\n');
507     jsonrpc_msg_destroy(reply);
508 }
509 \f
510 /* "monitor" command. */
511
512 struct monitored_table {
513     struct ovsdb_table_schema *table;
514     struct ovsdb_column_set columns;
515 };
516
517 static void
518 monitor_print_row(struct json *row, const char *type, const char *uuid,
519                   const struct ovsdb_column_set *columns, struct table *t)
520 {
521     size_t i;
522
523     if (!row) {
524         ovs_error(0, "missing %s row", type);
525         return;
526     } else if (row->type != JSON_OBJECT) {
527         ovs_error(0, "<row> is not object");
528         return;
529     }
530
531     table_add_row(t);
532     table_add_cell(t)->text = xstrdup(uuid);
533     table_add_cell(t)->text = xstrdup(type);
534     for (i = 0; i < columns->n_columns; i++) {
535         const struct ovsdb_column *column = columns->columns[i];
536         struct json *value = shash_find_data(json_object(row), column->name);
537         struct cell *cell = table_add_cell(t);
538         if (value) {
539             cell->json = json_clone(value);
540             cell->type = &column->type;
541         }
542     }
543 }
544
545 static void
546 monitor_print_table(struct json *table_update,
547                     const struct monitored_table *mt, char *caption,
548                     bool initial)
549 {
550     const struct ovsdb_table_schema *table = mt->table;
551     const struct ovsdb_column_set *columns = &mt->columns;
552     struct shash_node *node;
553     struct table t;
554     size_t i;
555
556     if (table_update->type != JSON_OBJECT) {
557         ovs_error(0, "<table-update> for table %s is not object", table->name);
558         return;
559     }
560
561     table_init(&t);
562     table_set_timestamp(&t, timestamp);
563     table_set_caption(&t, caption);
564
565     table_add_column(&t, "row");
566     table_add_column(&t, "action");
567     for (i = 0; i < columns->n_columns; i++) {
568         table_add_column(&t, "%s", columns->columns[i]->name);
569     }
570     SHASH_FOR_EACH (node, json_object(table_update)) {
571         struct json *row_update = node->data;
572         struct json *old, *new;
573
574         if (row_update->type != JSON_OBJECT) {
575             ovs_error(0, "<row-update> is not object");
576             continue;
577         }
578         old = shash_find_data(json_object(row_update), "old");
579         new = shash_find_data(json_object(row_update), "new");
580         if (initial) {
581             monitor_print_row(new, "initial", node->name, columns, &t);
582         } else if (!old) {
583             monitor_print_row(new, "insert", node->name, columns, &t);
584         } else if (!new) {
585             monitor_print_row(old, "delete", node->name, columns, &t);
586         } else {
587             monitor_print_row(old, "old", node->name, columns, &t);
588             monitor_print_row(new, "new", "", columns, &t);
589         }
590     }
591     table_print(&t, &table_style);
592     table_destroy(&t);
593 }
594
595 static void
596 monitor_print(struct json *table_updates,
597               const struct monitored_table *mts, size_t n_mts,
598               bool initial)
599 {
600     size_t i;
601
602     if (table_updates->type != JSON_OBJECT) {
603         ovs_error(0, "<table-updates> is not object");
604         return;
605     }
606
607     for (i = 0; i < n_mts; i++) {
608         const struct monitored_table *mt = &mts[i];
609         struct json *table_update = shash_find_data(json_object(table_updates),
610                                                     mt->table->name);
611         if (table_update) {
612             monitor_print_table(table_update, mt,
613                                 n_mts > 1 ? xstrdup(mt->table->name) : NULL,
614                                 initial);
615         }
616     }
617 }
618
619 static void
620 add_column(const char *server, const struct ovsdb_column *column,
621            struct ovsdb_column_set *columns, struct json *columns_json)
622 {
623     if (ovsdb_column_set_contains(columns, column->index)) {
624         ovs_fatal(0, "%s: column \"%s\" mentioned multiple times",
625                   server, column->name);
626     }
627     ovsdb_column_set_add(columns, column);
628     json_array_add(columns_json, json_string_create(column->name));
629 }
630
631 static struct json *
632 parse_monitor_columns(char *arg, const char *server, const char *database,
633                       const struct ovsdb_table_schema *table,
634                       struct ovsdb_column_set *columns)
635 {
636     bool initial, insert, delete, modify;
637     struct json *mr, *columns_json;
638     char *save_ptr = NULL;
639     char *token;
640
641     mr = json_object_create();
642     columns_json = json_array_create_empty();
643     json_object_put(mr, "columns", columns_json);
644
645     initial = insert = delete = modify = true;
646     for (token = strtok_r(arg, ",", &save_ptr); token != NULL;
647          token = strtok_r(NULL, ",", &save_ptr)) {
648         if (!strcmp(token, "!initial")) {
649             initial = false;
650         } else if (!strcmp(token, "!insert")) {
651             insert = false;
652         } else if (!strcmp(token, "!delete")) {
653             delete = false;
654         } else if (!strcmp(token, "!modify")) {
655             modify = false;
656         } else {
657             const struct ovsdb_column *column;
658
659             column = ovsdb_table_schema_get_column(table, token);
660             if (!column) {
661                 ovs_fatal(0, "%s: table \"%s\" in %s does not have a "
662                           "column named \"%s\"",
663                           server, table->name, database, token);
664             }
665             add_column(server, column, columns, columns_json);
666         }
667     }
668
669     if (columns_json->u.array.n == 0) {
670         const struct shash_node **nodes;
671         size_t i, n;
672
673         n = shash_count(&table->columns);
674         nodes = shash_sort(&table->columns);
675         for (i = 0; i < n; i++) {
676             const struct ovsdb_column *column = nodes[i]->data;
677             if (column->index != OVSDB_COL_UUID
678                 && column->index != OVSDB_COL_VERSION) {
679                 add_column(server, column, columns, columns_json);
680             }
681         }
682         free(nodes);
683
684         add_column(server, ovsdb_table_schema_get_column(table, "_version"),
685                    columns, columns_json);
686     }
687
688     if (!initial || !insert || !delete || !modify) {
689         struct json *select = json_object_create();
690         json_object_put(select, "initial", json_boolean_create(initial));
691         json_object_put(select, "insert", json_boolean_create(insert));
692         json_object_put(select, "delete", json_boolean_create(delete));
693         json_object_put(select, "modify", json_boolean_create(modify));
694         json_object_put(mr, "select", select);
695     }
696
697     return mr;
698 }
699
700 static void
701 ovsdb_client_exit(struct unixctl_conn *conn, int argc OVS_UNUSED,
702                   const char *argv[] OVS_UNUSED, void *exiting_)
703 {
704     bool *exiting = exiting_;
705     *exiting = true;
706     unixctl_command_reply(conn, NULL);
707 }
708
709 static void
710 ovsdb_client_block(struct unixctl_conn *conn, int argc OVS_UNUSED,
711                    const char *argv[] OVS_UNUSED, void *blocked_)
712 {
713     bool *blocked = blocked_;
714
715     if (!*blocked) {
716         *blocked = true;
717         unixctl_command_reply(conn, NULL);
718     } else {
719         unixctl_command_reply(conn, "already blocking");
720     }
721 }
722
723 static void
724 ovsdb_client_unblock(struct unixctl_conn *conn, int argc OVS_UNUSED,
725                      const char *argv[] OVS_UNUSED, void *blocked_)
726 {
727     bool *blocked = blocked_;
728
729     if (*blocked) {
730         *blocked = false;
731         unixctl_command_reply(conn, NULL);
732     } else {
733         unixctl_command_reply(conn, "already unblocked");
734     }
735 }
736
737 static void
738 add_monitored_table(int argc, char *argv[],
739                     const char *server, const char *database,
740                     struct ovsdb_table_schema *table,
741                     struct json *monitor_requests,
742                     struct monitored_table **mts,
743                     size_t *n_mts, size_t *allocated_mts)
744 {
745     struct json *monitor_request_array;
746     struct monitored_table *mt;
747
748     if (*n_mts >= *allocated_mts) {
749         *mts = x2nrealloc(*mts, allocated_mts, sizeof **mts);
750     }
751     mt = &(*mts)[(*n_mts)++];
752     mt->table = table;
753     ovsdb_column_set_init(&mt->columns);
754
755     monitor_request_array = json_array_create_empty();
756     if (argc > 1) {
757         int i;
758
759         for (i = 1; i < argc; i++) {
760             json_array_add(
761                 monitor_request_array,
762                 parse_monitor_columns(argv[i], server, database, table,
763                                       &mt->columns));
764         }
765     } else {
766         /* Allocate a writable empty string since parse_monitor_columns()
767          * is going to strtok() it and that's risky with literal "". */
768         char empty[] = "";
769         json_array_add(
770             monitor_request_array,
771             parse_monitor_columns(empty, server, database,
772                                   table, &mt->columns));
773     }
774
775     json_object_put(monitor_requests, table->name, monitor_request_array);
776 }
777
778 static void
779 do_monitor(struct jsonrpc *rpc, const char *database,
780            int argc, char *argv[])
781 {
782     const char *server = jsonrpc_get_name(rpc);
783     const char *table_name = argv[0];
784     struct unixctl_server *unixctl;
785     struct ovsdb_schema *schema;
786     struct jsonrpc_msg *request;
787     struct json *monitor, *monitor_requests, *request_id;
788     bool exiting = false;
789     bool blocked = false;
790
791     struct monitored_table *mts;
792     size_t n_mts, allocated_mts;
793
794     daemon_save_fd(STDOUT_FILENO);
795     daemonize_start(false);
796     if (get_detach()) {
797         int error;
798
799         error = unixctl_server_create(NULL, &unixctl);
800         if (error) {
801             ovs_fatal(error, "failed to create unixctl server");
802         }
803
804         unixctl_command_register("exit", "", 0, 0,
805                                  ovsdb_client_exit, &exiting);
806         unixctl_command_register("ovsdb-client/block", "", 0, 0,
807                                  ovsdb_client_block, &blocked);
808         unixctl_command_register("ovsdb-client/unblock", "", 0, 0,
809                                  ovsdb_client_unblock, &blocked);
810     } else {
811         unixctl = NULL;
812     }
813
814     schema = fetch_schema(rpc, database);
815
816     monitor_requests = json_object_create();
817
818     mts = NULL;
819     n_mts = allocated_mts = 0;
820     if (strcmp(table_name, "ALL")) {
821         struct ovsdb_table_schema *table;
822
823         table = shash_find_data(&schema->tables, table_name);
824         if (!table) {
825             ovs_fatal(0, "%s: %s does not have a table named \"%s\"",
826                       server, database, table_name);
827         }
828
829         add_monitored_table(argc, argv, server, database, table,
830                             monitor_requests, &mts, &n_mts, &allocated_mts);
831     } else {
832         size_t n = shash_count(&schema->tables);
833         const struct shash_node **nodes = shash_sort(&schema->tables);
834         size_t i;
835
836         for (i = 0; i < n; i++) {
837             struct ovsdb_table_schema *table = nodes[i]->data;
838
839             add_monitored_table(argc, argv, server, database, table,
840                                 monitor_requests,
841                                 &mts, &n_mts, &allocated_mts);
842         }
843         free(nodes);
844     }
845
846     monitor = json_array_create_3(json_string_create(database),
847                                   json_null_create(), monitor_requests);
848     request = jsonrpc_create_request("monitor", monitor, NULL);
849     request_id = json_clone(request->id);
850     jsonrpc_send(rpc, request);
851
852     for (;;) {
853         unixctl_server_run(unixctl);
854         while (!blocked) {
855             struct jsonrpc_msg *msg;
856             int error;
857
858             error = jsonrpc_recv(rpc, &msg);
859             if (error == EAGAIN) {
860                 break;
861             } else if (error) {
862                 ovs_fatal(error, "%s: receive failed", server);
863             }
864
865             if (msg->type == JSONRPC_REQUEST && !strcmp(msg->method, "echo")) {
866                 jsonrpc_send(rpc, jsonrpc_create_reply(json_clone(msg->params),
867                                                        msg->id));
868             } else if (msg->type == JSONRPC_REPLY
869                        && json_equal(msg->id, request_id)) {
870                 monitor_print(msg->result, mts, n_mts, true);
871                 fflush(stdout);
872                 daemonize_complete();
873             } else if (msg->type == JSONRPC_NOTIFY
874                        && !strcmp(msg->method, "update")) {
875                 struct json *params = msg->params;
876                 if (params->type == JSON_ARRAY
877                     && params->u.array.n == 2
878                     && params->u.array.elems[0]->type == JSON_NULL) {
879                     monitor_print(params->u.array.elems[1], mts, n_mts, false);
880                     fflush(stdout);
881                 }
882             }
883             jsonrpc_msg_destroy(msg);
884         }
885
886         if (exiting) {
887             break;
888         }
889
890         jsonrpc_run(rpc);
891         jsonrpc_wait(rpc);
892         if (!blocked) {
893             jsonrpc_recv_wait(rpc);
894         }
895         unixctl_server_wait(unixctl);
896         poll_block();
897     }
898 }
899
900 struct dump_table_aux {
901     struct ovsdb_datum **data;
902     const struct ovsdb_column **columns;
903     size_t n_columns;
904 };
905
906 static int
907 compare_data(size_t a_y, size_t b_y, size_t x,
908              const struct dump_table_aux *aux)
909 {
910     return ovsdb_datum_compare_3way(&aux->data[a_y][x],
911                                     &aux->data[b_y][x],
912                                     &aux->columns[x]->type);
913 }
914
915 static int
916 compare_rows(size_t a_y, size_t b_y, void *aux_)
917 {
918     struct dump_table_aux *aux = aux_;
919     size_t x;
920
921     /* Skip UUID columns on the first pass, since their values tend to be
922      * random and make our results less reproducible. */
923     for (x = 0; x < aux->n_columns; x++) {
924         if (aux->columns[x]->type.key.type != OVSDB_TYPE_UUID) {
925             int cmp = compare_data(a_y, b_y, x, aux);
926             if (cmp) {
927                 return cmp;
928             }
929         }
930     }
931
932     /* Use UUID columns as tie-breakers. */
933     for (x = 0; x < aux->n_columns; x++) {
934         if (aux->columns[x]->type.key.type == OVSDB_TYPE_UUID) {
935             int cmp = compare_data(a_y, b_y, x, aux);
936             if (cmp) {
937                 return cmp;
938             }
939         }
940     }
941
942     return 0;
943 }
944
945 static void
946 swap_rows(size_t a_y, size_t b_y, void *aux_)
947 {
948     struct dump_table_aux *aux = aux_;
949     struct ovsdb_datum *tmp = aux->data[a_y];
950     aux->data[a_y] = aux->data[b_y];
951     aux->data[b_y] = tmp;
952 }
953
954 static int
955 compare_columns(const void *a_, const void *b_)
956 {
957     const struct ovsdb_column *const *ap = a_;
958     const struct ovsdb_column *const *bp = b_;
959     const struct ovsdb_column *a = *ap;
960     const struct ovsdb_column *b = *bp;
961
962     return strcmp(a->name, b->name);
963 }
964
965 static void
966 dump_table(const struct ovsdb_table_schema *ts, struct json_array *rows)
967 {
968     const struct ovsdb_column **columns;
969     size_t n_columns;
970
971     struct ovsdb_datum **data;
972
973     struct dump_table_aux aux;
974     struct shash_node *node;
975     struct table t;
976     size_t x, y;
977
978     /* Sort columns by name, for reproducibility. */
979     columns = xmalloc(shash_count(&ts->columns) * sizeof *columns);
980     n_columns = 0;
981     SHASH_FOR_EACH (node, &ts->columns) {
982         struct ovsdb_column *column = node->data;
983         if (strcmp(column->name, "_version")) {
984             columns[n_columns++] = column;
985         }
986     }
987     qsort(columns, n_columns, sizeof *columns, compare_columns);
988
989     /* Extract data from table. */
990     data = xmalloc(rows->n * sizeof *data);
991     for (y = 0; y < rows->n; y++) {
992         struct shash *row;
993
994         if (rows->elems[y]->type != JSON_OBJECT) {
995             ovs_fatal(0,  "row %"PRIuSIZE" in table %s response is not a JSON object: "
996                       "%s", y, ts->name, json_to_string(rows->elems[y], 0));
997         }
998         row = json_object(rows->elems[y]);
999
1000         data[y] = xmalloc(n_columns * sizeof **data);
1001         for (x = 0; x < n_columns; x++) {
1002             const struct json *json = shash_find_data(row, columns[x]->name);
1003             if (!json) {
1004                 ovs_fatal(0, "row %"PRIuSIZE" in table %s response lacks %s column",
1005                           y, ts->name, columns[x]->name);
1006             }
1007
1008             check_ovsdb_error(ovsdb_datum_from_json(&data[y][x],
1009                                                     &columns[x]->type,
1010                                                     json, NULL));
1011         }
1012     }
1013
1014     /* Sort rows by column values, for reproducibility. */
1015     aux.data = data;
1016     aux.columns = columns;
1017     aux.n_columns = n_columns;
1018     sort(rows->n, compare_rows, swap_rows, &aux);
1019
1020     /* Add column headings. */
1021     table_init(&t);
1022     table_set_caption(&t, xasprintf("%s table", ts->name));
1023     for (x = 0; x < n_columns; x++) {
1024         table_add_column(&t, "%s", columns[x]->name);
1025     }
1026
1027     /* Print rows. */
1028     for (y = 0; y < rows->n; y++) {
1029         table_add_row(&t);
1030         for (x = 0; x < n_columns; x++) {
1031             struct cell *cell = table_add_cell(&t);
1032             cell->json = ovsdb_datum_to_json(&data[y][x], &columns[x]->type);
1033             cell->type = &columns[x]->type;
1034             ovsdb_datum_destroy(&data[y][x], &columns[x]->type);
1035         }
1036         free(data[y]);
1037     }
1038     table_print(&t, &table_style);
1039     table_destroy(&t);
1040
1041     free(data);
1042     free(columns);
1043 }
1044
1045 static void
1046 do_dump(struct jsonrpc *rpc, const char *database,
1047         int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
1048 {
1049     struct jsonrpc_msg *request, *reply;
1050     struct ovsdb_schema *schema;
1051     struct json *transaction;
1052
1053     const struct shash_node **tables;
1054     size_t n_tables;
1055
1056     size_t i;
1057
1058     schema = fetch_schema(rpc, database);
1059     tables = shash_sort(&schema->tables);
1060     n_tables = shash_count(&schema->tables);
1061
1062     /* Construct transaction to retrieve entire database. */
1063     transaction = json_array_create_1(json_string_create(database));
1064     for (i = 0; i < n_tables; i++) {
1065         const struct ovsdb_table_schema *ts = tables[i]->data;
1066         struct json *op, *columns;
1067         struct shash_node *node;
1068
1069         columns = json_array_create_empty();
1070         SHASH_FOR_EACH (node, &ts->columns) {
1071             const struct ovsdb_column *column = node->data;
1072
1073             if (strcmp(column->name, "_version")) {
1074                 json_array_add(columns, json_string_create(column->name));
1075             }
1076         }
1077
1078         op = json_object_create();
1079         json_object_put_string(op, "op", "select");
1080         json_object_put_string(op, "table", tables[i]->name);
1081         json_object_put(op, "where", json_array_create_empty());
1082         json_object_put(op, "columns", columns);
1083         json_array_add(transaction, op);
1084     }
1085
1086     /* Send request, get reply. */
1087     request = jsonrpc_create_request("transact", transaction, NULL);
1088     check_txn(jsonrpc_transact_block(rpc, request, &reply), &reply);
1089
1090     /* Print database contents. */
1091     if (reply->result->type != JSON_ARRAY
1092         || reply->result->u.array.n != n_tables) {
1093         ovs_fatal(0, "reply is not array of %"PRIuSIZE" elements: %s",
1094                   n_tables, json_to_string(reply->result, 0));
1095     }
1096     for (i = 0; i < n_tables; i++) {
1097         const struct ovsdb_table_schema *ts = tables[i]->data;
1098         const struct json *op_result = reply->result->u.array.elems[i];
1099         struct json *rows;
1100
1101         if (op_result->type != JSON_OBJECT
1102             || !(rows = shash_find_data(json_object(op_result), "rows"))
1103             || rows->type != JSON_ARRAY) {
1104             ovs_fatal(0, "%s table reply is not an object with a \"rows\" "
1105                       "member array: %s",
1106                       ts->name, json_to_string(op_result, 0));
1107         }
1108
1109         dump_table(ts, &rows->u.array);
1110     }
1111
1112     jsonrpc_msg_destroy(reply);
1113     free(tables);
1114     ovsdb_schema_destroy(schema);
1115 }
1116
1117 static void
1118 do_help(struct jsonrpc *rpc OVS_UNUSED, const char *database OVS_UNUSED,
1119         int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
1120 {
1121     usage();
1122 }
1123
1124 /* All command handlers (except for "help") are expected to take an optional
1125  * server socket name (e.g. "unix:...") as their first argument.  The socket
1126  * name argument must be included in max_args (but left out of min_args).  The
1127  * command name and socket name are not included in the arguments passed to the
1128  * handler: the argv[0] passed to the handler is the first argument after the
1129  * optional server socket name.  The connection to the server is available as
1130  * global variable 'rpc'. */
1131 static const struct ovsdb_client_command all_commands[] = {
1132     { "list-dbs",           NEED_RPC,      0, 0,       do_list_dbs },
1133     { "get-schema",         NEED_DATABASE, 0, 0,       do_get_schema },
1134     { "get-schema-version", NEED_DATABASE, 0, 0,       do_get_schema_version },
1135     { "list-tables",        NEED_DATABASE, 0, 0,       do_list_tables },
1136     { "list-columns",       NEED_DATABASE, 0, 1,       do_list_columns },
1137     { "transact",           NEED_RPC,      1, 1,       do_transact },
1138     { "monitor",            NEED_DATABASE, 1, INT_MAX, do_monitor },
1139     { "dump",               NEED_DATABASE, 0, 0,       do_dump },
1140
1141     { "help",               NEED_NONE,     0, INT_MAX, do_help },
1142
1143     { NULL,                 0,             0, 0,       NULL },
1144 };
1145
1146 static const struct ovsdb_client_command *get_all_commands(void)
1147 {
1148     return all_commands;
1149 }