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