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