netflow: Fix interpretation of flow_seq.
[cascardo/ovs.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             free(retval);
523             return NULL;
524         }
525
526         HMAP_FOR_EACH (row, hmap_node, &table->rows) {
527             const struct ovsdb_datum *datum;
528             size_t i;
529
530             datum = &row->fields[column->index];
531             for (i = 0; i < datum->n; i++) {
532                 if (datum->keys[i].string[0]) {
533                     return datum->keys[i].string;
534                 }
535             }
536         }
537         return NULL;
538     }
539 }
540
541 static struct ovsdb_jsonrpc_options *
542 add_remote(struct shash *remotes, const char *target)
543 {
544     struct ovsdb_jsonrpc_options *options;
545
546     options = shash_find_data(remotes, target);
547     if (!options) {
548         options = ovsdb_jsonrpc_default_options(target);
549         shash_add(remotes, target, options);
550     }
551
552     return options;
553 }
554
555 static struct ovsdb_datum *
556 get_datum(struct ovsdb_row *row, const char *column_name,
557           const enum ovsdb_atomic_type key_type,
558           const enum ovsdb_atomic_type value_type,
559           const size_t n_max)
560 {
561     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
562     const struct ovsdb_table_schema *schema = row->table->schema;
563     const struct ovsdb_column *column;
564
565     column = ovsdb_table_schema_get_column(schema, column_name);
566     if (!column) {
567         VLOG_DBG_RL(&rl, "Table `%s' has no `%s' column",
568                     schema->name, column_name);
569         return NULL;
570     }
571
572     if (column->type.key.type != key_type
573         || column->type.value.type != value_type
574         || column->type.n_max != n_max) {
575         if (!VLOG_DROP_DBG(&rl)) {
576             char *type_name = ovsdb_type_to_english(&column->type);
577             VLOG_DBG("Table `%s' column `%s' has type %s, not expected "
578                      "key type %s, value type %s, max elements %"PRIuSIZE".",
579                      schema->name, column_name, type_name,
580                      ovsdb_atomic_type_to_string(key_type),
581                      ovsdb_atomic_type_to_string(value_type),
582                      n_max);
583             free(type_name);
584         }
585         return NULL;
586     }
587
588     return &row->fields[column->index];
589 }
590
591 /* Read string-string key-values from a map.  Returns the value associated with
592  * 'key', if found, or NULL */
593 static const char *
594 read_map_string_column(const struct ovsdb_row *row, const char *column_name,
595                        const char *key)
596 {
597     const struct ovsdb_datum *datum;
598     union ovsdb_atom *atom_key = NULL, *atom_value = NULL;
599     size_t i;
600
601     datum = get_datum(CONST_CAST(struct ovsdb_row *, row), column_name,
602                       OVSDB_TYPE_STRING, OVSDB_TYPE_STRING, UINT_MAX);
603
604     if (!datum) {
605         return NULL;
606     }
607
608     for (i = 0; i < datum->n; i++) {
609         atom_key = &datum->keys[i];
610         if (!strcmp(atom_key->string, key)){
611             atom_value = &datum->values[i];
612             break;
613         }
614     }
615
616     return atom_value ? atom_value->string : NULL;
617 }
618
619 static const union ovsdb_atom *
620 read_column(const struct ovsdb_row *row, const char *column_name,
621             enum ovsdb_atomic_type type)
622 {
623     const struct ovsdb_datum *datum;
624
625     datum = get_datum(CONST_CAST(struct ovsdb_row *, row), column_name, type,
626                       OVSDB_TYPE_VOID, 1);
627     return datum && datum->n ? datum->keys : NULL;
628 }
629
630 static bool
631 read_integer_column(const struct ovsdb_row *row, const char *column_name,
632                     long long int *integerp)
633 {
634     const union ovsdb_atom *atom;
635
636     atom = read_column(row, column_name, OVSDB_TYPE_INTEGER);
637     *integerp = atom ? atom->integer : 0;
638     return atom != NULL;
639 }
640
641 static bool
642 read_string_column(const struct ovsdb_row *row, const char *column_name,
643                    const char **stringp)
644 {
645     const union ovsdb_atom *atom;
646
647     atom = read_column(row, column_name, OVSDB_TYPE_STRING);
648     *stringp = atom ? atom->string : NULL;
649     return atom != NULL;
650 }
651
652 static void
653 write_bool_column(struct ovsdb_row *row, const char *column_name, bool value)
654 {
655     const struct ovsdb_column *column;
656     struct ovsdb_datum *datum;
657
658     column = ovsdb_table_schema_get_column(row->table->schema, column_name);
659     datum = get_datum(row, column_name, OVSDB_TYPE_BOOLEAN,
660                       OVSDB_TYPE_VOID, 1);
661     if (!datum) {
662         return;
663     }
664
665     if (datum->n != 1) {
666         ovsdb_datum_destroy(datum, &column->type);
667
668         datum->n = 1;
669         datum->keys = xmalloc(sizeof *datum->keys);
670         datum->values = NULL;
671     }
672
673     datum->keys[0].boolean = value;
674 }
675
676 static void
677 write_string_string_column(struct ovsdb_row *row, const char *column_name,
678                            char **keys, char **values, size_t n)
679 {
680     const struct ovsdb_column *column;
681     struct ovsdb_datum *datum;
682     size_t i;
683
684     column = ovsdb_table_schema_get_column(row->table->schema, column_name);
685     datum = get_datum(row, column_name, OVSDB_TYPE_STRING, OVSDB_TYPE_STRING,
686                       UINT_MAX);
687     if (!datum) {
688         for (i = 0; i < n; i++) {
689             free(keys[i]);
690             free(values[i]);
691         }
692         return;
693     }
694
695     /* Free existing data. */
696     ovsdb_datum_destroy(datum, &column->type);
697
698     /* Allocate space for new values. */
699     datum->n = n;
700     datum->keys = xmalloc(n * sizeof *datum->keys);
701     datum->values = xmalloc(n * sizeof *datum->values);
702
703     for (i = 0; i < n; ++i) {
704         datum->keys[i].string = keys[i];
705         datum->values[i].string = values[i];
706     }
707
708     /* Sort and check constraints. */
709     ovsdb_datum_sort_assert(datum, column->type.key.type);
710 }
711
712 /* Adds a remote and options to 'remotes', based on the Manager table row in
713  * 'row'. */
714 static void
715 add_manager_options(struct shash *remotes, const struct ovsdb_row *row)
716 {
717     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
718     struct ovsdb_jsonrpc_options *options;
719     long long int max_backoff, probe_interval;
720     const char *target, *dscp_string;
721
722     if (!read_string_column(row, "target", &target) || !target) {
723         VLOG_INFO_RL(&rl, "Table `%s' has missing or invalid `target' column",
724                      row->table->schema->name);
725         return;
726     }
727
728     options = add_remote(remotes, target);
729     if (read_integer_column(row, "max_backoff", &max_backoff)) {
730         options->max_backoff = max_backoff;
731     }
732     if (read_integer_column(row, "inactivity_probe", &probe_interval)) {
733         options->probe_interval = probe_interval;
734     }
735
736     options->dscp = DSCP_DEFAULT;
737     dscp_string = read_map_string_column(row, "other_config", "dscp");
738     if (dscp_string) {
739         int dscp = atoi(dscp_string);
740         if (dscp >= 0 && dscp <= 63) {
741             options->dscp = dscp;
742         }
743     }
744 }
745
746 static void
747 query_db_remotes(const char *name, const struct shash *all_dbs,
748                  struct shash *remotes, struct ds *errors)
749 {
750     const struct ovsdb_column *column;
751     const struct ovsdb_table *table;
752     const struct ovsdb_row *row;
753     const struct db *db;
754     char *retval;
755
756     retval = parse_db_column(all_dbs, name, &db, &table, &column);
757     if (retval) {
758         ds_put_format(errors, "%s\n", retval);
759         free(retval);
760         return;
761     }
762
763     if (column->type.key.type == OVSDB_TYPE_STRING
764         && column->type.value.type == OVSDB_TYPE_VOID) {
765         HMAP_FOR_EACH (row, hmap_node, &table->rows) {
766             const struct ovsdb_datum *datum;
767             size_t i;
768
769             datum = &row->fields[column->index];
770             for (i = 0; i < datum->n; i++) {
771                 add_remote(remotes, datum->keys[i].string);
772             }
773         }
774     } else if (column->type.key.type == OVSDB_TYPE_UUID
775                && column->type.key.u.uuid.refTable
776                && column->type.value.type == OVSDB_TYPE_VOID) {
777         const struct ovsdb_table *ref_table = column->type.key.u.uuid.refTable;
778         HMAP_FOR_EACH (row, hmap_node, &table->rows) {
779             const struct ovsdb_datum *datum;
780             size_t i;
781
782             datum = &row->fields[column->index];
783             for (i = 0; i < datum->n; i++) {
784                 const struct ovsdb_row *ref_row;
785
786                 ref_row = ovsdb_table_get_row(ref_table, &datum->keys[i].uuid);
787                 if (ref_row) {
788                     add_manager_options(remotes, ref_row);
789                 }
790             }
791         }
792     }
793 }
794
795 static void
796 update_remote_row(const struct ovsdb_row *row, struct ovsdb_txn *txn,
797                   const struct ovsdb_jsonrpc_server *jsonrpc)
798 {
799     struct ovsdb_jsonrpc_remote_status status;
800     struct ovsdb_row *rw_row;
801     const char *target;
802     char *keys[9], *values[9];
803     size_t n = 0;
804
805     /* Get the "target" (protocol/host/port) spec. */
806     if (!read_string_column(row, "target", &target)) {
807         /* Bad remote spec or incorrect schema. */
808         return;
809     }
810     rw_row = ovsdb_txn_row_modify(txn, row);
811     ovsdb_jsonrpc_server_get_remote_status(jsonrpc, target, &status);
812
813     /* Update status information columns. */
814     write_bool_column(rw_row, "is_connected", status.is_connected);
815
816     if (status.state) {
817         keys[n] = xstrdup("state");
818         values[n++] = xstrdup(status.state);
819     }
820     if (status.sec_since_connect != UINT_MAX) {
821         keys[n] = xstrdup("sec_since_connect");
822         values[n++] = xasprintf("%u", status.sec_since_connect);
823     }
824     if (status.sec_since_disconnect != UINT_MAX) {
825         keys[n] = xstrdup("sec_since_disconnect");
826         values[n++] = xasprintf("%u", status.sec_since_disconnect);
827     }
828     if (status.last_error) {
829         keys[n] = xstrdup("last_error");
830         values[n++] =
831             xstrdup(ovs_retval_to_string(status.last_error));
832     }
833     if (status.locks_held && status.locks_held[0]) {
834         keys[n] = xstrdup("locks_held");
835         values[n++] = xstrdup(status.locks_held);
836     }
837     if (status.locks_waiting && status.locks_waiting[0]) {
838         keys[n] = xstrdup("locks_waiting");
839         values[n++] = xstrdup(status.locks_waiting);
840     }
841     if (status.locks_lost && status.locks_lost[0]) {
842         keys[n] = xstrdup("locks_lost");
843         values[n++] = xstrdup(status.locks_lost);
844     }
845     if (status.n_connections > 1) {
846         keys[n] = xstrdup("n_connections");
847         values[n++] = xasprintf("%d", status.n_connections);
848     }
849     if (status.bound_port != htons(0)) {
850         keys[n] = xstrdup("bound_port");
851         values[n++] = xasprintf("%"PRIu16, ntohs(status.bound_port));
852     }
853     write_string_string_column(rw_row, "status", keys, values, n);
854
855     ovsdb_jsonrpc_server_free_remote_status(&status);
856 }
857
858 static void
859 update_remote_rows(const struct shash *all_dbs,
860                    const char *remote_name,
861                    const struct ovsdb_jsonrpc_server *jsonrpc)
862 {
863     const struct ovsdb_table *table, *ref_table;
864     const struct ovsdb_column *column;
865     const struct ovsdb_row *row;
866     const struct db *db;
867     char *retval;
868
869     if (strncmp("db:", remote_name, 3)) {
870         return;
871     }
872
873     retval = parse_db_column(all_dbs, remote_name, &db, &table, &column);
874     if (retval) {
875         free(retval);
876         return;
877     }
878
879     if (column->type.key.type != OVSDB_TYPE_UUID
880         || !column->type.key.u.uuid.refTable
881         || column->type.value.type != OVSDB_TYPE_VOID) {
882         return;
883     }
884
885     ref_table = column->type.key.u.uuid.refTable;
886
887     HMAP_FOR_EACH (row, hmap_node, &table->rows) {
888         const struct ovsdb_datum *datum;
889         size_t i;
890
891         datum = &row->fields[column->index];
892         for (i = 0; i < datum->n; i++) {
893             const struct ovsdb_row *ref_row;
894
895             ref_row = ovsdb_table_get_row(ref_table, &datum->keys[i].uuid);
896             if (ref_row) {
897                 update_remote_row(ref_row, db->txn, jsonrpc);
898             }
899         }
900     }
901 }
902
903 static void
904 update_remote_status(const struct ovsdb_jsonrpc_server *jsonrpc,
905                      const struct sset *remotes,
906                      struct shash *all_dbs)
907 {
908     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
909     const char *remote;
910     struct db *db;
911     struct shash_node *node;
912
913     SHASH_FOR_EACH(node, all_dbs) {
914         db = node->data;
915         db->txn = ovsdb_txn_create(db->db);
916     }
917
918     /* Iterate over --remote arguments given on command line. */
919     SSET_FOR_EACH (remote, remotes) {
920         update_remote_rows(all_dbs, remote, jsonrpc);
921     }
922
923     SHASH_FOR_EACH(node, all_dbs) {
924         struct ovsdb_error *error;
925         db = node->data;
926         error = ovsdb_txn_commit(db->txn, false);
927         if (error) {
928             VLOG_ERR_RL(&rl, "Failed to update remote status: %s",
929                         ovsdb_error_to_string(error));
930             ovsdb_error_destroy(error);
931         }
932     }
933 }
934
935 /* Reconfigures ovsdb-server's remotes based on information in the database. */
936 static char *
937 reconfigure_remotes(struct ovsdb_jsonrpc_server *jsonrpc,
938                     const struct shash *all_dbs, struct sset *remotes)
939 {
940     struct ds errors = DS_EMPTY_INITIALIZER;
941     struct shash resolved_remotes;
942     const char *name;
943
944     /* Configure remotes. */
945     shash_init(&resolved_remotes);
946     SSET_FOR_EACH (name, remotes) {
947         if (!strncmp(name, "db:", 3)) {
948             query_db_remotes(name, all_dbs, &resolved_remotes, &errors);
949         } else {
950             add_remote(&resolved_remotes, name);
951         }
952     }
953     ovsdb_jsonrpc_server_set_remotes(jsonrpc, &resolved_remotes);
954     shash_destroy_free_data(&resolved_remotes);
955
956     return errors.string;
957 }
958
959 static char *
960 reconfigure_ssl(const struct shash *all_dbs)
961 {
962     struct ds errors = DS_EMPTY_INITIALIZER;
963     const char *resolved_private_key;
964     const char *resolved_certificate;
965     const char *resolved_ca_cert;
966
967     resolved_private_key = query_db_string(all_dbs, private_key_file, &errors);
968     resolved_certificate = query_db_string(all_dbs, certificate_file, &errors);
969     resolved_ca_cert = query_db_string(all_dbs, ca_cert_file, &errors);
970
971     stream_ssl_set_key_and_cert(resolved_private_key, resolved_certificate);
972     stream_ssl_set_ca_cert_file(resolved_ca_cert, bootstrap_ca_cert);
973
974     return errors.string;
975 }
976
977 static void
978 report_error_if_changed(char *error, char **last_errorp)
979 {
980     if (error) {
981         if (!*last_errorp || strcmp(error, *last_errorp)) {
982             VLOG_WARN("%s", error);
983             free(*last_errorp);
984             *last_errorp = error;
985             return;
986         }
987         free(error);
988     } else {
989         free(*last_errorp);
990         *last_errorp = NULL;
991     }
992 }
993
994 static void
995 ovsdb_server_exit(struct unixctl_conn *conn, int argc OVS_UNUSED,
996                   const char *argv[] OVS_UNUSED,
997                   void *exiting_)
998 {
999     bool *exiting = exiting_;
1000     *exiting = true;
1001     unixctl_command_reply(conn, NULL);
1002 }
1003
1004 static void
1005 ovsdb_server_compact(struct unixctl_conn *conn, int argc,
1006                      const char *argv[], void *dbs_)
1007 {
1008     struct shash *all_dbs = dbs_;
1009     struct ds reply;
1010     struct db *db;
1011     struct shash_node *node;
1012     int n = 0;
1013
1014     ds_init(&reply);
1015     SHASH_FOR_EACH(node, all_dbs) {
1016         const char *name;
1017
1018         db = node->data;
1019         name = db->db->schema->name;
1020
1021         if (argc < 2 || !strcmp(argv[1], name)) {
1022             struct ovsdb_error *error;
1023
1024             VLOG_INFO("compacting %s database by user request", name);
1025
1026             error = ovsdb_file_compact(db->file);
1027             if (error) {
1028                 char *s = ovsdb_error_to_string(error);
1029                 ds_put_format(&reply, "%s\n", s);
1030                 free(s);
1031                 ovsdb_error_destroy(error);
1032             }
1033
1034             n++;
1035         }
1036     }
1037
1038     if (!n) {
1039         unixctl_command_reply_error(conn, "no database by that name");
1040     } else if (reply.length) {
1041         unixctl_command_reply_error(conn, ds_cstr(&reply));
1042     } else {
1043         unixctl_command_reply(conn, NULL);
1044     }
1045     ds_destroy(&reply);
1046 }
1047
1048 /* "ovsdb-server/reconnect": makes ovsdb-server drop all of its JSON-RPC
1049  * connections and reconnect. */
1050 static void
1051 ovsdb_server_reconnect(struct unixctl_conn *conn, int argc OVS_UNUSED,
1052                        const char *argv[] OVS_UNUSED, void *jsonrpc_)
1053 {
1054     struct ovsdb_jsonrpc_server *jsonrpc = jsonrpc_;
1055
1056     ovsdb_jsonrpc_server_reconnect(jsonrpc);
1057     unixctl_command_reply(conn, NULL);
1058 }
1059
1060 /* "ovsdb-server/add-remote REMOTE": adds REMOTE to the set of remotes that
1061  * ovsdb-server services. */
1062 static void
1063 ovsdb_server_add_remote(struct unixctl_conn *conn, int argc OVS_UNUSED,
1064                         const char *argv[], void *config_)
1065 {
1066     struct server_config *config = config_;
1067     const char *remote = argv[1];
1068
1069     const struct ovsdb_column *column;
1070     const struct ovsdb_table *table;
1071     const struct db *db;
1072     char *retval;
1073
1074     retval = (strncmp("db:", remote, 3)
1075               ? NULL
1076               : parse_db_column(config->all_dbs, remote,
1077                                 &db, &table, &column));
1078     if (!retval) {
1079         if (sset_add(config->remotes, remote)) {
1080             save_config(config);
1081         }
1082         unixctl_command_reply(conn, NULL);
1083     } else {
1084         unixctl_command_reply_error(conn, retval);
1085         free(retval);
1086     }
1087 }
1088
1089 /* "ovsdb-server/remove-remote REMOTE": removes REMOTE frmo the set of remotes
1090  * that ovsdb-server services. */
1091 static void
1092 ovsdb_server_remove_remote(struct unixctl_conn *conn, int argc OVS_UNUSED,
1093                            const char *argv[], void *config_)
1094 {
1095     struct server_config *config = config_;
1096     struct sset_node *node;
1097
1098     node = sset_find(config->remotes, argv[1]);
1099     if (node) {
1100         sset_delete(config->remotes, node);
1101         save_config(config);
1102         unixctl_command_reply(conn, NULL);
1103     } else {
1104         unixctl_command_reply_error(conn, "no such remote");
1105     }
1106 }
1107
1108 /* "ovsdb-server/list-remotes": outputs a list of configured rmeotes. */
1109 static void
1110 ovsdb_server_list_remotes(struct unixctl_conn *conn, int argc OVS_UNUSED,
1111                           const char *argv[] OVS_UNUSED, void *remotes_)
1112 {
1113     struct sset *remotes = remotes_;
1114     const char **list, **p;
1115     struct ds s;
1116
1117     ds_init(&s);
1118
1119     list = sset_sort(remotes);
1120     for (p = list; *p; p++) {
1121         ds_put_format(&s, "%s\n", *p);
1122     }
1123     free(list);
1124
1125     unixctl_command_reply(conn, ds_cstr(&s));
1126     ds_destroy(&s);
1127 }
1128
1129
1130 /* "ovsdb-server/add-db DB": adds the DB to ovsdb-server. */
1131 static void
1132 ovsdb_server_add_database(struct unixctl_conn *conn, int argc OVS_UNUSED,
1133                           const char *argv[], void *config_)
1134 {
1135     struct server_config *config = config_;
1136     const char *filename = argv[1];
1137     char *error;
1138
1139     error = open_db(config, filename);
1140     if (!error) {
1141         save_config(config);
1142         unixctl_command_reply(conn, NULL);
1143     } else {
1144         unixctl_command_reply_error(conn, error);
1145         free(error);
1146     }
1147 }
1148
1149 static void
1150 ovsdb_server_remove_database(struct unixctl_conn *conn, int argc OVS_UNUSED,
1151                              const char *argv[], void *config_)
1152 {
1153     struct server_config *config = config_;
1154     struct shash_node *node;
1155     struct db *db;
1156     bool ok;
1157
1158     node = shash_find(config->all_dbs, argv[1]);
1159     if (!node)  {
1160         unixctl_command_reply_error(conn, "Failed to find the database.");
1161         return;
1162     }
1163     db = node->data;
1164
1165     ok = ovsdb_jsonrpc_server_remove_db(config->jsonrpc, db->db);
1166     ovs_assert(ok);
1167
1168     ovsdb_destroy(db->db);
1169     shash_delete(config->all_dbs, node);
1170     free(db->filename);
1171     free(db);
1172
1173     save_config(config);
1174     unixctl_command_reply(conn, NULL);
1175 }
1176
1177 static void
1178 ovsdb_server_list_databases(struct unixctl_conn *conn, int argc OVS_UNUSED,
1179                             const char *argv[] OVS_UNUSED, void *all_dbs_)
1180 {
1181     struct shash *all_dbs = all_dbs_;
1182     const struct shash_node **nodes;
1183     struct ds s;
1184     size_t i;
1185
1186     ds_init(&s);
1187
1188     nodes = shash_sort(all_dbs);
1189     for (i = 0; i < shash_count(all_dbs); i++) {
1190         struct db *db = nodes[i]->data;
1191         ds_put_format(&s, "%s\n", db->db->schema->name);
1192     }
1193     free(nodes);
1194
1195     unixctl_command_reply(conn, ds_cstr(&s));
1196     ds_destroy(&s);
1197 }
1198
1199 static void
1200 parse_options(int *argcp, char **argvp[],
1201               struct sset *remotes, char **unixctl_pathp, char **run_command)
1202 {
1203     enum {
1204         OPT_REMOTE = UCHAR_MAX + 1,
1205         OPT_UNIXCTL,
1206         OPT_RUN,
1207         OPT_BOOTSTRAP_CA_CERT,
1208         OPT_ENABLE_DUMMY,
1209         VLOG_OPTION_ENUMS,
1210         DAEMON_OPTION_ENUMS
1211     };
1212     static const struct option long_options[] = {
1213         {"remote",      required_argument, NULL, OPT_REMOTE},
1214         {"unixctl",     required_argument, NULL, OPT_UNIXCTL},
1215 #ifndef _WIN32
1216         {"run",         required_argument, NULL, OPT_RUN},
1217 #endif
1218         {"help",        no_argument, NULL, 'h'},
1219         {"version",     no_argument, NULL, 'V'},
1220         DAEMON_LONG_OPTIONS,
1221         VLOG_LONG_OPTIONS,
1222         {"bootstrap-ca-cert", required_argument, NULL, OPT_BOOTSTRAP_CA_CERT},
1223         {"private-key", required_argument, NULL, 'p'},
1224         {"certificate", required_argument, NULL, 'c'},
1225         {"ca-cert",     required_argument, NULL, 'C'},
1226         {"enable-dummy", optional_argument, NULL, OPT_ENABLE_DUMMY},
1227         {NULL, 0, NULL, 0},
1228     };
1229     char *short_options = long_options_to_short_options(long_options);
1230     int argc = *argcp;
1231     char **argv = *argvp;
1232
1233     sset_init(remotes);
1234     for (;;) {
1235         int c;
1236
1237         c = getopt_long(argc, argv, short_options, long_options, NULL);
1238         if (c == -1) {
1239             break;
1240         }
1241
1242         switch (c) {
1243         case OPT_REMOTE:
1244             sset_add(remotes, optarg);
1245             break;
1246
1247         case OPT_UNIXCTL:
1248             *unixctl_pathp = optarg;
1249             break;
1250
1251         case OPT_RUN:
1252             *run_command = optarg;
1253             break;
1254
1255         case 'h':
1256             usage();
1257
1258         case 'V':
1259             ovs_print_version(0, 0);
1260             exit(EXIT_SUCCESS);
1261
1262         VLOG_OPTION_HANDLERS
1263         DAEMON_OPTION_HANDLERS
1264
1265         case 'p':
1266             private_key_file = optarg;
1267             break;
1268
1269         case 'c':
1270             certificate_file = optarg;
1271             break;
1272
1273         case 'C':
1274             ca_cert_file = optarg;
1275             bootstrap_ca_cert = false;
1276             break;
1277
1278         case OPT_BOOTSTRAP_CA_CERT:
1279             ca_cert_file = optarg;
1280             bootstrap_ca_cert = true;
1281             break;
1282
1283         case OPT_ENABLE_DUMMY:
1284             dummy_enable(optarg && !strcmp(optarg, "override"));
1285             break;
1286
1287         case '?':
1288             exit(EXIT_FAILURE);
1289
1290         default:
1291             abort();
1292         }
1293     }
1294     free(short_options);
1295
1296     *argcp -= optind;
1297     *argvp += optind;
1298 }
1299
1300 static void
1301 usage(void)
1302 {
1303     printf("%s: Open vSwitch database server\n"
1304            "usage: %s [OPTIONS] [DATABASE...]\n"
1305            "where each DATABASE is a database file in ovsdb format.\n"
1306            "The default DATABASE, if none is given, is\n%s/conf.db.\n",
1307            program_name, program_name, ovs_dbdir());
1308     printf("\nJSON-RPC options (may be specified any number of times):\n"
1309            "  --remote=REMOTE         connect or listen to REMOTE\n");
1310     stream_usage("JSON-RPC", true, true, true);
1311     daemon_usage();
1312     vlog_usage();
1313     printf("\nOther options:\n"
1314            "  --run COMMAND           run COMMAND as subprocess then exit\n"
1315            "  --unixctl=SOCKET        override default control socket name\n"
1316            "  -h, --help              display this help message\n"
1317            "  -V, --version           display version information\n");
1318     exit(EXIT_SUCCESS);
1319 }
1320 \f
1321 static struct json *
1322 sset_to_json(const struct sset *sset)
1323 {
1324     struct json *array;
1325     const char *s;
1326
1327     array = json_array_create_empty();
1328     SSET_FOR_EACH (s, sset) {
1329         json_array_add(array, json_string_create(s));
1330     }
1331     return array;
1332 }
1333
1334 /* Truncates and replaces the contents of 'config_file' by a representation of
1335  * 'remotes' and 'db_filenames'. */
1336 static void
1337 save_config__(FILE *config_file, const struct sset *remotes,
1338               const struct sset *db_filenames)
1339 {
1340     struct json *obj;
1341     char *s;
1342
1343     if (ftruncate(fileno(config_file), 0) == -1) {
1344         VLOG_FATAL("failed to truncate temporary file (%s)",
1345                    ovs_strerror(errno));
1346     }
1347
1348     obj = json_object_create();
1349     json_object_put(obj, "remotes", sset_to_json(remotes));
1350     json_object_put(obj, "db_filenames", sset_to_json(db_filenames));
1351     s = json_to_string(obj, 0);
1352     json_destroy(obj);
1353
1354     if (fseek(config_file, 0, SEEK_SET) != 0
1355         || fputs(s, config_file) == EOF
1356         || fflush(config_file) == EOF) {
1357         VLOG_FATAL("failed to write temporary file (%s)", ovs_strerror(errno));
1358     }
1359     free(s);
1360 }
1361
1362 /* Truncates and replaces the contents of 'config_file' by a representation of
1363  * 'config'. */
1364 static void
1365 save_config(struct server_config *config)
1366 {
1367     struct sset db_filenames;
1368     struct shash_node *node;
1369
1370     sset_init(&db_filenames);
1371     SHASH_FOR_EACH (node, config->all_dbs) {
1372         struct db *db = node->data;
1373         sset_add(&db_filenames, db->filename);
1374     }
1375
1376     save_config__(config->config_tmpfile, config->remotes, &db_filenames);
1377
1378     sset_destroy(&db_filenames);
1379 }
1380
1381 static void
1382 sset_from_json(struct sset *sset, const struct json *array)
1383 {
1384     size_t i;
1385
1386     sset_clear(sset);
1387
1388     ovs_assert(array->type == JSON_ARRAY);
1389     for (i = 0; i < array->u.array.n; i++) {
1390         const struct json *elem = array->u.array.elems[i];
1391         sset_add(sset, json_string(elem));
1392     }
1393 }
1394
1395 /* Clears and replaces 'remotes' and 'dbnames' by a configuration read from
1396  * 'config_file', which must have been previously written by save_config(). */
1397 static void
1398 load_config(FILE *config_file, struct sset *remotes, struct sset *db_filenames)
1399 {
1400     struct json *json;
1401
1402     if (fseek(config_file, 0, SEEK_SET) != 0) {
1403         VLOG_FATAL("seek failed in temporary file (%s)", ovs_strerror(errno));
1404     }
1405     json = json_from_stream(config_file);
1406     if (json->type == JSON_STRING) {
1407         VLOG_FATAL("reading json failed (%s)", json_string(json));
1408     }
1409     ovs_assert(json->type == JSON_OBJECT);
1410
1411     sset_from_json(remotes, shash_find_data(json_object(json), "remotes"));
1412     sset_from_json(db_filenames,
1413                    shash_find_data(json_object(json), "db_filenames"));
1414     json_destroy(json);
1415 }