Catalli's threaded switch
[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 #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            "  extract-schema DB  print DB's schema on stdout\n"
114            "  query DB TRNS      execute read-only transaction on DB\n"
115            "  transact DB TRNS   execute read/write transaction on DB\n"
116            "  show-log DB        prints information about DB's log entries\n",
117            program_name, program_name);
118     vlog_usage();
119     printf("\nOther options:\n"
120            "  -m, --more                  increase show-log verbosity\n"
121            "  -h, --help                  display this help message\n"
122            "  -V, --version               display version information\n");
123     exit(EXIT_SUCCESS);
124 }
125 \f
126 static struct json *
127 parse_json(const char *s)
128 {
129     struct json *json = json_from_string(s);
130     if (json->type == JSON_STRING) {
131         ovs_fatal(0, "\"%s\": %s", s, json->u.string);
132     }
133     return json;
134 }
135
136 static void
137 print_and_free_json(struct json *json)
138 {
139     char *string = json_to_string(json, JSSF_SORT);
140     json_destroy(json);
141     puts(string);
142     free(string);
143 }
144
145 static void
146 check_ovsdb_error(struct ovsdb_error *error)
147 {
148     if (error) {
149         ovs_fatal(0, "%s", ovsdb_error_to_string(error));
150     }
151 }
152 \f
153 static void
154 do_create(int argc OVS_UNUSED, char *argv[])
155 {
156     const char *db_file_name = argv[1];
157     const char *schema_file_name = argv[2];
158     struct ovsdb_schema *schema;
159     struct ovsdb_log *log;
160     struct json *json;
161
162     /* Read schema from file and convert to JSON. */
163     check_ovsdb_error(ovsdb_schema_from_file(schema_file_name, &schema));
164     json = ovsdb_schema_to_json(schema);
165     ovsdb_schema_destroy(schema);
166
167     /* Create database file. */
168     check_ovsdb_error(ovsdb_log_open(db_file_name, OVSDB_LOG_CREATE,
169                                      -1, &log));
170     check_ovsdb_error(ovsdb_log_write(log, json));
171     check_ovsdb_error(ovsdb_log_commit(log));
172     ovsdb_log_close(log);
173
174     json_destroy(json);
175 }
176
177 static void
178 compact_or_convert(const char *src_name, const char *dst_name,
179                    const struct ovsdb_schema *new_schema,
180                    const char *comment)
181 {
182     struct lockfile *src_lock;
183     struct lockfile *dst_lock;
184     bool in_place = dst_name == NULL;
185     struct ovsdb *db;
186     int retval;
187
188     /* Lock the source, if we will be replacing it. */
189     if (in_place) {
190         retval = lockfile_lock(src_name, 0, &src_lock);
191         if (retval) {
192             ovs_fatal(retval, "%s: failed to lock lockfile", src_name);
193         }
194     }
195
196     /* Get (temporary) destination and lock it. */
197     if (in_place) {
198         dst_name = xasprintf("%s.tmp", src_name);
199     }
200     retval = lockfile_lock(dst_name, 0, &dst_lock);
201     if (retval) {
202         ovs_fatal(retval, "%s: failed to lock lockfile", dst_name);
203     }
204
205     /* Save a copy. */
206     check_ovsdb_error(new_schema
207                       ? ovsdb_file_open_as_schema(src_name, new_schema, &db)
208                       : ovsdb_file_open(src_name, true, &db, NULL));
209     check_ovsdb_error(ovsdb_file_save_copy(dst_name, false, comment, db));
210     ovsdb_destroy(db);
211
212     /* Replace source. */
213     if (in_place) {
214         if (rename(dst_name, src_name)) {
215             ovs_fatal(errno, "failed to rename \"%s\" to \"%s\"",
216                       dst_name, src_name);
217         }
218         fsync_parent_dir(dst_name);
219         lockfile_unlock(src_lock);
220     }
221
222     lockfile_unlock(dst_lock);
223 }
224
225 static void
226 do_compact(int argc OVS_UNUSED, char *argv[])
227 {
228     compact_or_convert(argv[1], argv[2], NULL, "compacted by ovsdb-tool");
229 }
230
231 static void
232 do_convert(int argc OVS_UNUSED, char *argv[])
233 {
234     const char *schema_file_name = argv[2];
235     struct ovsdb_schema *new_schema;
236
237     check_ovsdb_error(ovsdb_schema_from_file(schema_file_name, &new_schema));
238     compact_or_convert(argv[1], argv[3], new_schema,
239                        "converted by ovsdb-tool");
240     ovsdb_schema_destroy(new_schema);
241 }
242
243 static void
244 transact(bool read_only, const char *db_file_name, const char *transaction)
245 {
246     struct json *request, *result;
247     struct ovsdb *db;
248
249     check_ovsdb_error(ovsdb_file_open(db_file_name, read_only, &db, NULL));
250
251     request = parse_json(transaction);
252     result = ovsdb_execute(db, request, 0, NULL);
253     json_destroy(request);
254
255     print_and_free_json(result);
256     ovsdb_destroy(db);
257 }
258
259 static void
260 do_query(int argc OVS_UNUSED, char *argv[])
261 {
262     transact(true, argv[1], argv[2]);
263 }
264
265 static void
266 do_transact(int argc OVS_UNUSED, char *argv[])
267 {
268     transact(false, argv[1], argv[2]);
269 }
270
271 static void
272 print_db_changes(struct shash *tables, struct shash *names)
273 {
274     struct shash_node *n1;
275
276     SHASH_FOR_EACH (n1, tables) {
277         const char *table = n1->name;
278         struct json *rows = n1->data;
279         struct shash_node *n2;
280
281         if (n1->name[0] == '_' || rows->type != JSON_OBJECT) {
282             continue;
283         }
284
285         SHASH_FOR_EACH (n2, json_object(rows)) {
286             const char *row_uuid = n2->name;
287             struct json *columns = n2->data;
288             struct shash_node *n3;
289             char *old_name, *new_name;
290             bool free_new_name = false;
291
292             old_name = new_name = shash_find_data(names, row_uuid);
293             if (columns->type == JSON_OBJECT) {
294                 struct json *new_name_json;
295
296                 new_name_json = shash_find_data(json_object(columns), "name");
297                 if (new_name_json) {
298                     new_name = json_to_string(new_name_json, JSSF_SORT);
299                     free_new_name = true;
300                 }
301             }
302
303             printf("\ttable %s", table);
304
305             if (!old_name) {
306                 if (new_name) {
307                     printf(" insert row %s:\n", new_name);
308                 } else {
309                     printf(" insert row %.8s:\n", row_uuid);
310                 }
311             } else {
312                 printf(" row %s:\n", old_name);
313             }
314
315             if (columns->type == JSON_OBJECT) {
316                 if (show_log_verbosity > 1) {
317                     SHASH_FOR_EACH (n3, json_object(columns)) {
318                         const char *column = n3->name;
319                         struct json *value = n3->data;
320                         char *value_string;
321
322                         value_string = json_to_string(value, JSSF_SORT);
323                         printf("\t\t%s=%s\n", column, value_string);
324                         free(value_string);
325                     }
326                 }
327                 if (!old_name
328                     || (new_name != old_name && strcmp(old_name, new_name))) {
329                     if (old_name) {
330                         shash_delete(names, shash_find(names, row_uuid));
331                         free(old_name);
332                     }
333                     shash_add(names, row_uuid, (new_name
334                                                 ? xstrdup(new_name)
335                                                 : xmemdup0(row_uuid, 8)));
336                 }
337             } else if (columns->type == JSON_NULL) {
338                 struct shash_node *node;
339
340                 printf("\t\tdelete row\n");
341                 node = shash_find(names, row_uuid);
342                 if (node) {
343                     shash_delete(names, node);
344                 }
345                 free(old_name);
346             }
347
348             if (free_new_name) {
349                 free(new_name);
350             }
351         }
352     }
353 }
354
355 static void
356 do_show_log(int argc OVS_UNUSED, char *argv[])
357 {
358     const char *db_file_name = argv[1];
359     struct shash names;
360     struct ovsdb_log *log;
361     unsigned int i;
362
363     check_ovsdb_error(ovsdb_log_open(db_file_name, OVSDB_LOG_READ_ONLY,
364                                      -1, &log));
365     shash_init(&names);
366     for (i = 0; ; i++) {
367         struct json *json;
368
369         check_ovsdb_error(ovsdb_log_read(log, &json));
370         if (!json) {
371             break;
372         }
373
374         printf("record %u:", i);
375         if (json->type == JSON_OBJECT) {
376             struct json *date, *comment;
377
378             date = shash_find_data(json_object(json), "_date");
379             if (date && date->type == JSON_INTEGER) {
380                 time_t t = json_integer(date);
381                 char s[128];
382
383                 strftime(s, sizeof s, "%Y-%m-%d %H:%M:%S", localtime(&t));
384                 printf(" %s", s);
385             }
386
387             comment = shash_find_data(json_object(json), "_comment");
388             if (comment && comment->type == JSON_STRING) {
389                 printf(" \"%s\"", json_string(comment));
390             }
391
392             if (i > 0 && show_log_verbosity > 0) {
393                 putchar('\n');
394                 print_db_changes(json_object(json), &names);
395             }
396         }
397         json_destroy(json);
398         putchar('\n');
399     }
400
401     /* XXX free 'names'. */
402 }
403
404 static void
405 do_help(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
406 {
407     usage();
408 }
409
410 static const struct command all_commands[] = {
411     { "create", 2, 2, do_create },
412     { "compact", 1, 2, do_compact },
413     { "convert", 2, 3, do_convert },
414     { "query", 2, 2, do_query },
415     { "transact", 2, 2, do_transact },
416     { "show-log", 1, 1, do_show_log },
417     { "help", 0, INT_MAX, do_help },
418     { NULL, 0, 0, NULL },
419 };