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