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