timeval: Make time_init() static and remove calls to it.
[sliver-openvswitch.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
38 #include "vlog.h"
39 #define THIS_MODULE VLM_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     vlog_init();
54     parse_options(argc, argv);
55     signal(SIGPIPE, SIG_IGN);
56     run_command(argc - optind, argv + optind, all_commands);
57     return 0;
58 }
59
60 static void
61 parse_options(int argc, char *argv[])
62 {
63     static struct option long_options[] = {
64         {"more", no_argument, 0, 'm'},
65         {"verbose", optional_argument, 0, 'v'},
66         {"help", no_argument, 0, 'h'},
67         {"version", no_argument, 0, 'V'},
68         {0, 0, 0, 0},
69     };
70     char *short_options = long_options_to_short_options(long_options);
71
72     for (;;) {
73         int c;
74
75         c = getopt_long(argc, argv, short_options, long_options, NULL);
76         if (c == -1) {
77             break;
78         }
79
80         switch (c) {
81         case 'm':
82             show_log_verbosity++;
83             break;
84
85         case 'h':
86             usage();
87
88         case 'V':
89             OVS_PRINT_VERSION(0, 0);
90             exit(EXIT_SUCCESS);
91
92         case 'v':
93             vlog_set_verbosity(optarg);
94             break;
95
96         case '?':
97             exit(EXIT_FAILURE);
98
99         default:
100             abort();
101         }
102     }
103     free(short_options);
104 }
105
106 static void
107 usage(void)
108 {
109     printf("%s: Open vSwitch database management utility\n"
110            "usage: %s [OPTIONS] COMMAND [ARG...]\n"
111            "  create DB SCHEMA   create DB with the given SCHEMA\n"
112            "  compact DB [DST]   compact DB in-place (or to DST)\n"
113            "  convert DB SCHEMA [DST]   convert DB to SCHEMA (to DST)\n"
114            "  extract-schema DB  print DB's schema on stdout\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 transact(bool read_only, const char *db_file_name, const char *transaction)
246 {
247     struct json *request, *result;
248     struct ovsdb *db;
249
250     check_ovsdb_error(ovsdb_file_open(db_file_name, read_only, &db, NULL));
251
252     request = parse_json(transaction);
253     result = ovsdb_execute(db, request, 0, NULL);
254     json_destroy(request);
255
256     print_and_free_json(result);
257     ovsdb_destroy(db);
258 }
259
260 static void
261 do_query(int argc OVS_UNUSED, char *argv[])
262 {
263     transact(true, argv[1], argv[2]);
264 }
265
266 static void
267 do_transact(int argc OVS_UNUSED, char *argv[])
268 {
269     transact(false, argv[1], argv[2]);
270 }
271
272 static void
273 print_db_changes(struct shash *tables, struct shash *names)
274 {
275     struct shash_node *n1;
276
277     SHASH_FOR_EACH (n1, tables) {
278         const char *table = n1->name;
279         struct json *rows = n1->data;
280         struct shash_node *n2;
281
282         if (n1->name[0] == '_' || rows->type != JSON_OBJECT) {
283             continue;
284         }
285
286         SHASH_FOR_EACH (n2, json_object(rows)) {
287             const char *row_uuid = n2->name;
288             struct json *columns = n2->data;
289             struct shash_node *n3;
290             char *old_name, *new_name;
291             bool free_new_name = false;
292
293             old_name = new_name = shash_find_data(names, row_uuid);
294             if (columns->type == JSON_OBJECT) {
295                 struct json *new_name_json;
296
297                 new_name_json = shash_find_data(json_object(columns), "name");
298                 if (new_name_json) {
299                     new_name = json_to_string(new_name_json, JSSF_SORT);
300                     free_new_name = true;
301                 }
302             }
303
304             printf("\ttable %s", table);
305
306             if (!old_name) {
307                 if (new_name) {
308                     printf(" insert row %s:\n", new_name);
309                 } else {
310                     printf(" insert row %.8s:\n", row_uuid);
311                 }
312             } else {
313                 printf(" row %s:\n", old_name);
314             }
315
316             if (columns->type == JSON_OBJECT) {
317                 if (show_log_verbosity > 1) {
318                     SHASH_FOR_EACH (n3, json_object(columns)) {
319                         const char *column = n3->name;
320                         struct json *value = n3->data;
321                         char *value_string;
322
323                         value_string = json_to_string(value, JSSF_SORT);
324                         printf("\t\t%s=%s\n", column, value_string);
325                         free(value_string);
326                     }
327                 }
328                 if (!old_name
329                     || (new_name != old_name && strcmp(old_name, new_name))) {
330                     if (old_name) {
331                         shash_delete(names, shash_find(names, row_uuid));
332                         free(old_name);
333                     }
334                     shash_add(names, row_uuid, (new_name
335                                                 ? xstrdup(new_name)
336                                                 : xmemdup0(row_uuid, 8)));
337                 }
338             } else if (columns->type == JSON_NULL) {
339                 struct shash_node *node;
340
341                 printf("\t\tdelete row\n");
342                 node = shash_find(names, row_uuid);
343                 if (node) {
344                     shash_delete(names, node);
345                 }
346                 free(old_name);
347             }
348
349             if (free_new_name) {
350                 free(new_name);
351             }
352         }
353     }
354 }
355
356 static void
357 do_show_log(int argc OVS_UNUSED, char *argv[])
358 {
359     const char *db_file_name = argv[1];
360     struct shash names;
361     struct ovsdb_log *log;
362     unsigned int i;
363
364     check_ovsdb_error(ovsdb_log_open(db_file_name, OVSDB_LOG_READ_ONLY,
365                                      -1, &log));
366     shash_init(&names);
367     for (i = 0; ; i++) {
368         struct json *json;
369
370         check_ovsdb_error(ovsdb_log_read(log, &json));
371         if (!json) {
372             break;
373         }
374
375         printf("record %u:", i);
376         if (json->type == JSON_OBJECT) {
377             struct json *date, *comment;
378
379             date = shash_find_data(json_object(json), "_date");
380             if (date && date->type == JSON_INTEGER) {
381                 time_t t = json_integer(date);
382                 char s[128];
383
384                 strftime(s, sizeof s, "%Y-%m-%d %H:%M:%S", localtime(&t));
385                 printf(" %s", s);
386             }
387
388             comment = shash_find_data(json_object(json), "_comment");
389             if (comment && comment->type == JSON_STRING) {
390                 printf(" \"%s\"", json_string(comment));
391             }
392
393             if (i > 0 && show_log_verbosity > 0) {
394                 putchar('\n');
395                 print_db_changes(json_object(json), &names);
396             }
397         }
398         json_destroy(json);
399         putchar('\n');
400     }
401
402     /* XXX free 'names'. */
403 }
404
405 static void
406 do_help(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
407 {
408     usage();
409 }
410
411 static const struct command all_commands[] = {
412     { "create", 2, 2, do_create },
413     { "compact", 1, 2, do_compact },
414     { "convert", 2, 3, do_convert },
415     { "query", 2, 2, do_query },
416     { "transact", 2, 2, do_transact },
417     { "show-log", 1, 1, do_show_log },
418     { "help", 0, INT_MAX, do_help },
419     { NULL, 0, 0, NULL },
420 };