350e72af6463aa6b554d79c92d1a3940ad572de8
[cascardo/ovs.git] / ovsdb / ovsdb-tool.c
1 /*
2  * Copyright (c) 2009, 2010, 2011, 2012, 2013 Nicira, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18 #include <errno.h>
19 #include <fcntl.h>
20 #include <getopt.h>
21 #include <signal.h>
22 #include <stdlib.h>
23 #include <string.h>
24
25 #include "column.h"
26 #include "command-line.h"
27 #include "compiler.h"
28 #include "dirs.h"
29 #include "dynamic-string.h"
30 #include "fatal-signal.h"
31 #include "file.h"
32 #include "lockfile.h"
33 #include "log.h"
34 #include "json.h"
35 #include "ovsdb.h"
36 #include "ovsdb-data.h"
37 #include "ovsdb-error.h"
38 #include "socket-util.h"
39 #include "table.h"
40 #include "timeval.h"
41 #include "util.h"
42 #include "vlog.h"
43
44 /* -m, --more: Verbosity level for "show-log" command output. */
45 static int show_log_verbosity;
46
47 static const struct command *get_all_commands(void);
48
49 NO_RETURN static void usage(void);
50 static void parse_options(int argc, char *argv[]);
51
52 static const char *default_db(void);
53 static const char *default_schema(void);
54
55 int
56 main(int argc, char *argv[])
57 {
58     set_program_name(argv[0]);
59     parse_options(argc, argv);
60     fatal_ignore_sigpipe();
61     run_command(argc - optind, argv + optind, get_all_commands());
62     return 0;
63 }
64
65 static void
66 parse_options(int argc, char *argv[])
67 {
68     static const struct option long_options[] = {
69         {"more", no_argument, NULL, 'm'},
70         {"verbose", optional_argument, NULL, 'v'},
71         {"help", no_argument, NULL, 'h'},
72         {"version", no_argument, NULL, 'V'},
73         {NULL, 0, NULL, 0},
74     };
75     char *short_options = long_options_to_short_options(long_options);
76
77     for (;;) {
78         int c;
79
80         c = getopt_long(argc, argv, short_options, long_options, NULL);
81         if (c == -1) {
82             break;
83         }
84
85         switch (c) {
86         case 'm':
87             show_log_verbosity++;
88             break;
89
90         case 'h':
91             usage();
92
93         case 'V':
94             ovs_print_version(0, 0);
95             exit(EXIT_SUCCESS);
96
97         case 'v':
98             vlog_set_verbosity(optarg);
99             break;
100
101         case '?':
102             exit(EXIT_FAILURE);
103
104         default:
105             abort();
106         }
107     }
108     free(short_options);
109 }
110
111 static void
112 usage(void)
113 {
114     printf("%s: Open vSwitch database management utility\n"
115            "usage: %s [OPTIONS] COMMAND [ARG...]\n"
116            "  create [DB [SCHEMA]]    create DB with the given SCHEMA\n"
117            "  compact [DB [DST]]      compact DB in-place (or to DST)\n"
118            "  convert [DB [SCHEMA [DST]]]   convert DB to SCHEMA (to DST)\n"
119            "  db-version [DB]         report version of schema used by DB\n"
120            "  db-cksum [DB]           report checksum of schema used by DB\n"
121            "  schema-version [SCHEMA] report SCHEMA's schema version\n"
122            "  schema-cksum [SCHEMA]   report SCHEMA's checksum\n"
123            "  query [DB] TRNS         execute read-only transaction on DB\n"
124            "  transact [DB] TRNS      execute read/write transaction on DB\n"
125            "  [-m]... show-log [DB]   print DB's log entries\n"
126            "The default DB is %s.\n"
127            "The default SCHEMA is %s.\n",
128            program_name, program_name, default_db(), default_schema());
129     vlog_usage();
130     printf("\nOther options:\n"
131            "  -m, --more                  increase show-log verbosity\n"
132            "  -h, --help                  display this help message\n"
133            "  -V, --version               display version information\n");
134     exit(EXIT_SUCCESS);
135 }
136
137 static const char *
138 default_db(void)
139 {
140     static char *db;
141     if (!db) {
142         db = xasprintf("%s/conf.db", ovs_dbdir());
143     }
144     return db;
145 }
146
147 static const char *
148 default_schema(void)
149 {
150     static char *schema;
151     if (!schema) {
152         schema = xasprintf("%s/vswitch.ovsschema", ovs_pkgdatadir());
153     }
154     return schema;
155 }
156 \f
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 void
168 print_and_free_json(struct json *json)
169 {
170     char *string = json_to_string(json, JSSF_SORT);
171     json_destroy(json);
172     puts(string);
173     free(string);
174 }
175
176 static void
177 check_ovsdb_error(struct ovsdb_error *error)
178 {
179     if (error) {
180         ovs_fatal(0, "%s", ovsdb_error_to_string(error));
181     }
182 }
183 \f
184 static void
185 do_create(int argc, char *argv[])
186 {
187     const char *db_file_name = argc >= 2 ? argv[1] : default_db();
188     const char *schema_file_name = argc >= 3 ? argv[2] : default_schema();
189     struct ovsdb_schema *schema;
190     struct ovsdb_log *log;
191     struct json *json;
192
193     /* Read schema from file and convert to JSON. */
194     check_ovsdb_error(ovsdb_schema_from_file(schema_file_name, &schema));
195     json = ovsdb_schema_to_json(schema);
196     ovsdb_schema_destroy(schema);
197
198     /* Create database file. */
199     check_ovsdb_error(ovsdb_log_open(db_file_name, OVSDB_LOG_CREATE,
200                                      -1, &log));
201     check_ovsdb_error(ovsdb_log_write(log, json));
202     check_ovsdb_error(ovsdb_log_commit(log));
203     ovsdb_log_close(log);
204
205     json_destroy(json);
206 }
207
208 static void
209 compact_or_convert(const char *src_name_, const char *dst_name_,
210                    const struct ovsdb_schema *new_schema,
211                    const char *comment)
212 {
213     char *src_name, *dst_name;
214     struct lockfile *src_lock;
215     struct lockfile *dst_lock;
216     bool in_place = dst_name_ == NULL;
217     struct ovsdb *db;
218     int retval;
219
220     /* Dereference symlinks for source and destination names.  In the in-place
221      * case this ensures that, if the source name is a symlink, we replace its
222      * target instead of replacing the symlink by a regular file.  In the
223      * non-in-place, this has the same effect for the destination name. */
224     src_name = follow_symlinks(src_name_);
225     dst_name = (in_place
226                 ? xasprintf("%s.tmp", src_name)
227                 : follow_symlinks(dst_name_));
228
229     /* Lock the source, if we will be replacing it. */
230     if (in_place) {
231         retval = lockfile_lock(src_name, &src_lock);
232         if (retval) {
233             ovs_fatal(retval, "%s: failed to lock lockfile", src_name);
234         }
235     }
236
237     /* Get (temporary) destination and lock it. */
238     retval = lockfile_lock(dst_name, &dst_lock);
239     if (retval) {
240         ovs_fatal(retval, "%s: failed to lock lockfile", dst_name);
241     }
242
243     /* Save a copy. */
244     check_ovsdb_error(new_schema
245                       ? ovsdb_file_open_as_schema(src_name, new_schema, &db)
246                       : ovsdb_file_open(src_name, true, &db, NULL));
247     check_ovsdb_error(ovsdb_file_save_copy(dst_name, false, comment, db));
248     ovsdb_destroy(db);
249
250     /* Replace source. */
251     if (in_place) {
252 #ifdef _WIN32
253         unlink(src_name);
254 #endif
255         if (rename(dst_name, src_name)) {
256             ovs_fatal(errno, "failed to rename \"%s\" to \"%s\"",
257                       dst_name, src_name);
258         }
259         fsync_parent_dir(dst_name);
260         lockfile_unlock(src_lock);
261     }
262
263     lockfile_unlock(dst_lock);
264
265     free(src_name);
266     free(dst_name);
267 }
268
269 static void
270 do_compact(int argc, char *argv[])
271 {
272     const char *db = argc >= 2 ? argv[1] : default_db();
273     const char *target = argc >= 3 ? argv[2] : NULL;
274
275     compact_or_convert(db, target, NULL, "compacted by ovsdb-tool "VERSION);
276 }
277
278 static void
279 do_convert(int argc, char *argv[])
280 {
281     const char *db = argc >= 2 ? argv[1] : default_db();
282     const char *schema = argc >= 3 ? argv[2] : default_schema();
283     const char *target = argc >= 4 ? argv[3] : NULL;
284     struct ovsdb_schema *new_schema;
285
286     check_ovsdb_error(ovsdb_schema_from_file(schema, &new_schema));
287     compact_or_convert(db, target, new_schema,
288                        "converted by ovsdb-tool "VERSION);
289     ovsdb_schema_destroy(new_schema);
290 }
291
292 static void
293 do_needs_conversion(int argc, char *argv[])
294 {
295     const char *db_file_name = argc >= 2 ? argv[1] : default_db();
296     const char *schema_file_name = argc >= 3 ? argv[2] : default_schema();
297     struct ovsdb_schema *schema1, *schema2;
298
299     check_ovsdb_error(ovsdb_file_read_schema(db_file_name, &schema1));
300     check_ovsdb_error(ovsdb_schema_from_file(schema_file_name, &schema2));
301     puts(ovsdb_schema_equal(schema1, schema2) ? "no" : "yes");
302     ovsdb_schema_destroy(schema1);
303     ovsdb_schema_destroy(schema2);
304 }
305
306 static void
307 do_db_version(int argc, char *argv[])
308 {
309     const char *db_file_name = argc >= 2 ? argv[1] : default_db();
310     struct ovsdb_schema *schema;
311
312     check_ovsdb_error(ovsdb_file_read_schema(db_file_name, &schema));
313     puts(schema->version);
314     ovsdb_schema_destroy(schema);
315 }
316
317 static void
318 do_db_cksum(int argc OVS_UNUSED, char *argv[])
319 {
320     const char *db_file_name = argc >= 2 ? argv[1] : default_db();
321     struct ovsdb_schema *schema;
322
323     check_ovsdb_error(ovsdb_file_read_schema(db_file_name, &schema));
324     puts(schema->cksum);
325     ovsdb_schema_destroy(schema);
326 }
327
328 static void
329 do_schema_version(int argc, char *argv[])
330 {
331     const char *schema_file_name = argc >= 2 ? argv[1] : default_schema();
332     struct ovsdb_schema *schema;
333
334     check_ovsdb_error(ovsdb_schema_from_file(schema_file_name, &schema));
335     puts(schema->version);
336     ovsdb_schema_destroy(schema);
337 }
338
339 static void
340 do_schema_cksum(int argc, char *argv[])
341 {
342     const char *schema_file_name = argc >= 2 ? argv[1] : default_schema();
343     struct ovsdb_schema *schema;
344
345     check_ovsdb_error(ovsdb_schema_from_file(schema_file_name, &schema));
346     puts(schema->cksum);
347     ovsdb_schema_destroy(schema);
348 }
349
350 static void
351 transact(bool read_only, int argc, char *argv[])
352 {
353     const char *db_file_name = argc >= 3 ? argv[1] : default_db();
354     const char *transaction = argv[argc - 1];
355     struct json *request, *result;
356     struct ovsdb *db;
357
358     check_ovsdb_error(ovsdb_file_open(db_file_name, read_only, &db, NULL));
359
360     request = parse_json(transaction);
361     result = ovsdb_execute(db, NULL, request, 0, NULL);
362     json_destroy(request);
363
364     print_and_free_json(result);
365     ovsdb_destroy(db);
366 }
367
368 static void
369 do_query(int argc, char *argv[])
370 {
371     transact(true, argc, argv);
372 }
373
374 static void
375 do_transact(int argc, char *argv[])
376 {
377     transact(false, argc, argv);
378 }
379
380 static void
381 print_db_changes(struct shash *tables, struct shash *names,
382                  const struct ovsdb_schema *schema)
383 {
384     struct shash_node *n1;
385
386     SHASH_FOR_EACH (n1, tables) {
387         const char *table = n1->name;
388         struct ovsdb_table_schema *table_schema;
389         struct json *rows = n1->data;
390         struct shash_node *n2;
391
392         if (n1->name[0] == '_' || rows->type != JSON_OBJECT) {
393             continue;
394         }
395
396         table_schema = shash_find_data(&schema->tables, table);
397         SHASH_FOR_EACH (n2, json_object(rows)) {
398             const char *row_uuid = n2->name;
399             struct json *columns = n2->data;
400             struct shash_node *n3;
401             char *old_name, *new_name;
402             bool free_new_name = false;
403
404             old_name = new_name = shash_find_data(names, row_uuid);
405             if (columns->type == JSON_OBJECT) {
406                 struct json *new_name_json;
407
408                 new_name_json = shash_find_data(json_object(columns), "name");
409                 if (new_name_json) {
410                     new_name = json_to_string(new_name_json, JSSF_SORT);
411                     free_new_name = true;
412                 }
413             }
414
415             printf("\ttable %s", table);
416
417             if (!old_name) {
418                 if (new_name) {
419                     printf(" insert row %s (%.8s):\n", new_name, row_uuid);
420                 } else {
421                     printf(" insert row %.8s:\n", row_uuid);
422                 }
423             } else {
424                 printf(" row %s (%.8s):\n", old_name, row_uuid);
425             }
426
427             if (columns->type == JSON_OBJECT) {
428                 if (show_log_verbosity > 1) {
429                     SHASH_FOR_EACH (n3, json_object(columns)) {
430                         const char *column = n3->name;
431                         const struct ovsdb_column *column_schema;
432                         struct json *value = n3->data;
433                         char *value_string = NULL;
434
435                         column_schema =
436                             (table_schema
437                              ? shash_find_data(&table_schema->columns, column)
438                              : NULL);
439                         if (column_schema) {
440                             const struct ovsdb_type *type;
441                             struct ovsdb_error *error;
442                             struct ovsdb_datum datum;
443
444                             type = &column_schema->type;
445                             error = ovsdb_datum_from_json(&datum, type,
446                                                           value, NULL);
447                             if (!error) {
448                                 struct ds s;
449
450                                 ds_init(&s);
451                                 ovsdb_datum_to_string(&datum, type, &s);
452                                 value_string = ds_steal_cstr(&s);
453                             } else {
454                                 ovsdb_error_destroy(error);
455                             }
456                         }
457                         if (!value_string) {
458                             value_string = json_to_string(value, JSSF_SORT);
459                         }
460                         printf("\t\t%s=%s\n", column, value_string);
461                         free(value_string);
462                     }
463                 }
464                 if (!old_name
465                     || (new_name != old_name && strcmp(old_name, new_name))) {
466                     if (old_name) {
467                         shash_delete(names, shash_find(names, row_uuid));
468                         free(old_name);
469                     }
470                     shash_add(names, row_uuid, (new_name
471                                                 ? xstrdup(new_name)
472                                                 : xmemdup0(row_uuid, 8)));
473                 }
474             } else if (columns->type == JSON_NULL) {
475                 struct shash_node *node;
476
477                 printf("\t\tdelete row\n");
478                 node = shash_find(names, row_uuid);
479                 if (node) {
480                     shash_delete(names, node);
481                 }
482                 free(old_name);
483             }
484
485             if (free_new_name) {
486                 free(new_name);
487             }
488         }
489     }
490 }
491
492 static void
493 do_show_log(int argc, char *argv[])
494 {
495     const char *db_file_name = argc >= 2 ? argv[1] : default_db();
496     struct shash names;
497     struct ovsdb_log *log;
498     struct ovsdb_schema *schema;
499     unsigned int i;
500
501     check_ovsdb_error(ovsdb_log_open(db_file_name, OVSDB_LOG_READ_ONLY,
502                                      -1, &log));
503     shash_init(&names);
504     schema = NULL;
505     for (i = 0; ; i++) {
506         struct json *json;
507
508         check_ovsdb_error(ovsdb_log_read(log, &json));
509         if (!json) {
510             break;
511         }
512
513         printf("record %u:", i);
514         if (i == 0) {
515             check_ovsdb_error(ovsdb_schema_from_json(json, &schema));
516             printf(" \"%s\" schema, version=\"%s\", cksum=\"%s\"\n",
517                    schema->name, schema->version, schema->cksum);
518         } else if (json->type == JSON_OBJECT) {
519             struct json *date, *comment;
520
521             date = shash_find_data(json_object(json), "_date");
522             if (date && date->type == JSON_INTEGER) {
523                 long long int t = json_integer(date);
524                 char *s;
525
526                 if (t < INT32_MAX) {
527                     /* Older versions of ovsdb wrote timestamps in seconds. */
528                     t *= 1000;
529                 }
530
531                 s = xastrftime_msec(" %Y-%m-%d %H:%M:%S.###", t, true);
532                 fputs(s, stdout);
533                 free(s);
534             }
535
536             comment = shash_find_data(json_object(json), "_comment");
537             if (comment && comment->type == JSON_STRING) {
538                 printf(" \"%s\"", json_string(comment));
539             }
540
541             if (i > 0 && show_log_verbosity > 0) {
542                 putchar('\n');
543                 print_db_changes(json_object(json), &names, schema);
544             }
545         }
546         json_destroy(json);
547         putchar('\n');
548     }
549
550     ovsdb_log_close(log);
551     ovsdb_schema_destroy(schema);
552     /* XXX free 'names'. */
553 }
554
555 static void
556 do_help(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
557 {
558     usage();
559 }
560
561 static const struct command all_commands[] = {
562     { "create", 0, 2, do_create },
563     { "compact", 0, 2, do_compact },
564     { "convert", 0, 3, do_convert },
565     { "needs-conversion", 0, 2, do_needs_conversion },
566     { "db-version", 0, 1, do_db_version },
567     { "db-cksum", 0, 1, do_db_cksum },
568     { "schema-version", 0, 1, do_schema_version },
569     { "schema-cksum", 0, 1, do_schema_cksum },
570     { "query", 1, 2, do_query },
571     { "transact", 1, 2, do_transact },
572     { "show-log", 0, 1, do_show_log },
573     { "help", 0, INT_MAX, do_help },
574     { NULL, 0, 0, NULL },
575 };
576
577 static const struct command *get_all_commands(void)
578 {
579     return all_commands;
580 }