forked from openvswitch/ovs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathovsdb-client.c
2520 lines (2192 loc) · 81.3 KB
/
ovsdb-client.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2009-2017 Nicira, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <config.h>
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <getopt.h>
#include <limits.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "command-line.h"
#include "column.h"
#include "compiler.h"
#include "daemon.h"
#include "dirs.h"
#include "openvswitch/dynamic-string.h"
#include "fatal-signal.h"
#include "file.h"
#include "openvswitch/json.h"
#include "jsonrpc.h"
#include "lib/table.h"
#include "log.h"
#include "ovsdb.h"
#include "ovsdb-data.h"
#include "ovsdb-error.h"
#include "ovsdb-session.h"
#include "openvswitch/poll-loop.h"
#include "row.h"
#include "sort.h"
#include "svec.h"
#include "storage.h"
#include "stream.h"
#include "stream-ssl.h"
#include "table.h"
#include "transaction.h"
#include "monitor.h"
#include "condition.h"
#include "timeval.h"
#include "unixctl.h"
#include "util.h"
#include "openvswitch/vlog.h"
VLOG_DEFINE_THIS_MODULE(ovsdb_client);
enum args_needed {
NEED_NONE, /* No JSON-RPC connection or database name needed. */
NEED_RPC, /* JSON-RPC connection needed. */
NEED_DATABASE /* JSON-RPC connection and database name needed. */
};
struct ovsdb_client_command {
const char *name;
enum args_needed need;
int min_args;
int max_args;
void (*handler)(struct jsonrpc *rpc, const char *database,
int argc, char *argv[]);
};
/* --timestamp: Print a timestamp before each update on "monitor" command? */
static bool timestamp;
/* --db-change-aware, --no-db-change-aware: Enable db_change_aware feature for
* "monitor" command?
*
* -1 (default): Use db_change_aware if available.
* 0: Disable db_change_aware.
* 1: Require db_change_aware.
*
* (This option is undocumented because anything other than the default is
* expected to be useful only for testing that the db_change_aware feature
* actually works.) */
static int db_change_aware = -1;
/* --force: Ignore schema differences for "restore" command? */
static bool force;
/* --leader-only, --no-leader-only: Only accept the leader in a cluster. */
static bool leader_only = true;
/* Format for table output. */
static struct table_style table_style = TABLE_STYLE_DEFAULT;
static const struct ovsdb_client_command *get_all_commands(void);
static struct json *parse_json(const char *);
OVS_NO_RETURN static void usage(void);
static void parse_options(int argc, char *argv[]);
static struct jsonrpc *open_jsonrpc(const char *server);
static void fetch_dbs(struct jsonrpc *, struct svec *dbs);
static bool should_stay_connected(const char *server, const char *database,
const struct uuid *cid,
const struct jsonrpc_msg *reply);
struct jsonrpc_msg *create_database_info_request(const char *database);
static char *
default_remote(void)
{
return xasprintf("unix:%s/db.sock", ovs_rundir());
}
static int
open_rpc(int min_args, enum args_needed need,
int argc, char *argv[], struct jsonrpc **rpcp, char **databasep)
{
struct svec remotes = SVEC_EMPTY_INITIALIZER;
struct uuid cid = UUID_ZERO;
/* First figure out the remote(s). If the first command-line argument has
* the form of a remote, use it, otherwise use the default. */
int argidx = 0;
if (argc > min_args && (isalpha((unsigned char) argv[0][0])
&& strchr(argv[0], ':'))) {
ovsdb_session_parse_remote(argv[argidx++], &remotes, &cid);
} else {
svec_add_nocopy(&remotes, default_remote());
}
/* Handle the case where there's one remote. In this case, if we need a
* database name, we try to figure out a default if none was specified
* explicitly. */
char *database = *databasep;
if (remotes.n == 1) {
struct jsonrpc *rpc = open_jsonrpc(remotes.names[0]);
svec_destroy(&remotes);
if (need == NEED_DATABASE && !database) {
struct svec dbs;
svec_init(&dbs);
fetch_dbs(rpc, &dbs);
if (argc - argidx > min_args
&& svec_contains(&dbs, argv[argidx])) {
database = xstrdup(argv[argidx++]);
} else if (svec_contains(&dbs, "Open_vSwitch")) {
database = xstrdup("Open_vSwitch");
} else {
size_t n = 0;
const char *best = NULL;
for (size_t i = 0; i < dbs.n; i++) {
if (dbs.names[i][0] != '_') {
best = dbs.names[i];
n++;
}
}
if (n != 1) {
jsonrpc_close(rpc);
ovs_fatal(0, "could not find a default database, "
"please specify a database name");
}
database = xstrdup(best);
}
svec_destroy(&dbs);
}
*rpcp = rpc;
*databasep = database;
return argidx;
}
/* If there's more than one remote, and we need a database name, then it
* must be specified explicitly. It's too likely to cause surprising
* behavior if we try to pick a default across several servers. */
if (!database && need == NEED_DATABASE) {
if (argc - argidx > min_args) {
database = xstrdup(argv[argidx++]);
} else {
ovs_fatal(0, "database name is required with multiple remotes");
}
}
/* We have multiple remotes. Connect to them in a random order and choose
* the first one that is up and hosts the database we want (if any) in an
* acceptable state. */
struct jsonrpc_session *js = jsonrpc_session_open_multiple(
&remotes, false);
svec_destroy(&remotes);
unsigned int seqno = 0;
struct json *id = NULL;
for (;;) {
jsonrpc_session_run(js);
if (!jsonrpc_session_is_alive(js)) {
ovs_fatal(0, "no servers were available");
}
if (seqno != jsonrpc_session_get_seqno(js)
&& jsonrpc_session_is_connected(js)) {
if (!database) {
break;
}
seqno = jsonrpc_session_get_seqno(js);
struct jsonrpc_msg *txn = create_database_info_request(database);
json_destroy(id);
id = json_clone(txn->id);
jsonrpc_session_send(js, txn);
}
struct jsonrpc_msg *reply = jsonrpc_session_recv(js);
if (reply && id && reply->id && json_equal(id, reply->id)) {
if (reply->type == JSONRPC_REPLY
&& should_stay_connected(jsonrpc_session_get_name(js),
database, &cid, reply)) {
jsonrpc_msg_destroy(reply);
break;
}
jsonrpc_session_force_reconnect(js);
}
jsonrpc_msg_destroy(reply);
jsonrpc_session_recv_wait(js);
jsonrpc_session_wait(js);
poll_block();
}
json_destroy(id);
*rpcp = jsonrpc_session_steal(js);
*databasep = database;
return argidx;
}
int
main(int argc, char *argv[])
{
const struct ovsdb_client_command *command;
ovs_cmdl_proctitle_init(argc, argv);
set_program_name(argv[0]);
service_start(&argc, &argv);
parse_options(argc, argv);
fatal_ignore_sigpipe();
daemon_become_new_user(false);
if (optind >= argc) {
ovs_fatal(0, "missing command name; use --help for help");
}
for (command = get_all_commands(); ; command++) {
if (!command->name) {
VLOG_FATAL("unknown command '%s'; use --help for help",
argv[optind]);
} else if (!strcmp(command->name, argv[optind])) {
break;
}
}
optind++;
char *database = NULL;
struct jsonrpc *rpc = NULL;
if (command->need != NEED_NONE) {
optind += open_rpc(command->min_args, command->need,
argc - optind, argv + optind, &rpc, &database);
}
if (argc - optind < command->min_args ||
argc - optind > command->max_args) {
free(database);
VLOG_FATAL("invalid syntax for '%s' (use --help for help)",
command->name);
}
command->handler(rpc, database, argc - optind, argv + optind);
free(database);
jsonrpc_close(rpc);
if (ferror(stdout)) {
VLOG_FATAL("write to stdout failed");
}
if (ferror(stderr)) {
VLOG_FATAL("write to stderr failed");
}
return 0;
}
static void
parse_options(int argc, char *argv[])
{
enum {
OPT_BOOTSTRAP_CA_CERT = UCHAR_MAX + 1,
OPT_TIMESTAMP,
OPT_FORCE,
OPT_LEADER_ONLY,
OPT_NO_LEADER_ONLY,
VLOG_OPTION_ENUMS,
DAEMON_OPTION_ENUMS,
TABLE_OPTION_ENUMS,
SSL_OPTION_ENUMS,
};
static const struct option long_options[] = {
{"help", no_argument, NULL, 'h'},
{"version", no_argument, NULL, 'V'},
{"timestamp", no_argument, NULL, OPT_TIMESTAMP},
{"force", no_argument, NULL, OPT_FORCE},
{"timeout", required_argument, NULL, 't'},
{"db-change-aware", no_argument, &db_change_aware, 1},
{"no-db-change-aware", no_argument, &db_change_aware, 0},
{"leader-only", no_argument, NULL, OPT_LEADER_ONLY},
{"no-leader-only", no_argument, NULL, OPT_NO_LEADER_ONLY},
VLOG_LONG_OPTIONS,
DAEMON_LONG_OPTIONS,
#ifdef HAVE_OPENSSL
{"bootstrap-ca-cert", required_argument, NULL, OPT_BOOTSTRAP_CA_CERT},
STREAM_SSL_LONG_OPTIONS,
#endif
TABLE_LONG_OPTIONS,
{NULL, 0, NULL, 0},
};
char *short_options = ovs_cmdl_long_options_to_short_options(long_options);
unsigned int timeout = 0;
table_style.format = TF_TABLE;
for (;;) {
int c;
c = getopt_long(argc, argv, short_options, long_options, NULL);
if (c == -1) {
break;
}
switch (c) {
case 'h':
usage();
case 'V':
ovs_print_version(0, 0);
exit(EXIT_SUCCESS);
VLOG_OPTION_HANDLERS
DAEMON_OPTION_HANDLERS
TABLE_OPTION_HANDLERS(&table_style)
STREAM_SSL_OPTION_HANDLERS
case OPT_BOOTSTRAP_CA_CERT:
stream_ssl_set_ca_cert_file(optarg, true);
break;
case OPT_TIMESTAMP:
timestamp = true;
break;
case OPT_FORCE:
force = true;
break;
case 't':
if (!str_to_uint(optarg, 10, &timeout) || !timeout) {
ovs_fatal(0, "value %s on -t or --timeout is invalid", optarg);
}
break;
case OPT_LEADER_ONLY:
leader_only = true;
break;
case OPT_NO_LEADER_ONLY:
leader_only = false;
break;
case '?':
exit(EXIT_FAILURE);
case 0:
/* getopt_long() already set the value for us. */
break;
default:
abort();
}
}
free(short_options);
ctl_timeout_setup(timeout);
}
static void
usage(void)
{
printf("%s: Open vSwitch database JSON-RPC client\n"
"usage: %s [OPTIONS] COMMAND [ARG...]\n"
"\nValid commands are:\n"
"\n list-dbs [SERVER]\n"
" list databases available on SERVER\n"
"\n get-schema [SERVER] [DATABASE]\n"
" retrieve schema for DATABASE from SERVER\n"
"\n get-schema-version [SERVER] [DATABASE]\n"
" retrieve schema for DATABASE from SERVER and report only its\n"
" version number on stdout\n"
"\n get-schema-cksum [SERVER] [DATABASE]\n"
" retrieve schema for DATABASE from SERVER and report only its\n"
" checksum on stdout\n"
"\n list-tables [SERVER] [DATABASE]\n"
" list tables for DATABASE on SERVER\n"
"\n list-columns [SERVER] [DATABASE] [TABLE]\n"
" list columns in TABLE (or all tables) in DATABASE on SERVER\n"
"\n transact [SERVER] TRANSACTION\n"
" run TRANSACTION (params for \"transact\" request) on SERVER\n"
" and print the results as JSON on stdout\n"
"\n query [SERVER] TRANSACTION\n"
" run TRANSACTION (params for \"transact\" request) on SERVER,\n"
" as read-only, and print the results as JSON on stdout\n"
"\n monitor [SERVER] [DATABASE] TABLE [COLUMN,...]...\n"
" monitor contents of COLUMNs in TABLE in DATABASE on SERVER.\n"
" COLUMNs may include !initial, !insert, !delete, !modify\n"
" to avoid seeing the specified kinds of changes.\n"
"\n monitor-cond [SERVER] [DATABASE] CONDITION TABLE [COLUMN,...]...\n"
" monitor contents that match CONDITION of COLUMNs in TABLE in\n"
" DATABASE on SERVER.\n"
" COLUMNs may include !initial, !insert, !delete, !modify\n"
" to avoid seeing the specified kinds of changes.\n"
"\n monitor-cond-since [SERVER] [DATABASE] [LASTID] CONDITION TABLE [COLUMN,...]...\n"
" monitor contents that match CONDITION of COLUMNs in TABLE in\n"
" DATABASE on SERVER, since change after LASTID.\n"
" LASTID specifies transaction ID after which the monitoring\n"
" starts, which works only for cluster mode. If ignored, it\n"
" defaults to an all-zero uuid.\n"
" Other arguments are the same as in monitor-cond.\n"
"\n convert [SERVER] SCHEMA\n"
" convert database on SERVER named in SCHEMA to SCHEMA.\n"
"\n needs-conversion [SERVER] SCHEMA\n"
" tests whether SCHEMA's db on SERVER needs conversion.\n"
"\n monitor [SERVER] [DATABASE] ALL\n"
" monitor all changes to all columns in all tables\n"
"\n wait [SERVER] DATABASE STATE\n"
" wait until DATABASE reaches STATE "
"(\"added\" or \"connected\" or \"removed\")\n"
" in DATBASE on SERVER.\n"
"\n dump [SERVER] [DATABASE]\n"
" dump contents of DATABASE on SERVER to stdout\n"
"\n backup [SERVER] [DATABASE] > SNAPSHOT\n"
" dump database contents in the form of a database file\n"
"\n [--force] restore [SERVER] [DATABASE] < SNAPSHOT\n"
" restore database contents from a database file\n"
"\n lock [SERVER] LOCK\n"
" create or wait for LOCK in SERVER\n"
"\n steal [SERVER] LOCK\n"
" steal LOCK from SERVER\n"
"\n unlock [SERVER] LOCK\n"
" unlock LOCK from SERVER\n"
"\nThe default SERVER is unix:%s/db.sock.\n"
"The default DATABASE is Open_vSwitch.\n",
program_name, program_name, ovs_rundir());
stream_usage("SERVER", true, true, true);
table_usage();
printf(" --timestamp timestamp \"monitor\" output");
daemon_usage();
vlog_usage();
printf("\nOther options:\n"
" -h, --help display this help message\n"
" -V, --version display version information\n");
exit(EXIT_SUCCESS);
}
static void
check_txn(int error, struct jsonrpc_msg **reply_)
{
struct jsonrpc_msg *reply = *reply_;
if (error) {
ovs_fatal(error, "transaction failed");
}
if (reply->error) {
ovs_fatal(error, "transaction returned error: %s",
json_to_string(reply->error, table_style.json_flags));
}
}
static struct json *
parse_json(const char *s)
{
struct json *json = json_from_string(s);
if (json->type == JSON_STRING) {
ovs_fatal(0, "\"%s\": %s", s, json->string);
}
return json;
}
static struct jsonrpc *
open_jsonrpc(const char *server)
{
struct stream *stream;
int error;
error = stream_open_block(jsonrpc_stream_open(server, &stream,
DSCP_DEFAULT), -1, &stream);
if (error == EAFNOSUPPORT) {
struct pstream *pstream;
error = jsonrpc_pstream_open(server, &pstream, DSCP_DEFAULT);
if (error) {
ovs_fatal(error, "failed to connect or listen to \"%s\"", server);
}
VLOG_INFO("%s: waiting for connection...", server);
error = pstream_accept_block(pstream, &stream);
if (error) {
ovs_fatal(error, "failed to accept connection on \"%s\"", server);
}
pstream_close(pstream);
} else if (error) {
ovs_fatal(error, "failed to connect to \"%s\"", server);
}
return jsonrpc_open(stream);
}
static void
print_json(struct json *json)
{
char *string = json_to_string(json, table_style.json_flags);
puts(string);
free(string);
}
static void
print_and_free_json(struct json *json)
{
print_json(json);
json_destroy(json);
}
static void
check_ovsdb_error(struct ovsdb_error *error)
{
if (error) {
ovs_fatal(0, "%s", ovsdb_error_to_string(error));
}
}
static struct ovsdb_schema *
fetch_schema(struct jsonrpc *rpc, const char *database)
{
struct jsonrpc_msg *request, *reply;
struct ovsdb_schema *schema;
request = jsonrpc_create_request("get_schema",
json_array_create_1(
json_string_create(database)),
NULL);
check_txn(jsonrpc_transact_block(rpc, request, &reply), &reply);
check_ovsdb_error(ovsdb_schema_from_json(reply->result, &schema));
jsonrpc_msg_destroy(reply);
return schema;
}
static void
fetch_dbs(struct jsonrpc *rpc, struct svec *dbs)
{
struct jsonrpc_msg *request, *reply;
size_t i;
request = jsonrpc_create_request("list_dbs", json_array_create_empty(),
NULL);
check_txn(jsonrpc_transact_block(rpc, request, &reply), &reply);
if (reply->result->type != JSON_ARRAY) {
ovs_fatal(0, "list_dbs response is not array");
}
for (i = 0; i < reply->result->array.n; i++) {
const struct json *name = reply->result->array.elems[i];
if (name->type != JSON_STRING) {
ovs_fatal(0, "list_dbs response %"PRIuSIZE" is not string", i);
}
svec_add(dbs, name->string);
}
jsonrpc_msg_destroy(reply);
svec_sort(dbs);
}
static const char *
parse_string_column(const struct json *row, const char *column_name)
{
const struct json *column = shash_find_data(json_object(row), column_name);
return column && column->type == JSON_STRING ? json_string(column) : "";
}
static int
parse_boolean_column(const struct json *row, const char *column_name)
{
const struct json *column = shash_find_data(json_object(row), column_name);
return (!column ? -1
: column->type == JSON_TRUE ? true
: column->type == JSON_FALSE ? false
: -1);
}
static struct uuid
parse_uuid_column(const struct json *row, const char *column_name)
{
const struct json *column = shash_find_data(json_object(row), column_name);
if (!column) {
return UUID_ZERO;
}
struct ovsdb_type type = { OVSDB_BASE_UUID_INIT, OVSDB_BASE_VOID_INIT,
0, 1 };
struct ovsdb_datum datum;
struct ovsdb_error *error = ovsdb_datum_from_json(&datum, &type, column,
NULL);
if (error) {
ovsdb_error_destroy(error);
return UUID_ZERO;
}
struct uuid uuid = datum.n > 0 ? datum.keys[0].uuid : UUID_ZERO;
ovsdb_datum_destroy(&datum, &type);
return uuid;
}
struct jsonrpc_msg *
create_database_info_request(const char *database)
{
struct json *op = json_object_create();
json_object_put_string(op, "op", "select");
json_object_put_string(op, "table", "Database");
struct json *condition = json_array_create_3(
json_string_create("name"),
json_string_create("=="),
json_string_create(database));
json_object_put(op, "where", json_array_create_1(condition));
struct json *txn = json_array_create_2(
json_string_create("_Server"), op);
return jsonrpc_create_request("transact", txn, NULL);
}
static const struct json *
parse_database_info_reply(const struct jsonrpc_msg *reply, const char *server,
const char *database, const struct uuid *cid)
{
const struct json *result = reply->result;
if (result->type != JSON_ARRAY
|| result->array.n != 1
|| result->array.elems[0]->type != JSON_OBJECT) {
VLOG_WARN("%s: unexpected reply to _Server request for %s",
server, database);
return NULL;
}
const struct json *op_result = result->array.elems[0];
const struct json *rows = shash_find_data(json_object(op_result), "rows");
if (!rows || rows->type != JSON_ARRAY) {
VLOG_WARN("%s: missing \"rows\" member in _Server reply for %s",
server, database);
return NULL;
}
for (size_t i = 0; i < rows->array.n; i++) {
const struct json *row = rows->array.elems[i];
if (row->type != JSON_OBJECT) {
VLOG_WARN("%s: bad row in _Server reply for %s",
server, database);
continue;
}
if (strcmp(parse_string_column(row, "name"), database)) {
continue;
}
if (cid && !uuid_is_zero(cid)) {
struct uuid cid2 = parse_uuid_column(row, "cid");
if (!uuid_equals(cid, &cid2)) {
continue;
}
}
return row;
}
/* No such database. */
return NULL;
}
/* Parses 'reply', a JSON-RPC reply to our request asking for the status of
* 'database' on 'server'. Determines whether this server is acceptable for
* the transaction we want to make and returns true if so or false to
* disconnect and try a different server. */
static bool
should_stay_connected(const char *server, const char *database,
const struct uuid *cid, const struct jsonrpc_msg *reply)
{
const struct json *row = parse_database_info_reply(reply, server,
database, cid);
if (!row) {
/* No such database. */
return false;
}
if (strcmp(parse_string_column(row, "model"), "clustered")) {
/* Always accept standalone databases. */
return true;
}
if (!parse_boolean_column(row, "connected")) {
/* Reject disconnected servers. */
return false;
}
if (leader_only && !parse_boolean_column(row, "leader")) {
/* Reject if not leader.. */
return false;
}
return true;
}
static void
do_list_dbs(struct jsonrpc *rpc, const char *database OVS_UNUSED,
int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
{
const char *db_name;
struct svec dbs;
size_t i;
svec_init(&dbs);
fetch_dbs(rpc, &dbs);
SVEC_FOR_EACH (i, db_name, &dbs) {
puts(db_name);
}
svec_destroy(&dbs);
}
static void
do_get_schema(struct jsonrpc *rpc, const char *database,
int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
{
struct ovsdb_schema *schema = fetch_schema(rpc, database);
print_and_free_json(ovsdb_schema_to_json(schema));
ovsdb_schema_destroy(schema);
}
static void
do_get_schema_version(struct jsonrpc *rpc, const char *database,
int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
{
struct ovsdb_schema *schema = fetch_schema(rpc, database);
puts(schema->version);
ovsdb_schema_destroy(schema);
}
static void
do_get_schema_cksum(struct jsonrpc *rpc, const char *database,
int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
{
struct ovsdb_schema *schema = fetch_schema(rpc, database);
puts(schema->cksum);
ovsdb_schema_destroy(schema);
}
static void
do_list_tables(struct jsonrpc *rpc, const char *database,
int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
{
struct ovsdb_schema *schema;
struct shash_node *node;
struct table t;
schema = fetch_schema(rpc, database);
table_init(&t);
table_add_column(&t, "Table");
SHASH_FOR_EACH (node, &schema->tables) {
struct ovsdb_table_schema *ts = node->data;
table_add_row(&t);
table_add_cell(&t)->text = xstrdup(ts->name);
}
ovsdb_schema_destroy(schema);
table_print(&t, &table_style);
table_destroy(&t);
}
static void
do_list_columns(struct jsonrpc *rpc, const char *database,
int argc OVS_UNUSED, char *argv[])
{
const char *table_name = argv[0];
struct ovsdb_schema *schema;
struct shash_node *table_node;
struct table t;
schema = fetch_schema(rpc, database);
table_init(&t);
if (!table_name) {
table_add_column(&t, "Table");
}
table_add_column(&t, "Column");
table_add_column(&t, "Type");
SHASH_FOR_EACH (table_node, &schema->tables) {
struct ovsdb_table_schema *ts = table_node->data;
if (!table_name || !strcmp(table_name, ts->name)) {
struct shash_node *column_node;
SHASH_FOR_EACH (column_node, &ts->columns) {
const struct ovsdb_column *column = column_node->data;
table_add_row(&t);
if (!table_name) {
table_add_cell(&t)->text = xstrdup(ts->name);
}
table_add_cell(&t)->text = xstrdup(column->name);
table_add_cell(&t)->json = ovsdb_type_to_json(&column->type);
}
}
}
ovsdb_schema_destroy(schema);
table_print(&t, &table_style);
table_destroy(&t);
}
static void
send_db_change_aware(struct jsonrpc *rpc)
{
if (db_change_aware != 0) {
struct jsonrpc_msg *request = jsonrpc_create_request(
"set_db_change_aware",
json_array_create_1(json_boolean_create(true)),
NULL);
struct jsonrpc_msg *reply;
int error = jsonrpc_transact_block(rpc, request, &reply);
if (error) {
ovs_fatal(error, "%s: error setting db_change_aware",
jsonrpc_get_name(rpc));
}
if (reply->type == JSONRPC_ERROR && db_change_aware == 1) {
ovs_fatal(0, "%s: set_db_change_aware failed (%s)",
jsonrpc_get_name(rpc), json_to_string(reply->error, 0));
}
jsonrpc_msg_destroy(reply);
}
}
static struct json *
do_transact__(int argc, char *argv[], struct json *transaction)
{
struct jsonrpc_msg *request, *reply;
if (transaction->type != JSON_ARRAY
|| !transaction->array.n
|| transaction->array.elems[0]->type != JSON_STRING) {
ovs_fatal(0, "not a valid OVSDB query");
}
const char *db_name = json_string(transaction->array.elems[0]);
struct jsonrpc *rpc;
char *database = CONST_CAST(char *, db_name);
open_rpc(1, NEED_DATABASE, argc, argv, &rpc, &database);
if (db_change_aware == 1) {
send_db_change_aware(rpc);
}
daemon_save_fd(STDOUT_FILENO);
daemon_save_fd(STDERR_FILENO);
daemonize();
request = jsonrpc_create_request("transact", transaction, NULL);
check_txn(jsonrpc_transact_block(rpc, request, &reply), &reply);
struct json *result = json_clone(reply->result);
jsonrpc_msg_destroy(reply);
jsonrpc_close(rpc);
return result;
}
static void
do_transact(struct jsonrpc *rpc OVS_UNUSED, const char *database OVS_UNUSED,
int argc, char *argv[])
{
print_and_free_json(do_transact__(argc, argv, parse_json(argv[argc - 1])));
}
static void
do_query(struct jsonrpc *rpc OVS_UNUSED, const char *database OVS_UNUSED,
int argc, char *argv[])
{
struct json *transaction = parse_json(argv[argc - 1]);
if (transaction->type != JSON_ARRAY) {
ovs_fatal(0, "not a valid OVSDB query");
}
/* Append an "abort" operation to the query. */
struct json *abort_op = json_object_create();
json_object_put_string(abort_op, "op", "abort");
json_array_add(transaction, abort_op);
size_t abort_idx = transaction->array.n - 2;
/* Run query. */
struct json *result = do_transact__(argc, argv, transaction);
/* If the "abort" operation ended the transaction, remove its result. */
if (result->type == JSON_ARRAY
&& result->array.n == abort_idx + 1
&& result->array.elems[abort_idx]->type == JSON_OBJECT) {
struct json *op_result = result->array.elems[abort_idx];
struct json *error = shash_find_data(json_object(op_result), "error");
if (error
&& error->type == JSON_STRING
&& !strcmp(json_string(error), "aborted")) {
result->array.n--;
json_destroy(op_result);
}
}
/* Print the result. */
print_and_free_json(result);
}
/* "monitor" command. */
struct monitored_table {
struct ovsdb_table_schema *table;
struct ovsdb_column_set columns;
};
static void
monitor_print_row(struct json *row, const char *type, const char *uuid,
const struct ovsdb_column_set *columns, struct table *t)
{
size_t i;
if (!row) {
ovs_error(0, "missing %s row", type);
return;
} else if (row->type != JSON_OBJECT) {
ovs_error(0, "<row> is not object");
return;
}
table_add_row(t);
table_add_cell(t)->text = xstrdup(uuid);
table_add_cell(t)->text = xstrdup(type);
for (i = 0; i < columns->n_columns; i++) {
const struct ovsdb_column *column = columns->columns[i];
struct json *value = shash_find_data(json_object(row), column->name);
struct cell *cell = table_add_cell(t);
if (value) {
cell->json = json_clone(value);
cell->type = &column->type;
}
}
}
static void
monitor_print_table(struct json *table_update,
const struct monitored_table *mt, char *caption,
bool initial)
{
const struct ovsdb_table_schema *table = mt->table;
const struct ovsdb_column_set *columns = &mt->columns;
struct shash_node *node;
struct table t;
size_t i;
if (table_update->type != JSON_OBJECT) {
ovs_error(0, "<table-update> for table %s is not object", table->name);
return;
}
table_init(&t);
table_set_timestamp(&t, timestamp);
table_set_caption(&t, caption);
table_add_column(&t, "row");
table_add_column(&t, "action");
for (i = 0; i < columns->n_columns; i++) {
table_add_column(&t, "%s", columns->columns[i]->name);
}
SHASH_FOR_EACH (node, json_object(table_update)) {
struct json *row_update = node->data;
struct json *old, *new;
if (row_update->type != JSON_OBJECT) {
ovs_error(0, "<row-update> is not object");
continue;
}