Implement database schema versioning.
[cascardo/ovs.git] / ovsdb / ovsdb-tool.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 #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 "command-line.h"
26 #include "compiler.h"
27 #include "file.h"
28 #include "lockfile.h"
29 #include "log.h"
30 #include "json.h"
31 #include "ovsdb.h"
32 #include "ovsdb-error.h"
33 #include "socket-util.h"
34 #include "table.h"
35 #include "timeval.h"
36 #include "util.h"
37 #include "vlog.h"
38
39 VLOG_DEFINE_THIS_MODULE(ovsdb_tool);
40
41 /* -m, --more: Verbosity level for "show-log" command output. */
42 static int show_log_verbosity;
43
44 static const struct command all_commands[];
45
46 static void usage(void) NO_RETURN;
47 static void parse_options(int argc, char *argv[]);
48
49 int
50 main(int argc, char *argv[])
51 {
52     set_program_name(argv[0]);
53     parse_options(argc, argv);
54     signal(SIGPIPE, SIG_IGN);
55     run_command(argc - optind, argv + optind, all_commands);
56     return 0;
57 }
58
59 static void
60 parse_options(int argc, char *argv[])
61 {
62     static struct option long_options[] = {
63         {"more", no_argument, 0, 'm'},
64         {"verbose", optional_argument, 0, 'v'},
65         {"help", no_argument, 0, 'h'},
66         {"version", no_argument, 0, 'V'},
67         {0, 0, 0, 0},
68     };
69     char *short_options = long_options_to_short_options(long_options);
70
71     for (;;) {
72         int c;
73
74         c = getopt_long(argc, argv, short_options, long_options, NULL);
75         if (c == -1) {
76             break;
77         }
78
79         switch (c) {
80         case 'm':
81             show_log_verbosity++;
82             break;
83
84         case 'h':
85             usage();
86
87         case 'V':
88             OVS_PRINT_VERSION(0, 0);
89             exit(EXIT_SUCCESS);
90
91         case 'v':
92             vlog_set_verbosity(optarg);
93             break;
94
95         case '?':
96             exit(EXIT_FAILURE);
97
98         default:
99             abort();
100         }
101     }
102     free(short_options);
103 }
104
105 static void
106 usage(void)
107 {
108     printf("%s: Open vSwitch database management utility\n"
109            "usage: %s [OPTIONS] COMMAND [ARG...]\n"
110            "  create DB SCHEMA   create DB with the given SCHEMA\n"
111            "  compact DB [DST]   compact DB in-place (or to DST)\n"
112            "  convert DB SCHEMA [DST]   convert DB to SCHEMA (to DST)\n"
113            "  db-version DB      report version of schema used by DB\n"
114            "  schema-version SCHEMA  report SCHEMA's schema version\n"
115            "  query DB TRNS      execute read-only transaction on DB\n"
116            "  transact DB TRNS   execute read/write transaction on DB\n"
117            "  show-log DB        prints information about DB's log entries\n",
118            program_name, program_name);
119     vlog_usage();
120     printf("\nOther options:\n"
121            "  -m, --more                  increase show-log verbosity\n"
122            "  -h, --help                  display this help message\n"
123            "  -V, --version               display version information\n");
124     exit(EXIT_SUCCESS);
125 }
126 \f
127 static struct json *
128 parse_json(const char *s)
129 {
130     struct json *json = json_from_string(s);
131     if (json->type == JSON_STRING) {
132         ovs_fatal(0, "\"%s\": %s", s, json->u.string);
133     }
134     return json;
135 }
136
137 static void
138 print_and_free_json(struct json *json)
139 {
140     char *string = json_to_string(json, JSSF_SORT);
141     json_destroy(json);
142     puts(string);
143     free(string);
144 }
145
146 static void
147 check_ovsdb_error(struct ovsdb_error *error)
148 {
149     if (error) {
150         ovs_fatal(0, "%s", ovsdb_error_to_string(error));
151     }
152 }
153 \f
154 static void
155 do_create(int argc OVS_UNUSED, char *argv[])
156 {
157     const char *db_file_name = argv[1];
158     const char *schema_file_name = argv[2];
159     struct ovsdb_schema *schema;
160     struct ovsdb_log *log;
161     struct json *json;
162
163     /* Read schema from file and convert to JSON. */
164     check_ovsdb_error(ovsdb_schema_from_file(schema_file_name, &schema));
165     json = ovsdb_schema_to_json(schema);
166     ovsdb_schema_destroy(schema);
167
168     /* Create database file. */
169     check_ovsdb_error(ovsdb_log_open(db_file_name, OVSDB_LOG_CREATE,
170                                      -1, &log));
171     check_ovsdb_error(ovsdb_log_write(log, json));
172     check_ovsdb_error(ovsdb_log_commit(log));
173     ovsdb_log_close(log);
174
175     json_destroy(json);
176 }
177
178 static void
179 compact_or_convert(const char *src_name, const char *dst_name,
180                    const struct ovsdb_schema *new_schema,
181                    const char *comment)
182 {
183     struct lockfile *src_lock;
184     struct lockfile *dst_lock;
185     bool in_place = dst_name == NULL;
186     struct ovsdb *db;
187     int retval;
188
189     /* Lock the source, if we will be replacing it. */
190     if (in_place) {
191         retval = lockfile_lock(src_name, 0, &src_lock);
192         if (retval) {
193             ovs_fatal(retval, "%s: failed to lock lockfile", src_name);
194         }
195     }
196
197     /* Get (temporary) destination and lock it. */
198     if (in_place) {
199         dst_name = xasprintf("%s.tmp", src_name);
200     }
201     retval = lockfile_lock(dst_name, 0, &dst_lock);
202     if (retval) {
203         ovs_fatal(retval, "%s: failed to lock lockfile", dst_name);
204     }
205
206     /* Save a copy. */
207     check_ovsdb_error(new_schema
208                       ? ovsdb_file_open_as_schema(src_name, new_schema, &db)
209                       : ovsdb_file_open(src_name, true, &db, NULL));
210     check_ovsdb_error(ovsdb_file_save_copy(dst_name, false, comment, db));
211     ovsdb_destroy(db);
212
213     /* Replace source. */
214     if (in_place) {
215         if (rename(dst_name, src_name)) {
216             ovs_fatal(errno, "failed to rename \"%s\" to \"%s\"",
217                       dst_name, src_name);
218         }
219         fsync_parent_dir(dst_name);
220         lockfile_unlock(src_lock);
221     }
222
223     lockfile_unlock(dst_lock);
224 }
225
226 static void
227 do_compact(int argc OVS_UNUSED, char *argv[])
228 {
229     compact_or_convert(argv[1], argv[2], NULL, "compacted by ovsdb-tool");
230 }
231
232 static void
233 do_convert(int argc OVS_UNUSED, char *argv[])
234 {
235     const char *schema_file_name = argv[2];
236     struct ovsdb_schema *new_schema;
237
238     check_ovsdb_error(ovsdb_schema_from_file(schema_file_name, &new_schema));
239     compact_or_convert(argv[1], argv[3], new_schema,
240                        "converted by ovsdb-tool");
241     ovsdb_schema_destroy(new_schema);
242 }
243
244 static void
245 do_db_version(int argc OVS_UNUSED, char *argv[])
246 {
247     const char *db_file_name = argv[1];
248     struct ovsdb *db;
249
250     check_ovsdb_error(ovsdb_file_open(db_file_name, true, &db, NULL));
251     puts(db->schema->version);
252     ovsdb_destroy(db);
253 }
254
255 static void
256 do_schema_version(int argc OVS_UNUSED, char *argv[])
257 {
258     const char *schema_file_name = argv[1];
259     struct ovsdb_schema *schema;
260
261     check_ovsdb_error(ovsdb_schema_from_file(schema_file_name, &schema));
262     puts(schema->version);
263     ovsdb_schema_destroy(schema);
264 }
265
266 static void
267 transact(bool read_only, const char *db_file_name, const char *transaction)
268 {
269     struct json *request, *result;
270     struct ovsdb *db;
271
272     check_ovsdb_error(ovsdb_file_open(db_file_name, read_only, &db, NULL));
273
274     request = parse_json(transaction);
275     result = ovsdb_execute(db, request, 0, NULL);
276     json_destroy(request);
277
278     print_and_free_json(result);
279     ovsdb_destroy(db);
280 }
281
282 static void
283 do_query(int argc OVS_UNUSED, char *argv[])
284 {
285     transact(true, argv[1], argv[2]);
286 }
287
288 static void
289 do_transact(int argc OVS_UNUSED, char *argv[])
290 {
291     transact(false, argv[1], argv[2]);
292 }
293
294 static void
295 print_db_changes(struct shash *tables, struct shash *names)
296 {
297     struct shash_node *n1;
298
299     SHASH_FOR_EACH (n1, tables) {
300         const char *table = n1->name;
301         struct json *rows = n1->data;
302         struct shash_node *n2;
303
304         if (n1->name[0] == '_' || rows->type != JSON_OBJECT) {
305             continue;
306         }
307
308         SHASH_FOR_EACH (n2, json_object(rows)) {
309             const char *row_uuid = n2->name;
310             struct json *columns = n2->data;
311             struct shash_node *n3;
312             char *old_name, *new_name;
313             bool free_new_name = false;
314
315             old_name = new_name = shash_find_data(names, row_uuid);
316             if (columns->type == JSON_OBJECT) {
317                 struct json *new_name_json;
318
319                 new_name_json = shash_find_data(json_object(columns), "name");
320                 if (new_name_json) {
321                     new_name = json_to_string(new_name_json, JSSF_SORT);
322                     free_new_name = true;
323                 }
324             }
325
326             printf("\ttable %s", table);
327
328             if (!old_name) {
329                 if (new_name) {
330                     printf(" insert row %s:\n", new_name);
331                 } else {
332                     printf(" insert row %.8s:\n", row_uuid);
333                 }
334             } else {
335                 printf(" row %s:\n", old_name);
336             }
337
338             if (columns->type == JSON_OBJECT) {
339                 if (show_log_verbosity > 1) {
340                     SHASH_FOR_EACH (n3, json_object(columns)) {
341                         const char *column = n3->name;
342                         struct json *value = n3->data;
343                         char *value_string;
344
345                         value_string = json_to_string(value, JSSF_SORT);
346                         printf("\t\t%s=%s\n", column, value_string);
347                         free(value_string);
348                     }
349                 }
350                 if (!old_name
351                     || (new_name != old_name && strcmp(old_name, new_name))) {
352                     if (old_name) {
353                         shash_delete(names, shash_find(names, row_uuid));
354                         free(old_name);
355                     }
356                     shash_add(names, row_uuid, (new_name
357                                                 ? xstrdup(new_name)
358                                                 : xmemdup0(row_uuid, 8)));
359                 }
360             } else if (columns->type == JSON_NULL) {
361                 struct shash_node *node;
362
363                 printf("\t\tdelete row\n");
364                 node = shash_find(names, row_uuid);
365                 if (node) {
366                     shash_delete(names, node);
367                 }
368                 free(old_name);
369             }
370
371             if (free_new_name) {
372                 free(new_name);
373             }
374         }
375     }
376 }
377
378 static void
379 do_show_log(int argc OVS_UNUSED, char *argv[])
380 {
381     const char *db_file_name = argv[1];
382     struct shash names;
383     struct ovsdb_log *log;
384     unsigned int i;
385
386     check_ovsdb_error(ovsdb_log_open(db_file_name, OVSDB_LOG_READ_ONLY,
387                                      -1, &log));
388     shash_init(&names);
389     for (i = 0; ; i++) {
390         struct json *json;
391
392         check_ovsdb_error(ovsdb_log_read(log, &json));
393         if (!json) {
394             break;
395         }
396
397         printf("record %u:", i);
398         if (json->type == JSON_OBJECT) {
399             struct json *date, *comment;
400
401             date = shash_find_data(json_object(json), "_date");
402             if (date && date->type == JSON_INTEGER) {
403                 time_t t = json_integer(date);
404                 char s[128];
405
406                 strftime(s, sizeof s, "%Y-%m-%d %H:%M:%S", localtime(&t));
407                 printf(" %s", s);
408             }
409
410             comment = shash_find_data(json_object(json), "_comment");
411             if (comment && comment->type == JSON_STRING) {
412                 printf(" \"%s\"", json_string(comment));
413             }
414
415             if (i > 0 && show_log_verbosity > 0) {
416                 putchar('\n');
417                 print_db_changes(json_object(json), &names);
418             }
419         }
420         json_destroy(json);
421         putchar('\n');
422     }
423
424     /* XXX free 'names'. */
425 }
426
427 static void
428 do_help(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
429 {
430     usage();
431 }
432
433 static const struct command all_commands[] = {
434     { "create", 2, 2, do_create },
435     { "compact", 1, 2, do_compact },
436     { "convert", 2, 3, do_convert },
437     { "db-version", 1, 1, do_db_version },
438     { "schema-version", 1, 1, do_schema_version },
439     { "query", 2, 2, do_query },
440     { "transact", 2, 2, do_transact },
441     { "show-log", 1, 1, do_show_log },
442     { "help", 0, INT_MAX, do_help },
443     { NULL, 0, 0, NULL },
444 };