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