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