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