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