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