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