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