27523fb222d674146133826d245073bbc54ed4f9
[cascardo/ovs.git] / tests / test-ovsdb.c
1 /*
2  * Copyright (c) 2009 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 "json.h"
28 #include "ovsdb-data.h"
29 #include "ovsdb-error.h"
30 #include "ovsdb-types.h"
31 #include "ovsdb/column.h"
32 #include "ovsdb/condition.h"
33 #include "ovsdb/file.h"
34 #include "ovsdb/log.h"
35 #include "ovsdb/ovsdb.h"
36 #include "ovsdb/query.h"
37 #include "ovsdb/row.h"
38 #include "ovsdb/table.h"
39 #include "ovsdb/transaction.h"
40 #include "ovsdb/trigger.h"
41 #include "poll-loop.h"
42 #include "svec.h"
43 #include "timeval.h"
44 #include "util.h"
45 #include "vlog.h"
46
47 static struct command all_commands[];
48
49 static void usage(void) NO_RETURN;
50 static void parse_options(int argc, char *argv[]);
51
52 int
53 main(int argc, char *argv[])
54 {
55     set_program_name(argv[0]);
56     time_init();
57     vlog_init();
58     parse_options(argc, argv);
59     run_command(argc - optind, argv + optind, all_commands);
60     return 0;
61 }
62
63 static void
64 parse_options(int argc, char *argv[])
65 {
66     static struct option long_options[] = {
67         {"verbose", optional_argument, 0, 'v'},
68         {"help", no_argument, 0, 'h'},
69         {0, 0, 0, 0},
70     };
71     char *short_options = long_options_to_short_options(long_options);
72
73     for (;;) {
74         int c = getopt_long(argc, argv, short_options, long_options, NULL);
75         if (c == -1) {
76             break;
77         }
78
79         switch (c) {
80         case 'h':
81             usage();
82
83         case 'v':
84             vlog_set_verbosity(optarg);
85             break;
86
87         case '?':
88             exit(EXIT_FAILURE);
89
90         default:
91             abort();
92         }
93     }
94     free(short_options);
95 }
96
97 static void
98 usage(void)
99 {
100     printf("%s: Open vSwitch database test utility\n"
101            "usage: %s [OPTIONS] COMMAND [ARG...]\n\n"
102            "  log-io FILE FLAGS COMMAND...\n"
103            "    open FILE with FLAGS, run COMMANDs\n"
104            "  parse-atomic-type TYPE\n"
105            "    parse TYPE as OVSDB atomic type, and re-serialize\n"
106            "  parse-type JSON\n"
107            "    parse JSON as OVSDB type, and re-serialize\n"
108            "  parse-atoms TYPE ATOM...\n"
109            "    parse ATOMs as atoms of given TYPE, and re-serialize\n"
110            "  sort-atoms TYPE ATOM...\n"
111            "    print ATOMs in sorted order, and re-serialize\n"
112            "  parse-data TYPE DATUM...\n"
113            "    parse DATUMs as data of given TYPE, and re-serialize\n"
114            "  parse-column NAME OBJECT\n"
115            "    parse column NAME with info OBJECT, and re-serialize\n"
116            "  parse-table NAME OBJECT\n"
117            "    parse table NAME with info OBJECT\n"
118            "  parse-row TABLE ROW..., and re-serialize\n"
119            "    parse each ROW of defined TABLE\n"
120            "  compare-row TABLE ROW...\n"
121            "    mutually compare all of the ROWs, print those that are equal\n"
122            "  parse-conditions TABLE CONDITION...\n"
123            "    parse each CONDITION on TABLE, and re-serialize\n"
124            "  evaluate-conditions TABLE [CONDITION,...] [ROW,...]\n"
125            "    test CONDITIONS on TABLE against each ROW, print results\n"
126            "  query TABLE [ROW,...] [CONDITION,...]\n"
127            "    add each ROW to TABLE, then query and print the rows that\n"
128            "    satisfy each CONDITION.\n"
129            "  query-distinct TABLE [ROW,...] [CONDITION,...] COLUMNS\n"
130            "    add each ROW to TABLE, then query and print the rows that\n"
131            "    satisfy each CONDITION and have distinct COLUMNS.\n"
132            "  transact COMMAND\n"
133            "    execute each specified transactional COMMAND:\n"
134            "      commit\n"
135            "      abort\n"
136            "      insert UUID I J\n"
137            "      delete UUID\n"
138            "      modify UUID I J\n"
139            "      print\n"
140            "  execute SCHEMA TRANSACTION...\n"
141            "    executes each TRANSACTION on an initially empty database\n"
142            "    the specified SCHEMA\n"
143            "  trigger SCHEMA TRANSACTION...\n"
144            "    executes each TRANSACTION on an initially empty database\n"
145            "    the specified SCHEMA.   A TRANSACTION of the form\n"
146            "    [\"advance\", NUMBER] advances NUMBER milliseconds in\n"
147            "    simulated time, for causing triggers to time out.\n",
148            program_name, program_name);
149     vlog_usage();
150     printf("\nOther options:\n"
151            "  -h, --help                  display this help message\n");
152     exit(EXIT_SUCCESS);
153 }
154 \f
155 /* Command helper functions. */
156
157 static struct json *
158 parse_json(const char *s)
159 {
160     struct json *json = json_from_string(s);
161     if (json->type == JSON_STRING) {
162         ovs_fatal(0, "\"%s\": %s", s, json->u.string);
163     }
164     return json;
165 }
166
167 static struct json *
168 unbox_json(struct json *json)
169 {
170     if (json->type == JSON_ARRAY && json->u.array.n == 1) {
171         struct json *inner = json->u.array.elems[0];
172         json->u.array.elems[0] = NULL;
173         json_destroy(json);
174         return inner;
175     } else {
176         return json;
177     }
178 }
179
180 static void
181 print_and_free_json(struct json *json)
182 {
183     char *string = json_to_string(json, JSSF_SORT);
184     json_destroy(json);
185     puts(string);
186     free(string);
187 }
188
189 static void
190 check_ovsdb_error(struct ovsdb_error *error)
191 {
192     if (error) {
193         ovs_fatal(0, "%s", ovsdb_error_to_string(error));
194     }
195 }
196 \f
197 /* Command implementations. */
198
199 static void
200 do_log_io(int argc, char *argv[])
201 {
202     const char *name = argv[1];
203     char *mode = argv[2];
204
205     struct ovsdb_error *error;
206     struct ovsdb_log *log;
207     char *save_ptr = NULL;
208     const char *token;
209     int flags;
210     int i;
211
212     for (flags = 0, token = strtok_r(mode, " |", &save_ptr); token != NULL;
213          token = strtok_r(NULL, " |", &save_ptr))
214     {
215         if (!strcmp(token, "O_RDONLY")) {
216             flags |= O_RDONLY;
217         } else if (!strcmp(token, "O_RDWR")) {
218             flags |= O_RDWR;
219         } else if (!strcmp(token, "O_TRUNC")) {
220             flags |= O_TRUNC;
221         } else if (!strcmp(token, "O_CREAT")) {
222             flags |= O_CREAT;
223         } else if (!strcmp(token, "O_EXCL")) {
224             flags |= O_EXCL;
225         } else if (!strcmp(token, "O_TRUNC")) {
226             flags |= O_TRUNC;
227         }
228     }
229
230     check_ovsdb_error(ovsdb_log_open(name, flags, &log));
231     printf("%s: open successful\n", name);
232
233     for (i = 3; i < argc; i++) {
234         const char *command = argv[i];
235         if (!strcmp(command, "read")) {
236             struct json *json;
237
238             error = ovsdb_log_read(log, &json);
239             if (!error) {
240                 printf("%s: read: ", name);
241                 if (json) {
242                     print_and_free_json(json);
243                 } else {
244                     printf("end of log\n");
245                 }
246                 continue;
247             }
248         } else if (!strncmp(command, "write:", 6)) {
249             struct json *json = parse_json(command + 6);
250             error = ovsdb_log_write(log, json);
251             json_destroy(json);
252         } else if (!strcmp(command, "commit")) {
253             error = ovsdb_log_commit(log);
254         } else {
255             ovs_fatal(0, "unknown log-io command \"%s\"", command);
256         }
257         if (error) {
258             char *s = ovsdb_error_to_string(error);
259             printf("%s: %s failed: %s\n", name, command, s);
260             free(s);
261         } else {
262             printf("%s: %s successful\n", name, command);
263         }
264     }
265
266     ovsdb_log_close(log);
267 }
268
269 static void
270 do_parse_atomic_type(int argc UNUSED, char *argv[])
271 {
272     enum ovsdb_atomic_type type;
273     struct json *json;
274
275     json = unbox_json(parse_json(argv[1]));
276     check_ovsdb_error(ovsdb_atomic_type_from_json(&type, json));
277     json_destroy(json);
278     print_and_free_json(ovsdb_atomic_type_to_json(type));
279 }
280
281 static void
282 do_parse_type(int argc UNUSED, char *argv[])
283 {
284     struct ovsdb_type type;
285     struct json *json;
286
287     json = unbox_json(parse_json(argv[1]));
288     check_ovsdb_error(ovsdb_type_from_json(&type, json));
289     json_destroy(json);
290     print_and_free_json(ovsdb_type_to_json(&type));
291 }
292
293 static void
294 do_parse_atoms(int argc, char *argv[])
295 {
296     enum ovsdb_atomic_type type;
297     struct json *json;
298     int i;
299
300     json = unbox_json(parse_json(argv[1]));
301     check_ovsdb_error(ovsdb_atomic_type_from_json(&type, json));
302     json_destroy(json);
303
304     for (i = 2; i < argc; i++) {
305         union ovsdb_atom atom;
306
307         json = unbox_json(parse_json(argv[i]));
308         check_ovsdb_error(ovsdb_atom_from_json(&atom, type, json, NULL));
309         json_destroy(json);
310
311         print_and_free_json(ovsdb_atom_to_json(&atom, type));
312
313         ovsdb_atom_destroy(&atom, type);
314     }
315 }
316
317 static void
318 do_parse_data(int argc, char *argv[])
319 {
320     struct ovsdb_type type;
321     struct json *json;
322     int i;
323
324     json = unbox_json(parse_json(argv[1]));
325     check_ovsdb_error(ovsdb_type_from_json(&type, json));
326     json_destroy(json);
327
328     for (i = 2; i < argc; i++) {
329         struct ovsdb_datum datum;
330
331         json = unbox_json(parse_json(argv[i]));
332         check_ovsdb_error(ovsdb_datum_from_json(&datum, &type, json, NULL));
333         json_destroy(json);
334
335         print_and_free_json(ovsdb_datum_to_json(&datum, &type));
336
337         ovsdb_datum_destroy(&datum, &type);
338     }
339 }
340
341 static enum ovsdb_atomic_type compare_atoms_atomic_type;
342
343 static int
344 compare_atoms(const void *a_, const void *b_)
345 {
346     const union ovsdb_atom *a = a_;
347     const union ovsdb_atom *b = b_;
348
349     return ovsdb_atom_compare_3way(a, b, compare_atoms_atomic_type);
350 }
351
352 static void
353 do_sort_atoms(int argc UNUSED, char *argv[])
354 {
355     enum ovsdb_atomic_type type;
356     union ovsdb_atom *atoms;
357     struct json *json, **json_atoms;
358     size_t n_atoms;
359     int i;
360
361     json = unbox_json(parse_json(argv[1]));
362     check_ovsdb_error(ovsdb_atomic_type_from_json(&type, json));
363     json_destroy(json);
364
365     json = unbox_json(parse_json(argv[2]));
366     if (json->type != JSON_ARRAY) {
367         ovs_fatal(0, "second argument must be array");
368     }
369
370     /* Convert JSON atoms to internal representation. */
371     n_atoms = json->u.array.n;
372     atoms = xmalloc(n_atoms * sizeof *atoms);
373     for (i = 0; i < n_atoms; i++) {
374         check_ovsdb_error(ovsdb_atom_from_json(&atoms[i], type,
375                                                json->u.array.elems[i], NULL));
376     }
377     json_destroy(json);
378
379     /* Sort atoms. */
380     compare_atoms_atomic_type = type;
381     qsort(atoms, n_atoms, sizeof *atoms, compare_atoms);
382
383     /* Convert internal representation back to JSON. */
384     json_atoms = xmalloc(n_atoms * sizeof *json_atoms);
385     for (i = 0; i < n_atoms; i++) {
386         json_atoms[i] = ovsdb_atom_to_json(&atoms[i], type);
387         ovsdb_atom_destroy(&atoms[i], type);
388     }
389     print_and_free_json(json_array_create(json_atoms, n_atoms));
390 }
391
392 static void
393 do_parse_column(int argc UNUSED, char *argv[])
394 {
395     struct ovsdb_column *column;
396     struct json *json;
397
398     json = parse_json(argv[2]);
399     check_ovsdb_error(ovsdb_column_from_json(json, argv[1], &column));
400     json_destroy(json);
401     print_and_free_json(ovsdb_column_to_json(column));
402     ovsdb_column_destroy(column);
403 }
404
405 static void
406 do_parse_table(int argc UNUSED, char *argv[])
407 {
408     struct ovsdb_table_schema *ts;
409     struct json *json;
410
411     json = parse_json(argv[2]);
412     check_ovsdb_error(ovsdb_table_schema_from_json(json, argv[1], &ts));
413     json_destroy(json);
414     print_and_free_json(ovsdb_table_schema_to_json(ts));
415     ovsdb_table_schema_destroy(ts);
416 }
417
418 static void
419 do_parse_rows(int argc, char *argv[])
420 {
421     struct ovsdb_column_set all_columns;
422     struct ovsdb_table_schema *ts;
423     struct ovsdb_table *table;
424     struct json *json;
425     int i;
426
427     json = unbox_json(parse_json(argv[1]));
428     check_ovsdb_error(ovsdb_table_schema_from_json(json, "mytable", &ts));
429     json_destroy(json);
430
431     table = ovsdb_table_create(ts);
432     ovsdb_column_set_init(&all_columns);
433     ovsdb_column_set_add_all(&all_columns, table);
434
435     for (i = 2; i < argc; i++) {
436         struct ovsdb_column_set columns;
437         struct ovsdb_row *row;
438
439         ovsdb_column_set_init(&columns);
440         row = ovsdb_row_create(table);
441
442         json = unbox_json(parse_json(argv[i]));
443         check_ovsdb_error(ovsdb_row_from_json(row, json, NULL, &columns));
444         json_destroy(json);
445
446         print_and_free_json(ovsdb_row_to_json(row, &all_columns));
447
448         if (columns.n_columns) {
449             struct svec names;
450             size_t j;
451             char *s;
452
453             svec_init(&names);
454             for (j = 0; j < columns.n_columns; j++) {
455                 svec_add(&names, columns.columns[j]->name);
456             }
457             svec_sort(&names);
458             s = svec_join(&names, ", ", "");
459             puts(s);
460             free(s);
461             svec_destroy(&names);
462         } else {
463             printf("<none>\n");
464         }
465
466         ovsdb_column_set_destroy(&columns);
467         ovsdb_row_destroy(row);
468     }
469
470     ovsdb_column_set_destroy(&all_columns);
471     ovsdb_table_destroy(table); /* Also destroys 'ts'. */
472 }
473
474 static void
475 do_compare_rows(int argc, char *argv[])
476 {
477     struct ovsdb_column_set all_columns;
478     struct ovsdb_table_schema *ts;
479     struct ovsdb_table *table;
480     struct ovsdb_row **rows;
481     struct json *json;
482     char **names;
483     int n_rows;
484     int i, j;
485
486     json = unbox_json(parse_json(argv[1]));
487     check_ovsdb_error(ovsdb_table_schema_from_json(json, "mytable", &ts));
488     json_destroy(json);
489
490     table = ovsdb_table_create(ts);
491     ovsdb_column_set_init(&all_columns);
492     ovsdb_column_set_add_all(&all_columns, table);
493
494     n_rows = argc - 2;
495     rows = xmalloc(sizeof *rows * n_rows);
496     names = xmalloc(sizeof *names * n_rows);
497     for (i = 0; i < n_rows; i++) {
498         rows[i] = ovsdb_row_create(table);
499
500         json = parse_json(argv[i + 2]);
501         if (json->type != JSON_ARRAY || json->u.array.n != 2
502             || json->u.array.elems[0]->type != JSON_STRING) {
503             ovs_fatal(0, "\"%s\" does not have expected form "
504                       "[\"name\", {data}]", argv[i]);
505         }
506         names[i] = xstrdup(json->u.array.elems[0]->u.string);
507         check_ovsdb_error(ovsdb_row_from_json(rows[i], json->u.array.elems[1],
508                                               NULL, NULL));
509         json_destroy(json);
510     }
511     for (i = 0; i < n_rows; i++) {
512         uint32_t i_hash = ovsdb_row_hash_columns(rows[i], &all_columns, 0);
513         for (j = i + 1; j < n_rows; j++) {
514             uint32_t j_hash = ovsdb_row_hash_columns(rows[j], &all_columns, 0);
515             if (ovsdb_row_equal_columns(rows[i], rows[j], &all_columns)) {
516                 printf("%s == %s\n", names[i], names[j]);
517                 if (i_hash != j_hash) {
518                     printf("but hash(%s) != hash(%s)\n", names[i], names[j]);
519                     abort();
520                 }
521             } else if (i_hash == j_hash) {
522                 printf("hash(%s) == hash(%s)\n", names[i], names[j]);
523             }
524         }
525     }
526     free(rows);
527     free(names);
528
529     ovsdb_column_set_destroy(&all_columns);
530     ovsdb_table_destroy(table); /* Also destroys 'ts'. */
531 }
532
533 static void
534 do_parse_conditions(int argc, char *argv[])
535 {
536     struct ovsdb_table_schema *ts;
537     struct json *json;
538     int exit_code = 0;
539     int i;
540
541     json = unbox_json(parse_json(argv[1]));
542     check_ovsdb_error(ovsdb_table_schema_from_json(json, "mytable", &ts));
543     json_destroy(json);
544
545     for (i = 2; i < argc; i++) {
546         struct ovsdb_condition cnd;
547         struct ovsdb_error *error;
548
549         json = parse_json(argv[i]);
550         error = ovsdb_condition_from_json(ts, json, NULL, &cnd);
551         if (!error) {
552             print_and_free_json(ovsdb_condition_to_json(&cnd));
553         } else {
554             char *s = ovsdb_error_to_string(error);
555             ovs_error(0, "%s", s);
556             free(s);
557             ovsdb_error_destroy(error);
558             exit_code = 1;
559         }
560         json_destroy(json);
561
562         ovsdb_condition_destroy(&cnd);
563     }
564     ovsdb_table_schema_destroy(ts);
565
566     exit(exit_code);
567 }
568
569 static void
570 do_evaluate_conditions(int argc UNUSED, char *argv[])
571 {
572     struct ovsdb_table_schema *ts;
573     struct ovsdb_table *table;
574     struct ovsdb_condition *conditions;
575     size_t n_conditions;
576     struct ovsdb_row **rows;
577     size_t n_rows;
578     struct json *json;
579     size_t i, j;
580
581     /* Parse table schema, create table. */
582     json = unbox_json(parse_json(argv[1]));
583     check_ovsdb_error(ovsdb_table_schema_from_json(json, "mytable", &ts));
584     json_destroy(json);
585
586     table = ovsdb_table_create(ts);
587
588     /* Parse conditions. */
589     json = parse_json(argv[2]);
590     if (json->type != JSON_ARRAY) {
591         ovs_fatal(0, "CONDITION argument is not JSON array");
592     }
593     n_conditions = json->u.array.n;
594     conditions = xmalloc(n_conditions * sizeof *conditions);
595     for (i = 0; i < n_conditions; i++) {
596         check_ovsdb_error(ovsdb_condition_from_json(ts, json->u.array.elems[i],
597                                                     NULL, &conditions[i]));
598     }
599     json_destroy(json);
600
601     /* Parse rows. */
602     json = parse_json(argv[3]);
603     if (json->type != JSON_ARRAY) {
604         ovs_fatal(0, "ROW argument is not JSON array");
605     }
606     n_rows = json->u.array.n;
607     rows = xmalloc(n_rows * sizeof *rows);
608     for (i = 0; i < n_rows; i++) {
609         rows[i] = ovsdb_row_create(table);
610         check_ovsdb_error(ovsdb_row_from_json(rows[i], json->u.array.elems[i],
611                                               NULL, NULL));
612     }
613     json_destroy(json);
614
615     for (i = 0; i < n_conditions; i++) {
616         printf("condition %2d:", i);
617         for (j = 0; j < n_rows; j++) {
618             bool result = ovsdb_condition_evaluate(rows[j], &conditions[i]);
619             if (j % 5 == 0) {
620                 putchar(' ');
621             }
622             putchar(result ? 'T' : '-');
623         }
624         printf("\n");
625     }
626
627     for (i = 0; i < n_conditions; i++) {
628         ovsdb_condition_destroy(&conditions[i]);
629     }
630     for (i = 0; i < n_rows; i++) {
631         ovsdb_row_destroy(rows[i]);
632     }
633     ovsdb_table_destroy(table); /* Also destroys 'ts'. */
634 }
635
636 struct do_query_cbdata {
637     struct uuid *row_uuids;
638     int *counts;
639     size_t n_rows;
640 };
641
642 static bool
643 do_query_cb(const struct ovsdb_row *row, void *cbdata_)
644 {
645     struct do_query_cbdata *cbdata = cbdata_;
646     size_t i;
647
648     for (i = 0; i < cbdata->n_rows; i++) {
649         if (uuid_equals(ovsdb_row_get_uuid(row), &cbdata->row_uuids[i])) {
650             cbdata->counts[i]++;
651         }
652     }
653
654     return true;
655 }
656
657 static void
658 do_query(int argc UNUSED, char *argv[])
659 {
660     struct do_query_cbdata cbdata;
661     struct ovsdb_table_schema *ts;
662     struct ovsdb_table *table;
663     struct json *json;
664     int exit_code = 0;
665     size_t i;
666
667     /* Parse table schema, create table. */
668     json = unbox_json(parse_json(argv[1]));
669     check_ovsdb_error(ovsdb_table_schema_from_json(json, "mytable", &ts));
670     json_destroy(json);
671
672     table = ovsdb_table_create(ts);
673
674     /* Parse rows, add to table. */
675     json = parse_json(argv[2]);
676     if (json->type != JSON_ARRAY) {
677         ovs_fatal(0, "ROW argument is not JSON array");
678     }
679     cbdata.n_rows = json->u.array.n;
680     cbdata.row_uuids = xmalloc(cbdata.n_rows * sizeof *cbdata.row_uuids);
681     cbdata.counts = xmalloc(cbdata.n_rows * sizeof *cbdata.counts);
682     for (i = 0; i < cbdata.n_rows; i++) {
683         struct ovsdb_row *row = ovsdb_row_create(table);
684         uuid_generate(ovsdb_row_get_uuid_rw(row));
685         check_ovsdb_error(ovsdb_row_from_json(row, json->u.array.elems[i],
686                                               NULL, NULL));
687         if (ovsdb_table_get_row(table, ovsdb_row_get_uuid(row))) {
688             ovs_fatal(0, "duplicate UUID "UUID_FMT" in table",
689                       UUID_ARGS(ovsdb_row_get_uuid(row)));
690         }
691         cbdata.row_uuids[i] = *ovsdb_row_get_uuid(row);
692         ovsdb_table_put_row(table, row);
693     }
694     json_destroy(json);
695
696     /* Parse conditions and execute queries. */
697     json = parse_json(argv[3]);
698     if (json->type != JSON_ARRAY) {
699         ovs_fatal(0, "CONDITION argument is not JSON array");
700     }
701     for (i = 0; i < json->u.array.n; i++) {
702         struct ovsdb_condition cnd;
703         size_t j;
704
705         check_ovsdb_error(ovsdb_condition_from_json(ts, json->u.array.elems[i],
706                                                     NULL, &cnd));
707
708         memset(cbdata.counts, 0, cbdata.n_rows * sizeof *cbdata.counts);
709         ovsdb_query(table, &cnd, do_query_cb, &cbdata);
710
711         printf("query %2d:", i);
712         for (j = 0; j < cbdata.n_rows; j++) {
713             if (j % 5 == 0) {
714                 putchar(' ');
715             }
716             if (cbdata.counts[j]) {
717                 printf("%d", cbdata.counts[j]);
718                 if (cbdata.counts[j] > 1) {
719                     /* Dup! */
720                     exit_code = 1;
721                 }
722             } else {
723                 putchar('-');
724             }
725         }
726         putchar('\n');
727
728         ovsdb_condition_destroy(&cnd);
729     }
730     json_destroy(json);
731
732     ovsdb_table_destroy(table); /* Also destroys 'ts'. */
733
734     exit(exit_code);
735 }
736
737 struct do_query_distinct_class {
738     struct ovsdb_row *example;
739     int count;
740 };
741
742 struct do_query_distinct_row {
743     struct uuid uuid;
744     struct do_query_distinct_class *class;
745 };
746
747 static void
748 do_query_distinct(int argc UNUSED, char *argv[])
749 {
750     struct ovsdb_column_set columns;
751     struct ovsdb_table_schema *ts;
752     struct ovsdb_table *table;
753     struct do_query_distinct_row *rows;
754     size_t n_rows;
755     struct do_query_distinct_class *classes;
756     size_t n_classes;
757     struct json *json;
758     int exit_code = 0;
759     size_t i, j, k;
760
761     /* Parse table schema, create table. */
762     json = unbox_json(parse_json(argv[1]));
763     check_ovsdb_error(ovsdb_table_schema_from_json(json, "mytable", &ts));
764     json_destroy(json);
765
766     table = ovsdb_table_create(ts);
767
768     /* Parse column set. */
769     json = parse_json(argv[4]);
770     ovsdb_column_set_from_json(json, table, &columns);
771     json_destroy(json);
772
773     /* Parse rows, add to table. */
774     json = parse_json(argv[2]);
775     if (json->type != JSON_ARRAY) {
776         ovs_fatal(0, "ROW argument is not JSON array");
777     }
778     n_rows = json->u.array.n;
779     rows = xmalloc(n_rows * sizeof *rows);
780     classes = xmalloc(n_rows * sizeof *classes);
781     n_classes = 0;
782     for (i = 0; i < n_rows; i++) {
783         struct ovsdb_row *row;
784         size_t j;
785
786         /* Parse row. */
787         row = ovsdb_row_create(table);
788         uuid_generate(ovsdb_row_get_uuid_rw(row));
789         check_ovsdb_error(ovsdb_row_from_json(row, json->u.array.elems[i],
790                                               NULL, NULL));
791
792         /* Initialize row and find equivalence class. */
793         rows[i].uuid = *ovsdb_row_get_uuid(row);
794         rows[i].class = NULL;
795         for (j = 0; j < n_classes; j++) {
796             if (ovsdb_row_equal_columns(row, classes[j].example, &columns)) {
797                 rows[i].class = &classes[j];
798                 break;
799             }
800         }
801         if (!rows[i].class) {
802             rows[i].class = &classes[n_classes];
803             classes[n_classes].example = ovsdb_row_clone(row);
804             n_classes++;
805         }
806
807         /* Add row to table. */
808         if (ovsdb_table_get_row(table, ovsdb_row_get_uuid(row))) {
809             ovs_fatal(0, "duplicate UUID "UUID_FMT" in table",
810                       UUID_ARGS(ovsdb_row_get_uuid(row)));
811         }
812         ovsdb_table_put_row(table, row);
813
814     }
815     json_destroy(json);
816
817     /* Parse conditions and execute queries. */
818     json = parse_json(argv[3]);
819     if (json->type != JSON_ARRAY) {
820         ovs_fatal(0, "CONDITION argument is not JSON array");
821     }
822     for (i = 0; i < json->u.array.n; i++) {
823         struct ovsdb_row_set results;
824         struct ovsdb_condition cnd;
825
826         check_ovsdb_error(ovsdb_condition_from_json(ts, json->u.array.elems[i],
827                                                     NULL, &cnd));
828
829         for (j = 0; j < n_classes; j++) {
830             classes[j].count = 0;
831         }
832         ovsdb_row_set_init(&results);
833         ovsdb_query_distinct(table, &cnd, &columns, &results);
834         for (j = 0; j < results.n_rows; j++) {
835             for (k = 0; k < n_rows; k++) {
836                 if (uuid_equals(ovsdb_row_get_uuid(results.rows[j]),
837                                 &rows[k].uuid)) {
838                     rows[k].class->count++;
839                 }
840             }
841         }
842         ovsdb_row_set_destroy(&results);
843
844         printf("query %2d:", i);
845         for (j = 0; j < n_rows; j++) {
846             int count = rows[j].class->count;
847
848             if (j % 5 == 0) {
849                 putchar(' ');
850             }
851             if (count > 1) {
852                 /* Dup! */
853                 printf("%d", count);
854                 exit_code = 1;
855             } else if (count == 1) {
856                 putchar("abcdefghijklmnopqrstuvwxyz"[rows[j].class - classes]);
857             } else {
858                 putchar('-');
859             }
860         }
861         putchar('\n');
862
863         ovsdb_condition_destroy(&cnd);
864     }
865     json_destroy(json);
866
867     ovsdb_table_destroy(table); /* Also destroys 'ts'. */
868
869     exit(exit_code);
870 }
871
872 static void
873 do_execute(int argc UNUSED, char *argv[])
874 {
875     struct ovsdb_schema *schema;
876     struct json *json;
877     struct ovsdb *db;
878     int i;
879
880     /* Create database. */
881     json = parse_json(argv[1]);
882     check_ovsdb_error(ovsdb_schema_from_json(json, &schema));
883     json_destroy(json);
884     db = ovsdb_create(schema);
885
886     for (i = 2; i < argc; i++) {
887         struct json *params, *result;
888         char *s;
889
890         params = parse_json(argv[i]);
891         result = ovsdb_execute(db, params, 0, NULL);
892         s = json_to_string(result, JSSF_SORT);
893         printf("%s\n", s);
894         json_destroy(params);
895         json_destroy(result);
896     }
897
898     ovsdb_destroy(db);
899 }
900
901 struct test_trigger {
902     struct ovsdb_trigger trigger;
903     int number;
904 };
905
906 static void
907 do_trigger_dump(struct test_trigger *t, long long int now, const char *title)
908 {
909     struct json *result;
910     char *s;
911
912     result = ovsdb_trigger_steal_result(&t->trigger);
913     s = json_to_string(result, JSSF_SORT);
914     printf("t=%lld: trigger %d (%s): %s\n", now, t->number, title, s);
915     json_destroy(result);
916     ovsdb_trigger_destroy(&t->trigger);
917     free(t);
918 }
919
920 static void
921 do_trigger(int argc UNUSED, char *argv[])
922 {
923     struct ovsdb_schema *schema;
924     struct list completions;
925     struct json *json;
926     struct ovsdb *db;
927     long long int now;
928     int number;
929     int i;
930
931     /* Create database. */
932     json = parse_json(argv[1]);
933     check_ovsdb_error(ovsdb_schema_from_json(json, &schema));
934     json_destroy(json);
935     db = ovsdb_create(schema);
936
937     list_init(&completions);
938     now = 0;
939     number = 0;
940     for (i = 2; i < argc; i++) {
941         struct json *params = parse_json(argv[i]);
942         if (params->type == JSON_ARRAY
943             && json_array(params)->n == 2
944             && json_array(params)->elems[0]->type == JSON_STRING
945             && !strcmp(json_string(json_array(params)->elems[0]), "advance")
946             && json_array(params)->elems[1]->type == JSON_INTEGER) {
947             now += json_integer(json_array(params)->elems[1]);
948             json_destroy(params);
949         } else {
950             struct test_trigger *t = xmalloc(sizeof *t);
951             ovsdb_trigger_init(db, &t->trigger, params, &completions, now);
952             t->number = number++;
953             if (ovsdb_trigger_is_complete(&t->trigger)) {
954                 do_trigger_dump(t, now, "immediate");
955             } else {
956                 printf("t=%lld: new trigger %d\n", now, t->number);
957             }
958         }
959
960         ovsdb_trigger_run(db, now);
961         while (!list_is_empty(&completions)) {
962             do_trigger_dump(CONTAINER_OF(list_pop_front(&completions),
963                                          struct test_trigger, trigger.node),
964                             now, "delayed");
965         }
966
967         ovsdb_trigger_wait(db, now);
968         poll_immediate_wake();
969         poll_block();
970     }
971
972     ovsdb_destroy(db);
973 }
974
975 static void
976 do_help(int argc UNUSED, char *argv[] UNUSED)
977 {
978     usage();
979 }
980 \f
981 /* "transact" command. */
982
983 static struct ovsdb *do_transact_db;
984 static struct ovsdb_txn *do_transact_txn;
985 static struct ovsdb_table *do_transact_table;
986
987 static void
988 do_transact_commit(int argc UNUSED, char *argv[] UNUSED)
989 {
990     ovsdb_txn_commit(do_transact_txn, false);
991     do_transact_txn = NULL;
992 }
993
994 static void
995 do_transact_abort(int argc UNUSED, char *argv[] UNUSED)
996 {
997     ovsdb_txn_abort(do_transact_txn);
998     do_transact_txn = NULL;
999 }
1000
1001 static void
1002 uuid_from_integer(int integer, struct uuid *uuid)
1003 {
1004     uuid_zero(uuid);
1005     uuid->parts[3] = integer;
1006 }
1007
1008 static const struct ovsdb_row *
1009 do_transact_find_row(const char *uuid_string)
1010 {
1011     const struct ovsdb_row *row;
1012     struct uuid uuid;
1013
1014     uuid_from_integer(atoi(uuid_string), &uuid);
1015     row = ovsdb_table_get_row(do_transact_table, &uuid);
1016     if (!row) {
1017         ovs_fatal(0, "table does not contain row with UUID "UUID_FMT,
1018                   UUID_ARGS(&uuid));
1019     }
1020     return row;
1021 }
1022
1023 static void
1024 do_transact_set_integer(struct ovsdb_row *row, const char *column_name,
1025                         int integer)
1026 {
1027     if (integer != -1) {
1028         const struct ovsdb_column *column;
1029
1030         column = ovsdb_table_schema_get_column(do_transact_table->schema,
1031                                                column_name);
1032         row->fields[column->index].keys[0].integer = integer;
1033     }
1034 }
1035
1036 static int
1037 do_transact_get_integer(const struct ovsdb_row *row, const char *column_name)
1038 {
1039     const struct ovsdb_column *column;
1040
1041     column = ovsdb_table_schema_get_column(do_transact_table->schema,
1042                                            column_name);
1043     return row->fields[column->index].keys[0].integer;
1044 }
1045
1046 static void
1047 do_transact_set_i_j(struct ovsdb_row *row,
1048                     const char *i_string, const char *j_string)
1049 {
1050     do_transact_set_integer(row, "i", atoi(i_string));
1051     do_transact_set_integer(row, "j", atoi(j_string));
1052 }
1053
1054 static void
1055 do_transact_insert(int argc UNUSED, char *argv[] UNUSED)
1056 {
1057     struct ovsdb_row *row;
1058     struct uuid *uuid;
1059
1060     row = ovsdb_row_create(do_transact_table);
1061
1062     /* Set UUID. */
1063     uuid = ovsdb_row_get_uuid_rw(row);
1064     uuid_from_integer(atoi(argv[1]), uuid);
1065     if (ovsdb_table_get_row(do_transact_table, uuid)) {
1066         ovs_fatal(0, "table already contains row with UUID "UUID_FMT,
1067                   UUID_ARGS(uuid));
1068     }
1069
1070     do_transact_set_i_j(row, argv[2], argv[3]);
1071
1072     /* Insert row. */
1073     ovsdb_txn_row_insert(do_transact_txn, row);
1074 }
1075
1076 static void
1077 do_transact_delete(int argc UNUSED, char *argv[] UNUSED)
1078 {
1079     const struct ovsdb_row *row = do_transact_find_row(argv[1]);
1080     ovsdb_txn_row_delete(do_transact_txn, row);
1081 }
1082
1083 static void
1084 do_transact_modify(int argc UNUSED, char *argv[] UNUSED)
1085 {
1086     const struct ovsdb_row *row_ro;
1087     struct ovsdb_row *row_rw;
1088
1089     row_ro = do_transact_find_row(argv[1]);
1090     row_rw = ovsdb_txn_row_modify(do_transact_txn, row_ro);
1091     do_transact_set_i_j(row_rw, argv[2], argv[3]);
1092 }
1093
1094 static int
1095 compare_rows_by_uuid(const void *a_, const void *b_)
1096 {
1097     struct ovsdb_row *const *ap = a_;
1098     struct ovsdb_row *const *bp = b_;
1099
1100     return uuid_compare_3way(ovsdb_row_get_uuid(*ap), ovsdb_row_get_uuid(*bp));
1101 }
1102
1103 static void
1104 do_transact_print(int argc UNUSED, char *argv[] UNUSED)
1105 {
1106     const struct ovsdb_row **rows;
1107     const struct ovsdb_row *row;
1108     size_t n_rows;
1109     size_t i;
1110
1111     n_rows = hmap_count(&do_transact_table->rows);
1112     rows = xmalloc(n_rows * sizeof *rows);
1113     i = 0;
1114     HMAP_FOR_EACH (row, struct ovsdb_row, hmap_node,
1115                    &do_transact_table->rows) {
1116         rows[i++] = row;
1117     }
1118     assert(i == n_rows);
1119
1120     qsort(rows, n_rows, sizeof *rows, compare_rows_by_uuid);
1121
1122     for (i = 0; i < n_rows; i++) {
1123         printf("\n%"PRId32": i=%d, j=%d",
1124                ovsdb_row_get_uuid(rows[i])->parts[3],
1125                do_transact_get_integer(rows[i], "i"),
1126                do_transact_get_integer(rows[i], "j"));
1127     }
1128
1129     free(rows);
1130 }
1131
1132 static void
1133 do_transact(int argc, char *argv[])
1134 {
1135     static const struct command do_transact_commands[] = {
1136         { "commit", 0, 0, do_transact_commit },
1137         { "abort", 0, 0, do_transact_abort },
1138         { "insert", 2, 3, do_transact_insert },
1139         { "delete", 1, 1, do_transact_delete },
1140         { "modify", 2, 3, do_transact_modify },
1141         { "print", 0, 0, do_transact_print },
1142         { NULL, 0, 0, NULL },
1143     };
1144
1145     struct ovsdb_schema *schema;
1146     struct json *json;
1147     int i;
1148
1149     /* Create table. */
1150     json = parse_json("{\"name\": \"testdb\", "
1151                       " \"tables\": "
1152                       "  {\"mytable\": "
1153                       "    {\"columns\": "
1154                       "      {\"i\": {\"type\": \"integer\"}, "
1155                       "       \"j\": {\"type\": \"integer\"}}}}}");
1156     check_ovsdb_error(ovsdb_schema_from_json(json, &schema));
1157     json_destroy(json);
1158     do_transact_db = ovsdb_create(schema);
1159     do_transact_table = ovsdb_get_table(do_transact_db, "mytable");
1160     assert(do_transact_table != NULL);
1161
1162     for (i = 1; i < argc; i++) {
1163         struct json *command;
1164         size_t n_args;
1165         char **args;
1166         int j;
1167
1168         command = parse_json(argv[i]);
1169         if (command->type != JSON_ARRAY) {
1170             ovs_fatal(0, "transaction %d must be JSON array "
1171                       "with at least 1 element", i);
1172         }
1173
1174         n_args = command->u.array.n;
1175         args = xmalloc((n_args + 1) * sizeof *args);
1176         for (j = 0; j < n_args; j++) {
1177             struct json *s = command->u.array.elems[j];
1178             if (s->type != JSON_STRING) {
1179                 ovs_fatal(0, "transaction %d argument %d must be JSON string",
1180                           i, j);
1181             }
1182             args[j] = xstrdup(json_string(s));
1183         }
1184         args[n_args] = NULL;
1185
1186         if (!do_transact_txn) {
1187             do_transact_txn = ovsdb_txn_create(do_transact_db);
1188         }
1189
1190         for (j = 0; j < n_args; j++) {
1191             if (j) {
1192                 putchar(' ');
1193             }
1194             fputs(args[j], stdout);
1195         }
1196         fputs(":", stdout);
1197         run_command(n_args, args, do_transact_commands);
1198         putchar('\n');
1199
1200         for (j = 0; j < n_args; j++) {
1201             free(args[j]);
1202         }
1203         free(args);
1204         json_destroy(command);
1205     }
1206     ovsdb_txn_abort(do_transact_txn);
1207     ovsdb_destroy(do_transact_db); /* Also destroys 'schema'. */
1208 }
1209
1210 static struct command all_commands[] = {
1211     { "log-io", 2, INT_MAX, do_log_io },
1212     { "parse-atomic-type", 1, 1, do_parse_atomic_type },
1213     { "parse-type", 1, 1, do_parse_type },
1214     { "parse-atoms", 2, INT_MAX, do_parse_atoms },
1215     { "parse-data", 2, INT_MAX, do_parse_data },
1216     { "sort-atoms", 2, 2, do_sort_atoms },
1217     { "parse-column", 2, 2, do_parse_column },
1218     { "parse-table", 2, 2, do_parse_table },
1219     { "parse-rows", 2, INT_MAX, do_parse_rows },
1220     { "compare-rows", 2, INT_MAX, do_compare_rows },
1221     { "parse-conditions", 2, INT_MAX, do_parse_conditions },
1222     { "evaluate-conditions", 3, 3, do_evaluate_conditions },
1223     { "query", 3, 3, do_query },
1224     { "query-distinct", 4, 4, do_query_distinct },
1225     { "transact", 1, INT_MAX, do_transact },
1226     { "execute", 2, INT_MAX, do_execute },
1227     { "trigger", 2, INT_MAX, do_trigger },
1228     { "help", 0, INT_MAX, do_help },
1229     { NULL, 0, 0, NULL },
1230 };