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