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