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