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