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