b114a5a8ace3ebaf49ae89001564b5ee805bb37d
[cascardo/ovs.git] / utilities / ovs-vsctl.c
1 /*
2  * Copyright (c) 2009, 2010, 2011, 2012, 2013, 2014, 2015 Nicira, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18
19 #include <ctype.h>
20 #include <errno.h>
21 #include <float.h>
22 #include <getopt.h>
23 #include <inttypes.h>
24 #include <signal.h>
25 #include <stdarg.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <unistd.h>
29
30 #include "db-ctl-base.h"
31
32 #include "command-line.h"
33 #include "compiler.h"
34 #include "dirs.h"
35 #include "dynamic-string.h"
36 #include "fatal-signal.h"
37 #include "hash.h"
38 #include "json.h"
39 #include "ovsdb-data.h"
40 #include "ovsdb-idl.h"
41 #include "poll-loop.h"
42 #include "process.h"
43 #include "stream.h"
44 #include "stream-ssl.h"
45 #include "smap.h"
46 #include "sset.h"
47 #include "svec.h"
48 #include "lib/vswitch-idl.h"
49 #include "table.h"
50 #include "timeval.h"
51 #include "util.h"
52 #include "openvswitch/vconn.h"
53 #include "openvswitch/vlog.h"
54
55 VLOG_DEFINE_THIS_MODULE(vsctl);
56
57 struct vsctl_context;
58
59 /* --db: The database server to contact. */
60 static const char *db;
61
62 /* --oneline: Write each command's output as a single line? */
63 static bool oneline;
64
65 /* --dry-run: Do not commit any changes. */
66 static bool dry_run;
67
68 /* --no-wait: Wait for ovs-vswitchd to reload its configuration? */
69 static bool wait_for_reload = true;
70
71 /* --timeout: Time to wait for a connection to 'db'. */
72 static int timeout;
73
74 /* --retry: If true, ovs-vsctl will retry connecting to the database forever.
75  * If false and --db says to use an active connection method (e.g. "unix:",
76  * "tcp:", "ssl:"), then ovs-vsctl will try to connect once and exit with an
77  * error if the database server cannot be contacted (e.g. ovsdb-server is not
78  * running).
79  *
80  * Regardless of this setting, --timeout always limits how long ovs-vsctl will
81  * wait. */
82 static bool retry;
83
84 /* Format for table output. */
85 static struct table_style table_style = TABLE_STYLE_DEFAULT;
86
87 static void vsctl_cmd_init(void);
88 static char *default_db(void);
89 OVS_NO_RETURN static void usage(void);
90 OVS_NO_RETURN static void print_vsctl_commands(void);
91 OVS_NO_RETURN static void print_vsctl_options(const struct option *options);
92 static void parse_options(int argc, char *argv[], struct shash *local_options);
93 static void run_prerequisites(struct ctl_command[], size_t n_commands,
94                               struct ovsdb_idl *);
95 static void do_vsctl(const char *args, struct ctl_command *, size_t n,
96                      struct ovsdb_idl *);
97
98 /* post_db_reload_check frame work is to allow ovs-vsctl to do additional
99  * checks after OVSDB transactions are successfully recorded and reload by
100  * ovs-vswitchd.
101  *
102  * For example, When a new interface is added to OVSDB, ovs-vswitchd will
103  * either store a positive values on successful implementing the new
104  * interface, or -1 on failure.
105  *
106  * Unless -no-wait command line option is specified,
107  * post_db_reload_do_checks() is called right after any configuration
108  * changes is picked up (i.e. reload) by ovs-vswitchd. Any error detected
109  * post OVSDB reload is reported as ovs-vsctl errors. OVS-vswitchd logs
110  * more detailed messages about those errors.
111  *
112  * Current implementation only check for Post OVSDB reload failures on new
113  * interface additions with 'add-br' and 'add-port' commands.
114  *
115  * post_db_reload_expect_iface()
116  *
117  * keep track of interfaces to be checked post OVSDB reload. */
118 static void post_db_reload_check_init(void);
119 static void post_db_reload_do_checks(const struct vsctl_context *);
120 static void post_db_reload_expect_iface(const struct ovsrec_interface *);
121
122 static struct uuid *neoteric_ifaces;
123 static size_t n_neoteric_ifaces;
124 static size_t allocated_neoteric_ifaces;
125
126 int
127 main(int argc, char *argv[])
128 {
129     extern struct vlog_module VLM_reconnect;
130     struct ovsdb_idl *idl;
131     struct ctl_command *commands;
132     struct shash local_options;
133     unsigned int seqno;
134     size_t n_commands;
135     char *args;
136
137     set_program_name(argv[0]);
138     fatal_ignore_sigpipe();
139     vlog_set_levels(NULL, VLF_CONSOLE, VLL_WARN);
140     vlog_set_levels(&VLM_reconnect, VLF_ANY_DESTINATION, VLL_WARN);
141     ovsrec_init();
142
143     vsctl_cmd_init();
144
145     /* Log our arguments.  This is often valuable for debugging systems. */
146     args = process_escape_args(argv);
147     VLOG(ctl_might_write_to_db(argv) ? VLL_INFO : VLL_DBG, "Called as %s", args);
148
149     /* Parse command line. */
150     shash_init(&local_options);
151     parse_options(argc, argv, &local_options);
152     commands = ctl_parse_commands(argc - optind, argv + optind, &local_options,
153                                   &n_commands);
154
155     if (timeout) {
156         time_alarm(timeout);
157     }
158
159     /* Initialize IDL. */
160     idl = the_idl = ovsdb_idl_create(db, &ovsrec_idl_class, false, retry);
161     run_prerequisites(commands, n_commands, idl);
162
163     /* Execute the commands.
164      *
165      * 'seqno' is the database sequence number for which we last tried to
166      * execute our transaction.  There's no point in trying to commit more than
167      * once for any given sequence number, because if the transaction fails
168      * it's because the database changed and we need to obtain an up-to-date
169      * view of the database before we try the transaction again. */
170     seqno = ovsdb_idl_get_seqno(idl);
171     for (;;) {
172         ovsdb_idl_run(idl);
173         if (!ovsdb_idl_is_alive(idl)) {
174             int retval = ovsdb_idl_get_last_error(idl);
175             ctl_fatal("%s: database connection failed (%s)",
176                         db, ovs_retval_to_string(retval));
177         }
178
179         if (seqno != ovsdb_idl_get_seqno(idl)) {
180             seqno = ovsdb_idl_get_seqno(idl);
181             do_vsctl(args, commands, n_commands, idl);
182         }
183
184         if (seqno == ovsdb_idl_get_seqno(idl)) {
185             ovsdb_idl_wait(idl);
186             poll_block();
187         }
188     }
189 }
190
191 static struct option *
192 find_option(const char *name, struct option *options, size_t n_options)
193 {
194     size_t i;
195
196     for (i = 0; i < n_options; i++) {
197         if (!strcmp(options[i].name, name)) {
198             return &options[i];
199         }
200     }
201     return NULL;
202 }
203
204 static struct option *
205 add_option(struct option **optionsp, size_t *n_optionsp,
206            size_t *allocated_optionsp)
207 {
208     if (*n_optionsp >= *allocated_optionsp) {
209         *optionsp = x2nrealloc(*optionsp, allocated_optionsp,
210                                sizeof **optionsp);
211     }
212     return &(*optionsp)[(*n_optionsp)++];
213 }
214
215 static void
216 parse_options(int argc, char *argv[], struct shash *local_options)
217 {
218     enum {
219         OPT_DB = UCHAR_MAX + 1,
220         OPT_ONELINE,
221         OPT_NO_SYSLOG,
222         OPT_NO_WAIT,
223         OPT_DRY_RUN,
224         OPT_PEER_CA_CERT,
225         OPT_LOCAL,
226         OPT_RETRY,
227         OPT_COMMANDS,
228         OPT_OPTIONS,
229         VLOG_OPTION_ENUMS,
230         TABLE_OPTION_ENUMS
231     };
232     static const struct option global_long_options[] = {
233         {"db", required_argument, NULL, OPT_DB},
234         {"no-syslog", no_argument, NULL, OPT_NO_SYSLOG},
235         {"no-wait", no_argument, NULL, OPT_NO_WAIT},
236         {"dry-run", no_argument, NULL, OPT_DRY_RUN},
237         {"oneline", no_argument, NULL, OPT_ONELINE},
238         {"timeout", required_argument, NULL, 't'},
239         {"retry", no_argument, NULL, OPT_RETRY},
240         {"help", no_argument, NULL, 'h'},
241         {"commands", no_argument, NULL, OPT_COMMANDS},
242         {"options", no_argument, NULL, OPT_OPTIONS},
243         {"version", no_argument, NULL, 'V'},
244         VLOG_LONG_OPTIONS,
245         TABLE_LONG_OPTIONS,
246         STREAM_SSL_LONG_OPTIONS,
247         {"peer-ca-cert", required_argument, NULL, OPT_PEER_CA_CERT},
248         {NULL, 0, NULL, 0},
249     };
250     const int n_global_long_options = ARRAY_SIZE(global_long_options) - 1;
251     char *tmp, *short_options;
252
253     const struct shash_node *node;
254     struct option *options, *o;
255     size_t allocated_options;
256     size_t n_options;
257     size_t i;
258
259     tmp = ovs_cmdl_long_options_to_short_options(global_long_options);
260     short_options = xasprintf("+%s", tmp);
261     free(tmp);
262
263     /* We want to parse both global and command-specific options here, but
264      * getopt_long() isn't too convenient for the job.  We copy our global
265      * options into a dynamic array, then append all of the command-specific
266      * options. */
267     options = xmemdup(global_long_options, sizeof global_long_options);
268     allocated_options = ARRAY_SIZE(global_long_options);
269     n_options = n_global_long_options;
270     SHASH_FOR_EACH (node, ctl_get_all_commands()) {
271         const struct ctl_command_syntax *p = node->data;
272
273         if (p->options[0]) {
274             char *save_ptr = NULL;
275             char *name;
276             char *s;
277
278             s = xstrdup(p->options);
279             for (name = strtok_r(s, ",", &save_ptr); name != NULL;
280                  name = strtok_r(NULL, ",", &save_ptr)) {
281                 char *equals;
282                 int has_arg;
283
284                 ovs_assert(name[0] == '-' && name[1] == '-' && name[2]);
285                 name += 2;
286
287                 equals = strchr(name, '=');
288                 if (equals) {
289                     has_arg = required_argument;
290                     *equals = '\0';
291                 } else {
292                     has_arg = no_argument;
293                 }
294
295                 o = find_option(name, options, n_options);
296                 if (o) {
297                     ovs_assert(o - options >= n_global_long_options);
298                     ovs_assert(o->has_arg == has_arg);
299                 } else {
300                     o = add_option(&options, &n_options, &allocated_options);
301                     o->name = xstrdup(name);
302                     o->has_arg = has_arg;
303                     o->flag = NULL;
304                     o->val = OPT_LOCAL;
305                 }
306             }
307
308             free(s);
309         }
310     }
311     o = add_option(&options, &n_options, &allocated_options);
312     memset(o, 0, sizeof *o);
313
314     table_style.format = TF_LIST;
315
316     for (;;) {
317         int idx;
318         int c;
319
320         c = getopt_long(argc, argv, short_options, options, &idx);
321         if (c == -1) {
322             break;
323         }
324
325         switch (c) {
326         case OPT_DB:
327             db = optarg;
328             break;
329
330         case OPT_ONELINE:
331             oneline = true;
332             break;
333
334         case OPT_NO_SYSLOG:
335             vlog_set_levels(&VLM_vsctl, VLF_SYSLOG, VLL_WARN);
336             break;
337
338         case OPT_NO_WAIT:
339             wait_for_reload = false;
340             break;
341
342         case OPT_DRY_RUN:
343             dry_run = true;
344             break;
345
346         case OPT_LOCAL:
347             if (shash_find(local_options, options[idx].name)) {
348                 ctl_fatal("'%s' option specified multiple times",
349                             options[idx].name);
350             }
351             shash_add_nocopy(local_options,
352                              xasprintf("--%s", options[idx].name),
353                              optarg ? xstrdup(optarg) : NULL);
354             break;
355
356         case 'h':
357             usage();
358
359         case OPT_COMMANDS:
360             print_vsctl_commands();
361
362         case OPT_OPTIONS:
363             print_vsctl_options(global_long_options);
364
365         case 'V':
366             ovs_print_version(0, 0);
367             printf("DB Schema %s\n", ovsrec_get_db_version());
368             exit(EXIT_SUCCESS);
369
370         case 't':
371             timeout = strtoul(optarg, NULL, 10);
372             if (timeout < 0) {
373                 ctl_fatal("value %s on -t or --timeout is invalid",
374                             optarg);
375             }
376             break;
377
378         case OPT_RETRY:
379             retry = true;
380             break;
381
382         VLOG_OPTION_HANDLERS
383         TABLE_OPTION_HANDLERS(&table_style)
384
385         STREAM_SSL_OPTION_HANDLERS
386
387         case OPT_PEER_CA_CERT:
388             stream_ssl_set_peer_ca_cert_file(optarg);
389             break;
390
391         case '?':
392             exit(EXIT_FAILURE);
393
394         default:
395             abort();
396         }
397     }
398     free(short_options);
399
400     if (!db) {
401         db = default_db();
402     }
403
404     for (i = n_global_long_options; options[i].name; i++) {
405         free(CONST_CAST(char *, options[i].name));
406     }
407     free(options);
408 }
409
410 static void
411 usage(void)
412 {
413     printf("\
414 %s: ovs-vswitchd management utility\n\
415 usage: %s [OPTIONS] COMMAND [ARG...]\n\
416 \n\
417 Open vSwitch commands:\n\
418   init                        initialize database, if not yet initialized\n\
419   show                        print overview of database contents\n\
420   emer-reset                  reset configuration to clean state\n\
421 \n\
422 Bridge commands:\n\
423   add-br BRIDGE               create a new bridge named BRIDGE\n\
424   add-br BRIDGE PARENT VLAN   create new fake BRIDGE in PARENT on VLAN\n\
425   del-br BRIDGE               delete BRIDGE and all of its ports\n\
426   list-br                     print the names of all the bridges\n\
427   br-exists BRIDGE            exit 2 if BRIDGE does not exist\n\
428   br-to-vlan BRIDGE           print the VLAN which BRIDGE is on\n\
429   br-to-parent BRIDGE         print the parent of BRIDGE\n\
430   br-set-external-id BRIDGE KEY VALUE  set KEY on BRIDGE to VALUE\n\
431   br-set-external-id BRIDGE KEY  unset KEY on BRIDGE\n\
432   br-get-external-id BRIDGE KEY  print value of KEY on BRIDGE\n\
433   br-get-external-id BRIDGE  list key-value pairs on BRIDGE\n\
434 \n\
435 Port commands (a bond is considered to be a single port):\n\
436   list-ports BRIDGE           print the names of all the ports on BRIDGE\n\
437   add-port BRIDGE PORT        add network device PORT to BRIDGE\n\
438   add-bond BRIDGE PORT IFACE...  add bonded port PORT in BRIDGE from IFACES\n\
439   del-port [BRIDGE] PORT      delete PORT (which may be bonded) from BRIDGE\n\
440   port-to-br PORT             print name of bridge that contains PORT\n\
441 \n\
442 Interface commands (a bond consists of multiple interfaces):\n\
443   list-ifaces BRIDGE          print the names of all interfaces on BRIDGE\n\
444   iface-to-br IFACE           print name of bridge that contains IFACE\n\
445 \n\
446 Controller commands:\n\
447   get-controller BRIDGE      print the controllers for BRIDGE\n\
448   del-controller BRIDGE      delete the controllers for BRIDGE\n\
449   set-controller BRIDGE TARGET...  set the controllers for BRIDGE\n\
450   get-fail-mode BRIDGE       print the fail-mode for BRIDGE\n\
451   del-fail-mode BRIDGE       delete the fail-mode for BRIDGE\n\
452   set-fail-mode BRIDGE MODE  set the fail-mode for BRIDGE to MODE\n\
453 \n\
454 Manager commands:\n\
455   get-manager                print the managers\n\
456   del-manager                delete the managers\n\
457   set-manager TARGET...      set the list of managers to TARGET...\n\
458 \n\
459 SSL commands:\n\
460   get-ssl                     print the SSL configuration\n\
461   del-ssl                     delete the SSL configuration\n\
462   set-ssl PRIV-KEY CERT CA-CERT  set the SSL configuration\n\
463 \n\
464 Auto Attach commands:\n\
465   add-aa-mapping BRIDGE I-SID VLAN   add Auto Attach mapping to BRIDGE\n\
466   del-aa-mapping BRIDGE I-SID VLAN   delete Auto Attach mapping VLAN from BRIDGE\n\
467   get-aa-mapping BRIDGE              get Auto Attach mappings from BRIDGE\n\
468 \n\
469 Switch commands:\n\
470   emer-reset                  reset switch to known good state\n\
471 \n\
472 %s\
473 \n\
474 Options:\n\
475   --db=DATABASE               connect to DATABASE\n\
476                               (default: %s)\n\
477   --no-wait                   do not wait for ovs-vswitchd to reconfigure\n\
478   --retry                     keep trying to connect to server forever\n\
479   -t, --timeout=SECS          wait at most SECS seconds for ovs-vswitchd\n\
480   --dry-run                   do not commit changes to database\n\
481   --oneline                   print exactly one line of output per command\n",
482            program_name, program_name, ctl_get_db_cmd_usage(), default_db());
483     vlog_usage();
484     printf("\
485   --no-syslog             equivalent to --verbose=vsctl:syslog:warn\n");
486     stream_usage("database", true, true, false);
487     printf("\n\
488 Other options:\n\
489   -h, --help                  display this help message\n\
490   -V, --version               display version information\n");
491     exit(EXIT_SUCCESS);
492 }
493
494 /* Converts the command arguments into format that can be parsed by
495  * bash completion script.
496  *
497  * Therein, arguments will be attached with following prefixes:
498  *
499  *    !argument :: The argument is required
500  *    ?argument :: The argument is optional
501  *    *argument :: The argument may appear any number (0 or more) times
502  *    +argument :: The argument may appear one or more times
503  *
504  */
505 static void
506 print_command_arguments(const struct ctl_command_syntax *command)
507 {
508     /*
509      * The argument string is parsed in reverse.  We use a stack 'oew_stack' to
510      * keep track of nested optionals.  Whenever a ']' is encountered, we push
511      * a bit to 'oew_stack'.  The bit is set to 1 if the ']' is not nested.
512      * Subsequently, we pop an entry everytime '[' is met.
513      *
514      * We use 'whole_word_is_optional' value to decide whether or not a ! or +
515      * should be added on encountering a space: if the optional surrounds the
516      * whole word then it shouldn't be, but if it is only a part of the word
517      * (i.e. [key=]value), it should be.
518      */
519     uint32_t oew_stack = 0;
520
521     const char *arguments = command->arguments;
522     int length = strlen(arguments);
523     if (!length) {
524         return;
525     }
526
527     /* Output buffer, written backward from end. */
528     char *output = xmalloc(2 * length);
529     char *outp = output + 2 * length;
530     *--outp = '\0';
531
532     bool in_repeated = false;
533     bool whole_word_is_optional = false;
534
535     for (const char *inp = arguments + length; inp > arguments; ) {
536         switch (*--inp) {
537         case ']':
538             oew_stack <<= 1;
539             if (inp[1] == '\0' || inp[1] == ' ' || inp[1] == '.') {
540                 oew_stack |= 1;
541             }
542             break;
543         case '[':
544             /* Checks if the whole word is optional, and sets the
545              * 'whole_word_is_optional' accordingly. */
546             if ((inp == arguments || inp[-1] == ' ') && oew_stack & 1) {
547                 *--outp = in_repeated ? '*' : '?';
548                 whole_word_is_optional = true;
549             } else {
550                 *--outp = '?';
551                 whole_word_is_optional = false;
552             }
553             oew_stack >>= 1;
554             break;
555         case ' ':
556             if (!whole_word_is_optional) {
557                 *--outp = in_repeated ? '+' : '!';
558             }
559             *--outp = ' ';
560             in_repeated = false;
561             whole_word_is_optional = false;
562             break;
563         case '.':
564             in_repeated = true;
565             break;
566         default:
567             *--outp = *inp;
568             break;
569         }
570     }
571     if (arguments[0] != '[' && outp != output + 2 * length - 1) {
572         *--outp = in_repeated ? '+' : '!';
573     }
574     printf("%s", outp);
575     free(output);
576 }
577
578 static void
579 print_vsctl_commands(void)
580 {
581     const struct shash_node *node;
582
583     SHASH_FOR_EACH (node, ctl_get_all_commands()) {
584         const struct ctl_command_syntax *p = node->data;
585         char *options = xstrdup(p->options);
586         char *options_begin = options;
587         char *item;
588
589         for (item = strsep(&options, ","); item != NULL;
590              item = strsep(&options, ",")) {
591             if (item[0] != '\0') {
592                 printf("[%s] ", item);
593             }
594         }
595         printf(",%s,", p->name);
596         print_command_arguments(p);
597         printf("\n");
598
599         free(options_begin);
600     }
601
602     exit(EXIT_SUCCESS);
603 }
604
605 static void
606 print_vsctl_options(const struct option *options)
607 {
608     for (; options->name; options++) {
609         const struct option *o = options;
610
611         printf("--%s%s\n", o->name, o->has_arg ? "=ARG" : "");
612         if (o->flag == NULL && o->val > 0 && o->val <= UCHAR_MAX) {
613             printf("-%c%s\n", o->val, o->has_arg ? " ARG" : "");
614         }
615     }
616
617     exit(EXIT_SUCCESS);
618 }
619
620 static char *
621 default_db(void)
622 {
623     static char *def;
624     if (!def) {
625         def = xasprintf("unix:%s/db.sock", ovs_rundir());
626     }
627     return def;
628 }
629
630 \f
631 /* ovs-vsctl specific context.  Inherits the 'struct ctl_context' as base. */
632 struct vsctl_context {
633     struct ctl_context base;
634
635     /* Modifiable state. */
636     const struct ovsrec_open_vswitch *ovs;
637     bool verified_ports;
638
639     /* A cache of the contents of the database.
640      *
641      * A command that needs to use any of this information must first call
642      * vsctl_context_populate_cache().  A command that changes anything that
643      * could invalidate the cache must either call
644      * vsctl_context_invalidate_cache() or manually update the cache to
645      * maintain its correctness. */
646     bool cache_valid;
647     struct shash bridges;   /* Maps from bridge name to struct vsctl_bridge. */
648     struct shash ports;     /* Maps from port name to struct vsctl_port. */
649     struct shash ifaces;    /* Maps from port name to struct vsctl_iface. */
650 };
651
652 struct vsctl_bridge {
653     struct ovsrec_bridge *br_cfg;
654     char *name;
655     struct ovs_list ports;      /* Contains "struct vsctl_port"s. */
656
657     /* VLAN ("fake") bridge support.
658      *
659      * Use 'parent != NULL' to detect a fake bridge, because 'vlan' can be 0
660      * in either case. */
661     struct hmap children;        /* VLAN bridges indexed by 'vlan'. */
662     struct hmap_node children_node; /* Node in parent's 'children' hmap. */
663     struct vsctl_bridge *parent; /* Real bridge, or NULL. */
664     int vlan;                    /* VLAN VID (0...4095), or 0. */
665 };
666
667 struct vsctl_port {
668     struct ovs_list ports_node;  /* In struct vsctl_bridge's 'ports' list. */
669     struct ovs_list ifaces;      /* Contains "struct vsctl_iface"s. */
670     struct ovsrec_port *port_cfg;
671     struct vsctl_bridge *bridge;
672 };
673
674 struct vsctl_iface {
675     struct ovs_list ifaces_node; /* In struct vsctl_port's 'ifaces' list. */
676     struct ovsrec_interface *iface_cfg;
677     struct vsctl_port *port;
678 };
679
680 /* Casts 'base' into 'strcut vsctl_context'. */
681 static struct vsctl_context *
682 vsctl_context_cast(struct ctl_context *base)
683 {
684     return CONTAINER_OF(base, struct vsctl_context, base);
685 }
686
687 static struct vsctl_bridge *find_vlan_bridge(struct vsctl_bridge *parent,
688                                              int vlan);
689
690 static char *
691 vsctl_context_to_string(const struct ctl_context *ctx)
692 {
693     const struct shash_node *node;
694     struct svec words;
695     char *s;
696     int i;
697
698     svec_init(&words);
699     SHASH_FOR_EACH (node, &ctx->options) {
700         svec_add(&words, node->name);
701     }
702     for (i = 0; i < ctx->argc; i++) {
703         svec_add(&words, ctx->argv[i]);
704     }
705     svec_terminate(&words);
706
707     s = process_escape_args(words.names);
708
709     svec_destroy(&words);
710
711     return s;
712 }
713
714 static void
715 verify_ports(struct vsctl_context *vsctl_ctx)
716 {
717     if (!vsctl_ctx->verified_ports) {
718         const struct ovsrec_bridge *bridge;
719         const struct ovsrec_port *port;
720
721         ovsrec_open_vswitch_verify_bridges(vsctl_ctx->ovs);
722         OVSREC_BRIDGE_FOR_EACH (bridge, vsctl_ctx->base.idl) {
723             ovsrec_bridge_verify_ports(bridge);
724         }
725         OVSREC_PORT_FOR_EACH (port, vsctl_ctx->base.idl) {
726             ovsrec_port_verify_interfaces(port);
727         }
728
729         vsctl_ctx->verified_ports = true;
730     }
731 }
732
733 static struct vsctl_bridge *
734 add_bridge_to_cache(struct vsctl_context *vsctl_ctx,
735                     struct ovsrec_bridge *br_cfg, const char *name,
736                     struct vsctl_bridge *parent, int vlan)
737 {
738     struct vsctl_bridge *br = xmalloc(sizeof *br);
739     br->br_cfg = br_cfg;
740     br->name = xstrdup(name);
741     list_init(&br->ports);
742     br->parent = parent;
743     br->vlan = vlan;
744     hmap_init(&br->children);
745     if (parent) {
746         struct vsctl_bridge *conflict = find_vlan_bridge(parent, vlan);
747         if (conflict) {
748             VLOG_WARN("%s: bridge has multiple VLAN bridges (%s and %s) "
749                       "for VLAN %d, but only one is allowed",
750                       parent->name, name, conflict->name, vlan);
751         } else {
752             hmap_insert(&parent->children, &br->children_node,
753                         hash_int(vlan, 0));
754         }
755     }
756     shash_add(&vsctl_ctx->bridges, br->name, br);
757     return br;
758 }
759
760 static void
761 ovs_delete_bridge(const struct ovsrec_open_vswitch *ovs,
762                   struct ovsrec_bridge *bridge)
763 {
764     struct ovsrec_bridge **bridges;
765     size_t i, n;
766
767     bridges = xmalloc(sizeof *ovs->bridges * ovs->n_bridges);
768     for (i = n = 0; i < ovs->n_bridges; i++) {
769         if (ovs->bridges[i] != bridge) {
770             bridges[n++] = ovs->bridges[i];
771         }
772     }
773     ovsrec_open_vswitch_set_bridges(ovs, bridges, n);
774     free(bridges);
775 }
776
777 static void
778 del_cached_bridge(struct vsctl_context *vsctl_ctx, struct vsctl_bridge *br)
779 {
780     ovs_assert(list_is_empty(&br->ports));
781     ovs_assert(hmap_is_empty(&br->children));
782     if (br->parent) {
783         hmap_remove(&br->parent->children, &br->children_node);
784     }
785     if (br->br_cfg) {
786         ovsrec_bridge_delete(br->br_cfg);
787         ovs_delete_bridge(vsctl_ctx->ovs, br->br_cfg);
788     }
789     shash_find_and_delete(&vsctl_ctx->bridges, br->name);
790     hmap_destroy(&br->children);
791     free(br->name);
792     free(br);
793 }
794
795 static bool
796 port_is_fake_bridge(const struct ovsrec_port *port_cfg)
797 {
798     return (port_cfg->fake_bridge
799             && port_cfg->tag
800             && *port_cfg->tag >= 0 && *port_cfg->tag <= 4095);
801 }
802
803 static struct vsctl_bridge *
804 find_vlan_bridge(struct vsctl_bridge *parent, int vlan)
805 {
806     struct vsctl_bridge *child;
807
808     HMAP_FOR_EACH_IN_BUCKET (child, children_node, hash_int(vlan, 0),
809                              &parent->children) {
810         if (child->vlan == vlan) {
811             return child;
812         }
813     }
814
815     return NULL;
816 }
817
818 static struct vsctl_port *
819 add_port_to_cache(struct vsctl_context *vsctl_ctx, struct vsctl_bridge *parent,
820                   struct ovsrec_port *port_cfg)
821 {
822     struct vsctl_port *port;
823
824     if (port_cfg->tag
825         && *port_cfg->tag >= 0 && *port_cfg->tag <= 4095) {
826         struct vsctl_bridge *vlan_bridge;
827
828         vlan_bridge = find_vlan_bridge(parent, *port_cfg->tag);
829         if (vlan_bridge) {
830             parent = vlan_bridge;
831         }
832     }
833
834     port = xmalloc(sizeof *port);
835     list_push_back(&parent->ports, &port->ports_node);
836     list_init(&port->ifaces);
837     port->port_cfg = port_cfg;
838     port->bridge = parent;
839     shash_add(&vsctl_ctx->ports, port_cfg->name, port);
840
841     return port;
842 }
843
844 static void
845 del_cached_port(struct vsctl_context *vsctl_ctx, struct vsctl_port *port)
846 {
847     ovs_assert(list_is_empty(&port->ifaces));
848     list_remove(&port->ports_node);
849     shash_find_and_delete(&vsctl_ctx->ports, port->port_cfg->name);
850     ovsrec_port_delete(port->port_cfg);
851     free(port);
852 }
853
854 static struct vsctl_iface *
855 add_iface_to_cache(struct vsctl_context *vsctl_ctx, struct vsctl_port *parent,
856                    struct ovsrec_interface *iface_cfg)
857 {
858     struct vsctl_iface *iface;
859
860     iface = xmalloc(sizeof *iface);
861     list_push_back(&parent->ifaces, &iface->ifaces_node);
862     iface->iface_cfg = iface_cfg;
863     iface->port = parent;
864     shash_add(&vsctl_ctx->ifaces, iface_cfg->name, iface);
865
866     return iface;
867 }
868
869 static void
870 del_cached_iface(struct vsctl_context *vsctl_ctx, struct vsctl_iface *iface)
871 {
872     list_remove(&iface->ifaces_node);
873     shash_find_and_delete(&vsctl_ctx->ifaces, iface->iface_cfg->name);
874     ovsrec_interface_delete(iface->iface_cfg);
875     free(iface);
876 }
877
878 static void
879 vsctl_context_invalidate_cache(struct ctl_context *ctx)
880 {
881     struct vsctl_context *vsctl_ctx = vsctl_context_cast(ctx);
882     struct shash_node *node;
883
884     if (!vsctl_ctx->cache_valid) {
885         return;
886     }
887     vsctl_ctx->cache_valid = false;
888
889     SHASH_FOR_EACH (node, &vsctl_ctx->bridges) {
890         struct vsctl_bridge *bridge = node->data;
891         hmap_destroy(&bridge->children);
892         free(bridge->name);
893         free(bridge);
894     }
895     shash_destroy(&vsctl_ctx->bridges);
896
897     shash_destroy_free_data(&vsctl_ctx->ports);
898     shash_destroy_free_data(&vsctl_ctx->ifaces);
899 }
900
901 static void
902 pre_get_info(struct ctl_context *ctx)
903 {
904     ovsdb_idl_add_column(ctx->idl, &ovsrec_open_vswitch_col_bridges);
905
906     ovsdb_idl_add_column(ctx->idl, &ovsrec_bridge_col_name);
907     ovsdb_idl_add_column(ctx->idl, &ovsrec_bridge_col_controller);
908     ovsdb_idl_add_column(ctx->idl, &ovsrec_bridge_col_fail_mode);
909     ovsdb_idl_add_column(ctx->idl, &ovsrec_bridge_col_ports);
910
911     ovsdb_idl_add_column(ctx->idl, &ovsrec_port_col_name);
912     ovsdb_idl_add_column(ctx->idl, &ovsrec_port_col_fake_bridge);
913     ovsdb_idl_add_column(ctx->idl, &ovsrec_port_col_tag);
914     ovsdb_idl_add_column(ctx->idl, &ovsrec_port_col_interfaces);
915
916     ovsdb_idl_add_column(ctx->idl, &ovsrec_interface_col_name);
917
918     ovsdb_idl_add_column(ctx->idl, &ovsrec_interface_col_ofport);
919 }
920
921 static void
922 vsctl_context_populate_cache(struct ctl_context *ctx)
923 {
924     struct vsctl_context *vsctl_ctx = vsctl_context_cast(ctx);
925     const struct ovsrec_open_vswitch *ovs = vsctl_ctx->ovs;
926     struct sset bridges, ports;
927     size_t i;
928
929     if (vsctl_ctx->cache_valid) {
930         /* Cache is already populated. */
931         return;
932     }
933     vsctl_ctx->cache_valid = true;
934     shash_init(&vsctl_ctx->bridges);
935     shash_init(&vsctl_ctx->ports);
936     shash_init(&vsctl_ctx->ifaces);
937
938     sset_init(&bridges);
939     sset_init(&ports);
940     for (i = 0; i < ovs->n_bridges; i++) {
941         struct ovsrec_bridge *br_cfg = ovs->bridges[i];
942         struct vsctl_bridge *br;
943         size_t j;
944
945         if (!sset_add(&bridges, br_cfg->name)) {
946             VLOG_WARN("%s: database contains duplicate bridge name",
947                       br_cfg->name);
948             continue;
949         }
950         br = add_bridge_to_cache(vsctl_ctx, br_cfg, br_cfg->name, NULL, 0);
951         if (!br) {
952             continue;
953         }
954
955         for (j = 0; j < br_cfg->n_ports; j++) {
956             struct ovsrec_port *port_cfg = br_cfg->ports[j];
957
958             if (!sset_add(&ports, port_cfg->name)) {
959                 /* Duplicate port name.  (We will warn about that later.) */
960                 continue;
961             }
962
963             if (port_is_fake_bridge(port_cfg)
964                 && sset_add(&bridges, port_cfg->name)) {
965                 add_bridge_to_cache(vsctl_ctx, NULL, port_cfg->name, br,
966                                     *port_cfg->tag);
967             }
968         }
969     }
970     sset_destroy(&bridges);
971     sset_destroy(&ports);
972
973     sset_init(&bridges);
974     for (i = 0; i < ovs->n_bridges; i++) {
975         struct ovsrec_bridge *br_cfg = ovs->bridges[i];
976         struct vsctl_bridge *br;
977         size_t j;
978
979         if (!sset_add(&bridges, br_cfg->name)) {
980             continue;
981         }
982         br = shash_find_data(&vsctl_ctx->bridges, br_cfg->name);
983         for (j = 0; j < br_cfg->n_ports; j++) {
984             struct ovsrec_port *port_cfg = br_cfg->ports[j];
985             struct vsctl_port *port;
986             size_t k;
987
988             port = shash_find_data(&vsctl_ctx->ports, port_cfg->name);
989             if (port) {
990                 if (port_cfg == port->port_cfg) {
991                     VLOG_WARN("%s: port is in multiple bridges (%s and %s)",
992                               port_cfg->name, br->name, port->bridge->name);
993                 } else {
994                     /* Log as an error because this violates the database's
995                      * uniqueness constraints, so the database server shouldn't
996                      * have allowed it. */
997                     VLOG_ERR("%s: database contains duplicate port name",
998                              port_cfg->name);
999                 }
1000                 continue;
1001             }
1002
1003             if (port_is_fake_bridge(port_cfg)
1004                 && !sset_add(&bridges, port_cfg->name)) {
1005                 continue;
1006             }
1007
1008             port = add_port_to_cache(vsctl_ctx, br, port_cfg);
1009             for (k = 0; k < port_cfg->n_interfaces; k++) {
1010                 struct ovsrec_interface *iface_cfg = port_cfg->interfaces[k];
1011                 struct vsctl_iface *iface;
1012
1013                 iface = shash_find_data(&vsctl_ctx->ifaces, iface_cfg->name);
1014                 if (iface) {
1015                     if (iface_cfg == iface->iface_cfg) {
1016                         VLOG_WARN("%s: interface is in multiple ports "
1017                                   "(%s and %s)",
1018                                   iface_cfg->name,
1019                                   iface->port->port_cfg->name,
1020                                   port->port_cfg->name);
1021                     } else {
1022                         /* Log as an error because this violates the database's
1023                          * uniqueness constraints, so the database server
1024                          * shouldn't have allowed it. */
1025                         VLOG_ERR("%s: database contains duplicate interface "
1026                                  "name", iface_cfg->name);
1027                     }
1028                     continue;
1029                 }
1030
1031                 add_iface_to_cache(vsctl_ctx, port, iface_cfg);
1032             }
1033         }
1034     }
1035     sset_destroy(&bridges);
1036 }
1037
1038 static void
1039 check_conflicts(struct vsctl_context *vsctl_ctx, const char *name,
1040                 char *msg)
1041 {
1042     struct vsctl_iface *iface;
1043     struct vsctl_port *port;
1044
1045     verify_ports(vsctl_ctx);
1046
1047     if (shash_find(&vsctl_ctx->bridges, name)) {
1048         ctl_fatal("%s because a bridge named %s already exists",
1049                     msg, name);
1050     }
1051
1052     port = shash_find_data(&vsctl_ctx->ports, name);
1053     if (port) {
1054         ctl_fatal("%s because a port named %s already exists on "
1055                     "bridge %s", msg, name, port->bridge->name);
1056     }
1057
1058     iface = shash_find_data(&vsctl_ctx->ifaces, name);
1059     if (iface) {
1060         ctl_fatal("%s because an interface named %s already exists "
1061                     "on bridge %s", msg, name, iface->port->bridge->name);
1062     }
1063
1064     free(msg);
1065 }
1066
1067 static struct vsctl_bridge *
1068 find_bridge(struct vsctl_context *vsctl_ctx, const char *name, bool must_exist)
1069 {
1070     struct vsctl_bridge *br;
1071
1072     ovs_assert(vsctl_ctx->cache_valid);
1073
1074     br = shash_find_data(&vsctl_ctx->bridges, name);
1075     if (must_exist && !br) {
1076         ctl_fatal("no bridge named %s", name);
1077     }
1078     ovsrec_open_vswitch_verify_bridges(vsctl_ctx->ovs);
1079     return br;
1080 }
1081
1082 static struct vsctl_bridge *
1083 find_real_bridge(struct vsctl_context *vsctl_ctx,
1084                  const char *name, bool must_exist)
1085 {
1086     struct vsctl_bridge *br = find_bridge(vsctl_ctx, name, must_exist);
1087     if (br && br->parent) {
1088         ctl_fatal("%s is a fake bridge", name);
1089     }
1090     return br;
1091 }
1092
1093 static struct vsctl_port *
1094 find_port(struct vsctl_context *vsctl_ctx, const char *name, bool must_exist)
1095 {
1096     struct vsctl_port *port;
1097
1098     ovs_assert(vsctl_ctx->cache_valid);
1099
1100     port = shash_find_data(&vsctl_ctx->ports, name);
1101     if (port && !strcmp(name, port->bridge->name)) {
1102         port = NULL;
1103     }
1104     if (must_exist && !port) {
1105         ctl_fatal("no port named %s", name);
1106     }
1107     verify_ports(vsctl_ctx);
1108     return port;
1109 }
1110
1111 static struct vsctl_iface *
1112 find_iface(struct vsctl_context *vsctl_ctx, const char *name, bool must_exist)
1113 {
1114     struct vsctl_iface *iface;
1115
1116     ovs_assert(vsctl_ctx->cache_valid);
1117
1118     iface = shash_find_data(&vsctl_ctx->ifaces, name);
1119     if (iface && !strcmp(name, iface->port->bridge->name)) {
1120         iface = NULL;
1121     }
1122     if (must_exist && !iface) {
1123         ctl_fatal("no interface named %s", name);
1124     }
1125     verify_ports(vsctl_ctx);
1126     return iface;
1127 }
1128
1129 static void
1130 bridge_insert_port(struct ovsrec_bridge *br, struct ovsrec_port *port)
1131 {
1132     struct ovsrec_port **ports;
1133     size_t i;
1134
1135     ports = xmalloc(sizeof *br->ports * (br->n_ports + 1));
1136     for (i = 0; i < br->n_ports; i++) {
1137         ports[i] = br->ports[i];
1138     }
1139     ports[br->n_ports] = port;
1140     ovsrec_bridge_set_ports(br, ports, br->n_ports + 1);
1141     free(ports);
1142 }
1143
1144 static void
1145 bridge_delete_port(struct ovsrec_bridge *br, struct ovsrec_port *port)
1146 {
1147     struct ovsrec_port **ports;
1148     size_t i, n;
1149
1150     ports = xmalloc(sizeof *br->ports * br->n_ports);
1151     for (i = n = 0; i < br->n_ports; i++) {
1152         if (br->ports[i] != port) {
1153             ports[n++] = br->ports[i];
1154         }
1155     }
1156     ovsrec_bridge_set_ports(br, ports, n);
1157     free(ports);
1158 }
1159
1160 static void
1161 ovs_insert_bridge(const struct ovsrec_open_vswitch *ovs,
1162                   struct ovsrec_bridge *bridge)
1163 {
1164     struct ovsrec_bridge **bridges;
1165     size_t i;
1166
1167     bridges = xmalloc(sizeof *ovs->bridges * (ovs->n_bridges + 1));
1168     for (i = 0; i < ovs->n_bridges; i++) {
1169         bridges[i] = ovs->bridges[i];
1170     }
1171     bridges[ovs->n_bridges] = bridge;
1172     ovsrec_open_vswitch_set_bridges(ovs, bridges, ovs->n_bridges + 1);
1173     free(bridges);
1174 }
1175
1176 static void
1177 cmd_init(struct ctl_context *ctx OVS_UNUSED)
1178 {
1179 }
1180
1181 struct cmd_show_table {
1182     const struct ovsdb_idl_table_class *table;
1183     const struct ovsdb_idl_column *name_column;
1184     const struct ovsdb_idl_column *columns[3];
1185     bool recurse;
1186 };
1187
1188 static struct cmd_show_table cmd_show_tables[] = {
1189     {&ovsrec_table_open_vswitch,
1190      NULL,
1191      {&ovsrec_open_vswitch_col_manager_options,
1192       &ovsrec_open_vswitch_col_bridges,
1193       &ovsrec_open_vswitch_col_ovs_version},
1194      false},
1195
1196     {&ovsrec_table_bridge,
1197      &ovsrec_bridge_col_name,
1198      {&ovsrec_bridge_col_controller,
1199       &ovsrec_bridge_col_fail_mode,
1200       &ovsrec_bridge_col_ports},
1201      false},
1202
1203     {&ovsrec_table_port,
1204      &ovsrec_port_col_name,
1205      {&ovsrec_port_col_tag,
1206       &ovsrec_port_col_trunks,
1207       &ovsrec_port_col_interfaces},
1208      false},
1209
1210     {&ovsrec_table_interface,
1211      &ovsrec_interface_col_name,
1212      {&ovsrec_interface_col_type,
1213       &ovsrec_interface_col_options,
1214       &ovsrec_interface_col_error},
1215      false},
1216
1217     {&ovsrec_table_controller,
1218      &ovsrec_controller_col_target,
1219      {&ovsrec_controller_col_is_connected,
1220       NULL,
1221       NULL},
1222      false},
1223
1224     {&ovsrec_table_manager,
1225      &ovsrec_manager_col_target,
1226      {&ovsrec_manager_col_is_connected,
1227       NULL,
1228       NULL},
1229      false},
1230 };
1231
1232 static void
1233 pre_cmd_show(struct ctl_context *ctx)
1234 {
1235     struct cmd_show_table *show;
1236
1237     for (show = cmd_show_tables;
1238          show < &cmd_show_tables[ARRAY_SIZE(cmd_show_tables)];
1239          show++) {
1240         size_t i;
1241
1242         ovsdb_idl_add_table(ctx->idl, show->table);
1243         if (show->name_column) {
1244             ovsdb_idl_add_column(ctx->idl, show->name_column);
1245         }
1246         for (i = 0; i < ARRAY_SIZE(show->columns); i++) {
1247             const struct ovsdb_idl_column *column = show->columns[i];
1248             if (column) {
1249                 ovsdb_idl_add_column(ctx->idl, column);
1250             }
1251         }
1252     }
1253 }
1254
1255 static struct cmd_show_table *
1256 cmd_show_find_table_by_row(const struct ovsdb_idl_row *row)
1257 {
1258     struct cmd_show_table *show;
1259
1260     for (show = cmd_show_tables;
1261          show < &cmd_show_tables[ARRAY_SIZE(cmd_show_tables)];
1262          show++) {
1263         if (show->table == row->table->class) {
1264             return show;
1265         }
1266     }
1267     return NULL;
1268 }
1269
1270 static struct cmd_show_table *
1271 cmd_show_find_table_by_name(const char *name)
1272 {
1273     struct cmd_show_table *show;
1274
1275     for (show = cmd_show_tables;
1276          show < &cmd_show_tables[ARRAY_SIZE(cmd_show_tables)];
1277          show++) {
1278         if (!strcmp(show->table->name, name)) {
1279             return show;
1280         }
1281     }
1282     return NULL;
1283 }
1284
1285 static void
1286 cmd_show_row(struct ctl_context *ctx, const struct ovsdb_idl_row *row,
1287              int level)
1288 {
1289     struct cmd_show_table *show = cmd_show_find_table_by_row(row);
1290     size_t i;
1291
1292     ds_put_char_multiple(&ctx->output, ' ', level * 4);
1293     if (show && show->name_column) {
1294         const struct ovsdb_datum *datum;
1295
1296         ds_put_format(&ctx->output, "%s ", show->table->name);
1297         datum = ovsdb_idl_read(row, show->name_column);
1298         ovsdb_datum_to_string(datum, &show->name_column->type, &ctx->output);
1299     } else {
1300         ds_put_format(&ctx->output, UUID_FMT, UUID_ARGS(&row->uuid));
1301     }
1302     ds_put_char(&ctx->output, '\n');
1303
1304     if (!show || show->recurse) {
1305         return;
1306     }
1307
1308     show->recurse = true;
1309     for (i = 0; i < ARRAY_SIZE(show->columns); i++) {
1310         const struct ovsdb_idl_column *column = show->columns[i];
1311         const struct ovsdb_datum *datum;
1312
1313         if (!column) {
1314             break;
1315         }
1316
1317         datum = ovsdb_idl_read(row, column);
1318         if (column->type.key.type == OVSDB_TYPE_UUID &&
1319             column->type.key.u.uuid.refTableName) {
1320             struct cmd_show_table *ref_show;
1321             size_t j;
1322
1323             ref_show = cmd_show_find_table_by_name(
1324                 column->type.key.u.uuid.refTableName);
1325             if (ref_show) {
1326                 for (j = 0; j < datum->n; j++) {
1327                     const struct ovsdb_idl_row *ref_row;
1328
1329                     ref_row = ovsdb_idl_get_row_for_uuid(ctx->idl,
1330                                                          ref_show->table,
1331                                                          &datum->keys[j].uuid);
1332                     if (ref_row) {
1333                         cmd_show_row(ctx, ref_row, level + 1);
1334                     }
1335                 }
1336                 continue;
1337             }
1338         }
1339
1340         if (!ovsdb_datum_is_default(datum, &column->type)) {
1341             ds_put_char_multiple(&ctx->output, ' ', (level + 1) * 4);
1342             ds_put_format(&ctx->output, "%s: ", column->name);
1343             ovsdb_datum_to_string(datum, &column->type, &ctx->output);
1344             ds_put_char(&ctx->output, '\n');
1345         }
1346     }
1347     show->recurse = false;
1348 }
1349
1350 static void
1351 cmd_show(struct ctl_context *ctx)
1352 {
1353     const struct ovsdb_idl_row *row;
1354
1355     for (row = ovsdb_idl_first_row(ctx->idl, cmd_show_tables[0].table);
1356          row; row = ovsdb_idl_next_row(row)) {
1357         cmd_show_row(ctx, row, 0);
1358     }
1359 }
1360
1361 static void
1362 pre_cmd_emer_reset(struct ctl_context *ctx)
1363 {
1364     ovsdb_idl_add_column(ctx->idl, &ovsrec_open_vswitch_col_manager_options);
1365     ovsdb_idl_add_column(ctx->idl, &ovsrec_open_vswitch_col_ssl);
1366
1367     ovsdb_idl_add_column(ctx->idl, &ovsrec_bridge_col_controller);
1368     ovsdb_idl_add_column(ctx->idl, &ovsrec_bridge_col_fail_mode);
1369     ovsdb_idl_add_column(ctx->idl, &ovsrec_bridge_col_mirrors);
1370     ovsdb_idl_add_column(ctx->idl, &ovsrec_bridge_col_netflow);
1371     ovsdb_idl_add_column(ctx->idl, &ovsrec_bridge_col_sflow);
1372     ovsdb_idl_add_column(ctx->idl, &ovsrec_bridge_col_ipfix);
1373     ovsdb_idl_add_column(ctx->idl, &ovsrec_bridge_col_flood_vlans);
1374     ovsdb_idl_add_column(ctx->idl, &ovsrec_bridge_col_other_config);
1375
1376     ovsdb_idl_add_column(ctx->idl, &ovsrec_port_col_other_config);
1377
1378     ovsdb_idl_add_column(ctx->idl,
1379                           &ovsrec_interface_col_ingress_policing_rate);
1380     ovsdb_idl_add_column(ctx->idl,
1381                           &ovsrec_interface_col_ingress_policing_burst);
1382 }
1383
1384 static void
1385 cmd_emer_reset(struct ctl_context *ctx)
1386 {
1387     struct vsctl_context *vsctl_ctx = vsctl_context_cast(ctx);
1388     const struct ovsdb_idl *idl = ctx->idl;
1389     const struct ovsrec_bridge *br;
1390     const struct ovsrec_port *port;
1391     const struct ovsrec_interface *iface;
1392     const struct ovsrec_mirror *mirror, *next_mirror;
1393     const struct ovsrec_controller *ctrl, *next_ctrl;
1394     const struct ovsrec_manager *mgr, *next_mgr;
1395     const struct ovsrec_netflow *nf, *next_nf;
1396     const struct ovsrec_ssl *ssl, *next_ssl;
1397     const struct ovsrec_sflow *sflow, *next_sflow;
1398     const struct ovsrec_ipfix *ipfix, *next_ipfix;
1399     const struct ovsrec_flow_sample_collector_set *fscset, *next_fscset;
1400
1401     /* Reset the Open_vSwitch table. */
1402     ovsrec_open_vswitch_set_manager_options(vsctl_ctx->ovs, NULL, 0);
1403     ovsrec_open_vswitch_set_ssl(vsctl_ctx->ovs, NULL);
1404
1405     OVSREC_BRIDGE_FOR_EACH (br, idl) {
1406         const char *hwaddr;
1407
1408         ovsrec_bridge_set_controller(br, NULL, 0);
1409         ovsrec_bridge_set_fail_mode(br, NULL);
1410         ovsrec_bridge_set_mirrors(br, NULL, 0);
1411         ovsrec_bridge_set_netflow(br, NULL);
1412         ovsrec_bridge_set_sflow(br, NULL);
1413         ovsrec_bridge_set_ipfix(br, NULL);
1414         ovsrec_bridge_set_flood_vlans(br, NULL, 0);
1415
1416         /* We only want to save the "hwaddr" key from other_config. */
1417         hwaddr = smap_get(&br->other_config, "hwaddr");
1418         if (hwaddr) {
1419             struct smap smap = SMAP_INITIALIZER(&smap);
1420             smap_add(&smap, "hwaddr", hwaddr);
1421             ovsrec_bridge_set_other_config(br, &smap);
1422             smap_destroy(&smap);
1423         } else {
1424             ovsrec_bridge_set_other_config(br, NULL);
1425         }
1426     }
1427
1428     OVSREC_PORT_FOR_EACH (port, idl) {
1429         ovsrec_port_set_other_config(port, NULL);
1430     }
1431
1432     OVSREC_INTERFACE_FOR_EACH (iface, idl) {
1433         /* xxx What do we do about gre/patch devices created by mgr? */
1434
1435         ovsrec_interface_set_ingress_policing_rate(iface, 0);
1436         ovsrec_interface_set_ingress_policing_burst(iface, 0);
1437     }
1438
1439     OVSREC_MIRROR_FOR_EACH_SAFE (mirror, next_mirror, idl) {
1440         ovsrec_mirror_delete(mirror);
1441     }
1442
1443     OVSREC_CONTROLLER_FOR_EACH_SAFE (ctrl, next_ctrl, idl) {
1444         ovsrec_controller_delete(ctrl);
1445     }
1446
1447     OVSREC_MANAGER_FOR_EACH_SAFE (mgr, next_mgr, idl) {
1448         ovsrec_manager_delete(mgr);
1449     }
1450
1451     OVSREC_NETFLOW_FOR_EACH_SAFE (nf, next_nf, idl) {
1452         ovsrec_netflow_delete(nf);
1453     }
1454
1455     OVSREC_SSL_FOR_EACH_SAFE (ssl, next_ssl, idl) {
1456         ovsrec_ssl_delete(ssl);
1457     }
1458
1459     OVSREC_SFLOW_FOR_EACH_SAFE (sflow, next_sflow, idl) {
1460         ovsrec_sflow_delete(sflow);
1461     }
1462
1463     OVSREC_IPFIX_FOR_EACH_SAFE (ipfix, next_ipfix, idl) {
1464         ovsrec_ipfix_delete(ipfix);
1465     }
1466
1467     OVSREC_FLOW_SAMPLE_COLLECTOR_SET_FOR_EACH_SAFE (fscset, next_fscset, idl) {
1468         ovsrec_flow_sample_collector_set_delete(fscset);
1469     }
1470
1471     vsctl_context_invalidate_cache(ctx);
1472 }
1473
1474 static void
1475 cmd_add_br(struct ctl_context *ctx)
1476 {
1477     struct vsctl_context *vsctl_ctx = vsctl_context_cast(ctx);
1478     bool may_exist = shash_find(&ctx->options, "--may-exist") != NULL;
1479     const char *br_name, *parent_name;
1480     struct ovsrec_interface *iface;
1481     int vlan;
1482
1483     br_name = ctx->argv[1];
1484     if (ctx->argc == 2) {
1485         parent_name = NULL;
1486         vlan = 0;
1487     } else if (ctx->argc == 4) {
1488         parent_name = ctx->argv[2];
1489         vlan = atoi(ctx->argv[3]);
1490         if (vlan < 0 || vlan > 4095) {
1491             ctl_fatal("%s: vlan must be between 0 and 4095", ctx->argv[0]);
1492         }
1493     } else {
1494         ctl_fatal("'%s' command takes exactly 1 or 3 arguments",
1495                     ctx->argv[0]);
1496     }
1497
1498     vsctl_context_populate_cache(ctx);
1499     if (may_exist) {
1500         struct vsctl_bridge *br;
1501
1502         br = find_bridge(vsctl_ctx, br_name, false);
1503         if (br) {
1504             if (!parent_name) {
1505                 if (br->parent) {
1506                     ctl_fatal("\"--may-exist add-br %s\" but %s is "
1507                                 "a VLAN bridge for VLAN %d",
1508                                 br_name, br_name, br->vlan);
1509                 }
1510             } else {
1511                 if (!br->parent) {
1512                     ctl_fatal("\"--may-exist add-br %s %s %d\" but %s "
1513                                 "is not a VLAN bridge",
1514                                 br_name, parent_name, vlan, br_name);
1515                 } else if (strcmp(br->parent->name, parent_name)) {
1516                     ctl_fatal("\"--may-exist add-br %s %s %d\" but %s "
1517                                 "has the wrong parent %s",
1518                                 br_name, parent_name, vlan,
1519                                 br_name, br->parent->name);
1520                 } else if (br->vlan != vlan) {
1521                     ctl_fatal("\"--may-exist add-br %s %s %d\" but %s "
1522                                 "is a VLAN bridge for the wrong VLAN %d",
1523                                 br_name, parent_name, vlan, br_name, br->vlan);
1524                 }
1525             }
1526             return;
1527         }
1528     }
1529     check_conflicts(vsctl_ctx, br_name,
1530                     xasprintf("cannot create a bridge named %s", br_name));
1531
1532     if (!parent_name) {
1533         struct ovsrec_port *port;
1534         struct ovsrec_bridge *br;
1535
1536         iface = ovsrec_interface_insert(ctx->txn);
1537         ovsrec_interface_set_name(iface, br_name);
1538         ovsrec_interface_set_type(iface, "internal");
1539
1540         port = ovsrec_port_insert(ctx->txn);
1541         ovsrec_port_set_name(port, br_name);
1542         ovsrec_port_set_interfaces(port, &iface, 1);
1543
1544         br = ovsrec_bridge_insert(ctx->txn);
1545         ovsrec_bridge_set_name(br, br_name);
1546         ovsrec_bridge_set_ports(br, &port, 1);
1547
1548         ovs_insert_bridge(vsctl_ctx->ovs, br);
1549     } else {
1550         struct vsctl_bridge *conflict;
1551         struct vsctl_bridge *parent;
1552         struct ovsrec_port *port;
1553         struct ovsrec_bridge *br;
1554         int64_t tag = vlan;
1555
1556         parent = find_bridge(vsctl_ctx, parent_name, false);
1557         if (parent && parent->parent) {
1558             ctl_fatal("cannot create bridge with fake bridge as parent");
1559         }
1560         if (!parent) {
1561             ctl_fatal("parent bridge %s does not exist", parent_name);
1562         }
1563         conflict = find_vlan_bridge(parent, vlan);
1564         if (conflict) {
1565             ctl_fatal("bridge %s already has a child VLAN bridge %s "
1566                         "on VLAN %d", parent_name, conflict->name, vlan);
1567         }
1568         br = parent->br_cfg;
1569
1570         iface = ovsrec_interface_insert(ctx->txn);
1571         ovsrec_interface_set_name(iface, br_name);
1572         ovsrec_interface_set_type(iface, "internal");
1573
1574         port = ovsrec_port_insert(ctx->txn);
1575         ovsrec_port_set_name(port, br_name);
1576         ovsrec_port_set_interfaces(port, &iface, 1);
1577         ovsrec_port_set_fake_bridge(port, true);
1578         ovsrec_port_set_tag(port, &tag, 1);
1579
1580         bridge_insert_port(br, port);
1581     }
1582
1583     post_db_reload_expect_iface(iface);
1584     vsctl_context_invalidate_cache(ctx);
1585 }
1586
1587 static void
1588 del_port(struct vsctl_context *vsctl_ctx, struct vsctl_port *port)
1589 {
1590     struct vsctl_iface *iface, *next_iface;
1591
1592     bridge_delete_port((port->bridge->parent
1593                         ? port->bridge->parent->br_cfg
1594                         : port->bridge->br_cfg), port->port_cfg);
1595
1596     LIST_FOR_EACH_SAFE (iface, next_iface, ifaces_node, &port->ifaces) {
1597         del_cached_iface(vsctl_ctx, iface);
1598     }
1599     del_cached_port(vsctl_ctx, port);
1600 }
1601
1602 static void
1603 del_bridge(struct vsctl_context *vsctl_ctx, struct vsctl_bridge *br)
1604 {
1605     struct vsctl_bridge *child, *next_child;
1606     struct vsctl_port *port, *next_port;
1607     const struct ovsrec_flow_sample_collector_set *fscset, *next_fscset;
1608
1609     HMAP_FOR_EACH_SAFE (child, next_child, children_node, &br->children) {
1610         del_bridge(vsctl_ctx, child);
1611     }
1612
1613     LIST_FOR_EACH_SAFE (port, next_port, ports_node, &br->ports) {
1614         del_port(vsctl_ctx, port);
1615     }
1616
1617     OVSREC_FLOW_SAMPLE_COLLECTOR_SET_FOR_EACH_SAFE (fscset, next_fscset,
1618                                                     vsctl_ctx->base.idl) {
1619         if (fscset->bridge == br->br_cfg) {
1620             ovsrec_flow_sample_collector_set_delete(fscset);
1621         }
1622     }
1623
1624     del_cached_bridge(vsctl_ctx, br);
1625 }
1626
1627 static void
1628 cmd_del_br(struct ctl_context *ctx)
1629 {
1630     struct vsctl_context *vsctl_ctx = vsctl_context_cast(ctx);
1631     bool must_exist = !shash_find(&ctx->options, "--if-exists");
1632     struct vsctl_bridge *bridge;
1633
1634     vsctl_context_populate_cache(ctx);
1635     bridge = find_bridge(vsctl_ctx, ctx->argv[1], must_exist);
1636     if (bridge) {
1637         del_bridge(vsctl_ctx, bridge);
1638     }
1639 }
1640
1641 static void
1642 output_sorted(struct svec *svec, struct ds *output)
1643 {
1644     const char *name;
1645     size_t i;
1646
1647     svec_sort(svec);
1648     SVEC_FOR_EACH (i, name, svec) {
1649         ds_put_format(output, "%s\n", name);
1650     }
1651 }
1652
1653 static void
1654 cmd_list_br(struct ctl_context *ctx)
1655 {
1656     struct vsctl_context *vsctl_ctx = vsctl_context_cast(ctx);
1657     struct shash_node *node;
1658     struct svec bridges;
1659     bool real = shash_find(&ctx->options, "--real");
1660     bool fake = shash_find(&ctx->options, "--fake");
1661
1662     /* If neither fake nor real were requested, return both. */
1663     if (!real && !fake) {
1664         real = fake = true;
1665     }
1666
1667     vsctl_context_populate_cache(ctx);
1668
1669     svec_init(&bridges);
1670     SHASH_FOR_EACH (node, &vsctl_ctx->bridges) {
1671         struct vsctl_bridge *br = node->data;
1672
1673         if (br->parent ? fake : real) {
1674             svec_add(&bridges, br->name);
1675         }
1676     }
1677     output_sorted(&bridges, &ctx->output);
1678     svec_destroy(&bridges);
1679 }
1680
1681 static void
1682 cmd_br_exists(struct ctl_context *ctx)
1683 {
1684     struct vsctl_context *vsctl_ctx = vsctl_context_cast(ctx);
1685
1686     vsctl_context_populate_cache(ctx);
1687     if (!find_bridge(vsctl_ctx, ctx->argv[1], false)) {
1688         ctl_exit(2);
1689     }
1690 }
1691
1692 static void
1693 set_external_id(struct smap *old, struct smap *new,
1694                 char *key, char *value)
1695 {
1696     smap_clone(new, old);
1697
1698     if (value) {
1699         smap_replace(new, key, value);
1700     } else {
1701         smap_remove(new, key);
1702     }
1703 }
1704
1705 static void
1706 pre_cmd_br_set_external_id(struct ctl_context *ctx)
1707 {
1708     pre_get_info(ctx);
1709     ovsdb_idl_add_column(ctx->idl, &ovsrec_bridge_col_external_ids);
1710     ovsdb_idl_add_column(ctx->idl, &ovsrec_port_col_external_ids);
1711 }
1712
1713 static void
1714 cmd_br_set_external_id(struct ctl_context *ctx)
1715 {
1716     struct vsctl_context *vsctl_ctx = vsctl_context_cast(ctx);
1717     struct vsctl_bridge *bridge;
1718     struct smap new;
1719
1720     vsctl_context_populate_cache(ctx);
1721     bridge = find_bridge(vsctl_ctx, ctx->argv[1], true);
1722     if (bridge->br_cfg) {
1723
1724         set_external_id(&bridge->br_cfg->external_ids, &new, ctx->argv[2],
1725                         ctx->argc >= 4 ? ctx->argv[3] : NULL);
1726         ovsrec_bridge_verify_external_ids(bridge->br_cfg);
1727         ovsrec_bridge_set_external_ids(bridge->br_cfg, &new);
1728     } else {
1729         char *key = xasprintf("fake-bridge-%s", ctx->argv[2]);
1730         struct vsctl_port *port = shash_find_data(&vsctl_ctx->ports,
1731                                                   ctx->argv[1]);
1732         set_external_id(&port->port_cfg->external_ids, &new,
1733                         key, ctx->argc >= 4 ? ctx->argv[3] : NULL);
1734         ovsrec_port_verify_external_ids(port->port_cfg);
1735         ovsrec_port_set_external_ids(port->port_cfg, &new);
1736         free(key);
1737     }
1738     smap_destroy(&new);
1739 }
1740
1741 static void
1742 get_external_id(struct smap *smap, const char *prefix, const char *key,
1743                 struct ds *output)
1744 {
1745     if (key) {
1746         char *prefix_key = xasprintf("%s%s", prefix, key);
1747         const char *value = smap_get(smap, prefix_key);
1748
1749         if (value) {
1750             ds_put_format(output, "%s\n", value);
1751         }
1752         free(prefix_key);
1753     } else {
1754         const struct smap_node **sorted = smap_sort(smap);
1755         size_t prefix_len = strlen(prefix);
1756         size_t i;
1757
1758         for (i = 0; i < smap_count(smap); i++) {
1759             const struct smap_node *node = sorted[i];
1760             if (!strncmp(node->key, prefix, prefix_len)) {
1761                 ds_put_format(output, "%s=%s\n", node->key + prefix_len,
1762                               node->value);
1763             }
1764         }
1765         free(sorted);
1766     }
1767 }
1768
1769 static void
1770 pre_cmd_br_get_external_id(struct ctl_context *ctx)
1771 {
1772     pre_cmd_br_set_external_id(ctx);
1773 }
1774
1775 static void
1776 cmd_br_get_external_id(struct ctl_context *ctx)
1777 {
1778     struct vsctl_context *vsctl_ctx = vsctl_context_cast(ctx);
1779     struct vsctl_bridge *bridge;
1780
1781     vsctl_context_populate_cache(ctx);
1782
1783     bridge = find_bridge(vsctl_ctx, ctx->argv[1], true);
1784     if (bridge->br_cfg) {
1785         ovsrec_bridge_verify_external_ids(bridge->br_cfg);
1786         get_external_id(&bridge->br_cfg->external_ids, "",
1787                         ctx->argc >= 3 ? ctx->argv[2] : NULL, &ctx->output);
1788     } else {
1789         struct vsctl_port *port = shash_find_data(&vsctl_ctx->ports,
1790                                                   ctx->argv[1]);
1791         ovsrec_port_verify_external_ids(port->port_cfg);
1792         get_external_id(&port->port_cfg->external_ids, "fake-bridge-",
1793                         ctx->argc >= 3 ? ctx->argv[2] : NULL, &ctx->output);
1794     }
1795 }
1796
1797 static void
1798 cmd_list_ports(struct ctl_context *ctx)
1799 {
1800     struct vsctl_context *vsctl_ctx = vsctl_context_cast(ctx);
1801     struct vsctl_bridge *br;
1802     struct vsctl_port *port;
1803     struct svec ports;
1804
1805     vsctl_context_populate_cache(ctx);
1806     br = find_bridge(vsctl_ctx, ctx->argv[1], true);
1807     ovsrec_bridge_verify_ports(br->br_cfg ? br->br_cfg : br->parent->br_cfg);
1808
1809     svec_init(&ports);
1810     LIST_FOR_EACH (port, ports_node, &br->ports) {
1811         if (strcmp(port->port_cfg->name, br->name)) {
1812             svec_add(&ports, port->port_cfg->name);
1813         }
1814     }
1815     output_sorted(&ports, &ctx->output);
1816     svec_destroy(&ports);
1817 }
1818
1819 static void
1820 add_port(struct ctl_context *ctx,
1821          const char *br_name, const char *port_name,
1822          bool may_exist, bool fake_iface,
1823          char *iface_names[], int n_ifaces,
1824          char *settings[], int n_settings)
1825 {
1826     struct vsctl_context *vsctl_ctx = vsctl_context_cast(ctx);
1827     struct vsctl_port *vsctl_port;
1828     struct vsctl_bridge *bridge;
1829     struct ovsrec_interface **ifaces;
1830     struct ovsrec_port *port;
1831     size_t i;
1832
1833     vsctl_context_populate_cache(ctx);
1834     if (may_exist) {
1835         struct vsctl_port *vsctl_port;
1836
1837         vsctl_port = find_port(vsctl_ctx, port_name, false);
1838         if (vsctl_port) {
1839             struct svec want_names, have_names;
1840
1841             svec_init(&want_names);
1842             for (i = 0; i < n_ifaces; i++) {
1843                 svec_add(&want_names, iface_names[i]);
1844             }
1845             svec_sort(&want_names);
1846
1847             svec_init(&have_names);
1848             for (i = 0; i < vsctl_port->port_cfg->n_interfaces; i++) {
1849                 svec_add(&have_names,
1850                          vsctl_port->port_cfg->interfaces[i]->name);
1851             }
1852             svec_sort(&have_names);
1853
1854             if (strcmp(vsctl_port->bridge->name, br_name)) {
1855                 char *command = vsctl_context_to_string(ctx);
1856                 ctl_fatal("\"%s\" but %s is actually attached to bridge %s",
1857                             command, port_name, vsctl_port->bridge->name);
1858             }
1859
1860             if (!svec_equal(&want_names, &have_names)) {
1861                 char *have_names_string = svec_join(&have_names, ", ", "");
1862                 char *command = vsctl_context_to_string(ctx);
1863
1864                 ctl_fatal("\"%s\" but %s actually has interface(s) %s",
1865                             command, port_name, have_names_string);
1866             }
1867
1868             svec_destroy(&want_names);
1869             svec_destroy(&have_names);
1870
1871             return;
1872         }
1873     }
1874     check_conflicts(vsctl_ctx, port_name,
1875                     xasprintf("cannot create a port named %s", port_name));
1876     for (i = 0; i < n_ifaces; i++) {
1877         check_conflicts(vsctl_ctx, iface_names[i],
1878                         xasprintf("cannot create an interface named %s",
1879                                   iface_names[i]));
1880     }
1881     bridge = find_bridge(vsctl_ctx, br_name, true);
1882
1883     ifaces = xmalloc(n_ifaces * sizeof *ifaces);
1884     for (i = 0; i < n_ifaces; i++) {
1885         ifaces[i] = ovsrec_interface_insert(ctx->txn);
1886         ovsrec_interface_set_name(ifaces[i], iface_names[i]);
1887         post_db_reload_expect_iface(ifaces[i]);
1888     }
1889
1890     port = ovsrec_port_insert(ctx->txn);
1891     ovsrec_port_set_name(port, port_name);
1892     ovsrec_port_set_interfaces(port, ifaces, n_ifaces);
1893     ovsrec_port_set_bond_fake_iface(port, fake_iface);
1894
1895     if (bridge->parent) {
1896         int64_t tag = bridge->vlan;
1897         ovsrec_port_set_tag(port, &tag, 1);
1898     }
1899
1900     for (i = 0; i < n_settings; i++) {
1901         set_column(get_table("Port"), &port->header_, settings[i],
1902                    ctx->symtab);
1903     }
1904
1905     bridge_insert_port((bridge->parent ? bridge->parent->br_cfg
1906                         : bridge->br_cfg), port);
1907
1908     vsctl_port = add_port_to_cache(vsctl_ctx, bridge, port);
1909     for (i = 0; i < n_ifaces; i++) {
1910         add_iface_to_cache(vsctl_ctx, vsctl_port, ifaces[i]);
1911     }
1912     free(ifaces);
1913 }
1914
1915 static void
1916 cmd_add_port(struct ctl_context *ctx)
1917 {
1918     bool may_exist = shash_find(&ctx->options, "--may-exist") != NULL;
1919
1920     add_port(ctx, ctx->argv[1], ctx->argv[2], may_exist, false,
1921              &ctx->argv[2], 1, &ctx->argv[3], ctx->argc - 3);
1922 }
1923
1924 static void
1925 cmd_add_bond(struct ctl_context *ctx)
1926 {
1927     bool may_exist = shash_find(&ctx->options, "--may-exist") != NULL;
1928     bool fake_iface = shash_find(&ctx->options, "--fake-iface");
1929     int n_ifaces;
1930     int i;
1931
1932     n_ifaces = ctx->argc - 3;
1933     for (i = 3; i < ctx->argc; i++) {
1934         if (strchr(ctx->argv[i], '=')) {
1935             n_ifaces = i - 3;
1936             break;
1937         }
1938     }
1939     if (n_ifaces < 2) {
1940         ctl_fatal("add-bond requires at least 2 interfaces, but only "
1941                     "%d were specified", n_ifaces);
1942     }
1943
1944     add_port(ctx, ctx->argv[1], ctx->argv[2], may_exist, fake_iface,
1945              &ctx->argv[3], n_ifaces,
1946              &ctx->argv[n_ifaces + 3], ctx->argc - 3 - n_ifaces);
1947 }
1948
1949 static void
1950 cmd_del_port(struct ctl_context *ctx)
1951 {
1952     struct vsctl_context *vsctl_ctx = vsctl_context_cast(ctx);
1953     bool must_exist = !shash_find(&ctx->options, "--if-exists");
1954     bool with_iface = shash_find(&ctx->options, "--with-iface") != NULL;
1955     const char *target = ctx->argv[ctx->argc - 1];
1956     struct vsctl_port *port;
1957
1958     vsctl_context_populate_cache(ctx);
1959     if (find_bridge(vsctl_ctx, target, false)) {
1960         if (must_exist) {
1961             ctl_fatal("cannot delete port %s because it is the local port "
1962                         "for bridge %s (deleting this port requires deleting "
1963                         "the entire bridge)", target, target);
1964         }
1965         port = NULL;
1966     } else if (!with_iface) {
1967         port = find_port(vsctl_ctx, target, must_exist);
1968     } else {
1969         struct vsctl_iface *iface;
1970
1971         port = find_port(vsctl_ctx, target, false);
1972         if (!port) {
1973             iface = find_iface(vsctl_ctx, target, false);
1974             if (iface) {
1975                 port = iface->port;
1976             }
1977         }
1978         if (must_exist && !port) {
1979             ctl_fatal("no port or interface named %s", target);
1980         }
1981     }
1982
1983     if (port) {
1984         if (ctx->argc == 3) {
1985             struct vsctl_bridge *bridge;
1986
1987             bridge = find_bridge(vsctl_ctx, ctx->argv[1], true);
1988             if (port->bridge != bridge) {
1989                 if (port->bridge->parent == bridge) {
1990                     ctl_fatal("bridge %s does not have a port %s (although "
1991                                 "its parent bridge %s does)",
1992                                 ctx->argv[1], ctx->argv[2],
1993                                 bridge->parent->name);
1994                 } else {
1995                     ctl_fatal("bridge %s does not have a port %s",
1996                                 ctx->argv[1], ctx->argv[2]);
1997                 }
1998             }
1999         }
2000
2001         del_port(vsctl_ctx, port);
2002     }
2003 }
2004
2005 static void
2006 cmd_port_to_br(struct ctl_context *ctx)
2007 {
2008     struct vsctl_context *vsctl_ctx = vsctl_context_cast(ctx);
2009     struct vsctl_port *port;
2010
2011     vsctl_context_populate_cache(ctx);
2012
2013     port = find_port(vsctl_ctx, ctx->argv[1], true);
2014     ds_put_format(&ctx->output, "%s\n", port->bridge->name);
2015 }
2016
2017 static void
2018 cmd_br_to_vlan(struct ctl_context *ctx)
2019 {
2020     struct vsctl_context *vsctl_ctx = vsctl_context_cast(ctx);
2021     struct vsctl_bridge *bridge;
2022
2023     vsctl_context_populate_cache(ctx);
2024
2025     bridge = find_bridge(vsctl_ctx, ctx->argv[1], true);
2026     ds_put_format(&ctx->output, "%d\n", bridge->vlan);
2027 }
2028
2029 static void
2030 cmd_br_to_parent(struct ctl_context *ctx)
2031 {
2032     struct vsctl_context *vsctl_ctx = vsctl_context_cast(ctx);
2033     struct vsctl_bridge *bridge;
2034
2035     vsctl_context_populate_cache(ctx);
2036
2037     bridge = find_bridge(vsctl_ctx, ctx->argv[1], true);
2038     if (bridge->parent) {
2039         bridge = bridge->parent;
2040     }
2041     ds_put_format(&ctx->output, "%s\n", bridge->name);
2042 }
2043
2044 static void
2045 cmd_list_ifaces(struct ctl_context *ctx)
2046 {
2047     struct vsctl_context *vsctl_ctx = vsctl_context_cast(ctx);
2048     struct vsctl_bridge *br;
2049     struct vsctl_port *port;
2050     struct svec ifaces;
2051
2052     vsctl_context_populate_cache(ctx);
2053
2054     br = find_bridge(vsctl_ctx, ctx->argv[1], true);
2055     verify_ports(vsctl_ctx);
2056
2057     svec_init(&ifaces);
2058     LIST_FOR_EACH (port, ports_node, &br->ports) {
2059         struct vsctl_iface *iface;
2060
2061         LIST_FOR_EACH (iface, ifaces_node, &port->ifaces) {
2062             if (strcmp(iface->iface_cfg->name, br->name)) {
2063                 svec_add(&ifaces, iface->iface_cfg->name);
2064             }
2065         }
2066     }
2067     output_sorted(&ifaces, &ctx->output);
2068     svec_destroy(&ifaces);
2069 }
2070
2071 static void
2072 cmd_iface_to_br(struct ctl_context *ctx)
2073 {
2074     struct vsctl_context *vsctl_ctx = vsctl_context_cast(ctx);
2075     struct vsctl_iface *iface;
2076
2077     vsctl_context_populate_cache(ctx);
2078
2079     iface = find_iface(vsctl_ctx, ctx->argv[1], true);
2080     ds_put_format(&ctx->output, "%s\n", iface->port->bridge->name);
2081 }
2082
2083 static void
2084 verify_controllers(struct ovsrec_bridge *bridge)
2085 {
2086     size_t i;
2087
2088     ovsrec_bridge_verify_controller(bridge);
2089     for (i = 0; i < bridge->n_controller; i++) {
2090         ovsrec_controller_verify_target(bridge->controller[i]);
2091     }
2092 }
2093
2094 static void
2095 pre_controller(struct ctl_context *ctx)
2096 {
2097     pre_get_info(ctx);
2098
2099     ovsdb_idl_add_column(ctx->idl, &ovsrec_controller_col_target);
2100 }
2101
2102 static void
2103 cmd_get_controller(struct ctl_context *ctx)
2104 {
2105     struct vsctl_context *vsctl_ctx = vsctl_context_cast(ctx);
2106     struct vsctl_bridge *br;
2107     struct svec targets;
2108     size_t i;
2109
2110     vsctl_context_populate_cache(ctx);
2111
2112     br = find_bridge(vsctl_ctx, ctx->argv[1], true);
2113     if (br->parent) {
2114         br = br->parent;
2115     }
2116     verify_controllers(br->br_cfg);
2117
2118     /* Print the targets in sorted order for reproducibility. */
2119     svec_init(&targets);
2120     for (i = 0; i < br->br_cfg->n_controller; i++) {
2121         svec_add(&targets, br->br_cfg->controller[i]->target);
2122     }
2123
2124     svec_sort(&targets);
2125     for (i = 0; i < targets.n; i++) {
2126         ds_put_format(&ctx->output, "%s\n", targets.names[i]);
2127     }
2128     svec_destroy(&targets);
2129 }
2130
2131 static void
2132 delete_controllers(struct ovsrec_controller **controllers,
2133                    size_t n_controllers)
2134 {
2135     size_t i;
2136
2137     for (i = 0; i < n_controllers; i++) {
2138         ovsrec_controller_delete(controllers[i]);
2139     }
2140 }
2141
2142 static void
2143 cmd_del_controller(struct ctl_context *ctx)
2144 {
2145     struct vsctl_context *vsctl_ctx = vsctl_context_cast(ctx);
2146     struct ovsrec_bridge *br;
2147
2148     vsctl_context_populate_cache(ctx);
2149
2150     br = find_real_bridge(vsctl_ctx, ctx->argv[1], true)->br_cfg;
2151     verify_controllers(br);
2152
2153     if (br->controller) {
2154         delete_controllers(br->controller, br->n_controller);
2155         ovsrec_bridge_set_controller(br, NULL, 0);
2156     }
2157 }
2158
2159 static struct ovsrec_controller **
2160 insert_controllers(struct ovsdb_idl_txn *txn, char *targets[], size_t n)
2161 {
2162     struct ovsrec_controller **controllers;
2163     size_t i;
2164
2165     controllers = xmalloc(n * sizeof *controllers);
2166     for (i = 0; i < n; i++) {
2167         if (vconn_verify_name(targets[i]) && pvconn_verify_name(targets[i])) {
2168             VLOG_WARN("target type \"%s\" is possibly erroneous", targets[i]);
2169         }
2170         controllers[i] = ovsrec_controller_insert(txn);
2171         ovsrec_controller_set_target(controllers[i], targets[i]);
2172     }
2173
2174     return controllers;
2175 }
2176
2177 static void
2178 cmd_set_controller(struct ctl_context *ctx)
2179 {
2180     struct vsctl_context *vsctl_ctx = vsctl_context_cast(ctx);
2181     struct ovsrec_controller **controllers;
2182     struct ovsrec_bridge *br;
2183     size_t n;
2184
2185     vsctl_context_populate_cache(ctx);
2186
2187     br = find_real_bridge(vsctl_ctx, ctx->argv[1], true)->br_cfg;
2188     verify_controllers(br);
2189
2190     delete_controllers(br->controller, br->n_controller);
2191
2192     n = ctx->argc - 2;
2193     controllers = insert_controllers(ctx->txn, &ctx->argv[2], n);
2194     ovsrec_bridge_set_controller(br, controllers, n);
2195     free(controllers);
2196 }
2197
2198 static void
2199 cmd_get_fail_mode(struct ctl_context *ctx)
2200 {
2201     struct vsctl_context *vsctl_ctx = vsctl_context_cast(ctx);
2202     struct vsctl_bridge *br;
2203     const char *fail_mode;
2204
2205     vsctl_context_populate_cache(ctx);
2206     br = find_bridge(vsctl_ctx, ctx->argv[1], true);
2207
2208     if (br->parent) {
2209         br = br->parent;
2210     }
2211     ovsrec_bridge_verify_fail_mode(br->br_cfg);
2212
2213     fail_mode = br->br_cfg->fail_mode;
2214     if (fail_mode && strlen(fail_mode)) {
2215         ds_put_format(&ctx->output, "%s\n", fail_mode);
2216     }
2217 }
2218
2219 static void
2220 cmd_del_fail_mode(struct ctl_context *ctx)
2221 {
2222     struct vsctl_context *vsctl_ctx = vsctl_context_cast(ctx);
2223     struct vsctl_bridge *br;
2224
2225     vsctl_context_populate_cache(ctx);
2226
2227     br = find_real_bridge(vsctl_ctx, ctx->argv[1], true);
2228
2229     ovsrec_bridge_set_fail_mode(br->br_cfg, NULL);
2230 }
2231
2232 static void
2233 cmd_set_fail_mode(struct ctl_context *ctx)
2234 {
2235     struct vsctl_context *vsctl_ctx = vsctl_context_cast(ctx);
2236     struct vsctl_bridge *br;
2237     const char *fail_mode = ctx->argv[2];
2238
2239     vsctl_context_populate_cache(ctx);
2240
2241     br = find_real_bridge(vsctl_ctx, ctx->argv[1], true);
2242
2243     if (strcmp(fail_mode, "standalone") && strcmp(fail_mode, "secure")) {
2244         ctl_fatal("fail-mode must be \"standalone\" or \"secure\"");
2245     }
2246
2247     ovsrec_bridge_set_fail_mode(br->br_cfg, fail_mode);
2248 }
2249
2250 static void
2251 verify_managers(const struct ovsrec_open_vswitch *ovs)
2252 {
2253     size_t i;
2254
2255     ovsrec_open_vswitch_verify_manager_options(ovs);
2256
2257     for (i = 0; i < ovs->n_manager_options; ++i) {
2258         const struct ovsrec_manager *mgr = ovs->manager_options[i];
2259
2260         ovsrec_manager_verify_target(mgr);
2261     }
2262 }
2263
2264 static void
2265 pre_manager(struct ctl_context *ctx)
2266 {
2267     ovsdb_idl_add_column(ctx->idl, &ovsrec_open_vswitch_col_manager_options);
2268     ovsdb_idl_add_column(ctx->idl, &ovsrec_manager_col_target);
2269 }
2270
2271 static void
2272 cmd_get_manager(struct ctl_context *ctx)
2273 {
2274     struct vsctl_context *vsctl_ctx = vsctl_context_cast(ctx);
2275     const struct ovsrec_open_vswitch *ovs = vsctl_ctx->ovs;
2276     struct svec targets;
2277     size_t i;
2278
2279     verify_managers(ovs);
2280
2281     /* Print the targets in sorted order for reproducibility. */
2282     svec_init(&targets);
2283
2284     for (i = 0; i < ovs->n_manager_options; i++) {
2285         svec_add(&targets, ovs->manager_options[i]->target);
2286     }
2287
2288     svec_sort_unique(&targets);
2289     for (i = 0; i < targets.n; i++) {
2290         ds_put_format(&ctx->output, "%s\n", targets.names[i]);
2291     }
2292     svec_destroy(&targets);
2293 }
2294
2295 static void
2296 delete_managers(const struct ovsrec_open_vswitch *ovs)
2297 {
2298     size_t i;
2299
2300     /* Delete Manager rows pointed to by 'manager_options' column. */
2301     for (i = 0; i < ovs->n_manager_options; i++) {
2302         ovsrec_manager_delete(ovs->manager_options[i]);
2303     }
2304
2305     /* Delete 'Manager' row refs in 'manager_options' column. */
2306     ovsrec_open_vswitch_set_manager_options(ovs, NULL, 0);
2307 }
2308
2309 static void
2310 cmd_del_manager(struct ctl_context *ctx)
2311 {
2312     struct vsctl_context *vsctl_ctx = vsctl_context_cast(ctx);
2313     const struct ovsrec_open_vswitch *ovs = vsctl_ctx->ovs;
2314
2315     verify_managers(ovs);
2316     delete_managers(ovs);
2317 }
2318
2319 static void
2320 insert_managers(struct vsctl_context *vsctl_ctx, char *targets[], size_t n)
2321 {
2322     struct ovsrec_manager **managers;
2323     size_t i;
2324
2325     /* Insert each manager in a new row in Manager table. */
2326     managers = xmalloc(n * sizeof *managers);
2327     for (i = 0; i < n; i++) {
2328         if (stream_verify_name(targets[i]) && pstream_verify_name(targets[i])) {
2329             VLOG_WARN("target type \"%s\" is possibly erroneous", targets[i]);
2330         }
2331         managers[i] = ovsrec_manager_insert(vsctl_ctx->base.txn);
2332         ovsrec_manager_set_target(managers[i], targets[i]);
2333     }
2334
2335     /* Store uuids of new Manager rows in 'manager_options' column. */
2336     ovsrec_open_vswitch_set_manager_options(vsctl_ctx->ovs, managers, n);
2337     free(managers);
2338 }
2339
2340 static void
2341 cmd_set_manager(struct ctl_context *ctx)
2342 {
2343     struct vsctl_context *vsctl_ctx = vsctl_context_cast(ctx);
2344     const size_t n = ctx->argc - 1;
2345
2346     verify_managers(vsctl_ctx->ovs);
2347     delete_managers(vsctl_ctx->ovs);
2348     insert_managers(vsctl_ctx, &ctx->argv[1], n);
2349 }
2350
2351 static void
2352 pre_cmd_get_ssl(struct ctl_context *ctx)
2353 {
2354     ovsdb_idl_add_column(ctx->idl, &ovsrec_open_vswitch_col_ssl);
2355
2356     ovsdb_idl_add_column(ctx->idl, &ovsrec_ssl_col_private_key);
2357     ovsdb_idl_add_column(ctx->idl, &ovsrec_ssl_col_certificate);
2358     ovsdb_idl_add_column(ctx->idl, &ovsrec_ssl_col_ca_cert);
2359     ovsdb_idl_add_column(ctx->idl, &ovsrec_ssl_col_bootstrap_ca_cert);
2360 }
2361
2362 static void
2363 cmd_get_ssl(struct ctl_context *ctx)
2364 {
2365     struct vsctl_context *vsctl_ctx = vsctl_context_cast(ctx);
2366     struct ovsrec_ssl *ssl = vsctl_ctx->ovs->ssl;
2367
2368     ovsrec_open_vswitch_verify_ssl(vsctl_ctx->ovs);
2369     if (ssl) {
2370         ovsrec_ssl_verify_private_key(ssl);
2371         ovsrec_ssl_verify_certificate(ssl);
2372         ovsrec_ssl_verify_ca_cert(ssl);
2373         ovsrec_ssl_verify_bootstrap_ca_cert(ssl);
2374
2375         ds_put_format(&ctx->output, "Private key: %s\n", ssl->private_key);
2376         ds_put_format(&ctx->output, "Certificate: %s\n", ssl->certificate);
2377         ds_put_format(&ctx->output, "CA Certificate: %s\n", ssl->ca_cert);
2378         ds_put_format(&ctx->output, "Bootstrap: %s\n",
2379                 ssl->bootstrap_ca_cert ? "true" : "false");
2380     }
2381 }
2382
2383 static void
2384 pre_cmd_del_ssl(struct ctl_context *ctx)
2385 {
2386     ovsdb_idl_add_column(ctx->idl, &ovsrec_open_vswitch_col_ssl);
2387 }
2388
2389 static void
2390 cmd_del_ssl(struct ctl_context *ctx)
2391 {
2392     struct vsctl_context *vsctl_ctx = vsctl_context_cast(ctx);
2393     struct ovsrec_ssl *ssl = vsctl_ctx->ovs->ssl;
2394
2395     if (ssl) {
2396         ovsrec_open_vswitch_verify_ssl(vsctl_ctx->ovs);
2397         ovsrec_ssl_delete(ssl);
2398         ovsrec_open_vswitch_set_ssl(vsctl_ctx->ovs, NULL);
2399     }
2400 }
2401
2402 static void
2403 pre_cmd_set_ssl(struct ctl_context *ctx)
2404 {
2405     ovsdb_idl_add_column(ctx->idl, &ovsrec_open_vswitch_col_ssl);
2406 }
2407
2408 static void
2409 cmd_set_ssl(struct ctl_context *ctx)
2410 {
2411     struct vsctl_context *vsctl_ctx = vsctl_context_cast(ctx);
2412     bool bootstrap = shash_find(&ctx->options, "--bootstrap");
2413     struct ovsrec_ssl *ssl = vsctl_ctx->ovs->ssl;
2414
2415     ovsrec_open_vswitch_verify_ssl(vsctl_ctx->ovs);
2416     if (ssl) {
2417         ovsrec_ssl_delete(ssl);
2418     }
2419     ssl = ovsrec_ssl_insert(ctx->txn);
2420
2421     ovsrec_ssl_set_private_key(ssl, ctx->argv[1]);
2422     ovsrec_ssl_set_certificate(ssl, ctx->argv[2]);
2423     ovsrec_ssl_set_ca_cert(ssl, ctx->argv[3]);
2424
2425     ovsrec_ssl_set_bootstrap_ca_cert(ssl, bootstrap);
2426
2427     ovsrec_open_vswitch_set_ssl(vsctl_ctx->ovs, ssl);
2428 }
2429
2430 static void
2431 autoattach_insert_mapping(struct ovsrec_autoattach *aa,
2432                           int64_t isid,
2433                           int64_t vlan)
2434 {
2435     int64_t *key_mappings, *value_mappings;
2436     size_t i;
2437
2438     key_mappings = xmalloc(sizeof *aa->key_mappings * (aa->n_mappings + 1));
2439     value_mappings = xmalloc(sizeof *aa->value_mappings * (aa->n_mappings + 1));
2440
2441     for (i = 0; i < aa->n_mappings; i++) {
2442         key_mappings[i] = aa->key_mappings[i];
2443         value_mappings[i] = aa->value_mappings[i];
2444     }
2445     key_mappings[aa->n_mappings] = isid;
2446     value_mappings[aa->n_mappings] = vlan;
2447
2448     ovsrec_autoattach_set_mappings(aa, key_mappings, value_mappings,
2449                                    aa->n_mappings + 1);
2450
2451     free(key_mappings);
2452     free(value_mappings);
2453 }
2454
2455 static void
2456 cmd_add_aa_mapping(struct ctl_context *ctx)
2457 {
2458     struct vsctl_context *vsctl_ctx = vsctl_context_cast(ctx);
2459     struct vsctl_bridge *br;
2460     int64_t isid, vlan;
2461     char *nptr = NULL;
2462
2463     isid = strtoull(ctx->argv[2], &nptr, 10);
2464     if (nptr == ctx->argv[2] || nptr == NULL) {
2465         ctl_fatal("Invalid argument %s", ctx->argv[2]);
2466         return;
2467     }
2468
2469     vlan = strtoull(ctx->argv[3], &nptr, 10);
2470     if (nptr == ctx->argv[3] || nptr == NULL) {
2471         ctl_fatal("Invalid argument %s", ctx->argv[3]);
2472         return;
2473     }
2474
2475     vsctl_context_populate_cache(ctx);
2476
2477     br = find_bridge(vsctl_ctx, ctx->argv[1], true);
2478     if (br->parent) {
2479         br = br->parent;
2480     }
2481
2482     if (br && br->br_cfg) {
2483         if (!br->br_cfg->auto_attach) {
2484             struct ovsrec_autoattach *aa = ovsrec_autoattach_insert(ctx->txn);
2485             ovsrec_bridge_set_auto_attach(br->br_cfg, aa);
2486         }
2487         autoattach_insert_mapping(br->br_cfg->auto_attach, isid, vlan);
2488     }
2489 }
2490
2491 static void
2492 del_aa_mapping(struct ovsrec_autoattach *aa,
2493                int64_t isid,
2494                int64_t vlan)
2495 {
2496     int64_t *key_mappings, *value_mappings;
2497     size_t i, n;
2498
2499     key_mappings = xmalloc(sizeof *aa->key_mappings * (aa->n_mappings));
2500     value_mappings = xmalloc(sizeof *value_mappings * (aa->n_mappings));
2501
2502     for (i = n = 0; i < aa->n_mappings; i++) {
2503         if (aa->key_mappings[i] != isid && aa->value_mappings[i] != vlan) {
2504             key_mappings[n] = aa->key_mappings[i];
2505             value_mappings[n++] = aa->value_mappings[i];
2506         }
2507     }
2508
2509     ovsrec_autoattach_set_mappings(aa, key_mappings, value_mappings, n);
2510
2511     free(key_mappings);
2512     free(value_mappings);
2513 }
2514
2515 static void
2516 cmd_del_aa_mapping(struct ctl_context *ctx)
2517 {
2518     struct vsctl_context *vsctl_ctx = vsctl_context_cast(ctx);
2519     struct vsctl_bridge *br;
2520     int64_t isid, vlan;
2521     char *nptr = NULL;
2522
2523     isid = strtoull(ctx->argv[2], &nptr, 10);
2524     if (nptr == ctx->argv[2] || nptr == NULL) {
2525         ctl_fatal("Invalid argument %s", ctx->argv[2]);
2526         return;
2527     }
2528
2529     vlan = strtoull(ctx->argv[3], &nptr, 10);
2530     if (nptr == ctx->argv[3] || nptr == NULL) {
2531         ctl_fatal("Invalid argument %s", ctx->argv[3]);
2532         return;
2533     }
2534
2535     vsctl_context_populate_cache(ctx);
2536
2537     br = find_bridge(vsctl_ctx, ctx->argv[1], true);
2538     if (br->parent) {
2539         br = br->parent;
2540     }
2541
2542     if (br && br->br_cfg && br->br_cfg->auto_attach &&
2543         br->br_cfg->auto_attach->key_mappings &&
2544         br->br_cfg->auto_attach->value_mappings) {
2545         size_t i;
2546
2547         for (i = 0; i < br->br_cfg->auto_attach->n_mappings; i++) {
2548             if (br->br_cfg->auto_attach->key_mappings[i] == isid &&
2549                 br->br_cfg->auto_attach->value_mappings[i] == vlan) {
2550                 del_aa_mapping(br->br_cfg->auto_attach, isid, vlan);
2551                 break;
2552             }
2553         }
2554     }
2555 }
2556
2557 static void
2558 pre_aa_mapping(struct ctl_context *ctx)
2559 {
2560     pre_get_info(ctx);
2561
2562     ovsdb_idl_add_column(ctx->idl, &ovsrec_bridge_col_auto_attach);
2563     ovsdb_idl_add_column(ctx->idl, &ovsrec_autoattach_col_mappings);
2564 }
2565
2566 static void
2567 verify_auto_attach(struct ovsrec_bridge *bridge)
2568 {
2569     if (bridge) {
2570         ovsrec_bridge_verify_auto_attach(bridge);
2571
2572         if (bridge->auto_attach) {
2573             ovsrec_autoattach_verify_mappings(bridge->auto_attach);
2574         }
2575     }
2576 }
2577
2578 static void
2579 cmd_get_aa_mapping(struct ctl_context *ctx)
2580 {
2581     struct vsctl_context *vsctl_ctx = vsctl_context_cast(ctx);
2582     struct vsctl_bridge *br;
2583
2584     vsctl_context_populate_cache(ctx);
2585
2586     br = find_bridge(vsctl_ctx, ctx->argv[1], true);
2587     if (br->parent) {
2588         br = br->parent;
2589     }
2590
2591     verify_auto_attach(br->br_cfg);
2592
2593     if (br && br->br_cfg && br->br_cfg->auto_attach &&
2594         br->br_cfg->auto_attach->key_mappings &&
2595         br->br_cfg->auto_attach->value_mappings) {
2596         size_t i;
2597
2598         for (i = 0; i < br->br_cfg->auto_attach->n_mappings; i++) {
2599             ds_put_format(&ctx->output, "%"PRId64" %"PRId64"\n",
2600                           br->br_cfg->auto_attach->key_mappings[i],
2601                           br->br_cfg->auto_attach->value_mappings[i]);
2602         }
2603     }
2604 }
2605
2606 \f
2607 const struct ctl_table_class tables[] = {
2608     {&ovsrec_table_bridge,
2609      {{&ovsrec_table_bridge, &ovsrec_bridge_col_name, NULL},
2610       {&ovsrec_table_flow_sample_collector_set, NULL,
2611        &ovsrec_flow_sample_collector_set_col_bridge}}},
2612
2613     {&ovsrec_table_controller,
2614      {{&ovsrec_table_bridge,
2615        &ovsrec_bridge_col_name,
2616        &ovsrec_bridge_col_controller}}},
2617
2618     {&ovsrec_table_interface,
2619      {{&ovsrec_table_interface, &ovsrec_interface_col_name, NULL},
2620       {NULL, NULL, NULL}}},
2621
2622     {&ovsrec_table_mirror,
2623      {{&ovsrec_table_mirror, &ovsrec_mirror_col_name, NULL},
2624       {NULL, NULL, NULL}}},
2625
2626     {&ovsrec_table_manager,
2627      {{&ovsrec_table_manager, &ovsrec_manager_col_target, NULL},
2628       {NULL, NULL, NULL}}},
2629
2630     {&ovsrec_table_netflow,
2631      {{&ovsrec_table_bridge,
2632        &ovsrec_bridge_col_name,
2633        &ovsrec_bridge_col_netflow},
2634       {NULL, NULL, NULL}}},
2635
2636     {&ovsrec_table_open_vswitch,
2637      {{&ovsrec_table_open_vswitch, NULL, NULL},
2638       {NULL, NULL, NULL}}},
2639
2640     {&ovsrec_table_port,
2641      {{&ovsrec_table_port, &ovsrec_port_col_name, NULL},
2642       {NULL, NULL, NULL}}},
2643
2644     {&ovsrec_table_qos,
2645      {{&ovsrec_table_port, &ovsrec_port_col_name, &ovsrec_port_col_qos},
2646       {NULL, NULL, NULL}}},
2647
2648     {&ovsrec_table_queue,
2649      {{NULL, NULL, NULL},
2650       {NULL, NULL, NULL}}},
2651
2652     {&ovsrec_table_ssl,
2653      {{&ovsrec_table_open_vswitch, NULL, &ovsrec_open_vswitch_col_ssl}}},
2654
2655     {&ovsrec_table_sflow,
2656      {{&ovsrec_table_bridge,
2657        &ovsrec_bridge_col_name,
2658        &ovsrec_bridge_col_sflow},
2659       {NULL, NULL, NULL}}},
2660
2661     {&ovsrec_table_flow_table,
2662      {{&ovsrec_table_flow_table, &ovsrec_flow_table_col_name, NULL},
2663       {NULL, NULL, NULL}}},
2664
2665     {&ovsrec_table_ipfix,
2666      {{&ovsrec_table_bridge,
2667        &ovsrec_bridge_col_name,
2668        &ovsrec_bridge_col_ipfix},
2669       {&ovsrec_table_flow_sample_collector_set, NULL,
2670        &ovsrec_flow_sample_collector_set_col_ipfix}}},
2671
2672     {&ovsrec_table_autoattach,
2673      {{&ovsrec_table_bridge,
2674        &ovsrec_bridge_col_name,
2675        &ovsrec_bridge_col_auto_attach},
2676       {NULL, NULL, NULL}}},
2677
2678     {&ovsrec_table_flow_sample_collector_set,
2679      {{NULL, NULL, NULL},
2680       {NULL, NULL, NULL}}},
2681
2682     {NULL, {{NULL, NULL, NULL}, {NULL, NULL, NULL}}}
2683 };
2684
2685 static void
2686 post_db_reload_check_init(void)
2687 {
2688     n_neoteric_ifaces = 0;
2689 }
2690
2691 static void
2692 post_db_reload_expect_iface(const struct ovsrec_interface *iface)
2693 {
2694     if (n_neoteric_ifaces >= allocated_neoteric_ifaces) {
2695         neoteric_ifaces = x2nrealloc(neoteric_ifaces,
2696                                      &allocated_neoteric_ifaces,
2697                                      sizeof *neoteric_ifaces);
2698     }
2699     neoteric_ifaces[n_neoteric_ifaces++] = iface->header_.uuid;
2700 }
2701
2702 static void
2703 post_db_reload_do_checks(const struct vsctl_context *vsctl_ctx)
2704 {
2705     struct ds dead_ifaces = DS_EMPTY_INITIALIZER;
2706     size_t i;
2707
2708     for (i = 0; i < n_neoteric_ifaces; i++) {
2709         const struct uuid *uuid;
2710
2711         uuid = ovsdb_idl_txn_get_insert_uuid(vsctl_ctx->base.txn,
2712                                              &neoteric_ifaces[i]);
2713         if (uuid) {
2714             const struct ovsrec_interface *iface;
2715
2716             iface = ovsrec_interface_get_for_uuid(vsctl_ctx->base.idl, uuid);
2717             if (iface && (!iface->ofport || *iface->ofport == -1)) {
2718                 ds_put_format(&dead_ifaces, "'%s', ", iface->name);
2719             }
2720         }
2721     }
2722
2723     if (dead_ifaces.length) {
2724         dead_ifaces.length -= 2; /* Strip off trailing comma and space. */
2725         ovs_error(0, "Error detected while setting up %s.  See ovs-vswitchd "
2726                   "log for details.", ds_cstr(&dead_ifaces));
2727     }
2728
2729     ds_destroy(&dead_ifaces);
2730 }
2731
2732 \f
2733 static void
2734 vsctl_context_init_command(struct vsctl_context *vsctl_ctx,
2735                            struct ctl_command *command)
2736 {
2737     ctl_context_init_command(&vsctl_ctx->base, command);
2738     vsctl_ctx->verified_ports = false;
2739 }
2740
2741 static void
2742 vsctl_context_init(struct vsctl_context *vsctl_ctx,
2743                    struct ctl_command *command, struct ovsdb_idl *idl,
2744                    struct ovsdb_idl_txn *txn,
2745                    const struct ovsrec_open_vswitch *ovs,
2746                    struct ovsdb_symbol_table *symtab)
2747 {
2748     ctl_context_init(&vsctl_ctx->base, command, idl, txn, symtab,
2749                      vsctl_context_invalidate_cache);
2750     if (command) {
2751         vsctl_ctx->verified_ports = false;
2752     }
2753     vsctl_ctx->ovs = ovs;
2754     vsctl_ctx->cache_valid = false;
2755 }
2756
2757 static void
2758 vsctl_context_done_command(struct vsctl_context *vsctl_ctx,
2759                            struct ctl_command *command)
2760 {
2761     ctl_context_done_command(&vsctl_ctx->base, command);
2762 }
2763
2764 static void
2765 vsctl_context_done(struct vsctl_context *vsctl_ctx,
2766                    struct ctl_command *command)
2767 {
2768     ctl_context_done(&vsctl_ctx->base, command);
2769 }
2770
2771 static void
2772 run_prerequisites(struct ctl_command *commands, size_t n_commands,
2773                   struct ovsdb_idl *idl)
2774 {
2775     struct ctl_command *c;
2776
2777     ovsdb_idl_add_table(idl, &ovsrec_table_open_vswitch);
2778     if (wait_for_reload) {
2779         ovsdb_idl_add_column(idl, &ovsrec_open_vswitch_col_cur_cfg);
2780     }
2781     for (c = commands; c < &commands[n_commands]; c++) {
2782         if (c->syntax->prerequisites) {
2783             struct vsctl_context vsctl_ctx;
2784
2785             ds_init(&c->output);
2786             c->table = NULL;
2787
2788             vsctl_context_init(&vsctl_ctx, c, idl, NULL, NULL, NULL);
2789             (c->syntax->prerequisites)(&vsctl_ctx.base);
2790             vsctl_context_done(&vsctl_ctx, c);
2791
2792             ovs_assert(!c->output.string);
2793             ovs_assert(!c->table);
2794         }
2795     }
2796 }
2797
2798 static void
2799 do_vsctl(const char *args, struct ctl_command *commands, size_t n_commands,
2800          struct ovsdb_idl *idl)
2801 {
2802     struct ovsdb_idl_txn *txn;
2803     const struct ovsrec_open_vswitch *ovs;
2804     enum ovsdb_idl_txn_status status;
2805     struct ovsdb_symbol_table *symtab;
2806     struct vsctl_context vsctl_ctx;
2807     struct ctl_command *c;
2808     struct shash_node *node;
2809     int64_t next_cfg = 0;
2810     char *error = NULL;
2811
2812     txn = the_idl_txn = ovsdb_idl_txn_create(idl);
2813     if (dry_run) {
2814         ovsdb_idl_txn_set_dry_run(txn);
2815     }
2816
2817     ovsdb_idl_txn_add_comment(txn, "ovs-vsctl: %s", args);
2818
2819     ovs = ovsrec_open_vswitch_first(idl);
2820     if (!ovs) {
2821         /* XXX add verification that table is empty */
2822         ovs = ovsrec_open_vswitch_insert(txn);
2823     }
2824
2825     if (wait_for_reload) {
2826         ovsdb_idl_txn_increment(txn, &ovs->header_,
2827                                 &ovsrec_open_vswitch_col_next_cfg);
2828     }
2829
2830     post_db_reload_check_init();
2831     symtab = ovsdb_symbol_table_create();
2832     for (c = commands; c < &commands[n_commands]; c++) {
2833         ds_init(&c->output);
2834         c->table = NULL;
2835     }
2836     vsctl_context_init(&vsctl_ctx, NULL, idl, txn, ovs, symtab);
2837     for (c = commands; c < &commands[n_commands]; c++) {
2838         vsctl_context_init_command(&vsctl_ctx, c);
2839         if (c->syntax->run) {
2840             (c->syntax->run)(&vsctl_ctx.base);
2841         }
2842         vsctl_context_done_command(&vsctl_ctx, c);
2843
2844         if (vsctl_ctx.base.try_again) {
2845             vsctl_context_done(&vsctl_ctx, NULL);
2846             goto try_again;
2847         }
2848     }
2849     vsctl_context_done(&vsctl_ctx, NULL);
2850
2851     SHASH_FOR_EACH (node, &symtab->sh) {
2852         struct ovsdb_symbol *symbol = node->data;
2853         if (!symbol->created) {
2854             ctl_fatal("row id \"%s\" is referenced but never created (e.g. "
2855                         "with \"-- --id=%s create ...\")",
2856                         node->name, node->name);
2857         }
2858         if (!symbol->strong_ref) {
2859             if (!symbol->weak_ref) {
2860                 VLOG_WARN("row id \"%s\" was created but no reference to it "
2861                           "was inserted, so it will not actually appear in "
2862                           "the database", node->name);
2863             } else {
2864                 VLOG_WARN("row id \"%s\" was created but only a weak "
2865                           "reference to it was inserted, so it will not "
2866                           "actually appear in the database", node->name);
2867             }
2868         }
2869     }
2870
2871     status = ovsdb_idl_txn_commit_block(txn);
2872     if (wait_for_reload && status == TXN_SUCCESS) {
2873         next_cfg = ovsdb_idl_txn_get_increment_new_value(txn);
2874     }
2875     if (status == TXN_UNCHANGED || status == TXN_SUCCESS) {
2876         for (c = commands; c < &commands[n_commands]; c++) {
2877             if (c->syntax->postprocess) {
2878                 vsctl_context_init(&vsctl_ctx, c, idl, txn, ovs, symtab);
2879                 (c->syntax->postprocess)(&vsctl_ctx.base);
2880                 vsctl_context_done(&vsctl_ctx, c);
2881             }
2882         }
2883     }
2884     error = xstrdup(ovsdb_idl_txn_get_error(txn));
2885
2886     switch (status) {
2887     case TXN_UNCOMMITTED:
2888     case TXN_INCOMPLETE:
2889         OVS_NOT_REACHED();
2890
2891     case TXN_ABORTED:
2892         /* Should not happen--we never call ovsdb_idl_txn_abort(). */
2893         ctl_fatal("transaction aborted");
2894
2895     case TXN_UNCHANGED:
2896     case TXN_SUCCESS:
2897         break;
2898
2899     case TXN_TRY_AGAIN:
2900         goto try_again;
2901
2902     case TXN_ERROR:
2903         ctl_fatal("transaction error: %s", error);
2904
2905     case TXN_NOT_LOCKED:
2906         /* Should not happen--we never call ovsdb_idl_set_lock(). */
2907         ctl_fatal("database not locked");
2908
2909     default:
2910         OVS_NOT_REACHED();
2911     }
2912     free(error);
2913
2914     ovsdb_symbol_table_destroy(symtab);
2915
2916     for (c = commands; c < &commands[n_commands]; c++) {
2917         struct ds *ds = &c->output;
2918
2919         if (c->table) {
2920             table_print(c->table, &table_style);
2921         } else if (oneline) {
2922             size_t j;
2923
2924             ds_chomp(ds, '\n');
2925             for (j = 0; j < ds->length; j++) {
2926                 int ch = ds->string[j];
2927                 switch (ch) {
2928                 case '\n':
2929                     fputs("\\n", stdout);
2930                     break;
2931
2932                 case '\\':
2933                     fputs("\\\\", stdout);
2934                     break;
2935
2936                 default:
2937                     putchar(ch);
2938                 }
2939             }
2940             putchar('\n');
2941         } else {
2942             fputs(ds_cstr(ds), stdout);
2943         }
2944         ds_destroy(&c->output);
2945         table_destroy(c->table);
2946         free(c->table);
2947
2948         shash_destroy_free_data(&c->options);
2949     }
2950     free(commands);
2951
2952     if (wait_for_reload && status != TXN_UNCHANGED) {
2953         /* Even, if --retry flag was not specified, ovs-vsctl still
2954          * has to retry to establish OVSDB connection, if wait_for_reload
2955          * was set.  Otherwise, ovs-vsctl would end up waiting forever
2956          * until cur_cfg would be updated. */
2957         ovsdb_idl_enable_reconnect(idl);
2958         for (;;) {
2959             ovsdb_idl_run(idl);
2960             OVSREC_OPEN_VSWITCH_FOR_EACH (ovs, idl) {
2961                 if (ovs->cur_cfg >= next_cfg) {
2962                     post_db_reload_do_checks(&vsctl_ctx);
2963                     goto done;
2964                 }
2965             }
2966             ovsdb_idl_wait(idl);
2967             poll_block();
2968         }
2969     done: ;
2970     }
2971     ovsdb_idl_txn_destroy(txn);
2972     ovsdb_idl_destroy(idl);
2973
2974     exit(EXIT_SUCCESS);
2975
2976 try_again:
2977     /* Our transaction needs to be rerun, or a prerequisite was not met.  Free
2978      * resources and return so that the caller can try again. */
2979     if (txn) {
2980         ovsdb_idl_txn_abort(txn);
2981         ovsdb_idl_txn_destroy(txn);
2982         the_idl_txn = NULL;
2983     }
2984     ovsdb_symbol_table_destroy(symtab);
2985     for (c = commands; c < &commands[n_commands]; c++) {
2986         ds_destroy(&c->output);
2987         table_destroy(c->table);
2988         free(c->table);
2989     }
2990     free(error);
2991 }
2992
2993 /*
2994  * Developers who add new commands to the 'struct ctl_command_syntax' must
2995  * define the 'arguments' member of the struct.  The following keywords are
2996  * available for composing the argument format:
2997  *
2998  *    TABLE     RECORD       BRIDGE       PARENT         PORT
2999  *    KEY       VALUE        ARG          KEY=VALUE      ?KEY=VALUE
3000  *    IFACE     SYSIFACE     COLUMN       COLUMN?:KEY    COLUMN?:KEY=VALUE
3001  *    MODE      CA-CERT      CERTIFICATE  PRIVATE-KEY
3002  *    TARGET    NEW-* (e.g. NEW-PORT)
3003  *
3004  * For argument types not listed above, just uses 'ARG' as place holder.
3005  *
3006  * Encloses the keyword with '[]' if it is optional.  Appends '...' to
3007  * keyword or enclosed keyword to indicate that the argument can be specified
3008  * multiple times.
3009  *
3010  * */
3011 static const struct ctl_command_syntax vsctl_commands[] = {
3012     /* Open vSwitch commands. */
3013     {"init", 0, 0, "", NULL, cmd_init, NULL, "", RW},
3014     {"show", 0, 0, "", pre_cmd_show, cmd_show, NULL, "", RO},
3015
3016     /* Bridge commands. */
3017     {"add-br", 1, 3, "NEW-BRIDGE [PARENT] [NEW-VLAN]", pre_get_info,
3018      cmd_add_br, NULL, "--may-exist", RW},
3019     {"del-br", 1, 1, "BRIDGE", pre_get_info, cmd_del_br,
3020      NULL, "--if-exists", RW},
3021     {"list-br", 0, 0, "", pre_get_info, cmd_list_br, NULL, "--real,--fake",
3022      RO},
3023     {"br-exists", 1, 1, "BRIDGE", pre_get_info, cmd_br_exists, NULL, "", RO},
3024     {"br-to-vlan", 1, 1, "BRIDGE", pre_get_info, cmd_br_to_vlan, NULL, "",
3025      RO},
3026     {"br-to-parent", 1, 1, "BRIDGE", pre_get_info, cmd_br_to_parent, NULL,
3027      "", RO},
3028     {"br-set-external-id", 2, 3, "BRIDGE KEY [VALUE]",
3029      pre_cmd_br_set_external_id, cmd_br_set_external_id, NULL, "", RW},
3030     {"br-get-external-id", 1, 2, "BRIDGE [KEY]", pre_cmd_br_get_external_id,
3031      cmd_br_get_external_id, NULL, "", RO},
3032
3033     /* Port commands. */
3034     {"list-ports", 1, 1, "BRIDGE", pre_get_info, cmd_list_ports, NULL, "",
3035      RO},
3036     {"add-port", 2, INT_MAX, "BRIDGE NEW-PORT [COLUMN[:KEY]=VALUE]...",
3037      pre_get_info, cmd_add_port, NULL, "--may-exist", RW},
3038     {"add-bond", 4, INT_MAX,
3039      "BRIDGE NEW-BOND-PORT SYSIFACE... [COLUMN[:KEY]=VALUE]...", pre_get_info,
3040      cmd_add_bond, NULL, "--may-exist,--fake-iface", RW},
3041     {"del-port", 1, 2, "[BRIDGE] PORT|IFACE", pre_get_info, cmd_del_port, NULL,
3042      "--if-exists,--with-iface", RW},
3043     {"port-to-br", 1, 1, "PORT", pre_get_info, cmd_port_to_br, NULL, "", RO},
3044
3045     /* Interface commands. */
3046     {"list-ifaces", 1, 1, "BRIDGE", pre_get_info, cmd_list_ifaces, NULL, "",
3047      RO},
3048     {"iface-to-br", 1, 1, "IFACE", pre_get_info, cmd_iface_to_br, NULL, "",
3049      RO},
3050
3051     /* Controller commands. */
3052     {"get-controller", 1, 1, "BRIDGE", pre_controller, cmd_get_controller,
3053      NULL, "", RO},
3054     {"del-controller", 1, 1, "BRIDGE", pre_controller, cmd_del_controller,
3055      NULL, "", RW},
3056     {"set-controller", 1, INT_MAX, "BRIDGE TARGET...", pre_controller,
3057      cmd_set_controller, NULL, "", RW},
3058     {"get-fail-mode", 1, 1, "BRIDGE", pre_get_info, cmd_get_fail_mode, NULL,
3059      "", RO},
3060     {"del-fail-mode", 1, 1, "BRIDGE", pre_get_info, cmd_del_fail_mode, NULL,
3061      "", RW},
3062     {"set-fail-mode", 2, 2, "BRIDGE MODE", pre_get_info, cmd_set_fail_mode,
3063      NULL, "", RW},
3064
3065     /* Manager commands. */
3066     {"get-manager", 0, 0, "", pre_manager, cmd_get_manager, NULL, "", RO},
3067     {"del-manager", 0, 0, "", pre_manager, cmd_del_manager, NULL, "", RW},
3068     {"set-manager", 1, INT_MAX, "TARGET...", pre_manager, cmd_set_manager,
3069      NULL, "", RW},
3070
3071     /* SSL commands. */
3072     {"get-ssl", 0, 0, "", pre_cmd_get_ssl, cmd_get_ssl, NULL, "", RO},
3073     {"del-ssl", 0, 0, "", pre_cmd_del_ssl, cmd_del_ssl, NULL, "", RW},
3074     {"set-ssl", 3, 3, "PRIVATE-KEY CERTIFICATE CA-CERT", pre_cmd_set_ssl,
3075      cmd_set_ssl, NULL, "--bootstrap", RW},
3076
3077     /* Auto Attach commands. */
3078     {"add-aa-mapping", 3, 3, "BRIDGE ARG ARG", pre_aa_mapping, cmd_add_aa_mapping,
3079      NULL, "", RW},
3080     {"del-aa-mapping", 3, 3, "BRIDGE ARG ARG", pre_aa_mapping, cmd_del_aa_mapping,
3081      NULL, "", RW},
3082     {"get-aa-mapping", 1, 1, "BRIDGE", pre_aa_mapping, cmd_get_aa_mapping,
3083      NULL, "", RO},
3084
3085     /* Switch commands. */
3086     {"emer-reset", 0, 0, "", pre_cmd_emer_reset, cmd_emer_reset, NULL, "", RW},
3087
3088     {NULL, 0, 0, NULL, NULL, NULL, NULL, NULL, RO},
3089 };
3090
3091 /* Registers vsctl and common db commands. */
3092 static void
3093 vsctl_cmd_init(void)
3094 {
3095     ctl_init();
3096     ctl_register_commands(vsctl_commands);
3097 }