ovsdb: Frees database memory on ovsdb process cleanup.
[cascardo/ovs.git] / ovsdb / ovsdb-server.c
1 /* Copyright (c) 2009, 2010, 2011, 2012, 2013, 2014 Nicira, Inc.
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 <errno.h>
19 #include <getopt.h>
20 #include <inttypes.h>
21 #include <signal.h>
22 #include <sys/stat.h>
23 #include <unistd.h>
24
25 #include "column.h"
26 #include "command-line.h"
27 #include "daemon.h"
28 #include "dirs.h"
29 #include "dummy.h"
30 #include "dynamic-string.h"
31 #include "fatal-signal.h"
32 #include "file.h"
33 #include "hash.h"
34 #include "json.h"
35 #include "jsonrpc.h"
36 #include "jsonrpc-server.h"
37 #include "list.h"
38 #include "memory.h"
39 #include "ovsdb.h"
40 #include "ovsdb-data.h"
41 #include "ovsdb-types.h"
42 #include "ovsdb-error.h"
43 #include "poll-loop.h"
44 #include "process.h"
45 #include "row.h"
46 #include "simap.h"
47 #include "shash.h"
48 #include "stream-ssl.h"
49 #include "stream.h"
50 #include "sset.h"
51 #include "table.h"
52 #include "timeval.h"
53 #include "transaction.h"
54 #include "trigger.h"
55 #include "util.h"
56 #include "unixctl.h"
57 #include "vlog.h"
58
59 VLOG_DEFINE_THIS_MODULE(ovsdb_server);
60
61 struct db {
62     /* Initialized in main(). */
63     char *filename;
64     struct ovsdb_file *file;
65     struct ovsdb *db;
66
67     /* Only used by update_remote_status(). */
68     struct ovsdb_txn *txn;
69 };
70
71 /* SSL configuration. */
72 static char *private_key_file;
73 static char *certificate_file;
74 static char *ca_cert_file;
75 static bool bootstrap_ca_cert;
76
77 static unixctl_cb_func ovsdb_server_exit;
78 static unixctl_cb_func ovsdb_server_compact;
79 static unixctl_cb_func ovsdb_server_reconnect;
80
81 struct server_config {
82     struct sset *remotes;
83     struct shash *all_dbs;
84     FILE *config_tmpfile;
85     struct ovsdb_jsonrpc_server *jsonrpc;
86 };
87 static unixctl_cb_func ovsdb_server_add_remote;
88 static unixctl_cb_func ovsdb_server_remove_remote;
89 static unixctl_cb_func ovsdb_server_list_remotes;
90
91 static unixctl_cb_func ovsdb_server_add_database;
92 static unixctl_cb_func ovsdb_server_remove_database;
93 static unixctl_cb_func ovsdb_server_list_databases;
94
95 static char *open_db(struct server_config *config, const char *filename);
96 static void close_db(struct db *db);
97
98 static void parse_options(int *argc, char **argvp[],
99                           struct sset *remotes, char **unixctl_pathp,
100                           char **run_command);
101 static void usage(void) NO_RETURN;
102
103 static char *reconfigure_remotes(struct ovsdb_jsonrpc_server *,
104                                  const struct shash *all_dbs,
105                                  struct sset *remotes);
106 static char *reconfigure_ssl(const struct shash *all_dbs);
107 static void report_error_if_changed(char *error, char **last_errorp);
108
109 static void update_remote_status(const struct ovsdb_jsonrpc_server *jsonrpc,
110                                  const struct sset *remotes,
111                                  struct shash *all_dbs);
112
113 static void save_config__(FILE *config_file, const struct sset *remotes,
114                           const struct sset *db_filenames);
115 static void save_config(struct server_config *);
116 static void load_config(FILE *config_file, struct sset *remotes,
117                         struct sset *db_filenames);
118
119 int
120 main(int argc, char *argv[])
121 {
122     char *unixctl_path = NULL;
123     char *run_command = NULL;
124     struct unixctl_server *unixctl;
125     struct ovsdb_jsonrpc_server *jsonrpc;
126     struct sset remotes, db_filenames;
127     const char *db_filename;
128     struct process *run_process;
129     bool exiting;
130     int retval;
131     long long int status_timer = LLONG_MIN;
132     FILE *config_tmpfile;
133     struct server_config server_config;
134     struct shash all_dbs;
135     struct shash_node *node, *next;
136     char *remotes_error, *ssl_error;
137     char *error;
138     int i;
139
140     proctitle_init(argc, argv);
141     set_program_name(argv[0]);
142     service_start(&argc, &argv);
143     fatal_ignore_sigpipe();
144     process_init();
145
146     parse_options(&argc, &argv, &remotes, &unixctl_path, &run_command);
147
148     /* Create and initialize 'config_tmpfile' as a temporary file to hold
149      * ovsdb-server's most basic configuration, and then save our initial
150      * configuration to it.  When --monitor is used, this preserves the effects
151      * of ovs-appctl commands such as ovsdb-server/add-remote (which saves the
152      * new configuration) across crashes. */
153     config_tmpfile = tmpfile();
154     if (!config_tmpfile) {
155         ovs_fatal(errno, "failed to create temporary file");
156     }
157
158     sset_init(&db_filenames);
159     if (argc > 0) {
160         for (i = 0; i < argc; i++) {
161             sset_add(&db_filenames, argv[i]);
162          }
163     } else {
164         char *default_db = xasprintf("%s/conf.db", ovs_dbdir());
165         sset_add(&db_filenames, default_db);
166         free(default_db);
167     }
168
169     server_config.remotes = &remotes;
170     server_config.config_tmpfile = config_tmpfile;
171
172     save_config__(config_tmpfile, &remotes, &db_filenames);
173
174     daemonize_start();
175
176     /* Load the saved config. */
177     load_config(config_tmpfile, &remotes, &db_filenames);
178     jsonrpc = ovsdb_jsonrpc_server_create();
179
180     shash_init(&all_dbs);
181     server_config.all_dbs = &all_dbs;
182     server_config.jsonrpc = jsonrpc;
183     SSET_FOR_EACH (db_filename, &db_filenames) {
184         error = open_db(&server_config, db_filename);
185         if (error) {
186             ovs_fatal(0, "%s", error);
187         }
188     }
189
190     error = reconfigure_remotes(jsonrpc, &all_dbs, &remotes);
191     if (!error) {
192         error = reconfigure_ssl(&all_dbs);
193     }
194     if (error) {
195         ovs_fatal(0, "%s", error);
196     }
197
198     retval = unixctl_server_create(unixctl_path, &unixctl);
199     if (retval) {
200         exit(EXIT_FAILURE);
201     }
202
203     if (run_command) {
204         char *run_argv[4];
205
206         run_argv[0] = "/bin/sh";
207         run_argv[1] = "-c";
208         run_argv[2] = run_command;
209         run_argv[3] = NULL;
210
211         retval = process_start(run_argv, &run_process);
212         if (retval) {
213             ovs_fatal(retval, "%s: process failed to start", run_command);
214         }
215     } else {
216         run_process = NULL;
217     }
218
219     daemonize_complete();
220
221     if (!run_command) {
222         /* ovsdb-server is usually a long-running process, in which case it
223          * makes plenty of sense to log the version, but --run makes
224          * ovsdb-server more like a command-line tool, so skip it.  */
225         VLOG_INFO("%s (Open vSwitch) %s", program_name, VERSION);
226     }
227
228     unixctl_command_register("exit", "", 0, 0, ovsdb_server_exit, &exiting);
229     unixctl_command_register("ovsdb-server/compact", "", 0, 1,
230                              ovsdb_server_compact, &all_dbs);
231     unixctl_command_register("ovsdb-server/reconnect", "", 0, 0,
232                              ovsdb_server_reconnect, jsonrpc);
233
234     unixctl_command_register("ovsdb-server/add-remote", "REMOTE", 1, 1,
235                              ovsdb_server_add_remote, &server_config);
236     unixctl_command_register("ovsdb-server/remove-remote", "REMOTE", 1, 1,
237                              ovsdb_server_remove_remote, &server_config);
238     unixctl_command_register("ovsdb-server/list-remotes", "", 0, 0,
239                              ovsdb_server_list_remotes, &remotes);
240
241     unixctl_command_register("ovsdb-server/add-db", "DB", 1, 1,
242                              ovsdb_server_add_database, &server_config);
243     unixctl_command_register("ovsdb-server/remove-db", "DB", 1, 1,
244                              ovsdb_server_remove_database, &server_config);
245     unixctl_command_register("ovsdb-server/list-dbs", "", 0, 0,
246                              ovsdb_server_list_databases, &all_dbs);
247
248     exiting = false;
249     ssl_error = NULL;
250     remotes_error = NULL;
251     while (!exiting) {
252         memory_run();
253         if (memory_should_report()) {
254             struct simap usage;
255
256             simap_init(&usage);
257             ovsdb_jsonrpc_server_get_memory_usage(jsonrpc, &usage);
258             SHASH_FOR_EACH(node, &all_dbs) {
259                 struct db *db = node->data;
260                 ovsdb_get_memory_usage(db->db, &usage);
261             }
262             memory_report(&usage);
263             simap_destroy(&usage);
264         }
265
266         /* Run unixctl_server_run() before reconfigure_remotes() because
267          * ovsdb-server/add-remote and ovsdb-server/remove-remote can change
268          * the set of remotes that reconfigure_remotes() uses. */
269         unixctl_server_run(unixctl);
270
271         report_error_if_changed(
272             reconfigure_remotes(jsonrpc, &all_dbs, &remotes),
273             &remotes_error);
274         report_error_if_changed(reconfigure_ssl(&all_dbs), &ssl_error);
275         ovsdb_jsonrpc_server_run(jsonrpc);
276
277         SHASH_FOR_EACH(node, &all_dbs) {
278             struct db *db = node->data;
279             ovsdb_trigger_run(db->db, time_msec());
280         }
281         if (run_process) {
282             process_run();
283             if (process_exited(run_process)) {
284                 exiting = true;
285             }
286         }
287
288         /* update Manager status(es) every 5 seconds */
289         if (time_msec() >= status_timer) {
290             status_timer = time_msec() + 5000;
291             update_remote_status(jsonrpc, &remotes, &all_dbs);
292         }
293
294         memory_wait();
295         ovsdb_jsonrpc_server_wait(jsonrpc);
296         unixctl_server_wait(unixctl);
297         SHASH_FOR_EACH(node, &all_dbs) {
298             struct db *db = node->data;
299             ovsdb_trigger_wait(db->db, time_msec());
300         }
301         if (run_process) {
302             process_wait(run_process);
303         }
304         if (exiting) {
305             poll_immediate_wake();
306         }
307         poll_timer_wait_until(status_timer);
308         poll_block();
309         if (should_service_stop()) {
310             exiting = true;
311         }
312     }
313     ovsdb_jsonrpc_server_destroy(jsonrpc);
314     SHASH_FOR_EACH_SAFE(node, next, &all_dbs) {
315         struct db *db = node->data;
316         close_db(db);
317         shash_delete(&all_dbs, node);
318     }
319     sset_destroy(&remotes);
320     sset_destroy(&db_filenames);
321     unixctl_server_destroy(unixctl);
322
323     if (run_process && process_exited(run_process)) {
324         int status = process_status(run_process);
325         if (status) {
326             ovs_fatal(0, "%s: child exited, %s",
327                       run_command, process_status_msg(status));
328         }
329     }
330
331     service_stop();
332     return 0;
333 }
334
335 /* Returns true if 'filename' is known to be already open as a database,
336  * false if not.
337  *
338  * "False negatives" are possible. */
339 static bool
340 is_already_open(struct server_config *config OVS_UNUSED,
341                 const char *filename OVS_UNUSED)
342 {
343 #ifndef _WIN32
344     struct stat s;
345
346     if (!stat(filename, &s)) {
347         struct shash_node *node;
348
349         SHASH_FOR_EACH (node, config->all_dbs) {
350             struct db *db = node->data;
351             struct stat s2;
352
353             if (!stat(db->filename, &s2)
354                 && s.st_dev == s2.st_dev
355                 && s.st_ino == s2.st_ino) {
356                 return true;
357             }
358         }
359     }
360 #endif  /* !_WIN32 */
361
362     return false;
363 }
364
365 static void
366 close_db(struct db *db)
367 {
368     ovsdb_destroy(db->db);
369     free(db->filename);
370     free(db);
371 }
372
373 static char *
374 open_db(struct server_config *config, const char *filename)
375 {
376     struct ovsdb_error *db_error;
377     struct db *db;
378     char *error;
379
380     /* If we know that the file is already open, return a good error message.
381      * Otherwise, if the file is open, we'll fail later on with a harder to
382      * interpret file locking error. */
383     if (is_already_open(config, filename)) {
384         return xasprintf("%s: already open", filename);
385     }
386
387     db = xzalloc(sizeof *db);
388     db->filename = xstrdup(filename);
389
390     db_error = ovsdb_file_open(db->filename, false, &db->db, &db->file);
391     if (db_error) {
392         error = ovsdb_error_to_string(db_error);
393     } else if (!ovsdb_jsonrpc_server_add_db(config->jsonrpc, db->db)) {
394         error = xasprintf("%s: duplicate database name", db->db->schema->name);
395     } else {
396         shash_add_assert(config->all_dbs, db->db->schema->name, db);
397         return NULL;
398     }
399
400     ovsdb_error_destroy(db_error);
401     close_db(db);
402     return error;
403 }
404
405 static const struct db *
406 find_db(const struct shash *all_dbs, const char *db_name)
407 {
408     struct shash_node *node;
409
410     SHASH_FOR_EACH(node, all_dbs) {
411         struct db *db = node->data;
412         if (!strcmp(db->db->schema->name, db_name)) {
413             return db;
414         }
415     }
416
417     return NULL;
418 }
419
420 static char * WARN_UNUSED_RESULT
421 parse_db_column__(const struct shash *all_dbs,
422                   const char *name_, char *name,
423                   const struct db **dbp,
424                   const struct ovsdb_table **tablep,
425                   const struct ovsdb_column **columnp)
426 {
427     const char *db_name, *table_name, *column_name;
428     const struct ovsdb_column *column;
429     const struct ovsdb_table *table;
430     const char *tokens[3];
431     char *save_ptr = NULL;
432     const struct db *db;
433
434     *dbp = NULL;
435     *tablep = NULL;
436     *columnp = NULL;
437
438     strtok_r(name, ":", &save_ptr); /* "db:" */
439     tokens[0] = strtok_r(NULL, ",", &save_ptr);
440     tokens[1] = strtok_r(NULL, ",", &save_ptr);
441     tokens[2] = strtok_r(NULL, ",", &save_ptr);
442     if (!tokens[0] || !tokens[1] || !tokens[2]) {
443         return xasprintf("\"%s\": invalid syntax", name_);
444     }
445
446     db_name = tokens[0];
447     table_name = tokens[1];
448     column_name = tokens[2];
449
450     db = find_db(all_dbs, tokens[0]);
451     if (!db) {
452         return xasprintf("\"%s\": no database named %s", name_, db_name);
453     }
454
455     table = ovsdb_get_table(db->db, table_name);
456     if (!table) {
457         return xasprintf("\"%s\": no table named %s", name_, table_name);
458     }
459
460     column = ovsdb_table_schema_get_column(table->schema, column_name);
461     if (!column) {
462         return xasprintf("\"%s\": table \"%s\" has no column \"%s\"",
463                          name_, table_name, column_name);
464     }
465
466     *dbp = db;
467     *columnp = column;
468     *tablep = table;
469     return NULL;
470 }
471
472 /* Returns NULL if successful, otherwise a malloc()'d string describing the
473  * error. */
474 static char * WARN_UNUSED_RESULT
475 parse_db_column(const struct shash *all_dbs,
476                 const char *name_,
477                 const struct db **dbp,
478                 const struct ovsdb_table **tablep,
479                 const struct ovsdb_column **columnp)
480 {
481     char *name = xstrdup(name_);
482     char *retval = parse_db_column__(all_dbs, name_, name,
483                                      dbp, tablep, columnp);
484     free(name);
485     return retval;
486 }
487
488 /* Returns NULL if successful, otherwise a malloc()'d string describing the
489  * error. */
490 static char * WARN_UNUSED_RESULT
491 parse_db_string_column(const struct shash *all_dbs,
492                        const char *name,
493                        const struct db **dbp,
494                        const struct ovsdb_table **tablep,
495                        const struct ovsdb_column **columnp)
496 {
497     char *retval;
498
499     retval = parse_db_column(all_dbs, name, dbp, tablep, columnp);
500     if (retval) {
501         return retval;
502     }
503
504     if ((*columnp)->type.key.type != OVSDB_TYPE_STRING
505         || (*columnp)->type.value.type != OVSDB_TYPE_VOID) {
506         return xasprintf("\"%s\": table \"%s\" column \"%s\" is "
507                          "not string or set of strings",
508                          name, (*tablep)->schema->name, (*columnp)->name);
509     }
510
511     return NULL;
512 }
513
514 static const char *
515 query_db_string(const struct shash *all_dbs, const char *name,
516                 struct ds *errors)
517 {
518     if (!name || strncmp(name, "db:", 3)) {
519         return name;
520     } else {
521         const struct ovsdb_column *column;
522         const struct ovsdb_table *table;
523         const struct ovsdb_row *row;
524         const struct db *db;
525         char *retval;
526
527         retval = parse_db_string_column(all_dbs, name,
528                                         &db, &table, &column);
529         if (retval) {
530             ds_put_format(errors, "%s\n", retval);
531             return NULL;
532         }
533
534         HMAP_FOR_EACH (row, hmap_node, &table->rows) {
535             const struct ovsdb_datum *datum;
536             size_t i;
537
538             datum = &row->fields[column->index];
539             for (i = 0; i < datum->n; i++) {
540                 if (datum->keys[i].string[0]) {
541                     return datum->keys[i].string;
542                 }
543             }
544         }
545         return NULL;
546     }
547 }
548
549 static struct ovsdb_jsonrpc_options *
550 add_remote(struct shash *remotes, const char *target)
551 {
552     struct ovsdb_jsonrpc_options *options;
553
554     options = shash_find_data(remotes, target);
555     if (!options) {
556         options = ovsdb_jsonrpc_default_options(target);
557         shash_add(remotes, target, options);
558     }
559
560     return options;
561 }
562
563 static struct ovsdb_datum *
564 get_datum(struct ovsdb_row *row, const char *column_name,
565           const enum ovsdb_atomic_type key_type,
566           const enum ovsdb_atomic_type value_type,
567           const size_t n_max)
568 {
569     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
570     const struct ovsdb_table_schema *schema = row->table->schema;
571     const struct ovsdb_column *column;
572
573     column = ovsdb_table_schema_get_column(schema, column_name);
574     if (!column) {
575         VLOG_DBG_RL(&rl, "Table `%s' has no `%s' column",
576                     schema->name, column_name);
577         return NULL;
578     }
579
580     if (column->type.key.type != key_type
581         || column->type.value.type != value_type
582         || column->type.n_max != n_max) {
583         if (!VLOG_DROP_DBG(&rl)) {
584             char *type_name = ovsdb_type_to_english(&column->type);
585             VLOG_DBG("Table `%s' column `%s' has type %s, not expected "
586                      "key type %s, value type %s, max elements %"PRIuSIZE".",
587                      schema->name, column_name, type_name,
588                      ovsdb_atomic_type_to_string(key_type),
589                      ovsdb_atomic_type_to_string(value_type),
590                      n_max);
591             free(type_name);
592         }
593         return NULL;
594     }
595
596     return &row->fields[column->index];
597 }
598
599 /* Read string-string key-values from a map.  Returns the value associated with
600  * 'key', if found, or NULL */
601 static const char *
602 read_map_string_column(const struct ovsdb_row *row, const char *column_name,
603                        const char *key)
604 {
605     const struct ovsdb_datum *datum;
606     union ovsdb_atom *atom_key = NULL, *atom_value = NULL;
607     size_t i;
608
609     datum = get_datum(CONST_CAST(struct ovsdb_row *, row), column_name,
610                       OVSDB_TYPE_STRING, OVSDB_TYPE_STRING, UINT_MAX);
611
612     if (!datum) {
613         return NULL;
614     }
615
616     for (i = 0; i < datum->n; i++) {
617         atom_key = &datum->keys[i];
618         if (!strcmp(atom_key->string, key)){
619             atom_value = &datum->values[i];
620             break;
621         }
622     }
623
624     return atom_value ? atom_value->string : NULL;
625 }
626
627 static const union ovsdb_atom *
628 read_column(const struct ovsdb_row *row, const char *column_name,
629             enum ovsdb_atomic_type type)
630 {
631     const struct ovsdb_datum *datum;
632
633     datum = get_datum(CONST_CAST(struct ovsdb_row *, row), column_name, type,
634                       OVSDB_TYPE_VOID, 1);
635     return datum && datum->n ? datum->keys : NULL;
636 }
637
638 static bool
639 read_integer_column(const struct ovsdb_row *row, const char *column_name,
640                     long long int *integerp)
641 {
642     const union ovsdb_atom *atom;
643
644     atom = read_column(row, column_name, OVSDB_TYPE_INTEGER);
645     *integerp = atom ? atom->integer : 0;
646     return atom != NULL;
647 }
648
649 static bool
650 read_string_column(const struct ovsdb_row *row, const char *column_name,
651                    const char **stringp)
652 {
653     const union ovsdb_atom *atom;
654
655     atom = read_column(row, column_name, OVSDB_TYPE_STRING);
656     *stringp = atom ? atom->string : NULL;
657     return atom != NULL;
658 }
659
660 static void
661 write_bool_column(struct ovsdb_row *row, const char *column_name, bool value)
662 {
663     const struct ovsdb_column *column;
664     struct ovsdb_datum *datum;
665
666     column = ovsdb_table_schema_get_column(row->table->schema, column_name);
667     datum = get_datum(row, column_name, OVSDB_TYPE_BOOLEAN,
668                       OVSDB_TYPE_VOID, 1);
669     if (!datum) {
670         return;
671     }
672
673     if (datum->n != 1) {
674         ovsdb_datum_destroy(datum, &column->type);
675
676         datum->n = 1;
677         datum->keys = xmalloc(sizeof *datum->keys);
678         datum->values = NULL;
679     }
680
681     datum->keys[0].boolean = value;
682 }
683
684 static void
685 write_string_string_column(struct ovsdb_row *row, const char *column_name,
686                            char **keys, char **values, size_t n)
687 {
688     const struct ovsdb_column *column;
689     struct ovsdb_datum *datum;
690     size_t i;
691
692     column = ovsdb_table_schema_get_column(row->table->schema, column_name);
693     datum = get_datum(row, column_name, OVSDB_TYPE_STRING, OVSDB_TYPE_STRING,
694                       UINT_MAX);
695     if (!datum) {
696         for (i = 0; i < n; i++) {
697             free(keys[i]);
698             free(values[i]);
699         }
700         return;
701     }
702
703     /* Free existing data. */
704     ovsdb_datum_destroy(datum, &column->type);
705
706     /* Allocate space for new values. */
707     datum->n = n;
708     datum->keys = xmalloc(n * sizeof *datum->keys);
709     datum->values = xmalloc(n * sizeof *datum->values);
710
711     for (i = 0; i < n; ++i) {
712         datum->keys[i].string = keys[i];
713         datum->values[i].string = values[i];
714     }
715
716     /* Sort and check constraints. */
717     ovsdb_datum_sort_assert(datum, column->type.key.type);
718 }
719
720 /* Adds a remote and options to 'remotes', based on the Manager table row in
721  * 'row'. */
722 static void
723 add_manager_options(struct shash *remotes, const struct ovsdb_row *row)
724 {
725     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
726     struct ovsdb_jsonrpc_options *options;
727     long long int max_backoff, probe_interval;
728     const char *target, *dscp_string;
729
730     if (!read_string_column(row, "target", &target) || !target) {
731         VLOG_INFO_RL(&rl, "Table `%s' has missing or invalid `target' column",
732                      row->table->schema->name);
733         return;
734     }
735
736     options = add_remote(remotes, target);
737     if (read_integer_column(row, "max_backoff", &max_backoff)) {
738         options->max_backoff = max_backoff;
739     }
740     if (read_integer_column(row, "inactivity_probe", &probe_interval)) {
741         options->probe_interval = probe_interval;
742     }
743
744     options->dscp = DSCP_DEFAULT;
745     dscp_string = read_map_string_column(row, "other_config", "dscp");
746     if (dscp_string) {
747         int dscp = atoi(dscp_string);
748         if (dscp >= 0 && dscp <= 63) {
749             options->dscp = dscp;
750         }
751     }
752 }
753
754 static void
755 query_db_remotes(const char *name, const struct shash *all_dbs,
756                  struct shash *remotes, struct ds *errors)
757 {
758     const struct ovsdb_column *column;
759     const struct ovsdb_table *table;
760     const struct ovsdb_row *row;
761     const struct db *db;
762     char *retval;
763
764     retval = parse_db_column(all_dbs, name, &db, &table, &column);
765     if (retval) {
766         ds_put_format(errors, "%s\n", retval);
767         free(retval);
768         return;
769     }
770
771     if (column->type.key.type == OVSDB_TYPE_STRING
772         && column->type.value.type == OVSDB_TYPE_VOID) {
773         HMAP_FOR_EACH (row, hmap_node, &table->rows) {
774             const struct ovsdb_datum *datum;
775             size_t i;
776
777             datum = &row->fields[column->index];
778             for (i = 0; i < datum->n; i++) {
779                 add_remote(remotes, datum->keys[i].string);
780             }
781         }
782     } else if (column->type.key.type == OVSDB_TYPE_UUID
783                && column->type.key.u.uuid.refTable
784                && column->type.value.type == OVSDB_TYPE_VOID) {
785         const struct ovsdb_table *ref_table = column->type.key.u.uuid.refTable;
786         HMAP_FOR_EACH (row, hmap_node, &table->rows) {
787             const struct ovsdb_datum *datum;
788             size_t i;
789
790             datum = &row->fields[column->index];
791             for (i = 0; i < datum->n; i++) {
792                 const struct ovsdb_row *ref_row;
793
794                 ref_row = ovsdb_table_get_row(ref_table, &datum->keys[i].uuid);
795                 if (ref_row) {
796                     add_manager_options(remotes, ref_row);
797                 }
798             }
799         }
800     }
801 }
802
803 static void
804 update_remote_row(const struct ovsdb_row *row, struct ovsdb_txn *txn,
805                   const struct ovsdb_jsonrpc_server *jsonrpc)
806 {
807     struct ovsdb_jsonrpc_remote_status status;
808     struct ovsdb_row *rw_row;
809     const char *target;
810     char *keys[9], *values[9];
811     size_t n = 0;
812
813     /* Get the "target" (protocol/host/port) spec. */
814     if (!read_string_column(row, "target", &target)) {
815         /* Bad remote spec or incorrect schema. */
816         return;
817     }
818     rw_row = ovsdb_txn_row_modify(txn, row);
819     ovsdb_jsonrpc_server_get_remote_status(jsonrpc, target, &status);
820
821     /* Update status information columns. */
822     write_bool_column(rw_row, "is_connected", status.is_connected);
823
824     if (status.state) {
825         keys[n] = xstrdup("state");
826         values[n++] = xstrdup(status.state);
827     }
828     if (status.sec_since_connect != UINT_MAX) {
829         keys[n] = xstrdup("sec_since_connect");
830         values[n++] = xasprintf("%u", status.sec_since_connect);
831     }
832     if (status.sec_since_disconnect != UINT_MAX) {
833         keys[n] = xstrdup("sec_since_disconnect");
834         values[n++] = xasprintf("%u", status.sec_since_disconnect);
835     }
836     if (status.last_error) {
837         keys[n] = xstrdup("last_error");
838         values[n++] =
839             xstrdup(ovs_retval_to_string(status.last_error));
840     }
841     if (status.locks_held && status.locks_held[0]) {
842         keys[n] = xstrdup("locks_held");
843         values[n++] = xstrdup(status.locks_held);
844     }
845     if (status.locks_waiting && status.locks_waiting[0]) {
846         keys[n] = xstrdup("locks_waiting");
847         values[n++] = xstrdup(status.locks_waiting);
848     }
849     if (status.locks_lost && status.locks_lost[0]) {
850         keys[n] = xstrdup("locks_lost");
851         values[n++] = xstrdup(status.locks_lost);
852     }
853     if (status.n_connections > 1) {
854         keys[n] = xstrdup("n_connections");
855         values[n++] = xasprintf("%d", status.n_connections);
856     }
857     if (status.bound_port != htons(0)) {
858         keys[n] = xstrdup("bound_port");
859         values[n++] = xasprintf("%"PRIu16, ntohs(status.bound_port));
860     }
861     write_string_string_column(rw_row, "status", keys, values, n);
862
863     ovsdb_jsonrpc_server_free_remote_status(&status);
864 }
865
866 static void
867 update_remote_rows(const struct shash *all_dbs,
868                    const char *remote_name,
869                    const struct ovsdb_jsonrpc_server *jsonrpc)
870 {
871     const struct ovsdb_table *table, *ref_table;
872     const struct ovsdb_column *column;
873     const struct ovsdb_row *row;
874     const struct db *db;
875     char *retval;
876
877     if (strncmp("db:", remote_name, 3)) {
878         return;
879     }
880
881     retval = parse_db_column(all_dbs, remote_name, &db, &table, &column);
882     if (retval) {
883         free(retval);
884         return;
885     }
886
887     if (column->type.key.type != OVSDB_TYPE_UUID
888         || !column->type.key.u.uuid.refTable
889         || column->type.value.type != OVSDB_TYPE_VOID) {
890         return;
891     }
892
893     ref_table = column->type.key.u.uuid.refTable;
894
895     HMAP_FOR_EACH (row, hmap_node, &table->rows) {
896         const struct ovsdb_datum *datum;
897         size_t i;
898
899         datum = &row->fields[column->index];
900         for (i = 0; i < datum->n; i++) {
901             const struct ovsdb_row *ref_row;
902
903             ref_row = ovsdb_table_get_row(ref_table, &datum->keys[i].uuid);
904             if (ref_row) {
905                 update_remote_row(ref_row, db->txn, jsonrpc);
906             }
907         }
908     }
909 }
910
911 static void
912 update_remote_status(const struct ovsdb_jsonrpc_server *jsonrpc,
913                      const struct sset *remotes,
914                      struct shash *all_dbs)
915 {
916     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
917     const char *remote;
918     struct db *db;
919     struct shash_node *node;
920
921     SHASH_FOR_EACH(node, all_dbs) {
922         db = node->data;
923         db->txn = ovsdb_txn_create(db->db);
924     }
925
926     /* Iterate over --remote arguments given on command line. */
927     SSET_FOR_EACH (remote, remotes) {
928         update_remote_rows(all_dbs, remote, jsonrpc);
929     }
930
931     SHASH_FOR_EACH(node, all_dbs) {
932         struct ovsdb_error *error;
933         db = node->data;
934         error = ovsdb_txn_commit(db->txn, false);
935         if (error) {
936             VLOG_ERR_RL(&rl, "Failed to update remote status: %s",
937                         ovsdb_error_to_string(error));
938             ovsdb_error_destroy(error);
939         }
940     }
941 }
942
943 /* Reconfigures ovsdb-server's remotes based on information in the database. */
944 static char *
945 reconfigure_remotes(struct ovsdb_jsonrpc_server *jsonrpc,
946                     const struct shash *all_dbs, struct sset *remotes)
947 {
948     struct ds errors = DS_EMPTY_INITIALIZER;
949     struct shash resolved_remotes;
950     const char *name;
951
952     /* Configure remotes. */
953     shash_init(&resolved_remotes);
954     SSET_FOR_EACH (name, remotes) {
955         if (!strncmp(name, "db:", 3)) {
956             query_db_remotes(name, all_dbs, &resolved_remotes, &errors);
957         } else {
958             add_remote(&resolved_remotes, name);
959         }
960     }
961     ovsdb_jsonrpc_server_set_remotes(jsonrpc, &resolved_remotes);
962     shash_destroy_free_data(&resolved_remotes);
963
964     return errors.string;
965 }
966
967 static char *
968 reconfigure_ssl(const struct shash *all_dbs)
969 {
970     struct ds errors = DS_EMPTY_INITIALIZER;
971     const char *resolved_private_key;
972     const char *resolved_certificate;
973     const char *resolved_ca_cert;
974
975     resolved_private_key = query_db_string(all_dbs, private_key_file, &errors);
976     resolved_certificate = query_db_string(all_dbs, certificate_file, &errors);
977     resolved_ca_cert = query_db_string(all_dbs, ca_cert_file, &errors);
978
979     stream_ssl_set_key_and_cert(resolved_private_key, resolved_certificate);
980     stream_ssl_set_ca_cert_file(resolved_ca_cert, bootstrap_ca_cert);
981
982     return errors.string;
983 }
984
985 static void
986 report_error_if_changed(char *error, char **last_errorp)
987 {
988     if (error) {
989         if (!*last_errorp || strcmp(error, *last_errorp)) {
990             VLOG_WARN("%s", error);
991             free(*last_errorp);
992             *last_errorp = error;
993             return;
994         }
995         free(error);
996     } else {
997         free(*last_errorp);
998         *last_errorp = NULL;
999     }
1000 }
1001
1002 static void
1003 ovsdb_server_exit(struct unixctl_conn *conn, int argc OVS_UNUSED,
1004                   const char *argv[] OVS_UNUSED,
1005                   void *exiting_)
1006 {
1007     bool *exiting = exiting_;
1008     *exiting = true;
1009     unixctl_command_reply(conn, NULL);
1010 }
1011
1012 static void
1013 ovsdb_server_compact(struct unixctl_conn *conn, int argc,
1014                      const char *argv[], void *dbs_)
1015 {
1016     struct shash *all_dbs = dbs_;
1017     struct ds reply;
1018     struct db *db;
1019     struct shash_node *node;
1020     int n = 0;
1021
1022     ds_init(&reply);
1023     SHASH_FOR_EACH(node, all_dbs) {
1024         const char *name;
1025
1026         db = node->data;
1027         name = db->db->schema->name;
1028
1029         if (argc < 2 || !strcmp(argv[1], name)) {
1030             struct ovsdb_error *error;
1031
1032             VLOG_INFO("compacting %s database by user request", name);
1033
1034             error = ovsdb_file_compact(db->file);
1035             if (error) {
1036                 char *s = ovsdb_error_to_string(error);
1037                 ds_put_format(&reply, "%s\n", s);
1038                 free(s);
1039                 ovsdb_error_destroy(error);
1040             }
1041
1042             n++;
1043         }
1044     }
1045
1046     if (!n) {
1047         unixctl_command_reply_error(conn, "no database by that name");
1048     } else if (reply.length) {
1049         unixctl_command_reply_error(conn, ds_cstr(&reply));
1050     } else {
1051         unixctl_command_reply(conn, NULL);
1052     }
1053     ds_destroy(&reply);
1054 }
1055
1056 /* "ovsdb-server/reconnect": makes ovsdb-server drop all of its JSON-RPC
1057  * connections and reconnect. */
1058 static void
1059 ovsdb_server_reconnect(struct unixctl_conn *conn, int argc OVS_UNUSED,
1060                        const char *argv[] OVS_UNUSED, void *jsonrpc_)
1061 {
1062     struct ovsdb_jsonrpc_server *jsonrpc = jsonrpc_;
1063
1064     ovsdb_jsonrpc_server_reconnect(jsonrpc);
1065     unixctl_command_reply(conn, NULL);
1066 }
1067
1068 /* "ovsdb-server/add-remote REMOTE": adds REMOTE to the set of remotes that
1069  * ovsdb-server services. */
1070 static void
1071 ovsdb_server_add_remote(struct unixctl_conn *conn, int argc OVS_UNUSED,
1072                         const char *argv[], void *config_)
1073 {
1074     struct server_config *config = config_;
1075     const char *remote = argv[1];
1076
1077     const struct ovsdb_column *column;
1078     const struct ovsdb_table *table;
1079     const struct db *db;
1080     char *retval;
1081
1082     retval = (strncmp("db:", remote, 3)
1083               ? NULL
1084               : parse_db_column(config->all_dbs, remote,
1085                                 &db, &table, &column));
1086     if (!retval) {
1087         if (sset_add(config->remotes, remote)) {
1088             save_config(config);
1089         }
1090         unixctl_command_reply(conn, NULL);
1091     } else {
1092         unixctl_command_reply_error(conn, retval);
1093         free(retval);
1094     }
1095 }
1096
1097 /* "ovsdb-server/remove-remote REMOTE": removes REMOTE frmo the set of remotes
1098  * that ovsdb-server services. */
1099 static void
1100 ovsdb_server_remove_remote(struct unixctl_conn *conn, int argc OVS_UNUSED,
1101                            const char *argv[], void *config_)
1102 {
1103     struct server_config *config = config_;
1104     struct sset_node *node;
1105
1106     node = sset_find(config->remotes, argv[1]);
1107     if (node) {
1108         sset_delete(config->remotes, node);
1109         save_config(config);
1110         unixctl_command_reply(conn, NULL);
1111     } else {
1112         unixctl_command_reply_error(conn, "no such remote");
1113     }
1114 }
1115
1116 /* "ovsdb-server/list-remotes": outputs a list of configured rmeotes. */
1117 static void
1118 ovsdb_server_list_remotes(struct unixctl_conn *conn, int argc OVS_UNUSED,
1119                           const char *argv[] OVS_UNUSED, void *remotes_)
1120 {
1121     struct sset *remotes = remotes_;
1122     const char **list, **p;
1123     struct ds s;
1124
1125     ds_init(&s);
1126
1127     list = sset_sort(remotes);
1128     for (p = list; *p; p++) {
1129         ds_put_format(&s, "%s\n", *p);
1130     }
1131     free(list);
1132
1133     unixctl_command_reply(conn, ds_cstr(&s));
1134     ds_destroy(&s);
1135 }
1136
1137
1138 /* "ovsdb-server/add-db DB": adds the DB to ovsdb-server. */
1139 static void
1140 ovsdb_server_add_database(struct unixctl_conn *conn, int argc OVS_UNUSED,
1141                           const char *argv[], void *config_)
1142 {
1143     struct server_config *config = config_;
1144     const char *filename = argv[1];
1145     char *error;
1146
1147     error = open_db(config, filename);
1148     if (!error) {
1149         save_config(config);
1150         unixctl_command_reply(conn, NULL);
1151     } else {
1152         unixctl_command_reply_error(conn, error);
1153         free(error);
1154     }
1155 }
1156
1157 static void
1158 ovsdb_server_remove_database(struct unixctl_conn *conn, int argc OVS_UNUSED,
1159                              const char *argv[], void *config_)
1160 {
1161     struct server_config *config = config_;
1162     struct shash_node *node;
1163     struct db *db;
1164     bool ok;
1165
1166     node = shash_find(config->all_dbs, argv[1]);
1167     if (!node)  {
1168         unixctl_command_reply_error(conn, "Failed to find the database.");
1169         return;
1170     }
1171     db = node->data;
1172
1173     ok = ovsdb_jsonrpc_server_remove_db(config->jsonrpc, db->db);
1174     ovs_assert(ok);
1175
1176     close_db(db);
1177     shash_delete(config->all_dbs, node);
1178
1179     save_config(config);
1180     unixctl_command_reply(conn, NULL);
1181 }
1182
1183 static void
1184 ovsdb_server_list_databases(struct unixctl_conn *conn, int argc OVS_UNUSED,
1185                             const char *argv[] OVS_UNUSED, void *all_dbs_)
1186 {
1187     struct shash *all_dbs = all_dbs_;
1188     const struct shash_node **nodes;
1189     struct ds s;
1190     size_t i;
1191
1192     ds_init(&s);
1193
1194     nodes = shash_sort(all_dbs);
1195     for (i = 0; i < shash_count(all_dbs); i++) {
1196         struct db *db = nodes[i]->data;
1197         ds_put_format(&s, "%s\n", db->db->schema->name);
1198     }
1199     free(nodes);
1200
1201     unixctl_command_reply(conn, ds_cstr(&s));
1202     ds_destroy(&s);
1203 }
1204
1205 static void
1206 parse_options(int *argcp, char **argvp[],
1207               struct sset *remotes, char **unixctl_pathp, char **run_command)
1208 {
1209     enum {
1210         OPT_REMOTE = UCHAR_MAX + 1,
1211         OPT_UNIXCTL,
1212         OPT_RUN,
1213         OPT_BOOTSTRAP_CA_CERT,
1214         OPT_ENABLE_DUMMY,
1215         VLOG_OPTION_ENUMS,
1216         DAEMON_OPTION_ENUMS
1217     };
1218     static const struct option long_options[] = {
1219         {"remote",      required_argument, NULL, OPT_REMOTE},
1220         {"unixctl",     required_argument, NULL, OPT_UNIXCTL},
1221 #ifndef _WIN32
1222         {"run",         required_argument, NULL, OPT_RUN},
1223 #endif
1224         {"help",        no_argument, NULL, 'h'},
1225         {"version",     no_argument, NULL, 'V'},
1226         DAEMON_LONG_OPTIONS,
1227         VLOG_LONG_OPTIONS,
1228         {"bootstrap-ca-cert", required_argument, NULL, OPT_BOOTSTRAP_CA_CERT},
1229         {"private-key", required_argument, NULL, 'p'},
1230         {"certificate", required_argument, NULL, 'c'},
1231         {"ca-cert",     required_argument, NULL, 'C'},
1232         {"enable-dummy", optional_argument, NULL, OPT_ENABLE_DUMMY},
1233         {NULL, 0, NULL, 0},
1234     };
1235     char *short_options = long_options_to_short_options(long_options);
1236     int argc = *argcp;
1237     char **argv = *argvp;
1238
1239     sset_init(remotes);
1240     for (;;) {
1241         int c;
1242
1243         c = getopt_long(argc, argv, short_options, long_options, NULL);
1244         if (c == -1) {
1245             break;
1246         }
1247
1248         switch (c) {
1249         case OPT_REMOTE:
1250             sset_add(remotes, optarg);
1251             break;
1252
1253         case OPT_UNIXCTL:
1254             *unixctl_pathp = optarg;
1255             break;
1256
1257         case OPT_RUN:
1258             *run_command = optarg;
1259             break;
1260
1261         case 'h':
1262             usage();
1263
1264         case 'V':
1265             ovs_print_version(0, 0);
1266             exit(EXIT_SUCCESS);
1267
1268         VLOG_OPTION_HANDLERS
1269         DAEMON_OPTION_HANDLERS
1270
1271         case 'p':
1272             private_key_file = optarg;
1273             break;
1274
1275         case 'c':
1276             certificate_file = optarg;
1277             break;
1278
1279         case 'C':
1280             ca_cert_file = optarg;
1281             bootstrap_ca_cert = false;
1282             break;
1283
1284         case OPT_BOOTSTRAP_CA_CERT:
1285             ca_cert_file = optarg;
1286             bootstrap_ca_cert = true;
1287             break;
1288
1289         case OPT_ENABLE_DUMMY:
1290             dummy_enable(optarg && !strcmp(optarg, "override"));
1291             break;
1292
1293         case '?':
1294             exit(EXIT_FAILURE);
1295
1296         default:
1297             abort();
1298         }
1299     }
1300     free(short_options);
1301
1302     *argcp -= optind;
1303     *argvp += optind;
1304 }
1305
1306 static void
1307 usage(void)
1308 {
1309     printf("%s: Open vSwitch database server\n"
1310            "usage: %s [OPTIONS] [DATABASE...]\n"
1311            "where each DATABASE is a database file in ovsdb format.\n"
1312            "The default DATABASE, if none is given, is\n%s/conf.db.\n",
1313            program_name, program_name, ovs_dbdir());
1314     printf("\nJSON-RPC options (may be specified any number of times):\n"
1315            "  --remote=REMOTE         connect or listen to REMOTE\n");
1316     stream_usage("JSON-RPC", true, true, true);
1317     daemon_usage();
1318     vlog_usage();
1319     printf("\nOther options:\n"
1320            "  --run COMMAND           run COMMAND as subprocess then exit\n"
1321            "  --unixctl=SOCKET        override default control socket name\n"
1322            "  -h, --help              display this help message\n"
1323            "  -V, --version           display version information\n");
1324     exit(EXIT_SUCCESS);
1325 }
1326 \f
1327 static struct json *
1328 sset_to_json(const struct sset *sset)
1329 {
1330     struct json *array;
1331     const char *s;
1332
1333     array = json_array_create_empty();
1334     SSET_FOR_EACH (s, sset) {
1335         json_array_add(array, json_string_create(s));
1336     }
1337     return array;
1338 }
1339
1340 /* Truncates and replaces the contents of 'config_file' by a representation of
1341  * 'remotes' and 'db_filenames'. */
1342 static void
1343 save_config__(FILE *config_file, const struct sset *remotes,
1344               const struct sset *db_filenames)
1345 {
1346     struct json *obj;
1347     char *s;
1348
1349     if (ftruncate(fileno(config_file), 0) == -1) {
1350         VLOG_FATAL("failed to truncate temporary file (%s)",
1351                    ovs_strerror(errno));
1352     }
1353
1354     obj = json_object_create();
1355     json_object_put(obj, "remotes", sset_to_json(remotes));
1356     json_object_put(obj, "db_filenames", sset_to_json(db_filenames));
1357     s = json_to_string(obj, 0);
1358     json_destroy(obj);
1359
1360     if (fseek(config_file, 0, SEEK_SET) != 0
1361         || fputs(s, config_file) == EOF
1362         || fflush(config_file) == EOF) {
1363         VLOG_FATAL("failed to write temporary file (%s)", ovs_strerror(errno));
1364     }
1365     free(s);
1366 }
1367
1368 /* Truncates and replaces the contents of 'config_file' by a representation of
1369  * 'config'. */
1370 static void
1371 save_config(struct server_config *config)
1372 {
1373     struct sset db_filenames;
1374     struct shash_node *node;
1375
1376     sset_init(&db_filenames);
1377     SHASH_FOR_EACH (node, config->all_dbs) {
1378         struct db *db = node->data;
1379         sset_add(&db_filenames, db->filename);
1380     }
1381
1382     save_config__(config->config_tmpfile, config->remotes, &db_filenames);
1383
1384     sset_destroy(&db_filenames);
1385 }
1386
1387 static void
1388 sset_from_json(struct sset *sset, const struct json *array)
1389 {
1390     size_t i;
1391
1392     sset_clear(sset);
1393
1394     ovs_assert(array->type == JSON_ARRAY);
1395     for (i = 0; i < array->u.array.n; i++) {
1396         const struct json *elem = array->u.array.elems[i];
1397         sset_add(sset, json_string(elem));
1398     }
1399 }
1400
1401 /* Clears and replaces 'remotes' and 'dbnames' by a configuration read from
1402  * 'config_file', which must have been previously written by save_config(). */
1403 static void
1404 load_config(FILE *config_file, struct sset *remotes, struct sset *db_filenames)
1405 {
1406     struct json *json;
1407
1408     if (fseek(config_file, 0, SEEK_SET) != 0) {
1409         VLOG_FATAL("seek failed in temporary file (%s)", ovs_strerror(errno));
1410     }
1411     json = json_from_stream(config_file);
1412     if (json->type == JSON_STRING) {
1413         VLOG_FATAL("reading json failed (%s)", json_string(json));
1414     }
1415     ovs_assert(json->type == JSON_OBJECT);
1416
1417     sset_from_json(remotes, shash_find_data(json_object(json), "remotes"));
1418     sset_from_json(db_filenames,
1419                    shash_find_data(json_object(json), "db_filenames"));
1420     json_destroy(json);
1421 }