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