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