vlog: add "vlog/list-pattern" command
[cascardo/ovs.git] / tests / test-ovsdb.c
1 /*
2  * Copyright (c) 2009, 2010, 2011, 2012, 2013 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 <assert.h>
20 #include <fcntl.h>
21 #include <getopt.h>
22 #include <inttypes.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25
26 #include "command-line.h"
27 #include "dynamic-string.h"
28 #include "json.h"
29 #include "jsonrpc.h"
30 #include "ovsdb-data.h"
31 #include "ovsdb-error.h"
32 #include "ovsdb-idl.h"
33 #include "ovsdb-types.h"
34 #include "ovsdb/column.h"
35 #include "ovsdb/condition.h"
36 #include "ovsdb/file.h"
37 #include "ovsdb/log.h"
38 #include "ovsdb/mutation.h"
39 #include "ovsdb/ovsdb.h"
40 #include "ovsdb/query.h"
41 #include "ovsdb/row.h"
42 #include "ovsdb/server.h"
43 #include "ovsdb/table.h"
44 #include "ovsdb/transaction.h"
45 #include "ovsdb/trigger.h"
46 #include "poll-loop.h"
47 #include "stream.h"
48 #include "svec.h"
49 #include "tests/idltest.h"
50 #include "timeval.h"
51 #include "util.h"
52 #include "openvswitch/vlog.h"
53
54 OVS_NO_RETURN static void usage(void);
55 static void parse_options(int argc, char *argv[]);
56 static struct ovs_cmdl_command *get_all_commands(void);
57
58 int
59 main(int argc, char *argv[])
60 {
61     struct ovs_cmdl_context ctx = { .argc = 0, };
62     set_program_name(argv[0]);
63     parse_options(argc, argv);
64     ctx.argc = argc - optind;
65     ctx.argv = argv + optind;
66     ovs_cmdl_run_command(&ctx, get_all_commands());
67     return 0;
68 }
69
70 static void
71 parse_options(int argc, char *argv[])
72 {
73     static const struct option long_options[] = {
74         {"timeout", required_argument, NULL, 't'},
75         {"verbose", optional_argument, NULL, 'v'},
76         {"help", no_argument, NULL, 'h'},
77         {NULL, 0, NULL, 0},
78     };
79     char *short_options = ovs_cmdl_long_options_to_short_options(long_options);
80
81     for (;;) {
82         unsigned long int timeout;
83         int c;
84
85         c = getopt_long(argc, argv, short_options, long_options, NULL);
86         if (c == -1) {
87             break;
88         }
89
90         switch (c) {
91         case 't':
92             timeout = strtoul(optarg, NULL, 10);
93             if (timeout <= 0) {
94                 ovs_fatal(0, "value %s on -t or --timeout is not at least 1",
95                           optarg);
96             } else {
97                 time_alarm(timeout);
98             }
99             break;
100
101         case 'h':
102             usage();
103
104         case 'v':
105             vlog_set_verbosity(optarg);
106             break;
107
108         case '?':
109             exit(EXIT_FAILURE);
110
111         default:
112             abort();
113         }
114     }
115     free(short_options);
116 }
117
118 static void
119 usage(void)
120 {
121     printf("%s: Open vSwitch database test utility\n"
122            "usage: %s [OPTIONS] COMMAND [ARG...]\n\n"
123            "  log-io FILE FLAGS COMMAND...\n"
124            "    open FILE with FLAGS, run COMMANDs\n"
125            "  default-atoms\n"
126            "    test ovsdb_atom_default()\n"
127            "  default-data\n"
128            "    test ovsdb_datum_default()\n"
129            "  parse-atomic-type TYPE\n"
130            "    parse TYPE as OVSDB atomic type, and re-serialize\n"
131            "  parse-base-type TYPE\n"
132            "    parse TYPE as OVSDB base type, and re-serialize\n"
133            "  parse-type JSON\n"
134            "    parse JSON as OVSDB type, and re-serialize\n"
135            "  parse-atoms TYPE ATOM...\n"
136            "    parse JSON ATOMs as atoms of TYPE, and re-serialize\n"
137            "  parse-atom-strings TYPE ATOM...\n"
138            "    parse string ATOMs as atoms of given TYPE, and re-serialize\n"
139            "  sort-atoms TYPE ATOM...\n"
140            "    print JSON ATOMs in sorted order\n"
141            "  parse-data TYPE DATUM...\n"
142            "    parse JSON DATUMs as data of given TYPE, and re-serialize\n"
143            "  parse-data-strings TYPE DATUM...\n"
144            "    parse string DATUMs as data of given TYPE, and re-serialize\n"
145            "  parse-column NAME OBJECT\n"
146            "    parse column NAME with info OBJECT, and re-serialize\n"
147            "  parse-table NAME OBJECT [DEFAULT-IS-ROOT]\n"
148            "    parse table NAME with info OBJECT\n"
149            "  parse-row TABLE ROW..., and re-serialize\n"
150            "    parse each ROW of defined TABLE\n"
151            "  compare-row TABLE ROW...\n"
152            "    mutually compare all of the ROWs, print those that are equal\n"
153            "  parse-conditions TABLE CONDITION...\n"
154            "    parse each CONDITION on TABLE, and re-serialize\n"
155            "  evaluate-conditions TABLE [CONDITION,...] [ROW,...]\n"
156            "    test CONDITIONS on TABLE against each ROW, print results\n"
157            "  parse-mutations TABLE MUTATION...\n"
158            "    parse each MUTATION on TABLE, and re-serialize\n"
159            "  execute-mutations TABLE [MUTATION,...] [ROW,...]\n"
160            "    execute MUTATIONS on TABLE on each ROW, print results\n"
161            "  query TABLE [ROW,...] [CONDITION,...]\n"
162            "    add each ROW to TABLE, then query and print the rows that\n"
163            "    satisfy each CONDITION.\n"
164            "  query-distinct TABLE [ROW,...] [CONDITION,...] COLUMNS\n"
165            "    add each ROW to TABLE, then query and print the rows that\n"
166            "    satisfy each CONDITION and have distinct COLUMNS.\n"
167            "  parse-schema JSON\n"
168            "    parse JSON as an OVSDB schema, and re-serialize\n"
169            "  transact COMMAND\n"
170            "    execute each specified transactional COMMAND:\n"
171            "      commit\n"
172            "      abort\n"
173            "      insert UUID I J\n"
174            "      delete UUID\n"
175            "      modify UUID I J\n"
176            "      print\n"
177            "  execute SCHEMA TRANSACTION...\n"
178            "    executes each TRANSACTION on an initially empty database\n"
179            "    the specified SCHEMA\n"
180            "  trigger SCHEMA TRANSACTION...\n"
181            "    executes each TRANSACTION on an initially empty database\n"
182            "    the specified SCHEMA.   A TRANSACTION of the form\n"
183            "    [\"advance\", NUMBER] advances NUMBER milliseconds in\n"
184            "    simulated time, for causing triggers to time out.\n"
185            "  idl SERVER [TRANSACTION...]\n"
186            "    connect to SERVER and dump the contents of the database\n"
187            "    as seen initially by the IDL implementation and after\n"
188            "    executing each TRANSACTION.  (Each TRANSACTION must modify\n"
189            "    the database or this command will hang.)\n",
190            program_name, program_name);
191     vlog_usage();
192     printf("\nOther options:\n"
193            "  -t, --timeout=SECS          give up after SECS seconds\n"
194            "  -h, --help                  display this help message\n");
195     exit(EXIT_SUCCESS);
196 }
197 \f
198 /* Command helper functions. */
199
200 static struct json *
201 parse_json(const char *s)
202 {
203     struct json *json = json_from_string(s);
204     if (json->type == JSON_STRING) {
205         ovs_fatal(0, "\"%s\": %s", s, json->u.string);
206     }
207     return json;
208 }
209
210 static struct json *
211 unbox_json(struct json *json)
212 {
213     if (json->type == JSON_ARRAY && json->u.array.n == 1) {
214         struct json *inner = json->u.array.elems[0];
215         json->u.array.elems[0] = NULL;
216         json_destroy(json);
217         return inner;
218     } else {
219         return json;
220     }
221 }
222
223 static void
224 print_and_free_json(struct json *json)
225 {
226     char *string = json_to_string(json, JSSF_SORT);
227     json_destroy(json);
228     puts(string);
229     free(string);
230 }
231
232 static void
233 print_and_free_ovsdb_error(struct ovsdb_error *error)
234 {
235     char *string = ovsdb_error_to_string(error);
236     ovsdb_error_destroy(error);
237     puts(string);
238     free(string);
239 }
240
241 static void
242 check_ovsdb_error(struct ovsdb_error *error)
243 {
244     if (error) {
245         char *s = ovsdb_error_to_string(error);
246         ovsdb_error_destroy(error);
247         ovs_fatal(0, "%s", s);
248     }
249 }
250
251 static void
252 die_if_error(char *error)
253 {
254     if (error) {
255         ovs_fatal(0, "%s", error);
256     }
257 }
258 \f
259 /* Command implementations. */
260
261 static void
262 do_log_io(struct ovs_cmdl_context *ctx)
263 {
264     const char *name = ctx->argv[1];
265     char *mode_string = ctx->argv[2];
266
267     struct ovsdb_error *error;
268     enum ovsdb_log_open_mode mode;
269     struct ovsdb_log *log;
270     int i;
271
272     if (!strcmp(mode_string, "read-only")) {
273         mode = OVSDB_LOG_READ_ONLY;
274     } else if (!strcmp(mode_string, "read/write")) {
275         mode = OVSDB_LOG_READ_WRITE;
276     } else if (!strcmp(mode_string, "create")) {
277         mode = OVSDB_LOG_CREATE;
278     } else {
279         ovs_fatal(0, "unknown log-io open mode \"%s\"", mode_string);
280     }
281
282     check_ovsdb_error(ovsdb_log_open(name, mode, -1, &log));
283     printf("%s: open successful\n", name);
284
285     for (i = 3; i < ctx->argc; i++) {
286         const char *command = ctx->argv[i];
287         if (!strcmp(command, "read")) {
288             struct json *json;
289
290             error = ovsdb_log_read(log, &json);
291             if (!error) {
292                 printf("%s: read: ", name);
293                 if (json) {
294                     print_and_free_json(json);
295                 } else {
296                     printf("end of log\n");
297                 }
298                 continue;
299             }
300         } else if (!strncmp(command, "write:", 6)) {
301             struct json *json = parse_json(command + 6);
302             error = ovsdb_log_write(log, json);
303             json_destroy(json);
304         } else if (!strcmp(command, "commit")) {
305             error = ovsdb_log_commit(log);
306         } else {
307             ovs_fatal(0, "unknown log-io command \"%s\"", command);
308         }
309         if (error) {
310             char *s = ovsdb_error_to_string(error);
311             printf("%s: %s failed: %s\n", name, command, s);
312             free(s);
313             ovsdb_error_destroy(error);
314         } else {
315             printf("%s: %s successful\n", name, command);
316         }
317     }
318
319     ovsdb_log_close(log);
320 }
321
322 static void
323 do_default_atoms(struct ovs_cmdl_context *ctx OVS_UNUSED)
324 {
325     int type;
326
327     for (type = 0; type < OVSDB_N_TYPES; type++) {
328         union ovsdb_atom atom;
329
330         if (type == OVSDB_TYPE_VOID) {
331             continue;
332         }
333
334         printf("%s: ", ovsdb_atomic_type_to_string(type));
335
336         ovsdb_atom_init_default(&atom, type);
337         if (!ovsdb_atom_equals(&atom, ovsdb_atom_default(type), type)) {
338             printf("wrong\n");
339             exit(1);
340         }
341         ovsdb_atom_destroy(&atom, type);
342
343         printf("OK\n");
344     }
345 }
346
347 static void
348 do_default_data(struct ovs_cmdl_context *ctx OVS_UNUSED)
349 {
350     unsigned int n_min;
351     int key, value;
352
353     for (n_min = 0; n_min <= 1; n_min++) {
354         for (key = 0; key < OVSDB_N_TYPES; key++) {
355             if (key == OVSDB_TYPE_VOID) {
356                 continue;
357             }
358             for (value = 0; value < OVSDB_N_TYPES; value++) {
359                 struct ovsdb_datum datum;
360                 struct ovsdb_type type;
361
362                 ovsdb_base_type_init(&type.key, key);
363                 ovsdb_base_type_init(&type.value, value);
364                 type.n_min = n_min;
365                 type.n_max = 1;
366                 assert(ovsdb_type_is_valid(&type));
367
368                 printf("key %s, value %s, n_min %u: ",
369                        ovsdb_atomic_type_to_string(key),
370                        ovsdb_atomic_type_to_string(value), n_min);
371
372                 ovsdb_datum_init_default(&datum, &type);
373                 if (!ovsdb_datum_equals(&datum, ovsdb_datum_default(&type),
374                                         &type)) {
375                     printf("wrong\n");
376                     exit(1);
377                 }
378                 ovsdb_datum_destroy(&datum, &type);
379                 ovsdb_type_destroy(&type);
380
381                 printf("OK\n");
382             }
383         }
384     }
385 }
386
387 static void
388 do_parse_atomic_type(struct ovs_cmdl_context *ctx)
389 {
390     enum ovsdb_atomic_type type;
391     struct json *json;
392
393     json = unbox_json(parse_json(ctx->argv[1]));
394     check_ovsdb_error(ovsdb_atomic_type_from_json(&type, json));
395     json_destroy(json);
396     print_and_free_json(ovsdb_atomic_type_to_json(type));
397 }
398
399 static void
400 do_parse_base_type(struct ovs_cmdl_context *ctx)
401 {
402     struct ovsdb_base_type base;
403     struct json *json;
404
405     json = unbox_json(parse_json(ctx->argv[1]));
406     check_ovsdb_error(ovsdb_base_type_from_json(&base, json));
407     json_destroy(json);
408     print_and_free_json(ovsdb_base_type_to_json(&base));
409     ovsdb_base_type_destroy(&base);
410 }
411
412 static void
413 do_parse_type(struct ovs_cmdl_context *ctx)
414 {
415     struct ovsdb_type type;
416     struct json *json;
417
418     json = unbox_json(parse_json(ctx->argv[1]));
419     check_ovsdb_error(ovsdb_type_from_json(&type, json));
420     json_destroy(json);
421     print_and_free_json(ovsdb_type_to_json(&type));
422     ovsdb_type_destroy(&type);
423 }
424
425 static void
426 do_parse_atoms(struct ovs_cmdl_context *ctx)
427 {
428     struct ovsdb_base_type base;
429     struct json *json;
430     int i;
431
432     json = unbox_json(parse_json(ctx->argv[1]));
433     check_ovsdb_error(ovsdb_base_type_from_json(&base, json));
434     json_destroy(json);
435
436     for (i = 2; i < ctx->argc; i++) {
437         struct ovsdb_error *error;
438         union ovsdb_atom atom;
439
440         json = unbox_json(parse_json(ctx->argv[i]));
441         error = ovsdb_atom_from_json(&atom, &base, json, NULL);
442         json_destroy(json);
443
444         if (error) {
445             print_and_free_ovsdb_error(error);
446         } else {
447             print_and_free_json(ovsdb_atom_to_json(&atom, base.type));
448             ovsdb_atom_destroy(&atom, base.type);
449         }
450     }
451     ovsdb_base_type_destroy(&base);
452 }
453
454 static void
455 do_parse_atom_strings(struct ovs_cmdl_context *ctx)
456 {
457     struct ovsdb_base_type base;
458     struct json *json;
459     int i;
460
461     json = unbox_json(parse_json(ctx->argv[1]));
462     check_ovsdb_error(ovsdb_base_type_from_json(&base, json));
463     json_destroy(json);
464
465     for (i = 2; i < ctx->argc; i++) {
466         union ovsdb_atom atom;
467         struct ds out;
468
469         die_if_error(ovsdb_atom_from_string(&atom, &base, ctx->argv[i], NULL));
470
471         ds_init(&out);
472         ovsdb_atom_to_string(&atom, base.type, &out);
473         puts(ds_cstr(&out));
474         ds_destroy(&out);
475
476         ovsdb_atom_destroy(&atom, base.type);
477     }
478     ovsdb_base_type_destroy(&base);
479 }
480
481 static void
482 do_parse_data__(int argc, char *argv[],
483                 struct ovsdb_error *
484                 (*parse)(struct ovsdb_datum *datum,
485                          const struct ovsdb_type *type,
486                          const struct json *json,
487                          struct ovsdb_symbol_table *symtab))
488 {
489     struct ovsdb_type type;
490     struct json *json;
491     int i;
492
493     json = unbox_json(parse_json(argv[1]));
494     check_ovsdb_error(ovsdb_type_from_json(&type, json));
495     json_destroy(json);
496
497     for (i = 2; i < argc; i++) {
498         struct ovsdb_datum datum;
499
500         json = unbox_json(parse_json(argv[i]));
501         check_ovsdb_error(parse(&datum, &type, json, NULL));
502         json_destroy(json);
503
504         print_and_free_json(ovsdb_datum_to_json(&datum, &type));
505
506         ovsdb_datum_destroy(&datum, &type);
507     }
508     ovsdb_type_destroy(&type);
509 }
510
511 static void
512 do_parse_data(struct ovs_cmdl_context *ctx)
513 {
514     do_parse_data__(ctx->argc, ctx->argv, ovsdb_datum_from_json);
515 }
516
517 static void
518 do_parse_data_strings(struct ovs_cmdl_context *ctx)
519 {
520     struct ovsdb_type type;
521     struct json *json;
522     int i;
523
524     json = unbox_json(parse_json(ctx->argv[1]));
525     check_ovsdb_error(ovsdb_type_from_json(&type, json));
526     json_destroy(json);
527
528     for (i = 2; i < ctx->argc; i++) {
529         struct ovsdb_datum datum;
530         struct ds out;
531
532         die_if_error(ovsdb_datum_from_string(&datum, &type, ctx->argv[i], NULL));
533
534         ds_init(&out);
535         ovsdb_datum_to_string(&datum, &type, &out);
536         puts(ds_cstr(&out));
537         ds_destroy(&out);
538
539         ovsdb_datum_destroy(&datum, &type);
540     }
541     ovsdb_type_destroy(&type);
542 }
543
544 static enum ovsdb_atomic_type compare_atoms_atomic_type;
545
546 static int
547 compare_atoms(const void *a_, const void *b_)
548 {
549     const union ovsdb_atom *a = a_;
550     const union ovsdb_atom *b = b_;
551
552     return ovsdb_atom_compare_3way(a, b, compare_atoms_atomic_type);
553 }
554
555 static void
556 do_sort_atoms(struct ovs_cmdl_context *ctx)
557 {
558     struct ovsdb_base_type base;
559     union ovsdb_atom *atoms;
560     struct json *json, **json_atoms;
561     size_t n_atoms;
562     int i;
563
564     json = unbox_json(parse_json(ctx->argv[1]));
565     check_ovsdb_error(ovsdb_base_type_from_json(&base, json));
566     json_destroy(json);
567
568     json = unbox_json(parse_json(ctx->argv[2]));
569     if (json->type != JSON_ARRAY) {
570         ovs_fatal(0, "second argument must be array");
571     }
572
573     /* Convert JSON atoms to internal representation. */
574     n_atoms = json->u.array.n;
575     atoms = xmalloc(n_atoms * sizeof *atoms);
576     for (i = 0; i < n_atoms; i++) {
577         check_ovsdb_error(ovsdb_atom_from_json(&atoms[i], &base,
578                                                json->u.array.elems[i], NULL));
579     }
580     json_destroy(json);
581
582     /* Sort atoms. */
583     compare_atoms_atomic_type = base.type;
584     qsort(atoms, n_atoms, sizeof *atoms, compare_atoms);
585
586     /* Convert internal representation back to JSON. */
587     json_atoms = xmalloc(n_atoms * sizeof *json_atoms);
588     for (i = 0; i < n_atoms; i++) {
589         json_atoms[i] = ovsdb_atom_to_json(&atoms[i], base.type);
590         ovsdb_atom_destroy(&atoms[i], base.type);
591     }
592     print_and_free_json(json_array_create(json_atoms, n_atoms));
593     free(atoms);
594     ovsdb_base_type_destroy(&base);
595 }
596
597 static void
598 do_parse_column(struct ovs_cmdl_context *ctx)
599 {
600     struct ovsdb_column *column;
601     struct json *json;
602
603     json = parse_json(ctx->argv[2]);
604     check_ovsdb_error(ovsdb_column_from_json(json, ctx->argv[1], &column));
605     json_destroy(json);
606     print_and_free_json(ovsdb_column_to_json(column));
607     ovsdb_column_destroy(column);
608 }
609
610 static void
611 do_parse_table(struct ovs_cmdl_context *ctx)
612 {
613     struct ovsdb_table_schema *ts;
614     bool default_is_root;
615     struct json *json;
616
617     default_is_root = ctx->argc > 3 && !strcmp(ctx->argv[3], "true");
618
619     json = parse_json(ctx->argv[2]);
620     check_ovsdb_error(ovsdb_table_schema_from_json(json, ctx->argv[1], &ts));
621     json_destroy(json);
622     print_and_free_json(ovsdb_table_schema_to_json(ts, default_is_root));
623     ovsdb_table_schema_destroy(ts);
624 }
625
626 static void
627 do_parse_rows(struct ovs_cmdl_context *ctx)
628 {
629     struct ovsdb_column_set all_columns;
630     struct ovsdb_table_schema *ts;
631     struct ovsdb_table *table;
632     struct json *json;
633     int i;
634
635     json = unbox_json(parse_json(ctx->argv[1]));
636     check_ovsdb_error(ovsdb_table_schema_from_json(json, "mytable", &ts));
637     json_destroy(json);
638
639     table = ovsdb_table_create(ts);
640     ovsdb_column_set_init(&all_columns);
641     ovsdb_column_set_add_all(&all_columns, table);
642
643     for (i = 2; i < ctx->argc; i++) {
644         struct ovsdb_column_set columns;
645         struct ovsdb_row *row;
646
647         ovsdb_column_set_init(&columns);
648         row = ovsdb_row_create(table);
649
650         json = unbox_json(parse_json(ctx->argv[i]));
651         check_ovsdb_error(ovsdb_row_from_json(row, json, NULL, &columns));
652         json_destroy(json);
653
654         print_and_free_json(ovsdb_row_to_json(row, &all_columns));
655
656         if (columns.n_columns) {
657             struct svec names;
658             size_t j;
659             char *s;
660
661             svec_init(&names);
662             for (j = 0; j < columns.n_columns; j++) {
663                 svec_add(&names, columns.columns[j]->name);
664             }
665             svec_sort(&names);
666             s = svec_join(&names, ", ", "");
667             puts(s);
668             free(s);
669             svec_destroy(&names);
670         } else {
671             printf("<none>\n");
672         }
673
674         ovsdb_column_set_destroy(&columns);
675         ovsdb_row_destroy(row);
676     }
677
678     ovsdb_column_set_destroy(&all_columns);
679     ovsdb_table_destroy(table); /* Also destroys 'ts'. */
680 }
681
682 static void
683 do_compare_rows(struct ovs_cmdl_context *ctx)
684 {
685     struct ovsdb_column_set all_columns;
686     struct ovsdb_table_schema *ts;
687     struct ovsdb_table *table;
688     struct ovsdb_row **rows;
689     struct json *json;
690     char **names;
691     int n_rows;
692     int i, j;
693
694     json = unbox_json(parse_json(ctx->argv[1]));
695     check_ovsdb_error(ovsdb_table_schema_from_json(json, "mytable", &ts));
696     json_destroy(json);
697
698     table = ovsdb_table_create(ts);
699     ovsdb_column_set_init(&all_columns);
700     ovsdb_column_set_add_all(&all_columns, table);
701
702     n_rows = ctx->argc - 2;
703     rows = xmalloc(sizeof *rows * n_rows);
704     names = xmalloc(sizeof *names * n_rows);
705     for (i = 0; i < n_rows; i++) {
706         rows[i] = ovsdb_row_create(table);
707
708         json = parse_json(ctx->argv[i + 2]);
709         if (json->type != JSON_ARRAY || json->u.array.n != 2
710             || json->u.array.elems[0]->type != JSON_STRING) {
711             ovs_fatal(0, "\"%s\" does not have expected form "
712                       "[\"name\", {data}]", ctx->argv[i]);
713         }
714         names[i] = xstrdup(json->u.array.elems[0]->u.string);
715         check_ovsdb_error(ovsdb_row_from_json(rows[i], json->u.array.elems[1],
716                                               NULL, NULL));
717         json_destroy(json);
718     }
719     for (i = 0; i < n_rows; i++) {
720         uint32_t i_hash = ovsdb_row_hash_columns(rows[i], &all_columns, 0);
721         for (j = i + 1; j < n_rows; j++) {
722             uint32_t j_hash = ovsdb_row_hash_columns(rows[j], &all_columns, 0);
723             if (ovsdb_row_equal_columns(rows[i], rows[j], &all_columns)) {
724                 printf("%s == %s\n", names[i], names[j]);
725                 if (i_hash != j_hash) {
726                     printf("but hash(%s) != hash(%s)\n", names[i], names[j]);
727                     abort();
728                 }
729             } else if (i_hash == j_hash) {
730                 printf("hash(%s) == hash(%s)\n", names[i], names[j]);
731             }
732         }
733     }
734     for (i = 0; i < n_rows; i++) {
735         ovsdb_row_destroy(rows[i]);
736         free(names[i]);
737     }
738     free(rows);
739     free(names);
740
741     ovsdb_column_set_destroy(&all_columns);
742     ovsdb_table_destroy(table); /* Also destroys 'ts'. */
743 }
744
745 static void
746 do_parse_conditions(struct ovs_cmdl_context *ctx)
747 {
748     struct ovsdb_table_schema *ts;
749     struct json *json;
750     int exit_code = 0;
751     int i;
752
753     json = unbox_json(parse_json(ctx->argv[1]));
754     check_ovsdb_error(ovsdb_table_schema_from_json(json, "mytable", &ts));
755     json_destroy(json);
756
757     for (i = 2; i < ctx->argc; i++) {
758         struct ovsdb_condition cnd;
759         struct ovsdb_error *error;
760
761         json = parse_json(ctx->argv[i]);
762         error = ovsdb_condition_from_json(ts, json, NULL, &cnd);
763         if (!error) {
764             print_and_free_json(ovsdb_condition_to_json(&cnd));
765         } else {
766             char *s = ovsdb_error_to_string(error);
767             ovs_error(0, "%s", s);
768             free(s);
769             ovsdb_error_destroy(error);
770             exit_code = 1;
771         }
772         json_destroy(json);
773
774         ovsdb_condition_destroy(&cnd);
775     }
776     ovsdb_table_schema_destroy(ts);
777
778     exit(exit_code);
779 }
780
781 static void
782 do_evaluate_conditions(struct ovs_cmdl_context *ctx)
783 {
784     struct ovsdb_table_schema *ts;
785     struct ovsdb_table *table;
786     struct ovsdb_condition *conditions;
787     size_t n_conditions;
788     struct ovsdb_row **rows;
789     size_t n_rows;
790     struct json *json;
791     size_t i, j;
792
793     /* Parse table schema, create table. */
794     json = unbox_json(parse_json(ctx->argv[1]));
795     check_ovsdb_error(ovsdb_table_schema_from_json(json, "mytable", &ts));
796     json_destroy(json);
797
798     table = ovsdb_table_create(ts);
799
800     /* Parse conditions. */
801     json = parse_json(ctx->argv[2]);
802     if (json->type != JSON_ARRAY) {
803         ovs_fatal(0, "CONDITION argument is not JSON array");
804     }
805     n_conditions = json->u.array.n;
806     conditions = xmalloc(n_conditions * sizeof *conditions);
807     for (i = 0; i < n_conditions; i++) {
808         check_ovsdb_error(ovsdb_condition_from_json(ts, json->u.array.elems[i],
809                                                     NULL, &conditions[i]));
810     }
811     json_destroy(json);
812
813     /* Parse rows. */
814     json = parse_json(ctx->argv[3]);
815     if (json->type != JSON_ARRAY) {
816         ovs_fatal(0, "ROW argument is not JSON array");
817     }
818     n_rows = json->u.array.n;
819     rows = xmalloc(n_rows * sizeof *rows);
820     for (i = 0; i < n_rows; i++) {
821         rows[i] = ovsdb_row_create(table);
822         check_ovsdb_error(ovsdb_row_from_json(rows[i], json->u.array.elems[i],
823                                               NULL, NULL));
824     }
825     json_destroy(json);
826
827     for (i = 0; i < n_conditions; i++) {
828         printf("condition %2"PRIuSIZE":", i);
829         for (j = 0; j < n_rows; j++) {
830             bool result = ovsdb_condition_evaluate(rows[j], &conditions[i]);
831             if (j % 5 == 0) {
832                 putchar(' ');
833             }
834             putchar(result ? 'T' : '-');
835         }
836         printf("\n");
837     }
838
839     for (i = 0; i < n_conditions; i++) {
840         ovsdb_condition_destroy(&conditions[i]);
841     }
842     free(conditions);
843     for (i = 0; i < n_rows; i++) {
844         ovsdb_row_destroy(rows[i]);
845     }
846     free(rows);
847     ovsdb_table_destroy(table); /* Also destroys 'ts'. */
848 }
849
850 static void
851 do_parse_mutations(struct ovs_cmdl_context *ctx)
852 {
853     struct ovsdb_table_schema *ts;
854     struct json *json;
855     int exit_code = 0;
856     int i;
857
858     json = unbox_json(parse_json(ctx->argv[1]));
859     check_ovsdb_error(ovsdb_table_schema_from_json(json, "mytable", &ts));
860     json_destroy(json);
861
862     for (i = 2; i < ctx->argc; i++) {
863         struct ovsdb_mutation_set set;
864         struct ovsdb_error *error;
865
866         json = parse_json(ctx->argv[i]);
867         error = ovsdb_mutation_set_from_json(ts, json, NULL, &set);
868         if (!error) {
869             print_and_free_json(ovsdb_mutation_set_to_json(&set));
870         } else {
871             char *s = ovsdb_error_to_string(error);
872             ovs_error(0, "%s", s);
873             free(s);
874             ovsdb_error_destroy(error);
875             exit_code = 1;
876         }
877         json_destroy(json);
878
879         ovsdb_mutation_set_destroy(&set);
880     }
881     ovsdb_table_schema_destroy(ts);
882
883     exit(exit_code);
884 }
885
886 static void
887 do_execute_mutations(struct ovs_cmdl_context *ctx)
888 {
889     struct ovsdb_table_schema *ts;
890     struct ovsdb_table *table;
891     struct ovsdb_mutation_set *sets;
892     size_t n_sets;
893     struct ovsdb_row **rows;
894     size_t n_rows;
895     struct json *json;
896     size_t i, j;
897
898     /* Parse table schema, create table. */
899     json = unbox_json(parse_json(ctx->argv[1]));
900     check_ovsdb_error(ovsdb_table_schema_from_json(json, "mytable", &ts));
901     json_destroy(json);
902
903     table = ovsdb_table_create(ts);
904
905     /* Parse mutations. */
906     json = parse_json(ctx->argv[2]);
907     if (json->type != JSON_ARRAY) {
908         ovs_fatal(0, "MUTATION argument is not JSON array");
909     }
910     n_sets = json->u.array.n;
911     sets = xmalloc(n_sets * sizeof *sets);
912     for (i = 0; i < n_sets; i++) {
913         check_ovsdb_error(ovsdb_mutation_set_from_json(ts,
914                                                        json->u.array.elems[i],
915                                                        NULL, &sets[i]));
916     }
917     json_destroy(json);
918
919     /* Parse rows. */
920     json = parse_json(ctx->argv[3]);
921     if (json->type != JSON_ARRAY) {
922         ovs_fatal(0, "ROW argument is not JSON array");
923     }
924     n_rows = json->u.array.n;
925     rows = xmalloc(n_rows * sizeof *rows);
926     for (i = 0; i < n_rows; i++) {
927         rows[i] = ovsdb_row_create(table);
928         check_ovsdb_error(ovsdb_row_from_json(rows[i], json->u.array.elems[i],
929                                               NULL, NULL));
930     }
931     json_destroy(json);
932
933     for (i = 0; i < n_sets; i++) {
934         printf("mutation %2"PRIuSIZE":\n", i);
935         for (j = 0; j < n_rows; j++) {
936             struct ovsdb_error *error;
937             struct ovsdb_row *row;
938
939             row = ovsdb_row_clone(rows[j]);
940             error = ovsdb_mutation_set_execute(row, &sets[i]);
941
942             printf("row %"PRIuSIZE": ", j);
943             if (error) {
944                 print_and_free_ovsdb_error(error);
945             } else {
946                 struct ovsdb_column_set columns;
947                 struct shash_node *node;
948
949                 ovsdb_column_set_init(&columns);
950                 SHASH_FOR_EACH (node, &ts->columns) {
951                     struct ovsdb_column *c = node->data;
952                     if (!ovsdb_datum_equals(&row->fields[c->index],
953                                             &rows[j]->fields[c->index],
954                                             &c->type)) {
955                         ovsdb_column_set_add(&columns, c);
956                     }
957                 }
958                 if (columns.n_columns) {
959                     print_and_free_json(ovsdb_row_to_json(row, &columns));
960                 } else {
961                     printf("no change\n");
962                 }
963                 ovsdb_column_set_destroy(&columns);
964             }
965             ovsdb_row_destroy(row);
966         }
967         printf("\n");
968     }
969
970     for (i = 0; i < n_sets; i++) {
971         ovsdb_mutation_set_destroy(&sets[i]);
972     }
973     free(sets);
974     for (i = 0; i < n_rows; i++) {
975         ovsdb_row_destroy(rows[i]);
976     }
977     free(rows);
978     ovsdb_table_destroy(table); /* Also destroys 'ts'. */
979 }
980
981 /* Inserts a row, without bothering to update metadata such as refcounts. */
982 static void
983 put_row(struct ovsdb_table *table, struct ovsdb_row *row)
984 {
985     const struct uuid *uuid = ovsdb_row_get_uuid(row);
986     if (!ovsdb_table_get_row(table, uuid)) {
987         hmap_insert(&table->rows, &row->hmap_node, uuid_hash(uuid));
988     }
989 }
990
991 struct do_query_cbdata {
992     struct uuid *row_uuids;
993     int *counts;
994     size_t n_rows;
995 };
996
997 static bool
998 do_query_cb(const struct ovsdb_row *row, void *cbdata_)
999 {
1000     struct do_query_cbdata *cbdata = cbdata_;
1001     size_t i;
1002
1003     for (i = 0; i < cbdata->n_rows; i++) {
1004         if (uuid_equals(ovsdb_row_get_uuid(row), &cbdata->row_uuids[i])) {
1005             cbdata->counts[i]++;
1006         }
1007     }
1008
1009     return true;
1010 }
1011
1012 static void
1013 do_query(struct ovs_cmdl_context *ctx)
1014 {
1015     struct do_query_cbdata cbdata;
1016     struct ovsdb_table_schema *ts;
1017     struct ovsdb_table *table;
1018     struct json *json;
1019     int exit_code = 0;
1020     size_t i;
1021
1022     /* Parse table schema, create table. */
1023     json = unbox_json(parse_json(ctx->argv[1]));
1024     check_ovsdb_error(ovsdb_table_schema_from_json(json, "mytable", &ts));
1025     json_destroy(json);
1026
1027     table = ovsdb_table_create(ts);
1028
1029     /* Parse rows, add to table. */
1030     json = parse_json(ctx->argv[2]);
1031     if (json->type != JSON_ARRAY) {
1032         ovs_fatal(0, "ROW argument is not JSON array");
1033     }
1034     cbdata.n_rows = json->u.array.n;
1035     cbdata.row_uuids = xmalloc(cbdata.n_rows * sizeof *cbdata.row_uuids);
1036     cbdata.counts = xmalloc(cbdata.n_rows * sizeof *cbdata.counts);
1037     for (i = 0; i < cbdata.n_rows; i++) {
1038         struct ovsdb_row *row = ovsdb_row_create(table);
1039         uuid_generate(ovsdb_row_get_uuid_rw(row));
1040         check_ovsdb_error(ovsdb_row_from_json(row, json->u.array.elems[i],
1041                                               NULL, NULL));
1042         if (ovsdb_table_get_row(table, ovsdb_row_get_uuid(row))) {
1043             ovs_fatal(0, "duplicate UUID "UUID_FMT" in table",
1044                       UUID_ARGS(ovsdb_row_get_uuid(row)));
1045         }
1046         cbdata.row_uuids[i] = *ovsdb_row_get_uuid(row);
1047         put_row(table, row);
1048     }
1049     json_destroy(json);
1050
1051     /* Parse conditions and execute queries. */
1052     json = parse_json(ctx->argv[3]);
1053     if (json->type != JSON_ARRAY) {
1054         ovs_fatal(0, "CONDITION argument is not JSON array");
1055     }
1056     for (i = 0; i < json->u.array.n; i++) {
1057         struct ovsdb_condition cnd;
1058         size_t j;
1059
1060         check_ovsdb_error(ovsdb_condition_from_json(ts, json->u.array.elems[i],
1061                                                     NULL, &cnd));
1062
1063         memset(cbdata.counts, 0, cbdata.n_rows * sizeof *cbdata.counts);
1064         ovsdb_query(table, &cnd, do_query_cb, &cbdata);
1065
1066         printf("query %2"PRIuSIZE":", i);
1067         for (j = 0; j < cbdata.n_rows; j++) {
1068             if (j % 5 == 0) {
1069                 putchar(' ');
1070             }
1071             if (cbdata.counts[j]) {
1072                 printf("%d", cbdata.counts[j]);
1073                 if (cbdata.counts[j] > 1) {
1074                     /* Dup! */
1075                     exit_code = 1;
1076                 }
1077             } else {
1078                 putchar('-');
1079             }
1080         }
1081         putchar('\n');
1082
1083         ovsdb_condition_destroy(&cnd);
1084     }
1085     json_destroy(json);
1086
1087     ovsdb_table_destroy(table); /* Also destroys 'ts'. */
1088
1089     exit(exit_code);
1090 }
1091
1092 struct do_query_distinct_class {
1093     struct ovsdb_row *example;
1094     int count;
1095 };
1096
1097 struct do_query_distinct_row {
1098     struct uuid uuid;
1099     struct do_query_distinct_class *class;
1100 };
1101
1102 static void
1103 do_query_distinct(struct ovs_cmdl_context *ctx)
1104 {
1105     struct ovsdb_column_set columns;
1106     struct ovsdb_table_schema *ts;
1107     struct ovsdb_table *table;
1108     struct do_query_distinct_row *rows;
1109     size_t n_rows;
1110     struct do_query_distinct_class *classes;
1111     size_t n_classes;
1112     struct json *json;
1113     int exit_code = 0;
1114     size_t i;
1115
1116     /* Parse table schema, create table. */
1117     json = unbox_json(parse_json(ctx->argv[1]));
1118     check_ovsdb_error(ovsdb_table_schema_from_json(json, "mytable", &ts));
1119     json_destroy(json);
1120
1121     table = ovsdb_table_create(ts);
1122
1123     /* Parse column set. */
1124     json = parse_json(ctx->argv[4]);
1125     check_ovsdb_error(ovsdb_column_set_from_json(json, table->schema,
1126                                                  &columns));
1127     json_destroy(json);
1128
1129     /* Parse rows, add to table. */
1130     json = parse_json(ctx->argv[2]);
1131     if (json->type != JSON_ARRAY) {
1132         ovs_fatal(0, "ROW argument is not JSON array");
1133     }
1134     n_rows = json->u.array.n;
1135     rows = xmalloc(n_rows * sizeof *rows);
1136     classes = xmalloc(n_rows * sizeof *classes);
1137     n_classes = 0;
1138     for (i = 0; i < n_rows; i++) {
1139         struct ovsdb_row *row;
1140         size_t j;
1141
1142         /* Parse row. */
1143         row = ovsdb_row_create(table);
1144         uuid_generate(ovsdb_row_get_uuid_rw(row));
1145         check_ovsdb_error(ovsdb_row_from_json(row, json->u.array.elems[i],
1146                                               NULL, NULL));
1147
1148         /* Initialize row and find equivalence class. */
1149         rows[i].uuid = *ovsdb_row_get_uuid(row);
1150         rows[i].class = NULL;
1151         for (j = 0; j < n_classes; j++) {
1152             if (ovsdb_row_equal_columns(row, classes[j].example, &columns)) {
1153                 rows[i].class = &classes[j];
1154                 break;
1155             }
1156         }
1157         if (!rows[i].class) {
1158             rows[i].class = &classes[n_classes];
1159             classes[n_classes].example = ovsdb_row_clone(row);
1160             n_classes++;
1161         }
1162
1163         /* Add row to table. */
1164         if (ovsdb_table_get_row(table, ovsdb_row_get_uuid(row))) {
1165             ovs_fatal(0, "duplicate UUID "UUID_FMT" in table",
1166                       UUID_ARGS(ovsdb_row_get_uuid(row)));
1167         }
1168         put_row(table, row);
1169
1170     }
1171     json_destroy(json);
1172
1173     /* Parse conditions and execute queries. */
1174     json = parse_json(ctx->argv[3]);
1175     if (json->type != JSON_ARRAY) {
1176         ovs_fatal(0, "CONDITION argument is not JSON array");
1177     }
1178     for (i = 0; i < json->u.array.n; i++) {
1179         struct ovsdb_row_set results;
1180         struct ovsdb_condition cnd;
1181         size_t j;
1182
1183         check_ovsdb_error(ovsdb_condition_from_json(ts, json->u.array.elems[i],
1184                                                     NULL, &cnd));
1185
1186         for (j = 0; j < n_classes; j++) {
1187             classes[j].count = 0;
1188         }
1189         ovsdb_row_set_init(&results);
1190         ovsdb_query_distinct(table, &cnd, &columns, &results);
1191         for (j = 0; j < results.n_rows; j++) {
1192             size_t k;
1193
1194             for (k = 0; k < n_rows; k++) {
1195                 if (uuid_equals(ovsdb_row_get_uuid(results.rows[j]),
1196                                 &rows[k].uuid)) {
1197                     rows[k].class->count++;
1198                 }
1199             }
1200         }
1201         ovsdb_row_set_destroy(&results);
1202
1203         printf("query %2"PRIuSIZE":", i);
1204         for (j = 0; j < n_rows; j++) {
1205             int count = rows[j].class->count;
1206
1207             if (j % 5 == 0) {
1208                 putchar(' ');
1209             }
1210             if (count > 1) {
1211                 /* Dup! */
1212                 printf("%d", count);
1213                 exit_code = 1;
1214             } else if (count == 1) {
1215                 putchar("abcdefghijklmnopqrstuvwxyz"[rows[j].class - classes]);
1216             } else {
1217                 putchar('-');
1218             }
1219         }
1220         putchar('\n');
1221
1222         ovsdb_condition_destroy(&cnd);
1223     }
1224     json_destroy(json);
1225
1226     ovsdb_table_destroy(table); /* Also destroys 'ts'. */
1227
1228     exit(exit_code);
1229 }
1230
1231 static void
1232 do_parse_schema(struct ovs_cmdl_context *ctx)
1233 {
1234     struct ovsdb_schema *schema;
1235     struct json *json;
1236
1237     json = parse_json(ctx->argv[1]);
1238     check_ovsdb_error(ovsdb_schema_from_json(json, &schema));
1239     json_destroy(json);
1240     print_and_free_json(ovsdb_schema_to_json(schema));
1241     ovsdb_schema_destroy(schema);
1242 }
1243
1244 static void
1245 do_execute(struct ovs_cmdl_context *ctx)
1246 {
1247     struct ovsdb_schema *schema;
1248     struct json *json;
1249     struct ovsdb *db;
1250     int i;
1251
1252     /* Create database. */
1253     json = parse_json(ctx->argv[1]);
1254     check_ovsdb_error(ovsdb_schema_from_json(json, &schema));
1255     json_destroy(json);
1256     db = ovsdb_create(schema);
1257
1258     for (i = 2; i < ctx->argc; i++) {
1259         struct json *params, *result;
1260         char *s;
1261
1262         params = parse_json(ctx->argv[i]);
1263         result = ovsdb_execute(db, NULL, params, 0, NULL);
1264         s = json_to_string(result, JSSF_SORT);
1265         printf("%s\n", s);
1266         free(s);
1267         json_destroy(params);
1268         json_destroy(result);
1269     }
1270
1271     ovsdb_destroy(db);
1272 }
1273
1274 struct test_trigger {
1275     struct ovsdb_trigger trigger;
1276     int number;
1277 };
1278
1279 static void
1280 do_trigger_dump(struct test_trigger *t, long long int now, const char *title)
1281 {
1282     struct json *result;
1283     char *s;
1284
1285     result = ovsdb_trigger_steal_result(&t->trigger);
1286     s = json_to_string(result, JSSF_SORT);
1287     printf("t=%lld: trigger %d (%s): %s\n", now, t->number, title, s);
1288     free(s);
1289     json_destroy(result);
1290     ovsdb_trigger_destroy(&t->trigger);
1291     free(t);
1292 }
1293
1294 static void
1295 do_trigger(struct ovs_cmdl_context *ctx)
1296 {
1297     struct ovsdb_schema *schema;
1298     struct ovsdb_session session;
1299     struct ovsdb_server server;
1300     struct json *json;
1301     struct ovsdb *db;
1302     long long int now;
1303     int number;
1304     int i;
1305
1306     /* Create database. */
1307     json = parse_json(ctx->argv[1]);
1308     check_ovsdb_error(ovsdb_schema_from_json(json, &schema));
1309     json_destroy(json);
1310     db = ovsdb_create(schema);
1311
1312     ovsdb_server_init(&server);
1313     ovsdb_server_add_db(&server, db);
1314     ovsdb_session_init(&session, &server);
1315
1316     now = 0;
1317     number = 0;
1318     for (i = 2; i < ctx->argc; i++) {
1319         struct json *params = parse_json(ctx->argv[i]);
1320         if (params->type == JSON_ARRAY
1321             && json_array(params)->n == 2
1322             && json_array(params)->elems[0]->type == JSON_STRING
1323             && !strcmp(json_string(json_array(params)->elems[0]), "advance")
1324             && json_array(params)->elems[1]->type == JSON_INTEGER) {
1325             now += json_integer(json_array(params)->elems[1]);
1326             json_destroy(params);
1327         } else {
1328             struct test_trigger *t = xmalloc(sizeof *t);
1329             ovsdb_trigger_init(&session, db, &t->trigger, params, now);
1330             t->number = number++;
1331             if (ovsdb_trigger_is_complete(&t->trigger)) {
1332                 do_trigger_dump(t, now, "immediate");
1333             } else {
1334                 printf("t=%lld: new trigger %d\n", now, t->number);
1335             }
1336         }
1337
1338         ovsdb_trigger_run(db, now);
1339         while (!list_is_empty(&session.completions)) {
1340             do_trigger_dump(CONTAINER_OF(list_pop_front(&session.completions),
1341                                          struct test_trigger, trigger.node),
1342                             now, "delayed");
1343         }
1344
1345         ovsdb_trigger_wait(db, now);
1346         poll_immediate_wake();
1347         poll_block();
1348     }
1349
1350     ovsdb_server_destroy(&server);
1351     ovsdb_destroy(db);
1352 }
1353
1354 static void
1355 do_help(struct ovs_cmdl_context *ctx OVS_UNUSED)
1356 {
1357     usage();
1358 }
1359 \f
1360 /* "transact" command. */
1361
1362 static struct ovsdb *do_transact_db;
1363 static struct ovsdb_txn *do_transact_txn;
1364 static struct ovsdb_table *do_transact_table;
1365
1366 static void
1367 do_transact_commit(struct ovs_cmdl_context *ctx OVS_UNUSED)
1368 {
1369     ovsdb_error_destroy(ovsdb_txn_commit(do_transact_txn, false));
1370     do_transact_txn = NULL;
1371 }
1372
1373 static void
1374 do_transact_abort(struct ovs_cmdl_context *ctx OVS_UNUSED)
1375 {
1376     ovsdb_txn_abort(do_transact_txn);
1377     do_transact_txn = NULL;
1378 }
1379
1380 static void
1381 uuid_from_integer(int integer, struct uuid *uuid)
1382 {
1383     uuid_zero(uuid);
1384     uuid->parts[3] = integer;
1385 }
1386
1387 static const struct ovsdb_row *
1388 do_transact_find_row(const char *uuid_string)
1389 {
1390     const struct ovsdb_row *row;
1391     struct uuid uuid;
1392
1393     uuid_from_integer(atoi(uuid_string), &uuid);
1394     row = ovsdb_table_get_row(do_transact_table, &uuid);
1395     if (!row) {
1396         ovs_fatal(0, "table does not contain row with UUID "UUID_FMT,
1397                   UUID_ARGS(&uuid));
1398     }
1399     return row;
1400 }
1401
1402 static void
1403 do_transact_set_integer(struct ovsdb_row *row, const char *column_name,
1404                         int integer)
1405 {
1406     if (integer != -1) {
1407         const struct ovsdb_column *column;
1408
1409         column = ovsdb_table_schema_get_column(do_transact_table->schema,
1410                                                column_name);
1411         row->fields[column->index].keys[0].integer = integer;
1412     }
1413 }
1414
1415 static int
1416 do_transact_get_integer(const struct ovsdb_row *row, const char *column_name)
1417 {
1418     const struct ovsdb_column *column;
1419
1420     column = ovsdb_table_schema_get_column(do_transact_table->schema,
1421                                            column_name);
1422     return row->fields[column->index].keys[0].integer;
1423 }
1424
1425 static void
1426 do_transact_set_i_j(struct ovsdb_row *row,
1427                     const char *i_string, const char *j_string)
1428 {
1429     do_transact_set_integer(row, "i", atoi(i_string));
1430     do_transact_set_integer(row, "j", atoi(j_string));
1431 }
1432
1433 static void
1434 do_transact_insert(struct ovs_cmdl_context *ctx)
1435 {
1436     struct ovsdb_row *row;
1437     struct uuid *uuid;
1438
1439     row = ovsdb_row_create(do_transact_table);
1440
1441     /* Set UUID. */
1442     uuid = ovsdb_row_get_uuid_rw(row);
1443     uuid_from_integer(atoi(ctx->argv[1]), uuid);
1444     if (ovsdb_table_get_row(do_transact_table, uuid)) {
1445         ovs_fatal(0, "table already contains row with UUID "UUID_FMT,
1446                   UUID_ARGS(uuid));
1447     }
1448
1449     do_transact_set_i_j(row, ctx->argv[2], ctx->argv[3]);
1450
1451     /* Insert row. */
1452     ovsdb_txn_row_insert(do_transact_txn, row);
1453 }
1454
1455 static void
1456 do_transact_delete(struct ovs_cmdl_context *ctx)
1457 {
1458     const struct ovsdb_row *row = do_transact_find_row(ctx->argv[1]);
1459     ovsdb_txn_row_delete(do_transact_txn, row);
1460 }
1461
1462 static void
1463 do_transact_modify(struct ovs_cmdl_context *ctx)
1464 {
1465     const struct ovsdb_row *row_ro;
1466     struct ovsdb_row *row_rw;
1467
1468     row_ro = do_transact_find_row(ctx->argv[1]);
1469     row_rw = ovsdb_txn_row_modify(do_transact_txn, row_ro);
1470     do_transact_set_i_j(row_rw, ctx->argv[2], ctx->argv[3]);
1471 }
1472
1473 static int
1474 compare_rows_by_uuid(const void *a_, const void *b_)
1475 {
1476     struct ovsdb_row *const *ap = a_;
1477     struct ovsdb_row *const *bp = b_;
1478
1479     return uuid_compare_3way(ovsdb_row_get_uuid(*ap), ovsdb_row_get_uuid(*bp));
1480 }
1481
1482 static void
1483 do_transact_print(struct ovs_cmdl_context *ctx OVS_UNUSED)
1484 {
1485     const struct ovsdb_row **rows;
1486     const struct ovsdb_row *row;
1487     size_t n_rows;
1488     size_t i;
1489
1490     n_rows = hmap_count(&do_transact_table->rows);
1491     rows = xmalloc(n_rows * sizeof *rows);
1492     i = 0;
1493     HMAP_FOR_EACH (row, hmap_node, &do_transact_table->rows) {
1494         rows[i++] = row;
1495     }
1496     assert(i == n_rows);
1497
1498     qsort(rows, n_rows, sizeof *rows, compare_rows_by_uuid);
1499
1500     for (i = 0; i < n_rows; i++) {
1501         printf("\n%"PRId32": i=%d, j=%d",
1502                ovsdb_row_get_uuid(rows[i])->parts[3],
1503                do_transact_get_integer(rows[i], "i"),
1504                do_transact_get_integer(rows[i], "j"));
1505     }
1506
1507     free(rows);
1508 }
1509
1510 static void
1511 do_transact(struct ovs_cmdl_context *ctx)
1512 {
1513     static const struct ovs_cmdl_command do_transact_commands[] = {
1514         { "commit", NULL, 0, 0, do_transact_commit },
1515         { "abort", NULL, 0, 0, do_transact_abort },
1516         { "insert", NULL, 2, 3, do_transact_insert },
1517         { "delete", NULL, 1, 1, do_transact_delete },
1518         { "modify", NULL, 2, 3, do_transact_modify },
1519         { "print", NULL, 0, 0, do_transact_print },
1520         { NULL, NULL, 0, 0, NULL },
1521     };
1522
1523     struct ovsdb_schema *schema;
1524     struct json *json;
1525     int i;
1526
1527     /* Create table. */
1528     json = parse_json("{\"name\": \"testdb\", "
1529                       " \"tables\": "
1530                       "  {\"mytable\": "
1531                       "    {\"columns\": "
1532                       "      {\"i\": {\"type\": \"integer\"}, "
1533                       "       \"j\": {\"type\": \"integer\"}}}}}");
1534     check_ovsdb_error(ovsdb_schema_from_json(json, &schema));
1535     json_destroy(json);
1536     do_transact_db = ovsdb_create(schema);
1537     do_transact_table = ovsdb_get_table(do_transact_db, "mytable");
1538     assert(do_transact_table != NULL);
1539
1540     for (i = 1; i < ctx->argc; i++) {
1541         struct json *command;
1542         size_t n_args;
1543         char **args;
1544         int j;
1545         struct ovs_cmdl_context transact_ctx = { .argc = 0, };
1546
1547         command = parse_json(ctx->argv[i]);
1548         if (command->type != JSON_ARRAY) {
1549             ovs_fatal(0, "transaction %d must be JSON array "
1550                       "with at least 1 element", i);
1551         }
1552
1553         n_args = command->u.array.n;
1554         args = xmalloc((n_args + 1) * sizeof *args);
1555         for (j = 0; j < n_args; j++) {
1556             struct json *s = command->u.array.elems[j];
1557             if (s->type != JSON_STRING) {
1558                 ovs_fatal(0, "transaction %d argument %d must be JSON string",
1559                           i, j);
1560             }
1561             args[j] = xstrdup(json_string(s));
1562         }
1563         args[n_args] = NULL;
1564
1565         if (!do_transact_txn) {
1566             do_transact_txn = ovsdb_txn_create(do_transact_db);
1567         }
1568
1569         for (j = 0; j < n_args; j++) {
1570             if (j) {
1571                 putchar(' ');
1572             }
1573             fputs(args[j], stdout);
1574         }
1575         fputs(":", stdout);
1576         transact_ctx.argc = n_args;
1577         transact_ctx.argv = args;
1578         ovs_cmdl_run_command(&transact_ctx, do_transact_commands);
1579         putchar('\n');
1580
1581         for (j = 0; j < n_args; j++) {
1582             free(args[j]);
1583         }
1584         free(args);
1585         json_destroy(command);
1586     }
1587     ovsdb_txn_abort(do_transact_txn);
1588     ovsdb_destroy(do_transact_db); /* Also destroys 'schema'. */
1589 }
1590
1591 static int
1592 compare_link1(const void *a_, const void *b_)
1593 {
1594     const struct idltest_link1 *const *ap = a_;
1595     const struct idltest_link1 *const *bp = b_;
1596     const struct idltest_link1 *a = *ap;
1597     const struct idltest_link1 *b = *bp;
1598
1599     return a->i < b->i ? -1 : a->i > b->i;
1600 }
1601
1602 static void
1603 print_idl(struct ovsdb_idl *idl, int step)
1604 {
1605     const struct idltest_simple *s;
1606     const struct idltest_link1 *l1;
1607     const struct idltest_link2 *l2;
1608     int n = 0;
1609
1610     IDLTEST_SIMPLE_FOR_EACH (s, idl) {
1611         size_t i;
1612
1613         printf("%03d: i=%"PRId64" r=%g b=%s s=%s u="UUID_FMT" ia=[",
1614                step, s->i, s->r, s->b ? "true" : "false",
1615                s->s, UUID_ARGS(&s->u));
1616         for (i = 0; i < s->n_ia; i++) {
1617             printf("%s%"PRId64, i ? " " : "", s->ia[i]);
1618         }
1619         printf("] ra=[");
1620         for (i = 0; i < s->n_ra; i++) {
1621             printf("%s%g", i ? " " : "", s->ra[i]);
1622         }
1623         printf("] ba=[");
1624         for (i = 0; i < s->n_ba; i++) {
1625             printf("%s%s", i ? " " : "", s->ba[i] ? "true" : "false");
1626         }
1627         printf("] sa=[");
1628         for (i = 0; i < s->n_sa; i++) {
1629             printf("%s%s", i ? " " : "", s->sa[i]);
1630         }
1631         printf("] ua=[");
1632         for (i = 0; i < s->n_ua; i++) {
1633             printf("%s"UUID_FMT, i ? " " : "", UUID_ARGS(&s->ua[i]));
1634         }
1635         printf("] uuid="UUID_FMT"\n", UUID_ARGS(&s->header_.uuid));
1636         n++;
1637     }
1638     IDLTEST_LINK1_FOR_EACH (l1, idl) {
1639         struct idltest_link1 **links;
1640         size_t i;
1641
1642         printf("%03d: i=%"PRId64" k=", step, l1->i);
1643         if (l1->k) {
1644             printf("%"PRId64, l1->k->i);
1645         }
1646         printf(" ka=[");
1647         links = xmemdup(l1->ka, l1->n_ka * sizeof *l1->ka);
1648         qsort(links, l1->n_ka, sizeof *links, compare_link1);
1649         for (i = 0; i < l1->n_ka; i++) {
1650             printf("%s%"PRId64, i ? " " : "", links[i]->i);
1651         }
1652         free(links);
1653         printf("] l2=");
1654         if (l1->l2) {
1655             printf("%"PRId64, l1->l2->i);
1656         }
1657         printf(" uuid="UUID_FMT"\n", UUID_ARGS(&l1->header_.uuid));
1658         n++;
1659     }
1660     IDLTEST_LINK2_FOR_EACH (l2, idl) {
1661         printf("%03d: i=%"PRId64" l1=", step, l2->i);
1662         if (l2->l1) {
1663             printf("%"PRId64, l2->l1->i);
1664         }
1665         printf(" uuid="UUID_FMT"\n", UUID_ARGS(&l2->header_.uuid));
1666         n++;
1667     }
1668     if (!n) {
1669         printf("%03d: empty\n", step);
1670     }
1671 }
1672
1673 static void
1674 parse_uuids(const struct json *json, struct ovsdb_symbol_table *symtab,
1675             size_t *n)
1676 {
1677     struct uuid uuid;
1678
1679     if (json->type == JSON_STRING && uuid_from_string(&uuid, json->u.string)) {
1680         char *name = xasprintf("#%"PRIuSIZE"#", *n);
1681         fprintf(stderr, "%s = "UUID_FMT"\n", name, UUID_ARGS(&uuid));
1682         ovsdb_symbol_table_put(symtab, name, &uuid, false);
1683         free(name);
1684         *n += 1;
1685     } else if (json->type == JSON_ARRAY) {
1686         size_t i;
1687
1688         for (i = 0; i < json->u.array.n; i++) {
1689             parse_uuids(json->u.array.elems[i], symtab, n);
1690         }
1691     } else if (json->type == JSON_OBJECT) {
1692         const struct shash_node *node;
1693
1694         SHASH_FOR_EACH (node, json_object(json)) {
1695             parse_uuids(node->data, symtab, n);
1696         }
1697     }
1698 }
1699
1700 static void
1701 substitute_uuids(struct json *json, const struct ovsdb_symbol_table *symtab)
1702 {
1703     if (json->type == JSON_STRING) {
1704         const struct ovsdb_symbol *symbol;
1705
1706         symbol = ovsdb_symbol_table_get(symtab, json->u.string);
1707         if (symbol) {
1708             free(json->u.string);
1709             json->u.string = xasprintf(UUID_FMT, UUID_ARGS(&symbol->uuid));
1710         }
1711     } else if (json->type == JSON_ARRAY) {
1712         size_t i;
1713
1714         for (i = 0; i < json->u.array.n; i++) {
1715             substitute_uuids(json->u.array.elems[i], symtab);
1716         }
1717     } else if (json->type == JSON_OBJECT) {
1718         const struct shash_node *node;
1719
1720         SHASH_FOR_EACH (node, json_object(json)) {
1721             substitute_uuids(node->data, symtab);
1722         }
1723     }
1724 }
1725
1726 static const struct idltest_simple *
1727 idltest_find_simple(struct ovsdb_idl *idl, int i)
1728 {
1729     const struct idltest_simple *s;
1730
1731     IDLTEST_SIMPLE_FOR_EACH (s, idl) {
1732         if (s->i == i) {
1733             return s;
1734         }
1735     }
1736     return NULL;
1737 }
1738
1739 static void
1740 idl_set(struct ovsdb_idl *idl, char *commands, int step)
1741 {
1742     char *cmd, *save_ptr1 = NULL;
1743     struct ovsdb_idl_txn *txn;
1744     enum ovsdb_idl_txn_status status;
1745     bool increment = false;
1746
1747     txn = ovsdb_idl_txn_create(idl);
1748     for (cmd = strtok_r(commands, ",", &save_ptr1); cmd;
1749          cmd = strtok_r(NULL, ",", &save_ptr1)) {
1750         char *save_ptr2 = NULL;
1751         char *name, *arg1, *arg2, *arg3;
1752
1753         name = strtok_r(cmd, " ", &save_ptr2);
1754         arg1 = strtok_r(NULL, " ", &save_ptr2);
1755         arg2 = strtok_r(NULL, " ", &save_ptr2);
1756         arg3 = strtok_r(NULL, " ", &save_ptr2);
1757
1758         if (!strcmp(name, "set")) {
1759             const struct idltest_simple *s;
1760
1761             if (!arg3) {
1762                 ovs_fatal(0, "\"set\" command requires 3 arguments");
1763             }
1764
1765             s = idltest_find_simple(idl, atoi(arg1));
1766             if (!s) {
1767                 ovs_fatal(0, "\"set\" command asks for nonexistent "
1768                           "i=%d", atoi(arg1));
1769             }
1770
1771             if (!strcmp(arg2, "b")) {
1772                 idltest_simple_set_b(s, atoi(arg3));
1773             } else if (!strcmp(arg2, "s")) {
1774                 idltest_simple_set_s(s, arg3);
1775             } else if (!strcmp(arg2, "u")) {
1776                 struct uuid uuid;
1777                 if (!uuid_from_string(&uuid, arg3)) {
1778                     ovs_fatal(0, "\"%s\" is not a valid UUID", arg3);
1779                 }
1780                 idltest_simple_set_u(s, uuid);
1781             } else if (!strcmp(arg2, "r")) {
1782                 idltest_simple_set_r(s, atof(arg3));
1783             } else {
1784                 ovs_fatal(0, "\"set\" command asks for unknown column %s",
1785                           arg2);
1786             }
1787         } else if (!strcmp(name, "insert")) {
1788             struct idltest_simple *s;
1789
1790             if (!arg1 || arg2) {
1791                 ovs_fatal(0, "\"insert\" command requires 1 argument");
1792             }
1793
1794             s = idltest_simple_insert(txn);
1795             idltest_simple_set_i(s, atoi(arg1));
1796         } else if (!strcmp(name, "delete")) {
1797             const struct idltest_simple *s;
1798
1799             if (!arg1 || arg2) {
1800                 ovs_fatal(0, "\"delete\" command requires 1 argument");
1801             }
1802
1803             s = idltest_find_simple(idl, atoi(arg1));
1804             if (!s) {
1805                 ovs_fatal(0, "\"delete\" command asks for nonexistent "
1806                           "i=%d", atoi(arg1));
1807             }
1808             idltest_simple_delete(s);
1809         } else if (!strcmp(name, "verify")) {
1810             const struct idltest_simple *s;
1811
1812             if (!arg2 || arg3) {
1813                 ovs_fatal(0, "\"verify\" command requires 2 arguments");
1814             }
1815
1816             s = idltest_find_simple(idl, atoi(arg1));
1817             if (!s) {
1818                 ovs_fatal(0, "\"verify\" command asks for nonexistent "
1819                           "i=%d", atoi(arg1));
1820             }
1821
1822             if (!strcmp(arg2, "i")) {
1823                 idltest_simple_verify_i(s);
1824             } else if (!strcmp(arg2, "b")) {
1825                 idltest_simple_verify_b(s);
1826             } else if (!strcmp(arg2, "s")) {
1827                 idltest_simple_verify_s(s);
1828             } else if (!strcmp(arg2, "u")) {
1829                 idltest_simple_verify_s(s);
1830             } else if (!strcmp(arg2, "r")) {
1831                 idltest_simple_verify_r(s);
1832             } else {
1833                 ovs_fatal(0, "\"verify\" command asks for unknown column %s",
1834                           arg2);
1835             }
1836         } else if (!strcmp(name, "increment")) {
1837             const struct idltest_simple *s;
1838
1839             if (!arg1 || arg2) {
1840                 ovs_fatal(0, "\"increment\" command requires 1 argument");
1841             }
1842
1843             s = idltest_find_simple(idl, atoi(arg1));
1844             if (!s) {
1845                 ovs_fatal(0, "\"set\" command asks for nonexistent "
1846                           "i=%d", atoi(arg1));
1847             }
1848
1849             ovsdb_idl_txn_increment(txn, &s->header_, &idltest_simple_col_i);
1850             increment = true;
1851         } else if (!strcmp(name, "abort")) {
1852             ovsdb_idl_txn_abort(txn);
1853             break;
1854         } else if (!strcmp(name, "destroy")) {
1855             printf("%03d: destroy\n", step);
1856             ovsdb_idl_txn_destroy(txn);
1857             return;
1858         } else {
1859             ovs_fatal(0, "unknown command %s", name);
1860         }
1861     }
1862
1863     status = ovsdb_idl_txn_commit_block(txn);
1864     printf("%03d: commit, status=%s",
1865            step, ovsdb_idl_txn_status_to_string(status));
1866     if (increment) {
1867         printf(", increment=%"PRId64,
1868                ovsdb_idl_txn_get_increment_new_value(txn));
1869     }
1870     putchar('\n');
1871     ovsdb_idl_txn_destroy(txn);
1872 }
1873
1874 static void
1875 do_idl(struct ovs_cmdl_context *ctx)
1876 {
1877     struct jsonrpc *rpc;
1878     struct ovsdb_idl *idl;
1879     unsigned int seqno = 0;
1880     struct ovsdb_symbol_table *symtab;
1881     size_t n_uuids = 0;
1882     int step = 0;
1883     int error;
1884     int i;
1885
1886     idltest_init();
1887
1888     idl = ovsdb_idl_create(ctx->argv[1], &idltest_idl_class, true, true);
1889     if (ctx->argc > 2) {
1890         struct stream *stream;
1891
1892         error = stream_open_block(jsonrpc_stream_open(ctx->argv[1], &stream,
1893                                   DSCP_DEFAULT), &stream);
1894         if (error) {
1895             ovs_fatal(error, "failed to connect to \"%s\"", ctx->argv[1]);
1896         }
1897         rpc = jsonrpc_open(stream);
1898     } else {
1899         rpc = NULL;
1900     }
1901
1902     setvbuf(stdout, NULL, _IONBF, 0);
1903
1904     symtab = ovsdb_symbol_table_create();
1905     for (i = 2; i < ctx->argc; i++) {
1906         char *arg = ctx->argv[i];
1907         struct jsonrpc_msg *request, *reply;
1908
1909         if (*arg == '+') {
1910             /* The previous transaction didn't change anything. */
1911             arg++;
1912         } else {
1913             /* Wait for update. */
1914             for (;;) {
1915                 ovsdb_idl_run(idl);
1916                 if (ovsdb_idl_get_seqno(idl) != seqno) {
1917                     break;
1918                 }
1919                 jsonrpc_run(rpc);
1920
1921                 ovsdb_idl_wait(idl);
1922                 jsonrpc_wait(rpc);
1923                 poll_block();
1924             }
1925
1926             /* Print update. */
1927             print_idl(idl, step++);
1928         }
1929         seqno = ovsdb_idl_get_seqno(idl);
1930
1931         if (!strcmp(arg, "reconnect")) {
1932             printf("%03d: reconnect\n", step++);
1933             ovsdb_idl_force_reconnect(idl);
1934         } else if (arg[0] != '[') {
1935             idl_set(idl, arg, step++);
1936         } else {
1937             struct json *json = parse_json(arg);
1938             substitute_uuids(json, symtab);
1939             request = jsonrpc_create_request("transact", json, NULL);
1940             error = jsonrpc_transact_block(rpc, request, &reply);
1941             if (error || reply->error) {
1942                 ovs_fatal(error, "jsonrpc transaction failed");
1943             }
1944             printf("%03d: ", step++);
1945             if (reply->result) {
1946                 parse_uuids(reply->result, symtab, &n_uuids);
1947             }
1948             json_destroy(reply->id);
1949             reply->id = NULL;
1950             print_and_free_json(jsonrpc_msg_to_json(reply));
1951         }
1952     }
1953     ovsdb_symbol_table_destroy(symtab);
1954
1955     if (rpc) {
1956         jsonrpc_close(rpc);
1957     }
1958     for (;;) {
1959         ovsdb_idl_run(idl);
1960         if (ovsdb_idl_get_seqno(idl) != seqno) {
1961             break;
1962         }
1963         ovsdb_idl_wait(idl);
1964         poll_block();
1965     }
1966     print_idl(idl, step++);
1967     ovsdb_idl_destroy(idl);
1968     printf("%03d: done\n", step);
1969 }
1970
1971 static struct ovs_cmdl_command all_commands[] = {
1972     { "log-io", NULL, 2, INT_MAX, do_log_io },
1973     { "default-atoms", NULL, 0, 0, do_default_atoms },
1974     { "default-data", NULL, 0, 0, do_default_data },
1975     { "parse-atomic-type", NULL, 1, 1, do_parse_atomic_type },
1976     { "parse-base-type", NULL, 1, 1, do_parse_base_type },
1977     { "parse-type", NULL, 1, 1, do_parse_type },
1978     { "parse-atoms", NULL, 2, INT_MAX, do_parse_atoms },
1979     { "parse-atom-strings", NULL, 2, INT_MAX, do_parse_atom_strings },
1980     { "parse-data", NULL, 2, INT_MAX, do_parse_data },
1981     { "parse-data-strings", NULL, 2, INT_MAX, do_parse_data_strings },
1982     { "sort-atoms", NULL, 2, 2, do_sort_atoms },
1983     { "parse-column", NULL, 2, 2, do_parse_column },
1984     { "parse-table", NULL, 2, 3, do_parse_table },
1985     { "parse-rows", NULL, 2, INT_MAX, do_parse_rows },
1986     { "compare-rows", NULL, 2, INT_MAX, do_compare_rows },
1987     { "parse-conditions", NULL, 2, INT_MAX, do_parse_conditions },
1988     { "evaluate-conditions", NULL, 3, 3, do_evaluate_conditions },
1989     { "parse-mutations", NULL, 2, INT_MAX, do_parse_mutations },
1990     { "execute-mutations", NULL, 3, 3, do_execute_mutations },
1991     { "query", NULL, 3, 3, do_query },
1992     { "query-distinct", NULL, 4, 4, do_query_distinct },
1993     { "transact", NULL, 1, INT_MAX, do_transact },
1994     { "parse-schema", NULL, 1, 1, do_parse_schema },
1995     { "execute", NULL, 2, INT_MAX, do_execute },
1996     { "trigger", NULL, 2, INT_MAX, do_trigger },
1997     { "idl", NULL, 1, INT_MAX, do_idl },
1998     { "help", NULL, 0, INT_MAX, do_help },
1999     { NULL, NULL, 0, 0, NULL },
2000 };
2001
2002 static struct ovs_cmdl_command *
2003 get_all_commands(void)
2004 {
2005     return all_commands;
2006 }