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