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