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