ovsdb: Remove trailing whitespace
[sliver-openvswitch.git] / ovsdb / ovsdb-server.c
1 /* Copyright (c) 2009, 2010 Nicira Networks
2  *
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15
16 #include <config.h>
17
18 #include "ovsdb.h"
19
20 #include <errno.h>
21 #include <getopt.h>
22 #include <signal.h>
23 #include <unistd.h>
24
25 #include "column.h"
26 #include "command-line.h"
27 #include "daemon.h"
28 #include "file.h"
29 #include "json.h"
30 #include "jsonrpc.h"
31 #include "jsonrpc-server.h"
32 #include "leak-checker.h"
33 #include "list.h"
34 #include "ovsdb-data.h"
35 #include "ovsdb-types.h"
36 #include "ovsdb-error.h"
37 #include "poll-loop.h"
38 #include "process.h"
39 #include "row.h"
40 #include "stream-ssl.h"
41 #include "stream.h"
42 #include "svec.h"
43 #include "table.h"
44 #include "timeval.h"
45 #include "trigger.h"
46 #include "util.h"
47 #include "unixctl.h"
48 #include "vlog.h"
49
50 VLOG_DEFINE_THIS_MODULE(ovsdb_server);
51
52 #if HAVE_OPENSSL
53 /* SSL configuration. */
54 static char *private_key_file;
55 static char *certificate_file;
56 static char *ca_cert_file;
57 static bool bootstrap_ca_cert;
58 #endif
59
60 static unixctl_cb_func ovsdb_server_exit;
61 static unixctl_cb_func ovsdb_server_compact;
62 static unixctl_cb_func ovsdb_server_reconnect;
63
64 static void parse_options(int argc, char *argv[], char **file_namep,
65                           struct shash *remotes, char **unixctl_pathp,
66                           char **run_command);
67 static void usage(void) NO_RETURN;
68
69 static void reconfigure_from_db(struct ovsdb_jsonrpc_server *jsonrpc,
70                                 const struct ovsdb *db, struct shash *remotes);
71
72 int
73 main(int argc, char *argv[])
74 {
75     char *unixctl_path = NULL;
76     char *run_command = NULL;
77     struct unixctl_server *unixctl;
78     struct ovsdb_jsonrpc_server *jsonrpc;
79     struct shash remotes;
80     struct ovsdb_error *error;
81     struct ovsdb_file *file;
82     struct ovsdb *db;
83     struct process *run_process;
84     char *file_name;
85     bool exiting;
86     int retval;
87
88     proctitle_init(argc, argv);
89     set_program_name(argv[0]);
90     signal(SIGPIPE, SIG_IGN);
91     process_init();
92
93     parse_options(argc, argv, &file_name, &remotes, &unixctl_path,
94                   &run_command);
95
96     die_if_already_running();
97     daemonize_start();
98
99     error = ovsdb_file_open(file_name, false, &db, &file);
100     if (error) {
101         ovs_fatal(0, "%s", ovsdb_error_to_string(error));
102     }
103
104     jsonrpc = ovsdb_jsonrpc_server_create(db);
105     reconfigure_from_db(jsonrpc, db, &remotes);
106
107     retval = unixctl_server_create(unixctl_path, &unixctl);
108     if (retval) {
109         exit(EXIT_FAILURE);
110     }
111
112     if (run_command) {
113         char *run_argv[4];
114
115         run_argv[0] = "/bin/sh";
116         run_argv[1] = "-c";
117         run_argv[2] = run_command;
118         run_argv[3] = NULL;
119
120         retval = process_start(run_argv, NULL, 0, NULL, 0, &run_process);
121         if (retval) {
122             ovs_fatal(retval, "%s: process failed to start", run_command);
123         }
124     } else {
125         run_process = NULL;
126     }
127
128     daemonize_complete();
129
130     unixctl_command_register("exit", ovsdb_server_exit, &exiting);
131     unixctl_command_register("ovsdb-server/compact", ovsdb_server_compact,
132                              file);
133     unixctl_command_register("ovsdb-server/reconnect", ovsdb_server_reconnect,
134                              jsonrpc);
135
136     exiting = false;
137     while (!exiting) {
138         reconfigure_from_db(jsonrpc, db, &remotes);
139         ovsdb_jsonrpc_server_run(jsonrpc);
140         unixctl_server_run(unixctl);
141         ovsdb_trigger_run(db, time_msec());
142         if (run_process && process_exited(run_process)) {
143             exiting = true;
144         }
145
146         ovsdb_jsonrpc_server_wait(jsonrpc);
147         unixctl_server_wait(unixctl);
148         ovsdb_trigger_wait(db, time_msec());
149         if (run_process) {
150             process_wait(run_process);
151         }
152         if (exiting) {
153             poll_immediate_wake();
154         }
155         poll_block();
156     }
157     ovsdb_jsonrpc_server_destroy(jsonrpc);
158     ovsdb_destroy(db);
159     shash_destroy(&remotes);
160     unixctl_server_destroy(unixctl);
161
162     if (run_process && process_exited(run_process)) {
163         int status = process_status(run_process);
164         if (status) {
165             ovs_fatal(0, "%s: child exited, %s",
166                       run_command, process_status_msg(status));
167         }
168     }
169
170     return 0;
171 }
172
173 static void
174 parse_db_column(const struct ovsdb *db,
175                 const char *name_,
176                 const struct ovsdb_table **tablep,
177                 const struct ovsdb_column **columnp)
178 {
179     char *name, *table_name, *column_name;
180     const struct ovsdb_column *column;
181     const struct ovsdb_table *table;
182     char *save_ptr = NULL;
183
184     name = xstrdup(name_);
185     strtok_r(name, ":", &save_ptr); /* "db:" */
186     table_name = strtok_r(NULL, ",", &save_ptr);
187     column_name = strtok_r(NULL, ",", &save_ptr);
188     if (!table_name || !column_name) {
189         ovs_fatal(0, "\"%s\": invalid syntax", name_);
190     }
191
192     table = ovsdb_get_table(db, table_name);
193     if (!table) {
194         ovs_fatal(0, "\"%s\": no table named %s", name_, table_name);
195     }
196
197     column = ovsdb_table_schema_get_column(table->schema, column_name);
198     if (!column) {
199         ovs_fatal(0, "\"%s\": table \"%s\" has no column \"%s\"",
200                   name_, table_name, column_name);
201     }
202     free(name);
203
204     *columnp = column;
205     *tablep = table;
206 }
207
208 static void
209 parse_db_string_column(const struct ovsdb *db,
210                        const char *name,
211                        const struct ovsdb_table **tablep,
212                        const struct ovsdb_column **columnp)
213 {
214     const struct ovsdb_column *column;
215     const struct ovsdb_table *table;
216
217     parse_db_column(db, name, &table, &column);
218
219     if (column->type.key.type != OVSDB_TYPE_STRING
220         || column->type.value.type != OVSDB_TYPE_VOID) {
221         ovs_fatal(0, "\"%s\": table \"%s\" column \"%s\" is "
222                   "not string or set of strings",
223                   name, table->schema->name, column->name);
224     }
225
226     *columnp = column;
227     *tablep = table;
228 }
229
230 #if HAVE_OPENSSL
231 static const char *
232 query_db_string(const struct ovsdb *db, const char *name)
233 {
234     if (!name || strncmp(name, "db:", 3)) {
235         return name;
236     } else {
237         const struct ovsdb_column *column;
238         const struct ovsdb_table *table;
239         const struct ovsdb_row *row;
240
241         parse_db_string_column(db, name, &table, &column);
242
243         HMAP_FOR_EACH (row, hmap_node, &table->rows) {
244             const struct ovsdb_datum *datum;
245             size_t i;
246
247             datum = &row->fields[column->index];
248             for (i = 0; i < datum->n; i++) {
249                 if (datum->keys[i].string[0]) {
250                     return datum->keys[i].string;
251                 }
252             }
253         }
254         return NULL;
255     }
256 }
257 #endif /* HAVE_OPENSSL */
258
259 static struct ovsdb_jsonrpc_options *
260 add_remote(struct shash *remotes, const char *target)
261 {
262     struct ovsdb_jsonrpc_options *options;
263
264     options = shash_find_data(remotes, target);
265     if (!options) {
266         options = ovsdb_jsonrpc_default_options();
267         shash_add(remotes, target, options);
268     }
269
270     return options;
271 }
272
273 static const union ovsdb_atom *
274 read_column(const struct ovsdb_row *row, const char *column_name,
275             enum ovsdb_atomic_type type)
276 {
277     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
278     const struct ovsdb_table_schema *schema = row->table->schema;
279     const struct ovsdb_column *column;
280     const struct ovsdb_datum *datum;
281
282     column = ovsdb_table_schema_get_column(schema, column_name);
283     if (!column) {
284         VLOG_DBG_RL(&rl, "Table `%s' has no `%s' column",
285                     schema->name, column_name);
286         return false;
287     }
288
289     if (column->type.key.type != type
290         || column->type.value.type != OVSDB_TYPE_VOID
291         || column->type.n_max != 1) {
292         if (!VLOG_DROP_DBG(&rl)) {
293             char *type_name = ovsdb_type_to_english(&column->type);
294             VLOG_DBG("Table `%s' column `%s' has type %s, not expected "
295                      "type %s.", schema->name, column_name, type_name,
296                      ovsdb_atomic_type_to_string(type));
297         }
298         return false;
299     }
300
301     datum = &row->fields[column->index];
302     return datum->n ? datum->keys : NULL;
303 }
304
305 static bool
306 read_integer_column(const struct ovsdb_row *row, const char *column_name,
307                     long long int *integerp)
308 {
309     const union ovsdb_atom *atom;
310
311     atom = read_column(row, column_name, OVSDB_TYPE_INTEGER);
312     *integerp = atom ? atom->integer : 0;
313     return atom != NULL;
314 }
315
316 static bool
317 read_string_column(const struct ovsdb_row *row, const char *column_name,
318                    const char **stringp)
319 {
320     const union ovsdb_atom *atom;
321
322     atom = read_column(row, column_name, OVSDB_TYPE_STRING);
323     *stringp = atom ? atom->string : 0;
324     return atom != NULL;
325 }
326
327 /* Adds a remote and options to 'remotes', based on the Manager table row in
328  * 'row'. */
329 static void
330 add_manager_options(struct shash *remotes, const struct ovsdb_row *row)
331 {
332     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
333     struct ovsdb_jsonrpc_options *options;
334     long long int max_backoff, probe_interval;
335     const char *target;
336
337     if (!read_string_column(row, "target", &target) || !target) {
338         VLOG_INFO_RL(&rl, "Table `%s' has missing or invalid `target' column",
339                      row->table->schema->name);
340         return;
341     }
342
343     options = add_remote(remotes, target);
344     if (read_integer_column(row, "max_backoff", &max_backoff)) {
345         options->max_backoff = max_backoff;
346     }
347     if (read_integer_column(row, "probe_interval", &probe_interval)) {
348         options->probe_interval = probe_interval;
349     }
350 }
351
352 static void
353 query_db_remotes(const char *name, const struct ovsdb *db,
354                  struct shash *remotes)
355 {
356     const struct ovsdb_column *column;
357     const struct ovsdb_table *table;
358     const struct ovsdb_row *row;
359
360     parse_db_column(db, name, &table, &column);
361
362     if (column->type.key.type == OVSDB_TYPE_STRING
363         && column->type.value.type == OVSDB_TYPE_VOID) {
364         HMAP_FOR_EACH (row, hmap_node, &table->rows) {
365             const struct ovsdb_datum *datum;
366             size_t i;
367
368             datum = &row->fields[column->index];
369             for (i = 0; i < datum->n; i++) {
370                 add_remote(remotes, datum->keys[i].string);
371             }
372         }
373     } else if (column->type.key.type == OVSDB_TYPE_UUID
374                && column->type.key.u.uuid.refTable
375                && column->type.value.type == OVSDB_TYPE_VOID) {
376         const struct ovsdb_table *ref_table = column->type.key.u.uuid.refTable;
377         HMAP_FOR_EACH (row, hmap_node, &table->rows) {
378             const struct ovsdb_datum *datum;
379             size_t i;
380
381             datum = &row->fields[column->index];
382             for (i = 0; i < datum->n; i++) {
383                 const struct ovsdb_row *ref_row;
384
385                 ref_row = ovsdb_table_get_row(ref_table, &datum->keys[i].uuid);
386                 if (ref_row) {
387                     add_manager_options(remotes, ref_row);
388                 }
389             }
390         }
391     }
392 }
393
394 /* Reconfigures ovsdb-server based on information in the database. */
395 static void
396 reconfigure_from_db(struct ovsdb_jsonrpc_server *jsonrpc,
397                     const struct ovsdb *db, struct shash *remotes)
398 {
399     struct shash resolved_remotes;
400     struct shash_node *node;
401
402     /* Configure remotes. */
403     shash_init(&resolved_remotes);
404     SHASH_FOR_EACH (node, remotes) {
405         const char *name = node->name;
406
407         if (!strncmp(name, "db:", 3)) {
408             query_db_remotes(name, db, &resolved_remotes);
409         } else {
410             add_remote(&resolved_remotes, name);
411         }
412     }
413     ovsdb_jsonrpc_server_set_remotes(jsonrpc, &resolved_remotes);
414     shash_destroy(&resolved_remotes);
415
416 #if HAVE_OPENSSL
417     /* Configure SSL. */
418     stream_ssl_set_key_and_cert(query_db_string(db, private_key_file),
419                                 query_db_string(db, certificate_file));
420     stream_ssl_set_ca_cert_file(query_db_string(db, ca_cert_file),
421                                 bootstrap_ca_cert);
422 #endif
423 }
424
425 static void
426 ovsdb_server_exit(struct unixctl_conn *conn, const char *args OVS_UNUSED,
427                   void *exiting_)
428 {
429     bool *exiting = exiting_;
430     *exiting = true;
431     unixctl_command_reply(conn, 200, NULL);
432 }
433
434 static void
435 ovsdb_server_compact(struct unixctl_conn *conn, const char *args OVS_UNUSED,
436                      void *file_)
437 {
438     struct ovsdb_file *file = file_;
439     struct ovsdb_error *error;
440
441     VLOG_INFO("compacting database by user request");
442     error = ovsdb_file_compact(file);
443     if (!error) {
444         unixctl_command_reply(conn, 200, NULL);
445     } else {
446         char *s = ovsdb_error_to_string(error);
447         ovsdb_error_destroy(error);
448         unixctl_command_reply(conn, 503, s);
449         free(s);
450     }
451 }
452
453 /* "ovsdb-server/reconnect": makes ovsdb-server drop all of its JSON-RPC
454  * connections and reconnect. */
455 static void
456 ovsdb_server_reconnect(struct unixctl_conn *conn, const char *args OVS_UNUSED,
457                        void *jsonrpc_)
458 {
459     struct ovsdb_jsonrpc_server *jsonrpc = jsonrpc_;
460
461     ovsdb_jsonrpc_server_reconnect(jsonrpc);
462     unixctl_command_reply(conn, 200, NULL);
463 }
464
465 static void
466 parse_options(int argc, char *argv[], char **file_namep,
467               struct shash *remotes, char **unixctl_pathp,
468               char **run_command)
469 {
470     enum {
471         OPT_DUMMY = UCHAR_MAX + 1,
472         OPT_REMOTE,
473         OPT_UNIXCTL,
474         OPT_RUN,
475         OPT_BOOTSTRAP_CA_CERT,
476         VLOG_OPTION_ENUMS,
477         LEAK_CHECKER_OPTION_ENUMS
478     };
479     static struct option long_options[] = {
480         {"remote",      required_argument, 0, OPT_REMOTE},
481         {"unixctl",     required_argument, 0, OPT_UNIXCTL},
482         {"run",         required_argument, 0, OPT_RUN},
483         {"help",        no_argument, 0, 'h'},
484         {"version",     no_argument, 0, 'V'},
485         DAEMON_LONG_OPTIONS,
486         VLOG_LONG_OPTIONS,
487         LEAK_CHECKER_LONG_OPTIONS,
488 #ifdef HAVE_OPENSSL
489         {"bootstrap-ca-cert", required_argument, 0, OPT_BOOTSTRAP_CA_CERT},
490         {"private-key", required_argument, 0, 'p'},
491         {"certificate", required_argument, 0, 'c'},
492         {"ca-cert",     required_argument, 0, 'C'},
493 #endif
494         {0, 0, 0, 0},
495     };
496     char *short_options = long_options_to_short_options(long_options);
497
498     shash_init(remotes);
499     for (;;) {
500         int c;
501
502         c = getopt_long(argc, argv, short_options, long_options, NULL);
503         if (c == -1) {
504             break;
505         }
506
507         switch (c) {
508         case OPT_REMOTE:
509             shash_add_once(remotes, optarg, NULL);
510             break;
511
512         case OPT_UNIXCTL:
513             *unixctl_pathp = optarg;
514             break;
515
516         case OPT_RUN:
517             *run_command = optarg;
518             break;
519
520         case 'h':
521             usage();
522
523         case 'V':
524             OVS_PRINT_VERSION(0, 0);
525             exit(EXIT_SUCCESS);
526
527         VLOG_OPTION_HANDLERS
528         DAEMON_OPTION_HANDLERS
529         LEAK_CHECKER_OPTION_HANDLERS
530
531 #ifdef HAVE_OPENSSL
532         case 'p':
533             private_key_file = optarg;
534             break;
535
536         case 'c':
537             certificate_file = optarg;
538             break;
539
540         case 'C':
541             ca_cert_file = optarg;
542             bootstrap_ca_cert = false;
543             break;
544
545         case OPT_BOOTSTRAP_CA_CERT:
546             ca_cert_file = optarg;
547             bootstrap_ca_cert = true;
548             break;
549 #endif
550
551         case '?':
552             exit(EXIT_FAILURE);
553
554         default:
555             abort();
556         }
557     }
558     free(short_options);
559
560     argc -= optind;
561     argv += optind;
562
563     if (argc > 1) {
564         ovs_fatal(0, "database file is only non-option argument; "
565                 "use --help for usage");
566     } else if (argc < 1) {
567         ovs_fatal(0, "missing database file argument; use --help for usage");
568     }
569
570     *file_namep = argv[0];
571 }
572
573 static void
574 usage(void)
575 {
576     printf("%s: Open vSwitch database server\n"
577            "usage: %s [OPTIONS] DATABASE\n"
578            "where DATABASE is a database file in ovsdb format.\n",
579            program_name, program_name);
580     printf("\nJSON-RPC options (may be specified any number of times):\n"
581            "  --remote=REMOTE         connect or listen to REMOTE\n");
582     stream_usage("JSON-RPC", true, true, true);
583     daemon_usage();
584     vlog_usage();
585     printf("\nOther options:\n"
586            "  --run COMMAND           run COMMAND as subprocess then exit\n"
587            "  --unixctl=SOCKET        override default control socket name\n"
588            "  -h, --help              display this help message\n"
589            "  -V, --version           display version information\n");
590     leak_checker_usage();
591     exit(EXIT_SUCCESS);
592 }