3a93ef38e339d818dcc2fe92bc7190bdc3b7c897
[sliver-openvswitch.git] / utilities / ovs-vsctl.c
1 /*
2  * Copyright (c) 2009, 2010, 2011 Nicira Networks.
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 <assert.h>
20 #include <ctype.h>
21 #include <errno.h>
22 #include <float.h>
23 #include <getopt.h>
24 #include <inttypes.h>
25 #include <signal.h>
26 #include <stdarg.h>
27 #include <stdlib.h>
28 #include <string.h>
29
30 #include "command-line.h"
31 #include "compiler.h"
32 #include "dirs.h"
33 #include "dynamic-string.h"
34 #include "json.h"
35 #include "ovsdb-data.h"
36 #include "ovsdb-idl.h"
37 #include "poll-loop.h"
38 #include "process.h"
39 #include "stream.h"
40 #include "stream-ssl.h"
41 #include "svec.h"
42 #include "vswitchd/vswitch-idl.h"
43 #include "table.h"
44 #include "timeval.h"
45 #include "util.h"
46 #include "vlog.h"
47
48 VLOG_DEFINE_THIS_MODULE(vsctl);
49
50 /* vsctl_fatal() also logs the error, so it is preferred in this file. */
51 #define ovs_fatal please_use_vsctl_fatal_instead_of_ovs_fatal
52
53 struct vsctl_context;
54
55 /* A command supported by ovs-vsctl. */
56 struct vsctl_command_syntax {
57     const char *name;           /* e.g. "add-br" */
58     int min_args;               /* Min number of arguments following name. */
59     int max_args;               /* Max number of arguments following name. */
60
61     /* If nonnull, calls ovsdb_idl_add_column() or ovsdb_idl_add_table() for
62      * each column or table in ctx->idl that it uses. */
63     void (*prerequisites)(struct vsctl_context *ctx);
64
65     /* Does the actual work of the command and puts the command's output, if
66      * any, in ctx->output or ctx->table.
67      *
68      * Alternatively, if some prerequisite of the command is not met and the
69      * caller should wait for something to change and then retry, it may set
70      * ctx->try_again to true.  (Only the "wait-until" command currently does
71      * this.) */
72     void (*run)(struct vsctl_context *ctx);
73
74     /* If nonnull, called after the transaction has been successfully
75      * committed.  ctx->output is the output from the "run" function, which
76      * this function may modify and otherwise postprocess as needed.  (Only the
77      * "create" command currently does any postprocessing.) */
78     void (*postprocess)(struct vsctl_context *ctx);
79
80     /* A comma-separated list of supported options, e.g. "--a,--b", or the
81      * empty string if the command does not support any options. */
82     const char *options;
83     enum { RO, RW } mode;       /* Does this command modify the database? */
84 };
85
86 struct vsctl_command {
87     /* Data that remains constant after initialization. */
88     const struct vsctl_command_syntax *syntax;
89     int argc;
90     char **argv;
91     struct shash options;
92
93     /* Data modified by commands. */
94     struct ds output;
95     struct table *table;
96 };
97
98 /* --db: The database server to contact. */
99 static const char *db;
100
101 /* --oneline: Write each command's output as a single line? */
102 static bool oneline;
103
104 /* --dry-run: Do not commit any changes. */
105 static bool dry_run;
106
107 /* --no-wait: Wait for ovs-vswitchd to reload its configuration? */
108 static bool wait_for_reload = true;
109
110 /* --timeout: Time to wait for a connection to 'db'. */
111 static int timeout;
112
113 /* Format for table output. */
114 static struct table_style table_style = TABLE_STYLE_DEFAULT;
115
116 /* All supported commands. */
117 static const struct vsctl_command_syntax all_commands[];
118
119 /* The IDL we're using and the current transaction, if any.
120  * This is for use by vsctl_exit() only, to allow it to clean up.
121  * Other code should use its context arguments. */
122 static struct ovsdb_idl *the_idl;
123 static struct ovsdb_idl_txn *the_idl_txn;
124
125 static void vsctl_exit(int status) NO_RETURN;
126 static void vsctl_fatal(const char *, ...) PRINTF_FORMAT(1, 2) NO_RETURN;
127 static char *default_db(void);
128 static void usage(void) NO_RETURN;
129 static void parse_options(int argc, char *argv[]);
130 static bool might_write_to_db(char **argv);
131
132 static struct vsctl_command *parse_commands(int argc, char *argv[],
133                                             size_t *n_commandsp);
134 static void parse_command(int argc, char *argv[], struct vsctl_command *);
135 static const struct vsctl_command_syntax *find_command(const char *name);
136 static void run_prerequisites(struct vsctl_command[], size_t n_commands,
137                               struct ovsdb_idl *);
138 static void do_vsctl(const char *args,
139                      struct vsctl_command *, size_t n_commands,
140                      struct ovsdb_idl *);
141
142 static const struct vsctl_table_class *get_table(const char *table_name);
143 static void set_column(const struct vsctl_table_class *,
144                        const struct ovsdb_idl_row *, const char *arg,
145                        struct ovsdb_symbol_table *);
146
147 static bool is_condition_satisfied(const struct vsctl_table_class *,
148                                    const struct ovsdb_idl_row *,
149                                    const char *arg,
150                                    struct ovsdb_symbol_table *);
151
152 int
153 main(int argc, char *argv[])
154 {
155     extern struct vlog_module VLM_reconnect;
156     struct ovsdb_idl *idl;
157     struct vsctl_command *commands;
158     size_t n_commands;
159     char *args;
160
161     set_program_name(argv[0]);
162     signal(SIGPIPE, SIG_IGN);
163     vlog_set_levels(NULL, VLF_CONSOLE, VLL_WARN);
164     vlog_set_levels(&VLM_reconnect, VLF_ANY_FACILITY, VLL_WARN);
165     ovsrec_init();
166
167     /* Log our arguments.  This is often valuable for debugging systems. */
168     args = process_escape_args(argv);
169     VLOG(might_write_to_db(argv) ? VLL_INFO : VLL_DBG, "Called as %s", args);
170
171     /* Parse command line. */
172     parse_options(argc, argv);
173     commands = parse_commands(argc - optind, argv + optind, &n_commands);
174
175     if (timeout) {
176         time_alarm(timeout);
177     }
178
179     /* Initialize IDL. */
180     idl = the_idl = ovsdb_idl_create(db, &ovsrec_idl_class, false);
181     run_prerequisites(commands, n_commands, idl);
182
183     /* Now execute the commands. */
184     for (;;) {
185         if (ovsdb_idl_run(idl)) {
186             do_vsctl(args, commands, n_commands, idl);
187         }
188
189         ovsdb_idl_wait(idl);
190         poll_block();
191     }
192 }
193
194 static void
195 parse_options(int argc, char *argv[])
196 {
197     enum {
198         OPT_DB = UCHAR_MAX + 1,
199         OPT_ONELINE,
200         OPT_NO_SYSLOG,
201         OPT_NO_WAIT,
202         OPT_DRY_RUN,
203         OPT_PEER_CA_CERT,
204         VLOG_OPTION_ENUMS,
205         TABLE_OPTION_ENUMS
206     };
207     static struct option long_options[] = {
208         {"db", required_argument, 0, OPT_DB},
209         {"no-syslog", no_argument, 0, OPT_NO_SYSLOG},
210         {"no-wait", no_argument, 0, OPT_NO_WAIT},
211         {"dry-run", no_argument, 0, OPT_DRY_RUN},
212         {"oneline", no_argument, 0, OPT_ONELINE},
213         {"timeout", required_argument, 0, 't'},
214         {"help", no_argument, 0, 'h'},
215         {"version", no_argument, 0, 'V'},
216         VLOG_LONG_OPTIONS,
217         TABLE_LONG_OPTIONS,
218 #ifdef HAVE_OPENSSL
219         STREAM_SSL_LONG_OPTIONS
220         {"peer-ca-cert", required_argument, 0, OPT_PEER_CA_CERT},
221 #endif
222         {0, 0, 0, 0},
223     };
224     char *tmp, *short_options;
225
226     tmp = long_options_to_short_options(long_options);
227     short_options = xasprintf("+%s", tmp);
228     free(tmp);
229
230     table_style.format = TF_LIST;
231
232     for (;;) {
233         int c;
234
235         c = getopt_long(argc, argv, short_options, long_options, NULL);
236         if (c == -1) {
237             break;
238         }
239
240         switch (c) {
241         case OPT_DB:
242             db = optarg;
243             break;
244
245         case OPT_ONELINE:
246             oneline = true;
247             break;
248
249         case OPT_NO_SYSLOG:
250             vlog_set_levels(&VLM_vsctl, VLF_SYSLOG, VLL_WARN);
251             break;
252
253         case OPT_NO_WAIT:
254             wait_for_reload = false;
255             break;
256
257         case OPT_DRY_RUN:
258             dry_run = true;
259             break;
260
261         case 'h':
262             usage();
263
264         case 'V':
265             OVS_PRINT_VERSION(0, 0);
266             exit(EXIT_SUCCESS);
267
268         case 't':
269             timeout = strtoul(optarg, NULL, 10);
270             if (timeout < 0) {
271                 vsctl_fatal("value %s on -t or --timeout is invalid",
272                             optarg);
273             }
274             break;
275
276         VLOG_OPTION_HANDLERS
277         TABLE_OPTION_HANDLERS(&table_style)
278
279 #ifdef HAVE_OPENSSL
280         STREAM_SSL_OPTION_HANDLERS
281
282         case OPT_PEER_CA_CERT:
283             stream_ssl_set_peer_ca_cert_file(optarg);
284             break;
285 #endif
286
287         case '?':
288             exit(EXIT_FAILURE);
289
290         default:
291             abort();
292         }
293     }
294     free(short_options);
295
296     if (!db) {
297         db = default_db();
298     }
299 }
300
301 static struct vsctl_command *
302 parse_commands(int argc, char *argv[], size_t *n_commandsp)
303 {
304     struct vsctl_command *commands;
305     size_t n_commands, allocated_commands;
306     int i, start;
307
308     commands = NULL;
309     n_commands = allocated_commands = 0;
310
311     for (start = i = 0; i <= argc; i++) {
312         if (i == argc || !strcmp(argv[i], "--")) {
313             if (i > start) {
314                 if (n_commands >= allocated_commands) {
315                     struct vsctl_command *c;
316
317                     commands = x2nrealloc(commands, &allocated_commands,
318                                           sizeof *commands);
319                     for (c = commands; c < &commands[n_commands]; c++) {
320                         shash_moved(&c->options);
321                     }
322                 }
323                 parse_command(i - start, &argv[start],
324                               &commands[n_commands++]);
325             }
326             start = i + 1;
327         }
328     }
329     if (!n_commands) {
330         vsctl_fatal("missing command name (use --help for help)");
331     }
332     *n_commandsp = n_commands;
333     return commands;
334 }
335
336 static void
337 parse_command(int argc, char *argv[], struct vsctl_command *command)
338 {
339     const struct vsctl_command_syntax *p;
340     struct shash_node *node;
341     int n_arg;
342     int i;
343
344     shash_init(&command->options);
345     for (i = 0; i < argc; i++) {
346         const char *option = argv[i];
347         const char *equals;
348         char *key, *value;
349
350         if (option[0] != '-') {
351             break;
352         }
353
354         equals = strchr(option, '=');
355         if (equals) {
356             key = xmemdup0(option, equals - option);
357             value = xstrdup(equals + 1);
358         } else {
359             key = xstrdup(option);
360             value = NULL;
361         }
362
363         if (shash_find(&command->options, key)) {
364             vsctl_fatal("'%s' option specified multiple times", argv[i]);
365         }
366         shash_add_nocopy(&command->options, key, value);
367     }
368     if (i == argc) {
369         vsctl_fatal("missing command name");
370     }
371
372     p = find_command(argv[i]);
373     if (!p) {
374         vsctl_fatal("unknown command '%s'; use --help for help", argv[i]);
375     }
376
377     SHASH_FOR_EACH (node, &command->options) {
378         const char *s = strstr(p->options, node->name);
379         int end = s ? s[strlen(node->name)] : EOF;
380
381         if (end != '=' && end != ',' && end != ' ' && end != '\0') {
382             vsctl_fatal("'%s' command has no '%s' option",
383                         argv[i], node->name);
384         }
385         if ((end == '=') != (node->data != NULL)) {
386             if (end == '=') {
387                 vsctl_fatal("missing argument to '%s' option on '%s' "
388                             "command", node->name, argv[i]);
389             } else {
390                 vsctl_fatal("'%s' option on '%s' does not accept an "
391                             "argument", node->name, argv[i]);
392             }
393         }
394     }
395
396     n_arg = argc - i - 1;
397     if (n_arg < p->min_args) {
398         vsctl_fatal("'%s' command requires at least %d arguments",
399                     p->name, p->min_args);
400     } else if (n_arg > p->max_args) {
401         int j;
402
403         for (j = i + 1; j < argc; j++) {
404             if (argv[j][0] == '-') {
405                 vsctl_fatal("'%s' command takes at most %d arguments "
406                             "(note that options must precede command "
407                             "names and follow a \"--\" argument)",
408                             p->name, p->max_args);
409             }
410         }
411
412         vsctl_fatal("'%s' command takes at most %d arguments",
413                     p->name, p->max_args);
414     }
415
416     command->syntax = p;
417     command->argc = n_arg + 1;
418     command->argv = &argv[i];
419 }
420
421 /* Returns the "struct vsctl_command_syntax" for a given command 'name', or a
422  * null pointer if there is none. */
423 static const struct vsctl_command_syntax *
424 find_command(const char *name)
425 {
426     static struct shash commands = SHASH_INITIALIZER(&commands);
427
428     if (shash_is_empty(&commands)) {
429         const struct vsctl_command_syntax *p;
430
431         for (p = all_commands; p->name; p++) {
432             shash_add_assert(&commands, p->name, p);
433         }
434     }
435
436     return shash_find_data(&commands, name);
437 }
438
439 static void
440 vsctl_fatal(const char *format, ...)
441 {
442     char *message;
443     va_list args;
444
445     va_start(args, format);
446     message = xvasprintf(format, args);
447     va_end(args);
448
449     vlog_set_levels(&VLM_vsctl, VLF_CONSOLE, VLL_EMER);
450     VLOG_ERR("%s", message);
451     ovs_error(0, "%s", message);
452     vsctl_exit(EXIT_FAILURE);
453 }
454
455 /* Frees the current transaction and the underlying IDL and then calls
456  * exit(status).
457  *
458  * Freeing the transaction and the IDL is not strictly necessary, but it makes
459  * for a clean memory leak report from valgrind in the normal case.  That makes
460  * it easier to notice real memory leaks. */
461 static void
462 vsctl_exit(int status)
463 {
464     if (the_idl_txn) {
465         ovsdb_idl_txn_abort(the_idl_txn);
466         ovsdb_idl_txn_destroy(the_idl_txn);
467     }
468     ovsdb_idl_destroy(the_idl);
469     exit(status);
470 }
471
472 static void
473 usage(void)
474 {
475     printf("\
476 %s: ovs-vswitchd management utility\n\
477 usage: %s [OPTIONS] COMMAND [ARG...]\n\
478 \n\
479 Open vSwitch commands:\n\
480   init                        initialize database, if not yet initialized\n\
481   emer-reset                  reset configuration to clean state\n\
482 \n\
483 Bridge commands:\n\
484   add-br BRIDGE               create a new bridge named BRIDGE\n\
485   add-br BRIDGE PARENT VLAN   create new fake BRIDGE in PARENT on VLAN\n\
486   del-br BRIDGE               delete BRIDGE and all of its ports\n\
487   list-br                     print the names of all the bridges\n\
488   br-exists BRIDGE            test whether BRIDGE exists\n\
489   br-to-vlan BRIDGE           print the VLAN which BRIDGE is on\n\
490   br-to-parent BRIDGE         print the parent of BRIDGE\n\
491   br-set-external-id BRIDGE KEY VALUE  set KEY on BRIDGE to VALUE\n\
492   br-set-external-id BRIDGE KEY  unset KEY on BRIDGE\n\
493   br-get-external-id BRIDGE KEY  print value of KEY on BRIDGE\n\
494   br-get-external-id BRIDGE  list key-value pairs on BRIDGE\n\
495 \n\
496 Port commands (a bond is considered to be a single port):\n\
497   list-ports BRIDGE           print the names of all the ports on BRIDGE\n\
498   add-port BRIDGE PORT        add network device PORT to BRIDGE\n\
499   add-bond BRIDGE PORT IFACE...  add bonded port PORT in BRIDGE from IFACES\n\
500   del-port [BRIDGE] PORT      delete PORT (which may be bonded) from BRIDGE\n\
501   port-to-br PORT             print name of bridge that contains PORT\n\
502 \n\
503 Interface commands (a bond consists of multiple interfaces):\n\
504   list-ifaces BRIDGE          print the names of all interfaces on BRIDGE\n\
505   iface-to-br IFACE           print name of bridge that contains IFACE\n\
506 \n\
507 Controller commands:\n\
508   get-controller BRIDGE      print the controller for BRIDGE\n\
509   del-controller BRIDGE      delete the controller for BRIDGE\n\
510   set-controller BRIDGE TARGET  set the controller for BRIDGE to TARGET\n\
511   get-fail-mode BRIDGE       print the fail-mode for BRIDGE\n\
512   del-fail-mode BRIDGE       delete the fail-mode for BRIDGE\n\
513   set-fail-mode BRIDGE MODE  set the fail-mode for BRIDGE to MODE\n\
514 \n\
515 Manager commands:\n\
516   get-manager                print all manager(s)\n\
517   del-manager                delete all manager(s)\n\
518   set-manager TARGET...      set the list of manager(s) to TARGET(s)\n\
519 \n\
520 SSL commands:\n\
521   get-ssl                     print the SSL configuration\n\
522   del-ssl                     delete the SSL configuration\n\
523   set-ssl PRIV-KEY CERT CA-CERT  set the SSL configuration\n\
524 \n\
525 Switch commands:\n\
526   emer-reset                  reset switch to known good state\n\
527 \n\
528 Database commands:\n\
529   list TBL [REC]              list RECord (or all records) in TBL\n\
530   find TBL CONDITION...       list records satisfying CONDITION in TBL\n\
531   get TBL REC COL[:KEY]       print values of COLumns in RECord in TBL\n\
532   set TBL REC COL[:KEY]=VALUE set COLumn values in RECord in TBL\n\
533   add TBL REC COL [KEY=]VALUE add (KEY=)VALUE to COLumn in RECord in TBL\n\
534   remove TBL REC COL [KEY=]VALUE  remove (KEY=)VALUE from COLumn\n\
535   clear TBL REC COL           clear values from COLumn in RECord in TBL\n\
536   create TBL COL[:KEY]=VALUE  create and initialize new record\n\
537   destroy TBL REC             delete RECord from TBL\n\
538   wait-until TBL REC [COL[:KEY]=VALUE]  wait until condition is true\n\
539 Potentially unsafe database commands require --force option.\n\
540 \n\
541 Options:\n\
542   --db=DATABASE               connect to DATABASE\n\
543                               (default: %s)\n\
544   --no-wait                   do not wait for ovs-vswitchd to reconfigure\n\
545   -t, --timeout=SECS          wait at most SECS seconds for ovs-vswitchd\n\
546   --dry-run                   do not commit changes to database\n\
547   --oneline                   print exactly one line of output per command\n",
548            program_name, program_name, default_db());
549     vlog_usage();
550     printf("\
551   --no-syslog             equivalent to --verbose=vsctl:syslog:warn\n");
552     stream_usage("database", true, true, false);
553     printf("\n\
554 Other options:\n\
555   -h, --help                  display this help message\n\
556   -V, --version               display version information\n");
557     exit(EXIT_SUCCESS);
558 }
559
560 static char *
561 default_db(void)
562 {
563     static char *def;
564     if (!def) {
565         def = xasprintf("unix:%s/db.sock", ovs_rundir());
566     }
567     return def;
568 }
569
570 /* Returns true if it looks like this set of arguments might modify the
571  * database, otherwise false.  (Not very smart, so it's prone to false
572  * positives.) */
573 static bool
574 might_write_to_db(char **argv)
575 {
576     for (; *argv; argv++) {
577         const struct vsctl_command_syntax *p = find_command(*argv);
578         if (p && p->mode == RW) {
579             return true;
580         }
581     }
582     return false;
583 }
584 \f
585 struct vsctl_context {
586     /* Read-only. */
587     int argc;
588     char **argv;
589     struct shash options;
590
591     /* Modifiable state. */
592     struct ds output;
593     struct table *table;
594     struct ovsdb_idl *idl;
595     struct ovsdb_idl_txn *txn;
596     struct ovsdb_symbol_table *symtab;
597     const struct ovsrec_open_vswitch *ovs;
598     bool verified_ports;
599
600     /* A command may set this member to true if some prerequisite is not met
601      * and the caller should wait for something to change and then retry. */
602     bool try_again;
603 };
604
605 struct vsctl_bridge {
606     struct ovsrec_bridge *br_cfg;
607     char *name;
608     struct ovsrec_controller **ctrl;
609     char *fail_mode;
610     size_t n_ctrl;
611     struct vsctl_bridge *parent;
612     int vlan;
613 };
614
615 struct vsctl_port {
616     struct ovsrec_port *port_cfg;
617     struct vsctl_bridge *bridge;
618 };
619
620 struct vsctl_iface {
621     struct ovsrec_interface *iface_cfg;
622     struct vsctl_port *port;
623 };
624
625 struct vsctl_info {
626     struct vsctl_context *ctx;
627     struct shash bridges;   /* Maps from bridge name to struct vsctl_bridge. */
628     struct shash ports;     /* Maps from port name to struct vsctl_port. */
629     struct shash ifaces;    /* Maps from port name to struct vsctl_iface. */
630 };
631
632 static char *
633 vsctl_context_to_string(const struct vsctl_context *ctx)
634 {
635     const struct shash_node *node;
636     struct svec words;
637     char *s;
638     int i;
639
640     svec_init(&words);
641     SHASH_FOR_EACH (node, &ctx->options) {
642         svec_add(&words, node->name);
643     }
644     for (i = 0; i < ctx->argc; i++) {
645         svec_add(&words, ctx->argv[i]);
646     }
647     svec_terminate(&words);
648
649     s = process_escape_args(words.names);
650
651     svec_destroy(&words);
652
653     return s;
654 }
655
656 static void
657 verify_ports(struct vsctl_context *ctx)
658 {
659     if (!ctx->verified_ports) {
660         const struct ovsrec_bridge *bridge;
661         const struct ovsrec_port *port;
662
663         ovsrec_open_vswitch_verify_bridges(ctx->ovs);
664         OVSREC_BRIDGE_FOR_EACH (bridge, ctx->idl) {
665             ovsrec_bridge_verify_ports(bridge);
666         }
667         OVSREC_PORT_FOR_EACH (port, ctx->idl) {
668             ovsrec_port_verify_interfaces(port);
669         }
670
671         ctx->verified_ports = true;
672     }
673 }
674
675 static struct vsctl_bridge *
676 add_bridge(struct vsctl_info *b,
677            struct ovsrec_bridge *br_cfg, const char *name,
678            struct vsctl_bridge *parent, int vlan)
679 {
680     struct vsctl_bridge *br = xmalloc(sizeof *br);
681     br->br_cfg = br_cfg;
682     br->name = xstrdup(name);
683     br->parent = parent;
684     br->vlan = vlan;
685     if (parent) {
686         br->ctrl = parent->br_cfg->controller;
687         br->n_ctrl = parent->br_cfg->n_controller;
688         br->fail_mode = parent->br_cfg->fail_mode;
689     } else {
690         br->ctrl = br_cfg->controller;
691         br->n_ctrl = br_cfg->n_controller;
692         br->fail_mode = br_cfg->fail_mode;
693     }
694     shash_add(&b->bridges, br->name, br);
695     return br;
696 }
697
698 static bool
699 port_is_fake_bridge(const struct ovsrec_port *port_cfg)
700 {
701     return (port_cfg->fake_bridge
702             && port_cfg->tag
703             && *port_cfg->tag >= 1 && *port_cfg->tag <= 4095);
704 }
705
706 static struct vsctl_bridge *
707 find_vlan_bridge(struct vsctl_info *info,
708                  struct vsctl_bridge *parent, int vlan)
709 {
710     struct shash_node *node;
711
712     SHASH_FOR_EACH (node, &info->bridges) {
713         struct vsctl_bridge *br = node->data;
714         if (br->parent == parent && br->vlan == vlan) {
715             return br;
716         }
717     }
718
719     return NULL;
720 }
721
722 static void
723 free_info(struct vsctl_info *info)
724 {
725     struct shash_node *node;
726
727     SHASH_FOR_EACH (node, &info->bridges) {
728         struct vsctl_bridge *bridge = node->data;
729         free(bridge->name);
730         free(bridge);
731     }
732     shash_destroy(&info->bridges);
733
734     shash_destroy_free_data(&info->ports);
735     shash_destroy_free_data(&info->ifaces);
736 }
737
738 static void
739 pre_get_info(struct vsctl_context *ctx)
740 {
741     ovsdb_idl_add_column(ctx->idl, &ovsrec_open_vswitch_col_bridges);
742
743     ovsdb_idl_add_column(ctx->idl, &ovsrec_bridge_col_name);
744     ovsdb_idl_add_column(ctx->idl, &ovsrec_bridge_col_controller);
745     ovsdb_idl_add_column(ctx->idl, &ovsrec_bridge_col_fail_mode);
746     ovsdb_idl_add_column(ctx->idl, &ovsrec_bridge_col_ports);
747
748     ovsdb_idl_add_column(ctx->idl, &ovsrec_port_col_name);
749     ovsdb_idl_add_column(ctx->idl, &ovsrec_port_col_fake_bridge);
750     ovsdb_idl_add_column(ctx->idl, &ovsrec_port_col_tag);
751     ovsdb_idl_add_column(ctx->idl, &ovsrec_port_col_interfaces);
752
753     ovsdb_idl_add_column(ctx->idl, &ovsrec_interface_col_name);
754 }
755
756 static void
757 get_info(struct vsctl_context *ctx, struct vsctl_info *info)
758 {
759     const struct ovsrec_open_vswitch *ovs = ctx->ovs;
760     struct shash bridges, ports;
761     size_t i;
762
763     info->ctx = ctx;
764     shash_init(&info->bridges);
765     shash_init(&info->ports);
766     shash_init(&info->ifaces);
767
768     shash_init(&bridges);
769     shash_init(&ports);
770     for (i = 0; i < ovs->n_bridges; i++) {
771         struct ovsrec_bridge *br_cfg = ovs->bridges[i];
772         struct vsctl_bridge *br;
773         size_t j;
774
775         if (!shash_add_once(&bridges, br_cfg->name, NULL)) {
776             VLOG_WARN("%s: database contains duplicate bridge name",
777                       br_cfg->name);
778             continue;
779         }
780         br = add_bridge(info, br_cfg, br_cfg->name, NULL, 0);
781         if (!br) {
782             continue;
783         }
784
785         for (j = 0; j < br_cfg->n_ports; j++) {
786             struct ovsrec_port *port_cfg = br_cfg->ports[j];
787
788             if (!shash_add_once(&ports, port_cfg->name, NULL)) {
789                 VLOG_WARN("%s: database contains duplicate port name",
790                           port_cfg->name);
791                 continue;
792             }
793
794             if (port_is_fake_bridge(port_cfg)
795                 && shash_add_once(&bridges, port_cfg->name, NULL)) {
796                 add_bridge(info, NULL, port_cfg->name, br, *port_cfg->tag);
797             }
798         }
799     }
800     shash_destroy(&bridges);
801     shash_destroy(&ports);
802
803     shash_init(&bridges);
804     shash_init(&ports);
805     for (i = 0; i < ovs->n_bridges; i++) {
806         struct ovsrec_bridge *br_cfg = ovs->bridges[i];
807         struct vsctl_bridge *br;
808         size_t j;
809
810         if (!shash_add_once(&bridges, br_cfg->name, NULL)) {
811             continue;
812         }
813         br = shash_find_data(&info->bridges, br_cfg->name);
814         for (j = 0; j < br_cfg->n_ports; j++) {
815             struct ovsrec_port *port_cfg = br_cfg->ports[j];
816             struct vsctl_port *port;
817             size_t k;
818
819             if (!shash_add_once(&ports, port_cfg->name, NULL)) {
820                 continue;
821             }
822
823             if (port_is_fake_bridge(port_cfg)
824                 && !shash_add_once(&bridges, port_cfg->name, NULL)) {
825                 continue;
826             }
827
828             port = xmalloc(sizeof *port);
829             port->port_cfg = port_cfg;
830             if (port_cfg->tag
831                 && *port_cfg->tag >= 1 && *port_cfg->tag <= 4095) {
832                 port->bridge = find_vlan_bridge(info, br, *port_cfg->tag);
833                 if (!port->bridge) {
834                     port->bridge = br;
835                 }
836             } else {
837                 port->bridge = br;
838             }
839             shash_add(&info->ports, port_cfg->name, port);
840
841             for (k = 0; k < port_cfg->n_interfaces; k++) {
842                 struct ovsrec_interface *iface_cfg = port_cfg->interfaces[k];
843                 struct vsctl_iface *iface;
844
845                 if (shash_find(&info->ifaces, iface_cfg->name)) {
846                     VLOG_WARN("%s: database contains duplicate interface name",
847                               iface_cfg->name);
848                     continue;
849                 }
850
851                 iface = xmalloc(sizeof *iface);
852                 iface->iface_cfg = iface_cfg;
853                 iface->port = port;
854                 shash_add(&info->ifaces, iface_cfg->name, iface);
855             }
856         }
857     }
858     shash_destroy(&bridges);
859     shash_destroy(&ports);
860 }
861
862 static void
863 check_conflicts(struct vsctl_info *info, const char *name,
864                 char *msg)
865 {
866     struct vsctl_iface *iface;
867     struct vsctl_port *port;
868
869     verify_ports(info->ctx);
870
871     if (shash_find(&info->bridges, name)) {
872         vsctl_fatal("%s because a bridge named %s already exists",
873                     msg, name);
874     }
875
876     port = shash_find_data(&info->ports, name);
877     if (port) {
878         vsctl_fatal("%s because a port named %s already exists on "
879                     "bridge %s", msg, name, port->bridge->name);
880     }
881
882     iface = shash_find_data(&info->ifaces, name);
883     if (iface) {
884         vsctl_fatal("%s because an interface named %s already exists "
885                     "on bridge %s", msg, name, iface->port->bridge->name);
886     }
887
888     free(msg);
889 }
890
891 static struct vsctl_bridge *
892 find_bridge(struct vsctl_info *info, const char *name, bool must_exist)
893 {
894     struct vsctl_bridge *br = shash_find_data(&info->bridges, name);
895     if (must_exist && !br) {
896         vsctl_fatal("no bridge named %s", name);
897     }
898     ovsrec_open_vswitch_verify_bridges(info->ctx->ovs);
899     return br;
900 }
901
902 static struct vsctl_bridge *
903 find_real_bridge(struct vsctl_info *info, const char *name, bool must_exist)
904 {
905     struct vsctl_bridge *br = find_bridge(info, name, must_exist);
906     if (br && br->parent) {
907         vsctl_fatal("%s is a fake bridge", name);
908     }
909     return br;
910 }
911
912 static struct vsctl_port *
913 find_port(struct vsctl_info *info, const char *name, bool must_exist)
914 {
915     struct vsctl_port *port = shash_find_data(&info->ports, name);
916     if (port && !strcmp(name, port->bridge->name)) {
917         port = NULL;
918     }
919     if (must_exist && !port) {
920         vsctl_fatal("no port named %s", name);
921     }
922     verify_ports(info->ctx);
923     return port;
924 }
925
926 static struct vsctl_iface *
927 find_iface(struct vsctl_info *info, const char *name, bool must_exist)
928 {
929     struct vsctl_iface *iface = shash_find_data(&info->ifaces, name);
930     if (iface && !strcmp(name, iface->port->bridge->name)) {
931         iface = NULL;
932     }
933     if (must_exist && !iface) {
934         vsctl_fatal("no interface named %s", name);
935     }
936     verify_ports(info->ctx);
937     return iface;
938 }
939
940 static void
941 bridge_insert_port(struct ovsrec_bridge *br, struct ovsrec_port *port)
942 {
943     struct ovsrec_port **ports;
944     size_t i;
945
946     ports = xmalloc(sizeof *br->ports * (br->n_ports + 1));
947     for (i = 0; i < br->n_ports; i++) {
948         ports[i] = br->ports[i];
949     }
950     ports[br->n_ports] = port;
951     ovsrec_bridge_set_ports(br, ports, br->n_ports + 1);
952     free(ports);
953 }
954
955 static void
956 bridge_delete_port(struct ovsrec_bridge *br, struct ovsrec_port *port)
957 {
958     struct ovsrec_port **ports;
959     size_t i, n;
960
961     ports = xmalloc(sizeof *br->ports * br->n_ports);
962     for (i = n = 0; i < br->n_ports; i++) {
963         if (br->ports[i] != port) {
964             ports[n++] = br->ports[i];
965         }
966     }
967     ovsrec_bridge_set_ports(br, ports, n);
968     free(ports);
969 }
970
971 static void
972 ovs_insert_bridge(const struct ovsrec_open_vswitch *ovs,
973                   struct ovsrec_bridge *bridge)
974 {
975     struct ovsrec_bridge **bridges;
976     size_t i;
977
978     bridges = xmalloc(sizeof *ovs->bridges * (ovs->n_bridges + 1));
979     for (i = 0; i < ovs->n_bridges; i++) {
980         bridges[i] = ovs->bridges[i];
981     }
982     bridges[ovs->n_bridges] = bridge;
983     ovsrec_open_vswitch_set_bridges(ovs, bridges, ovs->n_bridges + 1);
984     free(bridges);
985 }
986
987 static void
988 ovs_delete_bridge(const struct ovsrec_open_vswitch *ovs,
989                   struct ovsrec_bridge *bridge)
990 {
991     struct ovsrec_bridge **bridges;
992     size_t i, n;
993
994     bridges = xmalloc(sizeof *ovs->bridges * ovs->n_bridges);
995     for (i = n = 0; i < ovs->n_bridges; i++) {
996         if (ovs->bridges[i] != bridge) {
997             bridges[n++] = ovs->bridges[i];
998         }
999     }
1000     ovsrec_open_vswitch_set_bridges(ovs, bridges, n);
1001     free(bridges);
1002 }
1003
1004 static void
1005 cmd_init(struct vsctl_context *ctx OVS_UNUSED)
1006 {
1007 }
1008
1009 static void
1010 pre_cmd_emer_reset(struct vsctl_context *ctx)
1011 {
1012     ovsdb_idl_add_column(ctx->idl, &ovsrec_open_vswitch_col_managers);
1013     ovsdb_idl_add_column(ctx->idl, &ovsrec_open_vswitch_col_manager_options);
1014     ovsdb_idl_add_column(ctx->idl, &ovsrec_open_vswitch_col_ssl);
1015
1016     ovsdb_idl_add_column(ctx->idl, &ovsrec_bridge_col_controller);
1017     ovsdb_idl_add_column(ctx->idl, &ovsrec_bridge_col_fail_mode);
1018     ovsdb_idl_add_column(ctx->idl, &ovsrec_bridge_col_mirrors);
1019     ovsdb_idl_add_column(ctx->idl, &ovsrec_bridge_col_netflow);
1020     ovsdb_idl_add_column(ctx->idl, &ovsrec_bridge_col_sflow);
1021     ovsdb_idl_add_column(ctx->idl, &ovsrec_bridge_col_flood_vlans);
1022     ovsdb_idl_add_column(ctx->idl, &ovsrec_bridge_col_other_config);
1023
1024     ovsdb_idl_add_column(ctx->idl, &ovsrec_port_col_other_config);
1025
1026     ovsdb_idl_add_column(ctx->idl,
1027                           &ovsrec_interface_col_ingress_policing_rate);
1028     ovsdb_idl_add_column(ctx->idl,
1029                           &ovsrec_interface_col_ingress_policing_burst);
1030 }
1031
1032 static void
1033 cmd_emer_reset(struct vsctl_context *ctx)
1034 {
1035     const struct ovsdb_idl *idl = ctx->idl;
1036     const struct ovsrec_bridge *br;
1037     const struct ovsrec_port *port;
1038     const struct ovsrec_interface *iface;
1039     const struct ovsrec_mirror *mirror, *next_mirror;
1040     const struct ovsrec_controller *ctrl, *next_ctrl;
1041     const struct ovsrec_manager *mgr, *next_mgr;
1042     const struct ovsrec_netflow *nf, *next_nf;
1043     const struct ovsrec_ssl *ssl, *next_ssl;
1044     const struct ovsrec_sflow *sflow, *next_sflow;
1045
1046     /* Reset the Open_vSwitch table. */
1047     ovsrec_open_vswitch_set_managers(ctx->ovs, NULL, 0);
1048     ovsrec_open_vswitch_set_manager_options(ctx->ovs, NULL, 0);
1049     ovsrec_open_vswitch_set_ssl(ctx->ovs, NULL);
1050
1051     OVSREC_BRIDGE_FOR_EACH (br, idl) {
1052         int i;
1053         char *hw_key = "hwaddr";
1054         char *hw_val = NULL;
1055
1056         ovsrec_bridge_set_controller(br, NULL, 0);
1057         ovsrec_bridge_set_fail_mode(br, NULL);
1058         ovsrec_bridge_set_mirrors(br, NULL, 0);
1059         ovsrec_bridge_set_netflow(br, NULL);
1060         ovsrec_bridge_set_sflow(br, NULL);
1061         ovsrec_bridge_set_flood_vlans(br, NULL, 0);
1062
1063         /* We only want to save the "hwaddr" key from other_config. */
1064         for (i=0; i < br->n_other_config; i++) {
1065             if (!strcmp(br->key_other_config[i], hw_key)) {
1066                 hw_val = br->value_other_config[i];
1067                 break;
1068             }
1069         }
1070         if (hw_val) {
1071             char *val = xstrdup(hw_val);
1072             ovsrec_bridge_set_other_config(br, &hw_key, &val, 1);
1073             free(val);
1074         } else {
1075             ovsrec_bridge_set_other_config(br, NULL, NULL, 0);
1076         }
1077     }
1078
1079     OVSREC_PORT_FOR_EACH (port, idl) {
1080         ovsrec_port_set_other_config(port, NULL, NULL, 0);
1081     }
1082
1083     OVSREC_INTERFACE_FOR_EACH (iface, idl) {
1084         /* xxx What do we do about gre/patch devices created by mgr? */
1085
1086         ovsrec_interface_set_ingress_policing_rate(iface, 0);
1087         ovsrec_interface_set_ingress_policing_burst(iface, 0);
1088     }
1089
1090     OVSREC_MIRROR_FOR_EACH_SAFE (mirror, next_mirror, idl) {
1091         ovsrec_mirror_delete(mirror);
1092     }
1093
1094     OVSREC_CONTROLLER_FOR_EACH_SAFE (ctrl, next_ctrl, idl) {
1095         ovsrec_controller_delete(ctrl);
1096     }
1097
1098     OVSREC_MANAGER_FOR_EACH_SAFE (mgr, next_mgr, idl) {
1099         ovsrec_manager_delete(mgr);
1100     }
1101
1102     OVSREC_NETFLOW_FOR_EACH_SAFE (nf, next_nf, idl) {
1103         ovsrec_netflow_delete(nf);
1104     }
1105
1106     OVSREC_SSL_FOR_EACH_SAFE (ssl, next_ssl, idl) {
1107         ovsrec_ssl_delete(ssl);
1108     }
1109
1110     OVSREC_SFLOW_FOR_EACH_SAFE (sflow, next_sflow, idl) {
1111         ovsrec_sflow_delete(sflow);
1112     }
1113 }
1114
1115 static void
1116 cmd_add_br(struct vsctl_context *ctx)
1117 {
1118     bool may_exist = shash_find(&ctx->options, "--may-exist") != 0;
1119     const char *br_name, *parent_name;
1120     struct vsctl_info info;
1121     int vlan;
1122
1123     br_name = ctx->argv[1];
1124     if (ctx->argc == 2) {
1125         parent_name = NULL;
1126         vlan = 0;
1127     } else if (ctx->argc == 4) {
1128         parent_name = ctx->argv[2];
1129         vlan = atoi(ctx->argv[3]);
1130         if (vlan < 1 || vlan > 4095) {
1131             vsctl_fatal("%s: vlan must be between 1 and 4095", ctx->argv[0]);
1132         }
1133     } else {
1134         vsctl_fatal("'%s' command takes exactly 1 or 3 arguments",
1135                     ctx->argv[0]);
1136     }
1137
1138     get_info(ctx, &info);
1139     if (may_exist) {
1140         struct vsctl_bridge *br;
1141
1142         br = find_bridge(&info, br_name, false);
1143         if (br) {
1144             if (!parent_name) {
1145                 if (br->parent) {
1146                     vsctl_fatal("\"--may-exist add-br %s\" but %s is "
1147                                 "a VLAN bridge for VLAN %d",
1148                                 br_name, br_name, br->vlan);
1149                 }
1150             } else {
1151                 if (!br->parent) {
1152                     vsctl_fatal("\"--may-exist add-br %s %s %d\" but %s "
1153                                 "is not a VLAN bridge",
1154                                 br_name, parent_name, vlan, br_name);
1155                 } else if (strcmp(br->parent->name, parent_name)) {
1156                     vsctl_fatal("\"--may-exist add-br %s %s %d\" but %s "
1157                                 "has the wrong parent %s",
1158                                 br_name, parent_name, vlan,
1159                                 br_name, br->parent->name);
1160                 } else if (br->vlan != vlan) {
1161                     vsctl_fatal("\"--may-exist add-br %s %s %d\" but %s "
1162                                 "is a VLAN bridge for the wrong VLAN %d",
1163                                 br_name, parent_name, vlan, br_name, br->vlan);
1164                 }
1165             }
1166             return;
1167         }
1168     }
1169     check_conflicts(&info, br_name,
1170                     xasprintf("cannot create a bridge named %s", br_name));
1171
1172     if (!parent_name) {
1173         struct ovsrec_port *port;
1174         struct ovsrec_interface *iface;
1175         struct ovsrec_bridge *br;
1176
1177         iface = ovsrec_interface_insert(ctx->txn);
1178         ovsrec_interface_set_name(iface, br_name);
1179         ovsrec_interface_set_type(iface, "internal");
1180
1181         port = ovsrec_port_insert(ctx->txn);
1182         ovsrec_port_set_name(port, br_name);
1183         ovsrec_port_set_interfaces(port, &iface, 1);
1184
1185         br = ovsrec_bridge_insert(ctx->txn);
1186         ovsrec_bridge_set_name(br, br_name);
1187         ovsrec_bridge_set_ports(br, &port, 1);
1188
1189         ovs_insert_bridge(ctx->ovs, br);
1190     } else {
1191         struct vsctl_bridge *parent;
1192         struct ovsrec_port *port;
1193         struct ovsrec_interface *iface;
1194         struct ovsrec_bridge *br;
1195         int64_t tag = vlan;
1196
1197         parent = find_bridge(&info, parent_name, false);
1198         if (parent && parent->vlan) {
1199             vsctl_fatal("cannot create bridge with fake bridge as parent");
1200         }
1201         if (!parent) {
1202             vsctl_fatal("parent bridge %s does not exist", parent_name);
1203         }
1204         br = parent->br_cfg;
1205
1206         iface = ovsrec_interface_insert(ctx->txn);
1207         ovsrec_interface_set_name(iface, br_name);
1208         ovsrec_interface_set_type(iface, "internal");
1209
1210         port = ovsrec_port_insert(ctx->txn);
1211         ovsrec_port_set_name(port, br_name);
1212         ovsrec_port_set_interfaces(port, &iface, 1);
1213         ovsrec_port_set_fake_bridge(port, true);
1214         ovsrec_port_set_tag(port, &tag, 1);
1215
1216         bridge_insert_port(br, port);
1217     }
1218
1219     free_info(&info);
1220 }
1221
1222 static void
1223 del_port(struct vsctl_info *info, struct vsctl_port *port)
1224 {
1225     struct shash_node *node;
1226
1227     SHASH_FOR_EACH (node, &info->ifaces) {
1228         struct vsctl_iface *iface = node->data;
1229         if (iface->port == port) {
1230             ovsrec_interface_delete(iface->iface_cfg);
1231         }
1232     }
1233     ovsrec_port_delete(port->port_cfg);
1234
1235     bridge_delete_port((port->bridge->parent
1236                         ? port->bridge->parent->br_cfg
1237                         : port->bridge->br_cfg), port->port_cfg);
1238 }
1239
1240 static void
1241 cmd_del_br(struct vsctl_context *ctx)
1242 {
1243     bool must_exist = !shash_find(&ctx->options, "--if-exists");
1244     struct vsctl_bridge *bridge;
1245     struct vsctl_info info;
1246
1247     get_info(ctx, &info);
1248     bridge = find_bridge(&info, ctx->argv[1], must_exist);
1249     if (bridge) {
1250         struct shash_node *node;
1251
1252         SHASH_FOR_EACH (node, &info.ports) {
1253             struct vsctl_port *port = node->data;
1254             if (port->bridge == bridge || port->bridge->parent == bridge
1255                 || !strcmp(port->port_cfg->name, bridge->name)) {
1256                 del_port(&info, port);
1257             }
1258         }
1259         if (bridge->br_cfg) {
1260             ovsrec_bridge_delete(bridge->br_cfg);
1261             ovs_delete_bridge(ctx->ovs, bridge->br_cfg);
1262         }
1263     }
1264     free_info(&info);
1265 }
1266
1267 static void
1268 output_sorted(struct svec *svec, struct ds *output)
1269 {
1270     const char *name;
1271     size_t i;
1272
1273     svec_sort(svec);
1274     SVEC_FOR_EACH (i, name, svec) {
1275         ds_put_format(output, "%s\n", name);
1276     }
1277 }
1278
1279 static void
1280 cmd_list_br(struct vsctl_context *ctx)
1281 {
1282     struct shash_node *node;
1283     struct vsctl_info info;
1284     struct svec bridges;
1285
1286     get_info(ctx, &info);
1287
1288     svec_init(&bridges);
1289     SHASH_FOR_EACH (node, &info.bridges) {
1290         struct vsctl_bridge *br = node->data;
1291         svec_add(&bridges, br->name);
1292     }
1293     output_sorted(&bridges, &ctx->output);
1294     svec_destroy(&bridges);
1295
1296     free_info(&info);
1297 }
1298
1299 static void
1300 cmd_br_exists(struct vsctl_context *ctx)
1301 {
1302     struct vsctl_info info;
1303
1304     get_info(ctx, &info);
1305     if (!find_bridge(&info, ctx->argv[1], false)) {
1306         vsctl_exit(2);
1307     }
1308     free_info(&info);
1309 }
1310
1311 /* Returns true if 'b_prefix' (of length 'b_prefix_len') concatenated with 'b'
1312  * equals 'a', false otherwise. */
1313 static bool
1314 key_matches(const char *a,
1315             const char *b_prefix, size_t b_prefix_len, const char *b)
1316 {
1317     return !strncmp(a, b_prefix, b_prefix_len) && !strcmp(a + b_prefix_len, b);
1318 }
1319
1320 static void
1321 set_external_id(char **old_keys, char **old_values, size_t old_n,
1322                 char *key, char *value,
1323                 char ***new_keysp, char ***new_valuesp, size_t *new_np)
1324 {
1325     char **new_keys;
1326     char **new_values;
1327     size_t new_n;
1328     size_t i;
1329
1330     new_keys = xmalloc(sizeof *new_keys * (old_n + 1));
1331     new_values = xmalloc(sizeof *new_values * (old_n + 1));
1332     new_n = 0;
1333     for (i = 0; i < old_n; i++) {
1334         if (strcmp(key, old_keys[i])) {
1335             new_keys[new_n] = old_keys[i];
1336             new_values[new_n] = old_values[i];
1337             new_n++;
1338         }
1339     }
1340     if (value) {
1341         new_keys[new_n] = key;
1342         new_values[new_n] = value;
1343         new_n++;
1344     }
1345     *new_keysp = new_keys;
1346     *new_valuesp = new_values;
1347     *new_np = new_n;
1348 }
1349
1350 static void
1351 pre_cmd_br_set_external_id(struct vsctl_context *ctx)
1352 {
1353     pre_get_info(ctx);
1354     ovsdb_idl_add_column(ctx->idl, &ovsrec_bridge_col_external_ids);
1355     ovsdb_idl_add_column(ctx->idl, &ovsrec_port_col_external_ids);
1356 }
1357
1358 static void
1359 cmd_br_set_external_id(struct vsctl_context *ctx)
1360 {
1361     struct vsctl_info info;
1362     struct vsctl_bridge *bridge;
1363     char **keys, **values;
1364     size_t n;
1365
1366     get_info(ctx, &info);
1367     bridge = find_bridge(&info, ctx->argv[1], true);
1368     if (bridge->br_cfg) {
1369         set_external_id(bridge->br_cfg->key_external_ids,
1370                         bridge->br_cfg->value_external_ids,
1371                         bridge->br_cfg->n_external_ids,
1372                         ctx->argv[2], ctx->argc >= 4 ? ctx->argv[3] : NULL,
1373                         &keys, &values, &n);
1374         ovsrec_bridge_verify_external_ids(bridge->br_cfg);
1375         ovsrec_bridge_set_external_ids(bridge->br_cfg, keys, values, n);
1376     } else {
1377         char *key = xasprintf("fake-bridge-%s", ctx->argv[2]);
1378         struct vsctl_port *port = shash_find_data(&info.ports, ctx->argv[1]);
1379         set_external_id(port->port_cfg->key_external_ids,
1380                         port->port_cfg->value_external_ids,
1381                         port->port_cfg->n_external_ids,
1382                         key, ctx->argc >= 4 ? ctx->argv[3] : NULL,
1383                         &keys, &values, &n);
1384         ovsrec_port_verify_external_ids(port->port_cfg);
1385         ovsrec_port_set_external_ids(port->port_cfg, keys, values, n);
1386         free(key);
1387     }
1388     free(keys);
1389     free(values);
1390
1391     free_info(&info);
1392 }
1393
1394 static void
1395 get_external_id(char **keys, char **values, size_t n,
1396                 const char *prefix, const char *key,
1397                 struct ds *output)
1398 {
1399     size_t prefix_len = strlen(prefix);
1400     struct svec svec;
1401     size_t i;
1402
1403     svec_init(&svec);
1404     for (i = 0; i < n; i++) {
1405         if (!key && !strncmp(keys[i], prefix, prefix_len)) {
1406             svec_add_nocopy(&svec, xasprintf("%s=%s",
1407                                              keys[i] + prefix_len, values[i]));
1408         } else if (key_matches(keys[i], prefix, prefix_len, key)) {
1409             svec_add(&svec, values[i]);
1410             break;
1411         }
1412     }
1413     output_sorted(&svec, output);
1414     svec_destroy(&svec);
1415 }
1416
1417 static void
1418 pre_cmd_br_get_external_id(struct vsctl_context *ctx)
1419 {
1420     pre_cmd_br_set_external_id(ctx);
1421 }
1422
1423 static void
1424 cmd_br_get_external_id(struct vsctl_context *ctx)
1425 {
1426     struct vsctl_info info;
1427     struct vsctl_bridge *bridge;
1428
1429     get_info(ctx, &info);
1430     bridge = find_bridge(&info, ctx->argv[1], true);
1431     if (bridge->br_cfg) {
1432         ovsrec_bridge_verify_external_ids(bridge->br_cfg);
1433         get_external_id(bridge->br_cfg->key_external_ids,
1434                         bridge->br_cfg->value_external_ids,
1435                         bridge->br_cfg->n_external_ids,
1436                         "", ctx->argc >= 3 ? ctx->argv[2] : NULL,
1437                         &ctx->output);
1438     } else {
1439         struct vsctl_port *port = shash_find_data(&info.ports, ctx->argv[1]);
1440         ovsrec_port_verify_external_ids(port->port_cfg);
1441         get_external_id(port->port_cfg->key_external_ids,
1442                         port->port_cfg->value_external_ids,
1443                         port->port_cfg->n_external_ids,
1444                         "fake-bridge-", ctx->argc >= 3 ? ctx->argv[2] : NULL, &ctx->output);
1445     }
1446     free_info(&info);
1447 }
1448
1449
1450 static void
1451 cmd_list_ports(struct vsctl_context *ctx)
1452 {
1453     struct vsctl_bridge *br;
1454     struct shash_node *node;
1455     struct vsctl_info info;
1456     struct svec ports;
1457
1458     get_info(ctx, &info);
1459     br = find_bridge(&info, ctx->argv[1], true);
1460     ovsrec_bridge_verify_ports(br->br_cfg ? br->br_cfg : br->parent->br_cfg);
1461
1462     svec_init(&ports);
1463     SHASH_FOR_EACH (node, &info.ports) {
1464         struct vsctl_port *port = node->data;
1465
1466         if (strcmp(port->port_cfg->name, br->name) && br == port->bridge) {
1467             svec_add(&ports, port->port_cfg->name);
1468         }
1469     }
1470     output_sorted(&ports, &ctx->output);
1471     svec_destroy(&ports);
1472
1473     free_info(&info);
1474 }
1475
1476 static void
1477 add_port(struct vsctl_context *ctx,
1478          const char *br_name, const char *port_name,
1479          bool may_exist, bool fake_iface,
1480          char *iface_names[], int n_ifaces,
1481          char *settings[], int n_settings)
1482 {
1483     struct vsctl_info info;
1484     struct vsctl_bridge *bridge;
1485     struct ovsrec_interface **ifaces;
1486     struct ovsrec_port *port;
1487     size_t i;
1488
1489     get_info(ctx, &info);
1490     if (may_exist) {
1491         struct vsctl_port *vsctl_port;
1492
1493         vsctl_port = find_port(&info, port_name, false);
1494         if (vsctl_port) {
1495             struct svec want_names, have_names;
1496
1497             svec_init(&want_names);
1498             for (i = 0; i < n_ifaces; i++) {
1499                 svec_add(&want_names, iface_names[i]);
1500             }
1501             svec_sort(&want_names);
1502
1503             svec_init(&have_names);
1504             for (i = 0; i < vsctl_port->port_cfg->n_interfaces; i++) {
1505                 svec_add(&have_names,
1506                          vsctl_port->port_cfg->interfaces[i]->name);
1507             }
1508             svec_sort(&have_names);
1509
1510             if (strcmp(vsctl_port->bridge->name, br_name)) {
1511                 char *command = vsctl_context_to_string(ctx);
1512                 vsctl_fatal("\"%s\" but %s is actually attached to bridge %s",
1513                             command, port_name, vsctl_port->bridge->name);
1514             }
1515
1516             if (!svec_equal(&want_names, &have_names)) {
1517                 char *have_names_string = svec_join(&have_names, ", ", "");
1518                 char *command = vsctl_context_to_string(ctx);
1519
1520                 vsctl_fatal("\"%s\" but %s actually has interface(s) %s",
1521                             command, port_name, have_names_string);
1522             }
1523
1524             svec_destroy(&want_names);
1525             svec_destroy(&have_names);
1526
1527             return;
1528         }
1529     }
1530     check_conflicts(&info, port_name,
1531                     xasprintf("cannot create a port named %s", port_name));
1532     for (i = 0; i < n_ifaces; i++) {
1533         check_conflicts(&info, iface_names[i],
1534                         xasprintf("cannot create an interface named %s",
1535                                   iface_names[i]));
1536     }
1537     bridge = find_bridge(&info, br_name, true);
1538
1539     ifaces = xmalloc(n_ifaces * sizeof *ifaces);
1540     for (i = 0; i < n_ifaces; i++) {
1541         ifaces[i] = ovsrec_interface_insert(ctx->txn);
1542         ovsrec_interface_set_name(ifaces[i], iface_names[i]);
1543     }
1544
1545     port = ovsrec_port_insert(ctx->txn);
1546     ovsrec_port_set_name(port, port_name);
1547     ovsrec_port_set_interfaces(port, ifaces, n_ifaces);
1548     ovsrec_port_set_bond_fake_iface(port, fake_iface);
1549     free(ifaces);
1550
1551     if (bridge->vlan) {
1552         int64_t tag = bridge->vlan;
1553         ovsrec_port_set_tag(port, &tag, 1);
1554     }
1555
1556     for (i = 0; i < n_settings; i++) {
1557         set_column(get_table("Port"), &port->header_, settings[i],
1558                    ctx->symtab);
1559     }
1560
1561     bridge_insert_port((bridge->parent ? bridge->parent->br_cfg
1562                         : bridge->br_cfg), port);
1563
1564     free_info(&info);
1565 }
1566
1567 static void
1568 cmd_add_port(struct vsctl_context *ctx)
1569 {
1570     bool may_exist = shash_find(&ctx->options, "--may-exist") != 0;
1571
1572     add_port(ctx, ctx->argv[1], ctx->argv[2], may_exist, false,
1573              &ctx->argv[2], 1, &ctx->argv[3], ctx->argc - 3);
1574 }
1575
1576 static void
1577 cmd_add_bond(struct vsctl_context *ctx)
1578 {
1579     bool may_exist = shash_find(&ctx->options, "--may-exist") != 0;
1580     bool fake_iface = shash_find(&ctx->options, "--fake-iface");
1581     int n_ifaces;
1582     int i;
1583
1584     n_ifaces = ctx->argc - 3;
1585     for (i = 3; i < ctx->argc; i++) {
1586         if (strchr(ctx->argv[i], '=')) {
1587             n_ifaces = i - 3;
1588             break;
1589         }
1590     }
1591     if (n_ifaces < 2) {
1592         vsctl_fatal("add-bond requires at least 2 interfaces, but only "
1593                     "%d were specified", n_ifaces);
1594     }
1595
1596     add_port(ctx, ctx->argv[1], ctx->argv[2], may_exist, fake_iface,
1597              &ctx->argv[3], n_ifaces,
1598              &ctx->argv[n_ifaces + 3], ctx->argc - 3 - n_ifaces);
1599 }
1600
1601 static void
1602 cmd_del_port(struct vsctl_context *ctx)
1603 {
1604     bool must_exist = !shash_find(&ctx->options, "--if-exists");
1605     bool with_iface = shash_find(&ctx->options, "--with-iface") != NULL;
1606     struct vsctl_port *port;
1607     struct vsctl_info info;
1608
1609     get_info(ctx, &info);
1610     if (!with_iface) {
1611         port = find_port(&info, ctx->argv[ctx->argc - 1], must_exist);
1612     } else {
1613         const char *target = ctx->argv[ctx->argc - 1];
1614         struct vsctl_iface *iface;
1615
1616         port = find_port(&info, target, false);
1617         if (!port) {
1618             iface = find_iface(&info, target, false);
1619             if (iface) {
1620                 port = iface->port;
1621             }
1622         }
1623         if (must_exist && !port) {
1624             vsctl_fatal("no port or interface named %s", target);
1625         }
1626     }
1627
1628     if (port) {
1629         if (ctx->argc == 3) {
1630             struct vsctl_bridge *bridge;
1631
1632             bridge = find_bridge(&info, ctx->argv[1], true);
1633             if (port->bridge != bridge) {
1634                 if (port->bridge->parent == bridge) {
1635                     vsctl_fatal("bridge %s does not have a port %s (although "
1636                                 "its parent bridge %s does)",
1637                                 ctx->argv[1], ctx->argv[2],
1638                                 bridge->parent->name);
1639                 } else {
1640                     vsctl_fatal("bridge %s does not have a port %s",
1641                                 ctx->argv[1], ctx->argv[2]);
1642                 }
1643             }
1644         }
1645
1646         del_port(&info, port);
1647     }
1648
1649     free_info(&info);
1650 }
1651
1652 static void
1653 cmd_port_to_br(struct vsctl_context *ctx)
1654 {
1655     struct vsctl_port *port;
1656     struct vsctl_info info;
1657
1658     get_info(ctx, &info);
1659     port = find_port(&info, ctx->argv[1], true);
1660     ds_put_format(&ctx->output, "%s\n", port->bridge->name);
1661     free_info(&info);
1662 }
1663
1664 static void
1665 cmd_br_to_vlan(struct vsctl_context *ctx)
1666 {
1667     struct vsctl_bridge *bridge;
1668     struct vsctl_info info;
1669
1670     get_info(ctx, &info);
1671     bridge = find_bridge(&info, ctx->argv[1], true);
1672     ds_put_format(&ctx->output, "%d\n", bridge->vlan);
1673     free_info(&info);
1674 }
1675
1676 static void
1677 cmd_br_to_parent(struct vsctl_context *ctx)
1678 {
1679     struct vsctl_bridge *bridge;
1680     struct vsctl_info info;
1681
1682     get_info(ctx, &info);
1683     bridge = find_bridge(&info, ctx->argv[1], true);
1684     if (bridge->parent) {
1685         bridge = bridge->parent;
1686     }
1687     ds_put_format(&ctx->output, "%s\n", bridge->name);
1688     free_info(&info);
1689 }
1690
1691 static void
1692 cmd_list_ifaces(struct vsctl_context *ctx)
1693 {
1694     struct vsctl_bridge *br;
1695     struct shash_node *node;
1696     struct vsctl_info info;
1697     struct svec ifaces;
1698
1699     get_info(ctx, &info);
1700     br = find_bridge(&info, ctx->argv[1], true);
1701     verify_ports(ctx);
1702
1703     svec_init(&ifaces);
1704     SHASH_FOR_EACH (node, &info.ifaces) {
1705         struct vsctl_iface *iface = node->data;
1706
1707         if (strcmp(iface->iface_cfg->name, br->name)
1708             && br == iface->port->bridge) {
1709             svec_add(&ifaces, iface->iface_cfg->name);
1710         }
1711     }
1712     output_sorted(&ifaces, &ctx->output);
1713     svec_destroy(&ifaces);
1714
1715     free_info(&info);
1716 }
1717
1718 static void
1719 cmd_iface_to_br(struct vsctl_context *ctx)
1720 {
1721     struct vsctl_iface *iface;
1722     struct vsctl_info info;
1723
1724     get_info(ctx, &info);
1725     iface = find_iface(&info, ctx->argv[1], true);
1726     ds_put_format(&ctx->output, "%s\n", iface->port->bridge->name);
1727     free_info(&info);
1728 }
1729
1730 static void
1731 verify_controllers(struct ovsrec_bridge *bridge)
1732 {
1733     if (bridge) {
1734         size_t i;
1735
1736         ovsrec_bridge_verify_controller(bridge);
1737         for (i = 0; i < bridge->n_controller; i++) {
1738             ovsrec_controller_verify_target(bridge->controller[i]);
1739         }
1740     }
1741 }
1742
1743 static void
1744 pre_controller(struct vsctl_context *ctx)
1745 {
1746     pre_get_info(ctx);
1747
1748     ovsdb_idl_add_column(ctx->idl, &ovsrec_controller_col_target);
1749 }
1750
1751 static void
1752 cmd_get_controller(struct vsctl_context *ctx)
1753 {
1754     struct vsctl_info info;
1755     struct vsctl_bridge *br;
1756     struct svec targets;
1757     size_t i;
1758
1759     get_info(ctx, &info);
1760     br = find_bridge(&info, ctx->argv[1], true);
1761     verify_controllers(br->br_cfg);
1762
1763     /* Print the targets in sorted order for reproducibility. */
1764     svec_init(&targets);
1765     for (i = 0; i < br->n_ctrl; i++) {
1766         svec_add(&targets, br->ctrl[i]->target);
1767     }
1768
1769     svec_sort(&targets);
1770     for (i = 0; i < targets.n; i++) {
1771         ds_put_format(&ctx->output, "%s\n", targets.names[i]);
1772     }
1773     svec_destroy(&targets);
1774
1775     free_info(&info);
1776 }
1777
1778 static void
1779 delete_controllers(struct ovsrec_controller **controllers,
1780                    size_t n_controllers)
1781 {
1782     size_t i;
1783
1784     for (i = 0; i < n_controllers; i++) {
1785         ovsrec_controller_delete(controllers[i]);
1786     }
1787 }
1788
1789 static void
1790 cmd_del_controller(struct vsctl_context *ctx)
1791 {
1792     struct vsctl_info info;
1793     struct vsctl_bridge *br;
1794
1795     get_info(ctx, &info);
1796     br = find_real_bridge(&info, ctx->argv[1], true);
1797     verify_controllers(br->br_cfg);
1798
1799     if (br->ctrl) {
1800         delete_controllers(br->ctrl, br->n_ctrl);
1801         ovsrec_bridge_set_controller(br->br_cfg, NULL, 0);
1802     }
1803
1804     free_info(&info);
1805 }
1806
1807 static struct ovsrec_controller **
1808 insert_controllers(struct ovsdb_idl_txn *txn, char *targets[], size_t n)
1809 {
1810     struct ovsrec_controller **controllers;
1811     size_t i;
1812
1813     controllers = xmalloc(n * sizeof *controllers);
1814     for (i = 0; i < n; i++) {
1815         controllers[i] = ovsrec_controller_insert(txn);
1816         ovsrec_controller_set_target(controllers[i], targets[i]);
1817     }
1818
1819     return controllers;
1820 }
1821
1822 static void
1823 cmd_set_controller(struct vsctl_context *ctx)
1824 {
1825     struct vsctl_info info;
1826     struct vsctl_bridge *br;
1827     struct ovsrec_controller **controllers;
1828     size_t n;
1829
1830     get_info(ctx, &info);
1831     br = find_real_bridge(&info, ctx->argv[1], true);
1832     verify_controllers(br->br_cfg);
1833
1834     delete_controllers(br->ctrl, br->n_ctrl);
1835
1836     n = ctx->argc - 2;
1837     controllers = insert_controllers(ctx->txn, &ctx->argv[2], n);
1838     ovsrec_bridge_set_controller(br->br_cfg, controllers, n);
1839     free(controllers);
1840
1841     free_info(&info);
1842 }
1843
1844 static void
1845 cmd_get_fail_mode(struct vsctl_context *ctx)
1846 {
1847     struct vsctl_info info;
1848     struct vsctl_bridge *br;
1849
1850     get_info(ctx, &info);
1851     br = find_bridge(&info, ctx->argv[1], true);
1852
1853     if (br->br_cfg) {
1854         ovsrec_bridge_verify_fail_mode(br->br_cfg);
1855     }
1856     if (br->fail_mode && strlen(br->fail_mode)) {
1857         ds_put_format(&ctx->output, "%s\n", br->fail_mode);
1858     }
1859
1860     free_info(&info);
1861 }
1862
1863 static void
1864 cmd_del_fail_mode(struct vsctl_context *ctx)
1865 {
1866     struct vsctl_info info;
1867     struct vsctl_bridge *br;
1868
1869     get_info(ctx, &info);
1870     br = find_real_bridge(&info, ctx->argv[1], true);
1871
1872     ovsrec_bridge_set_fail_mode(br->br_cfg, NULL);
1873
1874     free_info(&info);
1875 }
1876
1877 static void
1878 cmd_set_fail_mode(struct vsctl_context *ctx)
1879 {
1880     struct vsctl_info info;
1881     struct vsctl_bridge *br;
1882     const char *fail_mode = ctx->argv[2];
1883
1884     get_info(ctx, &info);
1885     br = find_real_bridge(&info, ctx->argv[1], true);
1886
1887     if (strcmp(fail_mode, "standalone") && strcmp(fail_mode, "secure")) {
1888         vsctl_fatal("fail-mode must be \"standalone\" or \"secure\"");
1889     }
1890
1891     ovsrec_bridge_set_fail_mode(br->br_cfg, fail_mode);
1892
1893     free_info(&info);
1894 }
1895
1896 static void
1897 verify_managers(const struct ovsrec_open_vswitch *ovs)
1898 {
1899     size_t i;
1900
1901     ovsrec_open_vswitch_verify_managers(ovs);
1902     ovsrec_open_vswitch_verify_manager_options(ovs);
1903
1904     for (i = 0; i < ovs->n_manager_options; ++i) {
1905         const struct ovsrec_manager *mgr = ovs->manager_options[i];
1906
1907         ovsrec_manager_verify_target(mgr);
1908     }
1909 }
1910
1911 static void
1912 pre_manager(struct vsctl_context *ctx)
1913 {
1914     ovsdb_idl_add_column(ctx->idl, &ovsrec_open_vswitch_col_managers);
1915     ovsdb_idl_add_column(ctx->idl, &ovsrec_open_vswitch_col_manager_options);
1916     ovsdb_idl_add_column(ctx->idl, &ovsrec_manager_col_target);
1917 }
1918
1919 static void
1920 cmd_get_manager(struct vsctl_context *ctx)
1921 {
1922     const struct ovsrec_open_vswitch *ovs = ctx->ovs;
1923     struct svec targets;
1924     size_t i;
1925
1926     verify_managers(ovs);
1927
1928     /* Print the targets in sorted order for reproducibility. */
1929     svec_init(&targets);
1930
1931     /* First, add all targets found in deprecated 'managers' column. */
1932     for (i = 0; i < ovs->n_managers; i++) {
1933         svec_add(&targets, ovs->managers[i]);
1934     }
1935
1936     /* Second, add all targets pointed to by 'manager_options' column. */
1937     for (i = 0; i < ovs->n_manager_options; i++) {
1938         svec_add(&targets, ovs->manager_options[i]->target);
1939     }
1940
1941     svec_sort_unique(&targets);
1942     for (i = 0; i < targets.n; i++) {
1943         ds_put_format(&ctx->output, "%s\n", targets.names[i]);
1944     }
1945     svec_destroy(&targets);
1946 }
1947
1948 static void
1949 delete_managers(const struct vsctl_context *ctx)
1950 {
1951     const struct ovsrec_open_vswitch *ovs = ctx->ovs;
1952     size_t i;
1953
1954     /* Delete manager targets in deprecated 'managers' column. */
1955     ovsrec_open_vswitch_set_managers(ovs, NULL, 0);
1956
1957     /* Delete Manager rows pointed to by 'manager_options' column. */
1958     for (i = 0; i < ovs->n_manager_options; i++) {
1959         ovsrec_manager_delete(ovs->manager_options[i]);
1960     }
1961
1962     /* Delete 'Manager' row refs in 'manager_options' column. */
1963     ovsrec_open_vswitch_set_manager_options(ovs, NULL, 0);
1964 }
1965
1966 static void
1967 cmd_del_manager(struct vsctl_context *ctx)
1968 {
1969     const struct ovsrec_open_vswitch *ovs = ctx->ovs;
1970
1971     verify_managers(ovs);
1972     delete_managers(ctx);
1973 }
1974
1975 static void
1976 insert_managers(struct vsctl_context *ctx, char *targets[], size_t n)
1977 {
1978     struct ovsrec_manager **managers;
1979     size_t i;
1980
1981     /* Store in deprecated 'manager' column. */
1982     ovsrec_open_vswitch_set_managers(ctx->ovs, targets, n);
1983
1984     /* Insert each manager in a new row in Manager table. */
1985     managers = xmalloc(n * sizeof *managers);
1986     for (i = 0; i < n; i++) {
1987         managers[i] = ovsrec_manager_insert(ctx->txn);
1988         ovsrec_manager_set_target(managers[i], targets[i]);
1989     }
1990
1991     /* Store uuids of new Manager rows in 'manager_options' column. */
1992     ovsrec_open_vswitch_set_manager_options(ctx->ovs, managers, n);
1993     free(managers);
1994 }
1995
1996 static void
1997 cmd_set_manager(struct vsctl_context *ctx)
1998 {
1999     const size_t n = ctx->argc - 1;
2000
2001     verify_managers(ctx->ovs);
2002     delete_managers(ctx);
2003     insert_managers(ctx, &ctx->argv[1], n);
2004 }
2005
2006 static void
2007 pre_cmd_get_ssl(struct vsctl_context *ctx)
2008 {
2009     ovsdb_idl_add_column(ctx->idl, &ovsrec_open_vswitch_col_ssl);
2010
2011     ovsdb_idl_add_column(ctx->idl, &ovsrec_ssl_col_private_key);
2012     ovsdb_idl_add_column(ctx->idl, &ovsrec_ssl_col_certificate);
2013     ovsdb_idl_add_column(ctx->idl, &ovsrec_ssl_col_ca_cert);
2014     ovsdb_idl_add_column(ctx->idl, &ovsrec_ssl_col_bootstrap_ca_cert);
2015 }
2016
2017 static void
2018 cmd_get_ssl(struct vsctl_context *ctx)
2019 {
2020     struct ovsrec_ssl *ssl = ctx->ovs->ssl;
2021
2022     ovsrec_open_vswitch_verify_ssl(ctx->ovs);
2023     if (ssl) {
2024         ovsrec_ssl_verify_private_key(ssl);
2025         ovsrec_ssl_verify_certificate(ssl);
2026         ovsrec_ssl_verify_ca_cert(ssl);
2027         ovsrec_ssl_verify_bootstrap_ca_cert(ssl);
2028
2029         ds_put_format(&ctx->output, "Private key: %s\n", ssl->private_key);
2030         ds_put_format(&ctx->output, "Certificate: %s\n", ssl->certificate);
2031         ds_put_format(&ctx->output, "CA Certificate: %s\n", ssl->ca_cert);
2032         ds_put_format(&ctx->output, "Bootstrap: %s\n",
2033                 ssl->bootstrap_ca_cert ? "true" : "false");
2034     }
2035 }
2036
2037 static void
2038 pre_cmd_del_ssl(struct vsctl_context *ctx)
2039 {
2040     ovsdb_idl_add_column(ctx->idl, &ovsrec_open_vswitch_col_ssl);
2041 }
2042
2043 static void
2044 cmd_del_ssl(struct vsctl_context *ctx)
2045 {
2046     struct ovsrec_ssl *ssl = ctx->ovs->ssl;
2047
2048     if (ssl) {
2049         ovsrec_open_vswitch_verify_ssl(ctx->ovs);
2050         ovsrec_ssl_delete(ssl);
2051         ovsrec_open_vswitch_set_ssl(ctx->ovs, NULL);
2052     }
2053 }
2054
2055 static void
2056 pre_cmd_set_ssl(struct vsctl_context *ctx)
2057 {
2058     ovsdb_idl_add_column(ctx->idl, &ovsrec_open_vswitch_col_ssl);
2059 }
2060
2061 static void
2062 cmd_set_ssl(struct vsctl_context *ctx)
2063 {
2064     bool bootstrap = shash_find(&ctx->options, "--bootstrap");
2065     struct ovsrec_ssl *ssl = ctx->ovs->ssl;
2066
2067     ovsrec_open_vswitch_verify_ssl(ctx->ovs);
2068     if (ssl) {
2069         ovsrec_ssl_delete(ssl);
2070     }
2071     ssl = ovsrec_ssl_insert(ctx->txn);
2072
2073     ovsrec_ssl_set_private_key(ssl, ctx->argv[1]);
2074     ovsrec_ssl_set_certificate(ssl, ctx->argv[2]);
2075     ovsrec_ssl_set_ca_cert(ssl, ctx->argv[3]);
2076
2077     ovsrec_ssl_set_bootstrap_ca_cert(ssl, bootstrap);
2078
2079     ovsrec_open_vswitch_set_ssl(ctx->ovs, ssl);
2080 }
2081 \f
2082 /* Parameter commands. */
2083
2084 struct vsctl_row_id {
2085     const struct ovsdb_idl_table_class *table;
2086     const struct ovsdb_idl_column *name_column;
2087     const struct ovsdb_idl_column *uuid_column;
2088 };
2089
2090 struct vsctl_table_class {
2091     struct ovsdb_idl_table_class *class;
2092     struct vsctl_row_id row_ids[2];
2093 };
2094
2095 static const struct vsctl_table_class tables[] = {
2096     {&ovsrec_table_bridge,
2097      {{&ovsrec_table_bridge, &ovsrec_bridge_col_name, NULL},
2098       {NULL, NULL, NULL}}},
2099
2100     {&ovsrec_table_controller,
2101      {{&ovsrec_table_bridge,
2102        &ovsrec_bridge_col_name,
2103        &ovsrec_bridge_col_controller}}},
2104
2105     {&ovsrec_table_interface,
2106      {{&ovsrec_table_interface, &ovsrec_interface_col_name, NULL},
2107       {NULL, NULL, NULL}}},
2108
2109     {&ovsrec_table_mirror,
2110      {{&ovsrec_table_mirror, &ovsrec_mirror_col_name, NULL},
2111       {NULL, NULL, NULL}}},
2112
2113     {&ovsrec_table_manager,
2114      {{&ovsrec_table_manager, &ovsrec_manager_col_target, NULL},
2115       {NULL, NULL, NULL}}},
2116
2117     {&ovsrec_table_netflow,
2118      {{&ovsrec_table_bridge,
2119        &ovsrec_bridge_col_name,
2120        &ovsrec_bridge_col_netflow},
2121       {NULL, NULL, NULL}}},
2122
2123     {&ovsrec_table_open_vswitch,
2124      {{&ovsrec_table_open_vswitch, NULL, NULL},
2125       {NULL, NULL, NULL}}},
2126
2127     {&ovsrec_table_port,
2128      {{&ovsrec_table_port, &ovsrec_port_col_name, NULL},
2129       {NULL, NULL, NULL}}},
2130
2131     {&ovsrec_table_qos,
2132      {{&ovsrec_table_port, &ovsrec_port_col_name, &ovsrec_port_col_qos},
2133       {NULL, NULL, NULL}}},
2134
2135     {&ovsrec_table_monitor,
2136      {{&ovsrec_table_interface,
2137        &ovsrec_interface_col_name,
2138        &ovsrec_interface_col_monitor},
2139       {NULL, NULL, NULL}}},
2140
2141     {&ovsrec_table_maintenance_point,
2142      {{NULL, NULL, NULL},
2143       {NULL, NULL, NULL}}},
2144
2145     {&ovsrec_table_queue,
2146      {{NULL, NULL, NULL},
2147       {NULL, NULL, NULL}}},
2148
2149     {&ovsrec_table_ssl,
2150      {{&ovsrec_table_open_vswitch, NULL, &ovsrec_open_vswitch_col_ssl}}},
2151
2152     {&ovsrec_table_sflow,
2153      {{&ovsrec_table_bridge,
2154        &ovsrec_bridge_col_name,
2155        &ovsrec_bridge_col_sflow},
2156       {NULL, NULL, NULL}}},
2157
2158     {NULL, {{NULL, NULL, NULL}, {NULL, NULL, NULL}}}
2159 };
2160
2161 static void
2162 die_if_error(char *error)
2163 {
2164     if (error) {
2165         vsctl_fatal("%s", error);
2166     }
2167 }
2168
2169 static int
2170 to_lower_and_underscores(unsigned c)
2171 {
2172     return c == '-' ? '_' : tolower(c);
2173 }
2174
2175 static unsigned int
2176 score_partial_match(const char *name, const char *s)
2177 {
2178     int score;
2179
2180     if (!strcmp(name, s)) {
2181         return UINT_MAX;
2182     }
2183     for (score = 0; ; score++, name++, s++) {
2184         if (to_lower_and_underscores(*name) != to_lower_and_underscores(*s)) {
2185             break;
2186         } else if (*name == '\0') {
2187             return UINT_MAX - 1;
2188         }
2189     }
2190     return *s == '\0' ? score : 0;
2191 }
2192
2193 static const struct vsctl_table_class *
2194 get_table(const char *table_name)
2195 {
2196     const struct vsctl_table_class *table;
2197     const struct vsctl_table_class *best_match = NULL;
2198     unsigned int best_score = 0;
2199
2200     for (table = tables; table->class; table++) {
2201         unsigned int score = score_partial_match(table->class->name,
2202                                                  table_name);
2203         if (score > best_score) {
2204             best_match = table;
2205             best_score = score;
2206         } else if (score == best_score) {
2207             best_match = NULL;
2208         }
2209     }
2210     if (best_match) {
2211         return best_match;
2212     } else if (best_score) {
2213         vsctl_fatal("multiple table names match \"%s\"", table_name);
2214     } else {
2215         vsctl_fatal("unknown table \"%s\"", table_name);
2216     }
2217 }
2218
2219 static const struct vsctl_table_class *
2220 pre_get_table(struct vsctl_context *ctx, const char *table_name)
2221 {
2222     const struct vsctl_table_class *table_class;
2223     int i;
2224
2225     table_class = get_table(table_name);
2226     ovsdb_idl_add_table(ctx->idl, table_class->class);
2227
2228     for (i = 0; i < ARRAY_SIZE(table_class->row_ids); i++) {
2229         const struct vsctl_row_id *id = &table_class->row_ids[i];
2230         if (id->table) {
2231             ovsdb_idl_add_table(ctx->idl, id->table);
2232         }
2233         if (id->name_column) {
2234             ovsdb_idl_add_column(ctx->idl, id->name_column);
2235         }
2236         if (id->uuid_column) {
2237             ovsdb_idl_add_column(ctx->idl, id->uuid_column);
2238         }
2239     }
2240
2241     return table_class;
2242 }
2243
2244 static const struct ovsdb_idl_row *
2245 get_row_by_id(struct vsctl_context *ctx, const struct vsctl_table_class *table,
2246               const struct vsctl_row_id *id, const char *record_id)
2247 {
2248     const struct ovsdb_idl_row *referrer, *final;
2249
2250     if (!id->table) {
2251         return NULL;
2252     }
2253
2254     if (!id->name_column) {
2255         if (strcmp(record_id, ".")) {
2256             return NULL;
2257         }
2258         referrer = ovsdb_idl_first_row(ctx->idl, id->table);
2259         if (!referrer || ovsdb_idl_next_row(referrer)) {
2260             return NULL;
2261         }
2262     } else {
2263         const struct ovsdb_idl_row *row;
2264
2265         referrer = NULL;
2266         for (row = ovsdb_idl_first_row(ctx->idl, id->table);
2267              row != NULL;
2268              row = ovsdb_idl_next_row(row))
2269         {
2270             const struct ovsdb_datum *name;
2271
2272             name = ovsdb_idl_get(row, id->name_column,
2273                                  OVSDB_TYPE_STRING, OVSDB_TYPE_VOID);
2274             if (name->n == 1 && !strcmp(name->keys[0].string, record_id)) {
2275                 if (referrer) {
2276                     vsctl_fatal("multiple rows in %s match \"%s\"",
2277                                 table->class->name, record_id);
2278                 }
2279                 referrer = row;
2280             }
2281         }
2282     }
2283     if (!referrer) {
2284         return NULL;
2285     }
2286
2287     final = NULL;
2288     if (id->uuid_column) {
2289         const struct ovsdb_datum *uuid;
2290
2291         ovsdb_idl_txn_verify(referrer, id->uuid_column);
2292         uuid = ovsdb_idl_get(referrer, id->uuid_column,
2293                              OVSDB_TYPE_UUID, OVSDB_TYPE_VOID);
2294         if (uuid->n == 1) {
2295             final = ovsdb_idl_get_row_for_uuid(ctx->idl, table->class,
2296                                                &uuid->keys[0].uuid);
2297         }
2298     } else {
2299         final = referrer;
2300     }
2301
2302     return final;
2303 }
2304
2305 static const struct ovsdb_idl_row *
2306 get_row (struct vsctl_context *ctx,
2307          const struct vsctl_table_class *table, const char *record_id)
2308 {
2309     const struct ovsdb_idl_row *row;
2310     struct uuid uuid;
2311
2312     if (uuid_from_string(&uuid, record_id)) {
2313         row = ovsdb_idl_get_row_for_uuid(ctx->idl, table->class, &uuid);
2314     } else {
2315         int i;
2316
2317         for (i = 0; i < ARRAY_SIZE(table->row_ids); i++) {
2318             row = get_row_by_id(ctx, table, &table->row_ids[i], record_id);
2319             if (row) {
2320                 break;
2321             }
2322         }
2323     }
2324     return row;
2325 }
2326
2327 static const struct ovsdb_idl_row *
2328 must_get_row(struct vsctl_context *ctx,
2329              const struct vsctl_table_class *table, const char *record_id)
2330 {
2331     const struct ovsdb_idl_row *row = get_row(ctx, table, record_id);
2332     if (!row) {
2333         vsctl_fatal("no row \"%s\" in table %s",
2334                     record_id, table->class->name);
2335     }
2336     return row;
2337 }
2338
2339 static char *
2340 get_column(const struct vsctl_table_class *table, const char *column_name,
2341            const struct ovsdb_idl_column **columnp)
2342 {
2343     const struct ovsdb_idl_column *best_match = NULL;
2344     unsigned int best_score = 0;
2345     size_t i;
2346
2347     for (i = 0; i < table->class->n_columns; i++) {
2348         const struct ovsdb_idl_column *column = &table->class->columns[i];
2349         unsigned int score = score_partial_match(column->name, column_name);
2350         if (score > best_score) {
2351             best_match = column;
2352             best_score = score;
2353         } else if (score == best_score) {
2354             best_match = NULL;
2355         }
2356     }
2357
2358     *columnp = best_match;
2359     if (best_match) {
2360         return NULL;
2361     } else if (best_score) {
2362         return xasprintf("%s contains more than one column whose name "
2363                          "matches \"%s\"", table->class->name, column_name);
2364     } else {
2365         return xasprintf("%s does not contain a column whose name matches "
2366                          "\"%s\"", table->class->name, column_name);
2367     }
2368 }
2369
2370 static struct uuid *
2371 create_symbol(struct ovsdb_symbol_table *symtab, const char *id, bool *newp)
2372 {
2373     struct ovsdb_symbol *symbol;
2374
2375     if (id[0] != '@') {
2376         vsctl_fatal("row id \"%s\" does not begin with \"@\"", id);
2377     }
2378
2379     if (newp) {
2380         *newp = ovsdb_symbol_table_get(symtab, id) == NULL;
2381     }
2382
2383     symbol = ovsdb_symbol_table_insert(symtab, id);
2384     if (symbol->used) {
2385         vsctl_fatal("row id \"%s\" may only be specified on one --id option",
2386                     id);
2387     }
2388     symbol->used = true;
2389     return &symbol->uuid;
2390 }
2391
2392 static void
2393 pre_get_column(struct vsctl_context *ctx,
2394                const struct vsctl_table_class *table, const char *column_name,
2395                const struct ovsdb_idl_column **columnp)
2396 {
2397     die_if_error(get_column(table, column_name, columnp));
2398     ovsdb_idl_add_column(ctx->idl, *columnp);
2399 }
2400
2401 static char *
2402 missing_operator_error(const char *arg, const char **allowed_operators,
2403                        size_t n_allowed)
2404 {
2405     struct ds s;
2406
2407     ds_init(&s);
2408     ds_put_format(&s, "%s: argument does not end in ", arg);
2409     ds_put_format(&s, "\"%s\"", allowed_operators[0]);
2410     if (n_allowed == 2) {
2411         ds_put_format(&s, " or \"%s\"", allowed_operators[1]);
2412     } else if (n_allowed > 2) {
2413         size_t i;
2414
2415         for (i = 1; i < n_allowed - 1; i++) {
2416             ds_put_format(&s, ", \"%s\"", allowed_operators[i]);
2417         }
2418         ds_put_format(&s, ", or \"%s\"", allowed_operators[i]);
2419     }
2420     ds_put_format(&s, " followed by a value.");
2421
2422     return ds_steal_cstr(&s);
2423 }
2424
2425 /* Breaks 'arg' apart into a number of fields in the following order:
2426  *
2427  *      - If 'columnp' is nonnull, the name of a column in 'table'.  The column
2428  *        is stored into '*columnp'.  The column name may be abbreviated.
2429  *
2430  *      - If 'keyp' is nonnull, optionally a key string.  (If both 'columnp'
2431  *        and 'keyp' are nonnull, then the column and key names are expected to
2432  *        be separated by ':').  The key is stored as a malloc()'d string into
2433  *        '*keyp', or NULL if no key is present in 'arg'.
2434  *
2435  *      - If 'valuep' is nonnull, an operator followed by a value string.  The
2436  *        allowed operators are the 'n_allowed' string in 'allowed_operators',
2437  *        or just "=" if 'n_allowed' is 0.  If 'operatorp' is nonnull, then the
2438  *        operator is stored into '*operatorp' (one of the pointers from
2439  *        'allowed_operators' is stored; nothing is malloc()'d).  The value is
2440  *        stored as a malloc()'d string into '*valuep', or NULL if no value is
2441  *        present in 'arg'.
2442  *
2443  * At least 'columnp' or 'keyp' must be nonnull.
2444  *
2445  * On success, returns NULL.  On failure, returned a malloc()'d string error
2446  * message and stores NULL into all of the nonnull output arguments. */
2447 static char * WARN_UNUSED_RESULT
2448 parse_column_key_value(const char *arg,
2449                        const struct vsctl_table_class *table,
2450                        const struct ovsdb_idl_column **columnp, char **keyp,
2451                        const char **operatorp,
2452                        const char **allowed_operators, size_t n_allowed,
2453                        char **valuep)
2454 {
2455     const char *p = arg;
2456     char *error;
2457
2458     assert(columnp || keyp);
2459     assert(!(operatorp && !valuep));
2460     if (keyp) {
2461         *keyp = NULL;
2462     }
2463     if (valuep) {
2464         *valuep = NULL;
2465     }
2466
2467     /* Parse column name. */
2468     if (columnp) {
2469         char *column_name;
2470
2471         error = ovsdb_token_parse(&p, &column_name);
2472         if (error) {
2473             goto error;
2474         }
2475         if (column_name[0] == '\0') {
2476             free(column_name);
2477             error = xasprintf("%s: missing column name", arg);
2478             goto error;
2479         }
2480         error = get_column(table, column_name, columnp);
2481         free(column_name);
2482         if (error) {
2483             goto error;
2484         }
2485     }
2486
2487     /* Parse key string. */
2488     if (*p == ':' || !columnp) {
2489         if (columnp) {
2490             p++;
2491         } else if (!keyp) {
2492             error = xasprintf("%s: key not accepted here", arg);
2493             goto error;
2494         }
2495         error = ovsdb_token_parse(&p, keyp);
2496         if (error) {
2497             goto error;
2498         }
2499     } else if (keyp) {
2500         *keyp = NULL;
2501     }
2502
2503     /* Parse value string. */
2504     if (valuep) {
2505         const char *best;
2506         size_t best_len;
2507         size_t i;
2508
2509         if (!allowed_operators) {
2510             static const char *equals = "=";
2511             allowed_operators = &equals;
2512             n_allowed = 1;
2513         }
2514
2515         best = NULL;
2516         best_len = 0;
2517         for (i = 0; i < n_allowed; i++) {
2518             const char *op = allowed_operators[i];
2519             size_t op_len = strlen(op);
2520
2521             if (op_len > best_len && !strncmp(op, p, op_len) && p[op_len]) {
2522                 best_len = op_len;
2523                 best = op;
2524             }
2525         }
2526         if (!best) {
2527             error = missing_operator_error(arg, allowed_operators, n_allowed);
2528             goto error;
2529         }
2530
2531         if (operatorp) {
2532             *operatorp = best;
2533         }
2534         *valuep = xstrdup(p + best_len);
2535     } else {
2536         if (valuep) {
2537             *valuep = NULL;
2538         }
2539         if (*p != '\0') {
2540             error = xasprintf("%s: trailing garbage \"%s\" in argument",
2541                               arg, p);
2542             goto error;
2543         }
2544     }
2545     return NULL;
2546
2547 error:
2548     if (columnp) {
2549         *columnp = NULL;
2550     }
2551     if (keyp) {
2552         free(*keyp);
2553         *keyp = NULL;
2554     }
2555     if (valuep) {
2556         free(*valuep);
2557         *valuep = NULL;
2558         if (operatorp) {
2559             *operatorp = NULL;
2560         }
2561     }
2562     return error;
2563 }
2564
2565 static void
2566 pre_parse_column_key_value(struct vsctl_context *ctx,
2567                            const char *arg,
2568                            const struct vsctl_table_class *table)
2569 {
2570     const struct ovsdb_idl_column *column;
2571     const char *p;
2572     char *column_name;
2573
2574     p = arg;
2575     die_if_error(ovsdb_token_parse(&p, &column_name));
2576     if (column_name[0] == '\0') {
2577         vsctl_fatal("%s: missing column name", arg);
2578     }
2579
2580     pre_get_column(ctx, table, column_name, &column);
2581     free(column_name);
2582 }
2583
2584 static void
2585 pre_cmd_get(struct vsctl_context *ctx)
2586 {
2587     const char *table_name = ctx->argv[1];
2588     const struct vsctl_table_class *table;
2589     int i;
2590
2591     table = pre_get_table(ctx, table_name);
2592     for (i = 3; i < ctx->argc; i++) {
2593         if (!strcasecmp(ctx->argv[i], "_uuid")
2594             || !strcasecmp(ctx->argv[i], "-uuid")) {
2595             continue;
2596         }
2597
2598         pre_parse_column_key_value(ctx, ctx->argv[i], table);
2599     }
2600 }
2601
2602 static void
2603 cmd_get(struct vsctl_context *ctx)
2604 {
2605     const char *id = shash_find_data(&ctx->options, "--id");
2606     bool if_exists = shash_find(&ctx->options, "--if-exists");
2607     const char *table_name = ctx->argv[1];
2608     const char *record_id = ctx->argv[2];
2609     const struct vsctl_table_class *table;
2610     const struct ovsdb_idl_row *row;
2611     struct ds *out = &ctx->output;
2612     int i;
2613
2614     table = get_table(table_name);
2615     row = must_get_row(ctx, table, record_id);
2616     if (id) {
2617         bool new;
2618
2619         *create_symbol(ctx->symtab, id, &new) = row->uuid;
2620         if (!new) {
2621             vsctl_fatal("row id \"%s\" specified on \"get\" command was used "
2622                         "before it was defined", id);
2623         }
2624     }
2625     for (i = 3; i < ctx->argc; i++) {
2626         const struct ovsdb_idl_column *column;
2627         const struct ovsdb_datum *datum;
2628         char *key_string;
2629
2630         /* Special case for obtaining the UUID of a row.  We can't just do this
2631          * through parse_column_key_value() below since it returns a "struct
2632          * ovsdb_idl_column" and the UUID column doesn't have one. */
2633         if (!strcasecmp(ctx->argv[i], "_uuid")
2634             || !strcasecmp(ctx->argv[i], "-uuid")) {
2635             ds_put_format(out, UUID_FMT"\n", UUID_ARGS(&row->uuid));
2636             continue;
2637         }
2638
2639         die_if_error(parse_column_key_value(ctx->argv[i], table,
2640                                             &column, &key_string,
2641                                             NULL, NULL, 0, NULL));
2642
2643         ovsdb_idl_txn_verify(row, column);
2644         datum = ovsdb_idl_read(row, column);
2645         if (key_string) {
2646             union ovsdb_atom key;
2647             unsigned int idx;
2648
2649             if (column->type.value.type == OVSDB_TYPE_VOID) {
2650                 vsctl_fatal("cannot specify key to get for non-map column %s",
2651                             column->name);
2652             }
2653
2654             die_if_error(ovsdb_atom_from_string(&key,
2655                                                 &column->type.key,
2656                                                 key_string, ctx->symtab));
2657
2658             idx = ovsdb_datum_find_key(datum, &key,
2659                                        column->type.key.type);
2660             if (idx == UINT_MAX) {
2661                 if (!if_exists) {
2662                     vsctl_fatal("no key \"%s\" in %s record \"%s\" column %s",
2663                                 key_string, table->class->name, record_id,
2664                                 column->name);
2665                 }
2666             } else {
2667                 ovsdb_atom_to_string(&datum->values[idx],
2668                                      column->type.value.type, out);
2669             }
2670             ovsdb_atom_destroy(&key, column->type.key.type);
2671         } else {
2672             ovsdb_datum_to_string(datum, &column->type, out);
2673         }
2674         ds_put_char(out, '\n');
2675
2676         free(key_string);
2677     }
2678 }
2679
2680 static void
2681 parse_column_names(const char *column_names,
2682                    const struct vsctl_table_class *table,
2683                    const struct ovsdb_idl_column ***columnsp,
2684                    size_t *n_columnsp)
2685 {
2686     const struct ovsdb_idl_column **columns;
2687     size_t n_columns;
2688
2689     if (!column_names) {
2690         size_t i;
2691
2692         n_columns = table->class->n_columns + 1;
2693         columns = xmalloc(n_columns * sizeof *columns);
2694         columns[0] = NULL;
2695         for (i = 0; i < table->class->n_columns; i++) {
2696             columns[i + 1] = &table->class->columns[i];
2697         }
2698     } else {
2699         char *s = xstrdup(column_names);
2700         size_t allocated_columns;
2701         char *save_ptr = NULL;
2702         char *column_name;
2703
2704         columns = NULL;
2705         allocated_columns = n_columns = 0;
2706         for (column_name = strtok_r(s, ", ", &save_ptr); column_name;
2707              column_name = strtok_r(NULL, ", ", &save_ptr)) {
2708             const struct ovsdb_idl_column *column;
2709
2710             if (!strcasecmp(column_name, "_uuid")) {
2711                 column = NULL;
2712             } else {
2713                 die_if_error(get_column(table, column_name, &column));
2714             }
2715             if (n_columns >= allocated_columns) {
2716                 columns = x2nrealloc(columns, &allocated_columns,
2717                                      sizeof *columns);
2718             }
2719             columns[n_columns++] = column;
2720         }
2721         free(s);
2722
2723         if (!n_columns) {
2724             vsctl_fatal("must specify at least one column name");
2725         }
2726     }
2727     *columnsp = columns;
2728     *n_columnsp = n_columns;
2729 }
2730
2731
2732 static void
2733 pre_list_columns(struct vsctl_context *ctx,
2734                  const struct vsctl_table_class *table,
2735                  const char *column_names)
2736 {
2737     const struct ovsdb_idl_column **columns;
2738     size_t n_columns;
2739     size_t i;
2740
2741     parse_column_names(column_names, table, &columns, &n_columns);
2742     for (i = 0; i < n_columns; i++) {
2743         if (columns[i]) {
2744             ovsdb_idl_add_column(ctx->idl, columns[i]);
2745         }
2746     }
2747     free(columns);
2748 }
2749
2750 static void
2751 pre_cmd_list(struct vsctl_context *ctx)
2752 {
2753     const char *column_names = shash_find_data(&ctx->options, "--columns");
2754     const char *table_name = ctx->argv[1];
2755     const struct vsctl_table_class *table;
2756
2757     table = pre_get_table(ctx, table_name);
2758     pre_list_columns(ctx, table, column_names);
2759 }
2760
2761 static struct table *
2762 list_make_table(const struct ovsdb_idl_column **columns, size_t n_columns)
2763 {
2764     struct table *out;
2765     size_t i;
2766
2767     out = xmalloc(sizeof *out);
2768     table_init(out);
2769
2770     for (i = 0; i < n_columns; i++) {
2771         const struct ovsdb_idl_column *column = columns[i];
2772         const char *column_name = column ? column->name : "_uuid";
2773
2774         table_add_column(out, "%s", column_name);
2775     }
2776
2777     return out;
2778 }
2779
2780 static void
2781 list_record(const struct ovsdb_idl_row *row,
2782             const struct ovsdb_idl_column **columns, size_t n_columns,
2783             struct table *out)
2784 {
2785     size_t i;
2786
2787     table_add_row(out);
2788     for (i = 0; i < n_columns; i++) {
2789         const struct ovsdb_idl_column *column = columns[i];
2790         struct cell *cell = table_add_cell(out);
2791
2792         if (!column) {
2793             struct ovsdb_datum datum;
2794             union ovsdb_atom atom;
2795
2796             atom.uuid = row->uuid;
2797
2798             datum.keys = &atom;
2799             datum.values = NULL;
2800             datum.n = 1;
2801
2802             cell->json = ovsdb_datum_to_json(&datum, &ovsdb_type_uuid);
2803             cell->type = &ovsdb_type_uuid;
2804         } else {
2805             const struct ovsdb_datum *datum = ovsdb_idl_read(row, column);
2806
2807             cell->json = ovsdb_datum_to_json(datum, &column->type);
2808             cell->type = &column->type;
2809         }
2810     }
2811 }
2812
2813 static void
2814 cmd_list(struct vsctl_context *ctx)
2815 {
2816     const char *column_names = shash_find_data(&ctx->options, "--columns");
2817     const struct ovsdb_idl_column **columns;
2818     const char *table_name = ctx->argv[1];
2819     const struct vsctl_table_class *table;
2820     struct table *out;
2821     size_t n_columns;
2822     int i;
2823
2824     table = get_table(table_name);
2825     parse_column_names(column_names, table, &columns, &n_columns);
2826     out = ctx->table = list_make_table(columns, n_columns);
2827     if (ctx->argc > 2) {
2828         for (i = 2; i < ctx->argc; i++) {
2829             list_record(must_get_row(ctx, table, ctx->argv[i]),
2830                         columns, n_columns, out);
2831         }
2832     } else {
2833         const struct ovsdb_idl_row *row;
2834         bool first;
2835
2836         for (row = ovsdb_idl_first_row(ctx->idl, table->class), first = true;
2837              row != NULL;
2838              row = ovsdb_idl_next_row(row), first = false) {
2839             list_record(row, columns, n_columns, out);
2840         }
2841     }
2842     free(columns);
2843 }
2844
2845 static void
2846 pre_cmd_find(struct vsctl_context *ctx)
2847 {
2848     const char *column_names = shash_find_data(&ctx->options, "--columns");
2849     const char *table_name = ctx->argv[1];
2850     const struct vsctl_table_class *table;
2851     int i;
2852
2853     table = pre_get_table(ctx, table_name);
2854     pre_list_columns(ctx, table, column_names);
2855     for (i = 2; i < ctx->argc; i++) {
2856         pre_parse_column_key_value(ctx, ctx->argv[i], table);
2857     }
2858 }
2859
2860 static void
2861 cmd_find(struct vsctl_context *ctx)
2862 {
2863     const char *column_names = shash_find_data(&ctx->options, "--columns");
2864     const struct ovsdb_idl_column **columns;
2865     const char *table_name = ctx->argv[1];
2866     const struct vsctl_table_class *table;
2867     const struct ovsdb_idl_row *row;
2868     struct table *out;
2869     size_t n_columns;
2870
2871     table = get_table(table_name);
2872     parse_column_names(column_names, table, &columns, &n_columns);
2873     out = ctx->table = list_make_table(columns, n_columns);
2874     for (row = ovsdb_idl_first_row(ctx->idl, table->class); row;
2875          row = ovsdb_idl_next_row(row)) {
2876         int i;
2877
2878         for (i = 2; i < ctx->argc; i++) {
2879             if (!is_condition_satisfied(table, row, ctx->argv[i],
2880                                         ctx->symtab)) {
2881                 goto next_row;
2882             }
2883         }
2884         list_record(row, columns, n_columns, out);
2885
2886     next_row: ;
2887     }
2888 }
2889
2890 static void
2891 pre_cmd_set(struct vsctl_context *ctx)
2892 {
2893     const char *table_name = ctx->argv[1];
2894     const struct vsctl_table_class *table;
2895     int i;
2896
2897     table = pre_get_table(ctx, table_name);
2898     for (i = 3; i < ctx->argc; i++) {
2899         pre_parse_column_key_value(ctx, ctx->argv[i], table);
2900     }
2901 }
2902
2903 static void
2904 set_column(const struct vsctl_table_class *table,
2905            const struct ovsdb_idl_row *row, const char *arg,
2906            struct ovsdb_symbol_table *symtab)
2907 {
2908     const struct ovsdb_idl_column *column;
2909     char *key_string, *value_string;
2910     char *error;
2911
2912     error = parse_column_key_value(arg, table, &column, &key_string,
2913                                    NULL, NULL, 0, &value_string);
2914     die_if_error(error);
2915     if (!value_string) {
2916         vsctl_fatal("%s: missing value", arg);
2917     }
2918
2919     if (key_string) {
2920         union ovsdb_atom key, value;
2921         struct ovsdb_datum datum;
2922
2923         if (column->type.value.type == OVSDB_TYPE_VOID) {
2924             vsctl_fatal("cannot specify key to set for non-map column %s",
2925                         column->name);
2926         }
2927
2928         die_if_error(ovsdb_atom_from_string(&key, &column->type.key,
2929                                             key_string, symtab));
2930         die_if_error(ovsdb_atom_from_string(&value, &column->type.value,
2931                                             value_string, symtab));
2932
2933         ovsdb_datum_init_empty(&datum);
2934         ovsdb_datum_add_unsafe(&datum, &key, &value, &column->type);
2935
2936         ovsdb_atom_destroy(&key, column->type.key.type);
2937         ovsdb_atom_destroy(&value, column->type.value.type);
2938
2939         ovsdb_datum_union(&datum, ovsdb_idl_read(row, column),
2940                           &column->type, false);
2941         ovsdb_idl_txn_write(row, column, &datum);
2942     } else {
2943         struct ovsdb_datum datum;
2944
2945         die_if_error(ovsdb_datum_from_string(&datum, &column->type,
2946                                              value_string, symtab));
2947         ovsdb_idl_txn_write(row, column, &datum);
2948     }
2949
2950     free(key_string);
2951     free(value_string);
2952 }
2953
2954 static void
2955 cmd_set(struct vsctl_context *ctx)
2956 {
2957     const char *table_name = ctx->argv[1];
2958     const char *record_id = ctx->argv[2];
2959     const struct vsctl_table_class *table;
2960     const struct ovsdb_idl_row *row;
2961     int i;
2962
2963     table = get_table(table_name);
2964     row = must_get_row(ctx, table, record_id);
2965     for (i = 3; i < ctx->argc; i++) {
2966         set_column(table, row, ctx->argv[i], ctx->symtab);
2967     }
2968 }
2969
2970 static void
2971 pre_cmd_add(struct vsctl_context *ctx)
2972 {
2973     const char *table_name = ctx->argv[1];
2974     const char *column_name = ctx->argv[3];
2975     const struct vsctl_table_class *table;
2976     const struct ovsdb_idl_column *column;
2977
2978     table = pre_get_table(ctx, table_name);
2979     pre_get_column(ctx, table, column_name, &column);
2980 }
2981
2982 static void
2983 cmd_add(struct vsctl_context *ctx)
2984 {
2985     const char *table_name = ctx->argv[1];
2986     const char *record_id = ctx->argv[2];
2987     const char *column_name = ctx->argv[3];
2988     const struct vsctl_table_class *table;
2989     const struct ovsdb_idl_column *column;
2990     const struct ovsdb_idl_row *row;
2991     const struct ovsdb_type *type;
2992     struct ovsdb_datum old;
2993     int i;
2994
2995     table = get_table(table_name);
2996     row = must_get_row(ctx, table, record_id);
2997     die_if_error(get_column(table, column_name, &column));
2998
2999     type = &column->type;
3000     ovsdb_datum_clone(&old, ovsdb_idl_read(row, column), &column->type);
3001     for (i = 4; i < ctx->argc; i++) {
3002         struct ovsdb_type add_type;
3003         struct ovsdb_datum add;
3004
3005         add_type = *type;
3006         add_type.n_min = 1;
3007         add_type.n_max = UINT_MAX;
3008         die_if_error(ovsdb_datum_from_string(&add, &add_type, ctx->argv[i],
3009                                              ctx->symtab));
3010         ovsdb_datum_union(&old, &add, type, false);
3011         ovsdb_datum_destroy(&add, type);
3012     }
3013     if (old.n > type->n_max) {
3014         vsctl_fatal("\"add\" operation would put %u %s in column %s of "
3015                     "table %s but the maximum number is %u",
3016                     old.n,
3017                     type->value.type == OVSDB_TYPE_VOID ? "values" : "pairs",
3018                     column->name, table->class->name, type->n_max);
3019     }
3020     ovsdb_idl_txn_verify(row, column);
3021     ovsdb_idl_txn_write(row, column, &old);
3022 }
3023
3024 static void
3025 pre_cmd_remove(struct vsctl_context *ctx)
3026 {
3027     const char *table_name = ctx->argv[1];
3028     const char *column_name = ctx->argv[3];
3029     const struct vsctl_table_class *table;
3030     const struct ovsdb_idl_column *column;
3031
3032     table = pre_get_table(ctx, table_name);
3033     pre_get_column(ctx, table, column_name, &column);
3034 }
3035
3036 static void
3037 cmd_remove(struct vsctl_context *ctx)
3038 {
3039     const char *table_name = ctx->argv[1];
3040     const char *record_id = ctx->argv[2];
3041     const char *column_name = ctx->argv[3];
3042     const struct vsctl_table_class *table;
3043     const struct ovsdb_idl_column *column;
3044     const struct ovsdb_idl_row *row;
3045     const struct ovsdb_type *type;
3046     struct ovsdb_datum old;
3047     int i;
3048
3049     table = get_table(table_name);
3050     row = must_get_row(ctx, table, record_id);
3051     die_if_error(get_column(table, column_name, &column));
3052
3053     type = &column->type;
3054     ovsdb_datum_clone(&old, ovsdb_idl_read(row, column), &column->type);
3055     for (i = 4; i < ctx->argc; i++) {
3056         struct ovsdb_type rm_type;
3057         struct ovsdb_datum rm;
3058         char *error;
3059
3060         rm_type = *type;
3061         rm_type.n_min = 1;
3062         rm_type.n_max = UINT_MAX;
3063         error = ovsdb_datum_from_string(&rm, &rm_type,
3064                                         ctx->argv[i], ctx->symtab);
3065         if (error && ovsdb_type_is_map(&rm_type)) {
3066             free(error);
3067             rm_type.value.type = OVSDB_TYPE_VOID;
3068             die_if_error(ovsdb_datum_from_string(&rm, &rm_type,
3069                                                  ctx->argv[i], ctx->symtab));
3070         }
3071         ovsdb_datum_subtract(&old, type, &rm, &rm_type);
3072         ovsdb_datum_destroy(&rm, &rm_type);
3073     }
3074     if (old.n < type->n_min) {
3075         vsctl_fatal("\"remove\" operation would put %u %s in column %s of "
3076                     "table %s but the minimum number is %u",
3077                     old.n,
3078                     type->value.type == OVSDB_TYPE_VOID ? "values" : "pairs",
3079                     column->name, table->class->name, type->n_min);
3080     }
3081     ovsdb_idl_txn_verify(row, column);
3082     ovsdb_idl_txn_write(row, column, &old);
3083 }
3084
3085 static void
3086 pre_cmd_clear(struct vsctl_context *ctx)
3087 {
3088     const char *table_name = ctx->argv[1];
3089     const struct vsctl_table_class *table;
3090     int i;
3091
3092     table = pre_get_table(ctx, table_name);
3093     for (i = 3; i < ctx->argc; i++) {
3094         const struct ovsdb_idl_column *column;
3095
3096         pre_get_column(ctx, table, ctx->argv[i], &column);
3097     }
3098 }
3099
3100 static void
3101 cmd_clear(struct vsctl_context *ctx)
3102 {
3103     const char *table_name = ctx->argv[1];
3104     const char *record_id = ctx->argv[2];
3105     const struct vsctl_table_class *table;
3106     const struct ovsdb_idl_row *row;
3107     int i;
3108
3109     table = get_table(table_name);
3110     row = must_get_row(ctx, table, record_id);
3111     for (i = 3; i < ctx->argc; i++) {
3112         const struct ovsdb_idl_column *column;
3113         const struct ovsdb_type *type;
3114         struct ovsdb_datum datum;
3115
3116         die_if_error(get_column(table, ctx->argv[i], &column));
3117
3118         type = &column->type;
3119         if (type->n_min > 0) {
3120             vsctl_fatal("\"clear\" operation cannot be applied to column %s "
3121                         "of table %s, which is not allowed to be empty",
3122                         column->name, table->class->name);
3123         }
3124
3125         ovsdb_datum_init_empty(&datum);
3126         ovsdb_idl_txn_write(row, column, &datum);
3127     }
3128 }
3129
3130 static void
3131 cmd_create(struct vsctl_context *ctx)
3132 {
3133     const char *id = shash_find_data(&ctx->options, "--id");
3134     const char *table_name = ctx->argv[1];
3135     const struct vsctl_table_class *table;
3136     const struct ovsdb_idl_row *row;
3137     const struct uuid *uuid;
3138     int i;
3139
3140     uuid = id ? create_symbol(ctx->symtab, id, NULL) : NULL;
3141
3142     table = get_table(table_name);
3143     row = ovsdb_idl_txn_insert(ctx->txn, table->class, uuid);
3144     for (i = 2; i < ctx->argc; i++) {
3145         set_column(table, row, ctx->argv[i], ctx->symtab);
3146     }
3147     ds_put_format(&ctx->output, UUID_FMT, UUID_ARGS(&row->uuid));
3148 }
3149
3150 /* This function may be used as the 'postprocess' function for commands that
3151  * insert new rows into the database.  It expects that the command's 'run'
3152  * function prints the UUID reported by ovsdb_idl_txn_insert() as the command's
3153  * sole output.  It replaces that output by the row's permanent UUID assigned
3154  * by the database server and appends a new-line.
3155  *
3156  * Currently we use this only for "create", because the higher-level commands
3157  * are supposed to be independent of the actual structure of the vswitch
3158  * configuration. */
3159 static void
3160 post_create(struct vsctl_context *ctx)
3161 {
3162     const struct uuid *real;
3163     struct uuid dummy;
3164
3165     uuid_from_string(&dummy, ds_cstr(&ctx->output));
3166     real = ovsdb_idl_txn_get_insert_uuid(ctx->txn, &dummy);
3167     if (real) {
3168         ds_clear(&ctx->output);
3169         ds_put_format(&ctx->output, UUID_FMT, UUID_ARGS(real));
3170     }
3171     ds_put_char(&ctx->output, '\n');
3172 }
3173
3174 static void
3175 pre_cmd_destroy(struct vsctl_context *ctx)
3176 {
3177     const char *table_name = ctx->argv[1];
3178
3179     pre_get_table(ctx, table_name);
3180 }
3181
3182 static void
3183 cmd_destroy(struct vsctl_context *ctx)
3184 {
3185     bool must_exist = !shash_find(&ctx->options, "--if-exists");
3186     const char *table_name = ctx->argv[1];
3187     const struct vsctl_table_class *table;
3188     int i;
3189
3190     table = get_table(table_name);
3191     for (i = 2; i < ctx->argc; i++) {
3192         const struct ovsdb_idl_row *row;
3193
3194         row = (must_exist ? must_get_row : get_row)(ctx, table, ctx->argv[i]);
3195         if (row) {
3196             ovsdb_idl_txn_delete(row);
3197         }
3198     }
3199 }
3200
3201 static bool
3202 is_condition_satisfied(const struct vsctl_table_class *table,
3203                        const struct ovsdb_idl_row *row, const char *arg,
3204                        struct ovsdb_symbol_table *symtab)
3205 {
3206     static const char *operators[] = {
3207         "=", "!=", "<", ">", "<=", ">="
3208     };
3209
3210     const struct ovsdb_idl_column *column;
3211     const struct ovsdb_datum *have_datum;
3212     char *key_string, *value_string;
3213     const char *operator;
3214     unsigned int idx;
3215     char *error;
3216     int cmp = 0;
3217
3218     error = parse_column_key_value(arg, table, &column, &key_string,
3219                                    &operator, operators, ARRAY_SIZE(operators),
3220                                    &value_string);
3221     die_if_error(error);
3222     if (!value_string) {
3223         vsctl_fatal("%s: missing value", arg);
3224     }
3225
3226     have_datum = ovsdb_idl_read(row, column);
3227     if (key_string) {
3228         union ovsdb_atom want_key, want_value;
3229
3230         if (column->type.value.type == OVSDB_TYPE_VOID) {
3231             vsctl_fatal("cannot specify key to check for non-map column %s",
3232                         column->name);
3233         }
3234
3235         die_if_error(ovsdb_atom_from_string(&want_key, &column->type.key,
3236                                             key_string, symtab));
3237         die_if_error(ovsdb_atom_from_string(&want_value, &column->type.value,
3238                                             value_string, symtab));
3239
3240         idx = ovsdb_datum_find_key(have_datum,
3241                                    &want_key, column->type.key.type);
3242         if (idx != UINT_MAX) {
3243             cmp = ovsdb_atom_compare_3way(&have_datum->values[idx],
3244                                           &want_value,
3245                                           column->type.value.type);
3246         }
3247
3248         ovsdb_atom_destroy(&want_key, column->type.key.type);
3249         ovsdb_atom_destroy(&want_value, column->type.value.type);
3250     } else {
3251         struct ovsdb_datum want_datum;
3252
3253         die_if_error(ovsdb_datum_from_string(&want_datum, &column->type,
3254                                              value_string, symtab));
3255         idx = 0;
3256         cmp = ovsdb_datum_compare_3way(have_datum, &want_datum,
3257                                        &column->type);
3258         ovsdb_datum_destroy(&want_datum, &column->type);
3259     }
3260
3261     free(key_string);
3262     free(value_string);
3263
3264     return (idx == UINT_MAX ? false
3265             : !strcmp(operator, "=") ? cmp == 0
3266             : !strcmp(operator, "!=") ? cmp != 0
3267             : !strcmp(operator, "<") ? cmp < 0
3268             : !strcmp(operator, ">") ? cmp > 0
3269             : !strcmp(operator, "<=") ? cmp <= 0
3270             : !strcmp(operator, ">=") ? cmp >= 0
3271             : (abort(), 0));
3272 }
3273
3274 static void
3275 pre_cmd_wait_until(struct vsctl_context *ctx)
3276 {
3277     const char *table_name = ctx->argv[1];
3278     const struct vsctl_table_class *table;
3279     int i;
3280
3281     table = pre_get_table(ctx, table_name);
3282
3283     for (i = 3; i < ctx->argc; i++) {
3284         pre_parse_column_key_value(ctx, ctx->argv[i], table);
3285     }
3286 }
3287
3288 static void
3289 cmd_wait_until(struct vsctl_context *ctx)
3290 {
3291     const char *table_name = ctx->argv[1];
3292     const char *record_id = ctx->argv[2];
3293     const struct vsctl_table_class *table;
3294     const struct ovsdb_idl_row *row;
3295     int i;
3296
3297     table = get_table(table_name);
3298
3299     row = get_row(ctx, table, record_id);
3300     if (!row) {
3301         ctx->try_again = true;
3302         return;
3303     }
3304
3305     for (i = 3; i < ctx->argc; i++) {
3306         if (!is_condition_satisfied(table, row, ctx->argv[i], ctx->symtab)) {
3307             ctx->try_again = true;
3308             return;
3309         }
3310     }
3311 }
3312 \f
3313 static struct json *
3314 where_uuid_equals(const struct uuid *uuid)
3315 {
3316     return
3317         json_array_create_1(
3318             json_array_create_3(
3319                 json_string_create("_uuid"),
3320                 json_string_create("=="),
3321                 json_array_create_2(
3322                     json_string_create("uuid"),
3323                     json_string_create_nocopy(
3324                         xasprintf(UUID_FMT, UUID_ARGS(uuid))))));
3325 }
3326
3327 static void
3328 vsctl_context_init(struct vsctl_context *ctx, struct vsctl_command *command,
3329                    struct ovsdb_idl *idl, struct ovsdb_idl_txn *txn,
3330                    const struct ovsrec_open_vswitch *ovs,
3331                    struct ovsdb_symbol_table *symtab)
3332 {
3333     ctx->argc = command->argc;
3334     ctx->argv = command->argv;
3335     ctx->options = command->options;
3336
3337     ds_swap(&ctx->output, &command->output);
3338     ctx->table = command->table;
3339     ctx->idl = idl;
3340     ctx->txn = txn;
3341     ctx->ovs = ovs;
3342     ctx->symtab = symtab;
3343     ctx->verified_ports = false;
3344
3345     ctx->try_again = false;
3346 }
3347
3348 static void
3349 vsctl_context_done(struct vsctl_context *ctx, struct vsctl_command *command)
3350 {
3351     ds_swap(&ctx->output, &command->output);
3352     command->table = ctx->table;
3353 }
3354
3355 static void
3356 run_prerequisites(struct vsctl_command *commands, size_t n_commands,
3357                   struct ovsdb_idl *idl)
3358 {
3359     struct vsctl_command *c;
3360
3361     ovsdb_idl_add_table(idl, &ovsrec_table_open_vswitch);
3362     if (wait_for_reload) {
3363         ovsdb_idl_add_column(idl, &ovsrec_open_vswitch_col_cur_cfg);
3364     }
3365     for (c = commands; c < &commands[n_commands]; c++) {
3366         if (c->syntax->prerequisites) {
3367             struct vsctl_context ctx;
3368
3369             ds_init(&c->output);
3370             c->table = NULL;
3371
3372             vsctl_context_init(&ctx, c, idl, NULL, NULL, NULL);
3373             (c->syntax->prerequisites)(&ctx);
3374             vsctl_context_done(&ctx, c);
3375
3376             assert(!c->output.string);
3377             assert(!c->table);
3378         }
3379     }
3380 }
3381
3382 static void
3383 do_vsctl(const char *args, struct vsctl_command *commands, size_t n_commands,
3384          struct ovsdb_idl *idl)
3385 {
3386     struct ovsdb_idl_txn *txn;
3387     const struct ovsrec_open_vswitch *ovs;
3388     enum ovsdb_idl_txn_status status;
3389     struct ovsdb_symbol_table *symtab;
3390     const char *unused;
3391     struct vsctl_command *c;
3392     int64_t next_cfg = 0;
3393     char *error = NULL;
3394
3395     txn = the_idl_txn = ovsdb_idl_txn_create(idl);
3396     if (dry_run) {
3397         ovsdb_idl_txn_set_dry_run(txn);
3398     }
3399
3400     ovsdb_idl_txn_add_comment(txn, "ovs-vsctl: %s", args);
3401
3402     ovs = ovsrec_open_vswitch_first(idl);
3403     if (!ovs) {
3404         /* XXX add verification that table is empty */
3405         ovs = ovsrec_open_vswitch_insert(txn);
3406     }
3407
3408     if (wait_for_reload) {
3409         struct json *where = where_uuid_equals(&ovs->header_.uuid);
3410         ovsdb_idl_txn_increment(txn, "Open_vSwitch", "next_cfg", where);
3411         json_destroy(where);
3412     }
3413
3414     symtab = ovsdb_symbol_table_create();
3415     for (c = commands; c < &commands[n_commands]; c++) {
3416         ds_init(&c->output);
3417         c->table = NULL;
3418     }
3419     for (c = commands; c < &commands[n_commands]; c++) {
3420         struct vsctl_context ctx;
3421
3422         vsctl_context_init(&ctx, c, idl, txn, ovs, symtab);
3423         (c->syntax->run)(&ctx);
3424         vsctl_context_done(&ctx, c);
3425
3426         if (ctx.try_again) {
3427             goto try_again;
3428         }
3429     }
3430
3431     status = ovsdb_idl_txn_commit_block(txn);
3432     if (wait_for_reload && status == TXN_SUCCESS) {
3433         next_cfg = ovsdb_idl_txn_get_increment_new_value(txn);
3434     }
3435     if (status == TXN_UNCHANGED || status == TXN_SUCCESS) {
3436         for (c = commands; c < &commands[n_commands]; c++) {
3437             if (c->syntax->postprocess) {
3438                 struct vsctl_context ctx;
3439
3440                 vsctl_context_init(&ctx, c, idl, txn, ovs, symtab);
3441                 (c->syntax->postprocess)(&ctx);
3442                 vsctl_context_done(&ctx, c);
3443             }
3444         }
3445     }
3446     error = xstrdup(ovsdb_idl_txn_get_error(txn));
3447     ovsdb_idl_txn_destroy(txn);
3448     txn = the_idl_txn = NULL;
3449
3450     unused = ovsdb_symbol_table_find_unused(symtab);
3451     if (unused) {
3452         vsctl_fatal("row id \"%s\" is referenced but never created (e.g. "
3453                     "with \"-- --id=%s create ...\")", unused, unused);
3454     }
3455
3456     switch (status) {
3457     case TXN_INCOMPLETE:
3458         NOT_REACHED();
3459
3460     case TXN_ABORTED:
3461         /* Should not happen--we never call ovsdb_idl_txn_abort(). */
3462         vsctl_fatal("transaction aborted");
3463
3464     case TXN_UNCHANGED:
3465     case TXN_SUCCESS:
3466         break;
3467
3468     case TXN_TRY_AGAIN:
3469         goto try_again;
3470
3471     case TXN_ERROR:
3472         vsctl_fatal("transaction error: %s", error);
3473
3474     default:
3475         NOT_REACHED();
3476     }
3477     free(error);
3478
3479     ovsdb_symbol_table_destroy(symtab);
3480
3481     for (c = commands; c < &commands[n_commands]; c++) {
3482         struct ds *ds = &c->output;
3483
3484         if (c->table) {
3485             table_print(c->table, &table_style);
3486         } else if (oneline) {
3487             size_t j;
3488
3489             ds_chomp(ds, '\n');
3490             for (j = 0; j < ds->length; j++) {
3491                 int ch = ds->string[j];
3492                 switch (ch) {
3493                 case '\n':
3494                     fputs("\\n", stdout);
3495                     break;
3496
3497                 case '\\':
3498                     fputs("\\\\", stdout);
3499                     break;
3500
3501                 default:
3502                     putchar(ch);
3503                 }
3504             }
3505             putchar('\n');
3506         } else {
3507             fputs(ds_cstr(ds), stdout);
3508         }
3509         ds_destroy(&c->output);
3510         table_destroy(c->table);
3511         free(c->table);
3512
3513         smap_destroy(&c->options);
3514     }
3515     free(commands);
3516
3517     if (wait_for_reload && status != TXN_UNCHANGED) {
3518         for (;;) {
3519             ovsdb_idl_run(idl);
3520             OVSREC_OPEN_VSWITCH_FOR_EACH (ovs, idl) {
3521                 if (ovs->cur_cfg >= next_cfg) {
3522                     goto done;
3523                 }
3524             }
3525             ovsdb_idl_wait(idl);
3526             poll_block();
3527         }
3528     done: ;
3529     }
3530     ovsdb_idl_destroy(idl);
3531
3532     exit(EXIT_SUCCESS);
3533
3534 try_again:
3535     /* Our transaction needs to be rerun, or a prerequisite was not met.  Free
3536      * resources and return so that the caller can try again. */
3537     if (txn) {
3538         ovsdb_idl_txn_abort(txn);
3539         ovsdb_idl_txn_destroy(txn);
3540     }
3541     ovsdb_symbol_table_destroy(symtab);
3542     for (c = commands; c < &commands[n_commands]; c++) {
3543         ds_destroy(&c->output);
3544         table_destroy(c->table);
3545         free(c->table);
3546     }
3547     free(error);
3548 }
3549
3550 static const struct vsctl_command_syntax all_commands[] = {
3551     /* Open vSwitch commands. */
3552     {"init", 0, 0, NULL, cmd_init, NULL, "", RW},
3553
3554     /* Bridge commands. */
3555     {"add-br", 1, 3, pre_get_info, cmd_add_br, NULL, "--may-exist", RW},
3556     {"del-br", 1, 1, pre_get_info, cmd_del_br, NULL, "--if-exists", RW},
3557     {"list-br", 0, 0, pre_get_info, cmd_list_br, NULL, "", RO},
3558     {"br-exists", 1, 1, pre_get_info, cmd_br_exists, NULL, "", RO},
3559     {"br-to-vlan", 1, 1, pre_get_info, cmd_br_to_vlan, NULL, "", RO},
3560     {"br-to-parent", 1, 1, pre_get_info, cmd_br_to_parent, NULL, "", RO},
3561     {"br-set-external-id", 2, 3, pre_cmd_br_set_external_id,
3562      cmd_br_set_external_id, NULL, "", RW},
3563     {"br-get-external-id", 1, 2, pre_cmd_br_get_external_id,
3564      cmd_br_get_external_id, NULL, "", RO},
3565
3566     /* Port commands. */
3567     {"list-ports", 1, 1, pre_get_info, cmd_list_ports, NULL, "", RO},
3568     {"add-port", 2, INT_MAX, pre_get_info, cmd_add_port, NULL, "--may-exist",
3569      RW},
3570     {"add-bond", 4, INT_MAX, pre_get_info, cmd_add_bond, NULL,
3571      "--may-exist,--fake-iface", RW},
3572     {"del-port", 1, 2, pre_get_info, cmd_del_port, NULL,
3573      "--if-exists,--with-iface", RW},
3574     {"port-to-br", 1, 1, pre_get_info, cmd_port_to_br, NULL, "", RO},
3575
3576     /* Interface commands. */
3577     {"list-ifaces", 1, 1, pre_get_info, cmd_list_ifaces, NULL, "", RO},
3578     {"iface-to-br", 1, 1, pre_get_info, cmd_iface_to_br, NULL, "", RO},
3579
3580     /* Controller commands. */
3581     {"get-controller", 1, 1, pre_controller, cmd_get_controller, NULL, "", RO},
3582     {"del-controller", 1, 1, pre_controller, cmd_del_controller, NULL, "", RW},
3583     {"set-controller", 1, INT_MAX, pre_controller, cmd_set_controller, NULL,
3584      "", RW},
3585     {"get-fail-mode", 1, 1, pre_get_info, cmd_get_fail_mode, NULL, "", RO},
3586     {"del-fail-mode", 1, 1, pre_get_info, cmd_del_fail_mode, NULL, "", RW},
3587     {"set-fail-mode", 2, 2, pre_get_info, cmd_set_fail_mode, NULL, "", RW},
3588
3589     /* Manager commands. */
3590     {"get-manager", 0, 0, pre_manager, cmd_get_manager, NULL, "", RO},
3591     {"del-manager", 0, INT_MAX, pre_manager, cmd_del_manager, NULL, "", RW},
3592     {"set-manager", 1, INT_MAX, pre_manager, cmd_set_manager, NULL, "", RW},
3593
3594     /* SSL commands. */
3595     {"get-ssl", 0, 0, pre_cmd_get_ssl, cmd_get_ssl, NULL, "", RO},
3596     {"del-ssl", 0, 0, pre_cmd_del_ssl, cmd_del_ssl, NULL, "", RW},
3597     {"set-ssl", 3, 3, pre_cmd_set_ssl, cmd_set_ssl, NULL, "--bootstrap", RW},
3598
3599     /* Switch commands. */
3600     {"emer-reset", 0, 0, pre_cmd_emer_reset, cmd_emer_reset, NULL, "", RW},
3601
3602     /* Parameter commands. */
3603     {"get", 2, INT_MAX, pre_cmd_get, cmd_get, NULL, "--if-exists,--id=", RO},
3604     {"list", 1, INT_MAX, pre_cmd_list, cmd_list, NULL, "--columns=", RO},
3605     {"find", 1, INT_MAX, pre_cmd_find, cmd_find, NULL, "--columns=", RO},
3606     {"set", 3, INT_MAX, pre_cmd_set, cmd_set, NULL, "", RW},
3607     {"add", 4, INT_MAX, pre_cmd_add, cmd_add, NULL, "", RW},
3608     {"remove", 4, INT_MAX, pre_cmd_remove, cmd_remove, NULL, "", RW},
3609     {"clear", 3, INT_MAX, pre_cmd_clear, cmd_clear, NULL, "", RW},
3610     {"create", 2, INT_MAX, NULL, cmd_create, post_create, "--id=", RW},
3611     {"destroy", 1, INT_MAX, pre_cmd_destroy, cmd_destroy, NULL, "--if-exists",
3612      RW},
3613     {"wait-until", 2, INT_MAX, pre_cmd_wait_until, cmd_wait_until, NULL, "",
3614      RO},
3615
3616     {NULL, 0, 0, NULL, NULL, NULL, NULL, RO},
3617 };
3618