Support vlan_group workaround implemented in XenServer kernels.
[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_manager_options);
1013     ovsdb_idl_add_column(ctx->idl, &ovsrec_open_vswitch_col_ssl);
1014
1015     ovsdb_idl_add_column(ctx->idl, &ovsrec_bridge_col_controller);
1016     ovsdb_idl_add_column(ctx->idl, &ovsrec_bridge_col_fail_mode);
1017     ovsdb_idl_add_column(ctx->idl, &ovsrec_bridge_col_mirrors);
1018     ovsdb_idl_add_column(ctx->idl, &ovsrec_bridge_col_netflow);
1019     ovsdb_idl_add_column(ctx->idl, &ovsrec_bridge_col_sflow);
1020     ovsdb_idl_add_column(ctx->idl, &ovsrec_bridge_col_flood_vlans);
1021     ovsdb_idl_add_column(ctx->idl, &ovsrec_bridge_col_other_config);
1022
1023     ovsdb_idl_add_column(ctx->idl, &ovsrec_port_col_other_config);
1024
1025     ovsdb_idl_add_column(ctx->idl,
1026                           &ovsrec_interface_col_ingress_policing_rate);
1027     ovsdb_idl_add_column(ctx->idl,
1028                           &ovsrec_interface_col_ingress_policing_burst);
1029 }
1030
1031 static void
1032 cmd_emer_reset(struct vsctl_context *ctx)
1033 {
1034     const struct ovsdb_idl *idl = ctx->idl;
1035     const struct ovsrec_bridge *br;
1036     const struct ovsrec_port *port;
1037     const struct ovsrec_interface *iface;
1038
1039     /* Reset the Open_vSwitch table. */
1040     ovsrec_open_vswitch_set_manager_options(ctx->ovs, NULL, 0);
1041     ovsrec_open_vswitch_set_ssl(ctx->ovs, NULL);
1042
1043     OVSREC_BRIDGE_FOR_EACH (br, idl) {
1044         int i;
1045         char *hw_key = "hwaddr";
1046         char *hw_val = NULL;
1047
1048         ovsrec_bridge_set_controller(br, NULL, 0);
1049         ovsrec_bridge_set_fail_mode(br, NULL);
1050         ovsrec_bridge_set_mirrors(br, NULL, 0);
1051         ovsrec_bridge_set_netflow(br, NULL);
1052         ovsrec_bridge_set_sflow(br, NULL);
1053         ovsrec_bridge_set_flood_vlans(br, NULL, 0);
1054
1055         /* We only want to save the "hwaddr" key from other_config. */
1056         for (i=0; i < br->n_other_config; i++) {
1057             if (!strcmp(br->key_other_config[i], hw_key)) {
1058                 hw_val = br->value_other_config[i];
1059                 break;
1060             }
1061         }
1062         if (hw_val) {
1063             char *val = xstrdup(hw_val);
1064             ovsrec_bridge_set_other_config(br, &hw_key, &val, 1);
1065             free(val);
1066         } else {
1067             ovsrec_bridge_set_other_config(br, NULL, NULL, 0);
1068         }
1069     }
1070
1071     OVSREC_PORT_FOR_EACH (port, idl) {
1072         ovsrec_port_set_other_config(port, NULL, NULL, 0);
1073     }
1074
1075     OVSREC_INTERFACE_FOR_EACH (iface, idl) {
1076         /* xxx What do we do about gre/patch devices created by mgr? */
1077
1078         ovsrec_interface_set_ingress_policing_rate(iface, 0);
1079         ovsrec_interface_set_ingress_policing_burst(iface, 0);
1080     }
1081 }
1082
1083 static void
1084 cmd_add_br(struct vsctl_context *ctx)
1085 {
1086     bool may_exist = shash_find(&ctx->options, "--may-exist") != 0;
1087     const char *br_name, *parent_name;
1088     struct vsctl_info info;
1089     int vlan;
1090
1091     br_name = ctx->argv[1];
1092     if (ctx->argc == 2) {
1093         parent_name = NULL;
1094         vlan = 0;
1095     } else if (ctx->argc == 4) {
1096         parent_name = ctx->argv[2];
1097         vlan = atoi(ctx->argv[3]);
1098         if (vlan < 1 || vlan > 4095) {
1099             vsctl_fatal("%s: vlan must be between 1 and 4095", ctx->argv[0]);
1100         }
1101     } else {
1102         vsctl_fatal("'%s' command takes exactly 1 or 3 arguments",
1103                     ctx->argv[0]);
1104     }
1105
1106     get_info(ctx, &info);
1107     if (may_exist) {
1108         struct vsctl_bridge *br;
1109
1110         br = find_bridge(&info, br_name, false);
1111         if (br) {
1112             if (!parent_name) {
1113                 if (br->parent) {
1114                     vsctl_fatal("\"--may-exist add-br %s\" but %s is "
1115                                 "a VLAN bridge for VLAN %d",
1116                                 br_name, br_name, br->vlan);
1117                 }
1118             } else {
1119                 if (!br->parent) {
1120                     vsctl_fatal("\"--may-exist add-br %s %s %d\" but %s "
1121                                 "is not a VLAN bridge",
1122                                 br_name, parent_name, vlan, br_name);
1123                 } else if (strcmp(br->parent->name, parent_name)) {
1124                     vsctl_fatal("\"--may-exist add-br %s %s %d\" but %s "
1125                                 "has the wrong parent %s",
1126                                 br_name, parent_name, vlan,
1127                                 br_name, br->parent->name);
1128                 } else if (br->vlan != vlan) {
1129                     vsctl_fatal("\"--may-exist add-br %s %s %d\" but %s "
1130                                 "is a VLAN bridge for the wrong VLAN %d",
1131                                 br_name, parent_name, vlan, br_name, br->vlan);
1132                 }
1133             }
1134             return;
1135         }
1136     }
1137     check_conflicts(&info, br_name,
1138                     xasprintf("cannot create a bridge named %s", br_name));
1139
1140     if (!parent_name) {
1141         struct ovsrec_port *port;
1142         struct ovsrec_interface *iface;
1143         struct ovsrec_bridge *br;
1144
1145         iface = ovsrec_interface_insert(ctx->txn);
1146         ovsrec_interface_set_name(iface, br_name);
1147         ovsrec_interface_set_type(iface, "internal");
1148
1149         port = ovsrec_port_insert(ctx->txn);
1150         ovsrec_port_set_name(port, br_name);
1151         ovsrec_port_set_interfaces(port, &iface, 1);
1152
1153         br = ovsrec_bridge_insert(ctx->txn);
1154         ovsrec_bridge_set_name(br, br_name);
1155         ovsrec_bridge_set_ports(br, &port, 1);
1156
1157         ovs_insert_bridge(ctx->ovs, br);
1158     } else {
1159         struct vsctl_bridge *parent;
1160         struct ovsrec_port *port;
1161         struct ovsrec_interface *iface;
1162         struct ovsrec_bridge *br;
1163         int64_t tag = vlan;
1164
1165         parent = find_bridge(&info, parent_name, false);
1166         if (parent && parent->vlan) {
1167             vsctl_fatal("cannot create bridge with fake bridge as parent");
1168         }
1169         if (!parent) {
1170             vsctl_fatal("parent bridge %s does not exist", parent_name);
1171         }
1172         br = parent->br_cfg;
1173
1174         iface = ovsrec_interface_insert(ctx->txn);
1175         ovsrec_interface_set_name(iface, br_name);
1176         ovsrec_interface_set_type(iface, "internal");
1177
1178         port = ovsrec_port_insert(ctx->txn);
1179         ovsrec_port_set_name(port, br_name);
1180         ovsrec_port_set_interfaces(port, &iface, 1);
1181         ovsrec_port_set_fake_bridge(port, true);
1182         ovsrec_port_set_tag(port, &tag, 1);
1183
1184         bridge_insert_port(br, port);
1185     }
1186
1187     free_info(&info);
1188 }
1189
1190 static void
1191 del_port(struct vsctl_port *port)
1192 {
1193     bridge_delete_port((port->bridge->parent
1194                         ? port->bridge->parent->br_cfg
1195                         : port->bridge->br_cfg), port->port_cfg);
1196 }
1197
1198 static void
1199 cmd_del_br(struct vsctl_context *ctx)
1200 {
1201     bool must_exist = !shash_find(&ctx->options, "--if-exists");
1202     struct vsctl_bridge *bridge;
1203     struct vsctl_info info;
1204
1205     get_info(ctx, &info);
1206     bridge = find_bridge(&info, ctx->argv[1], must_exist);
1207     if (bridge) {
1208         if (bridge->br_cfg) {
1209             ovs_delete_bridge(ctx->ovs, bridge->br_cfg);
1210         } else {
1211             struct shash_node *node;
1212
1213             SHASH_FOR_EACH (node, &info.ports) {
1214                 struct vsctl_port *port = node->data;
1215                 if (port->bridge == bridge || port->bridge->parent == bridge
1216                     || !strcmp(port->port_cfg->name, bridge->name)) {
1217                     del_port(port);
1218                 }
1219             }
1220         }
1221     }
1222     free_info(&info);
1223 }
1224
1225 static void
1226 output_sorted(struct svec *svec, struct ds *output)
1227 {
1228     const char *name;
1229     size_t i;
1230
1231     svec_sort(svec);
1232     SVEC_FOR_EACH (i, name, svec) {
1233         ds_put_format(output, "%s\n", name);
1234     }
1235 }
1236
1237 static void
1238 cmd_list_br(struct vsctl_context *ctx)
1239 {
1240     struct shash_node *node;
1241     struct vsctl_info info;
1242     struct svec bridges;
1243
1244     get_info(ctx, &info);
1245
1246     svec_init(&bridges);
1247     SHASH_FOR_EACH (node, &info.bridges) {
1248         struct vsctl_bridge *br = node->data;
1249         svec_add(&bridges, br->name);
1250     }
1251     output_sorted(&bridges, &ctx->output);
1252     svec_destroy(&bridges);
1253
1254     free_info(&info);
1255 }
1256
1257 static void
1258 cmd_br_exists(struct vsctl_context *ctx)
1259 {
1260     struct vsctl_info info;
1261
1262     get_info(ctx, &info);
1263     if (!find_bridge(&info, ctx->argv[1], false)) {
1264         vsctl_exit(2);
1265     }
1266     free_info(&info);
1267 }
1268
1269 /* Returns true if 'b_prefix' (of length 'b_prefix_len') concatenated with 'b'
1270  * equals 'a', false otherwise. */
1271 static bool
1272 key_matches(const char *a,
1273             const char *b_prefix, size_t b_prefix_len, const char *b)
1274 {
1275     return !strncmp(a, b_prefix, b_prefix_len) && !strcmp(a + b_prefix_len, b);
1276 }
1277
1278 static void
1279 set_external_id(char **old_keys, char **old_values, size_t old_n,
1280                 char *key, char *value,
1281                 char ***new_keysp, char ***new_valuesp, size_t *new_np)
1282 {
1283     char **new_keys;
1284     char **new_values;
1285     size_t new_n;
1286     size_t i;
1287
1288     new_keys = xmalloc(sizeof *new_keys * (old_n + 1));
1289     new_values = xmalloc(sizeof *new_values * (old_n + 1));
1290     new_n = 0;
1291     for (i = 0; i < old_n; i++) {
1292         if (strcmp(key, old_keys[i])) {
1293             new_keys[new_n] = old_keys[i];
1294             new_values[new_n] = old_values[i];
1295             new_n++;
1296         }
1297     }
1298     if (value) {
1299         new_keys[new_n] = key;
1300         new_values[new_n] = value;
1301         new_n++;
1302     }
1303     *new_keysp = new_keys;
1304     *new_valuesp = new_values;
1305     *new_np = new_n;
1306 }
1307
1308 static void
1309 pre_cmd_br_set_external_id(struct vsctl_context *ctx)
1310 {
1311     pre_get_info(ctx);
1312     ovsdb_idl_add_column(ctx->idl, &ovsrec_bridge_col_external_ids);
1313     ovsdb_idl_add_column(ctx->idl, &ovsrec_port_col_external_ids);
1314 }
1315
1316 static void
1317 cmd_br_set_external_id(struct vsctl_context *ctx)
1318 {
1319     struct vsctl_info info;
1320     struct vsctl_bridge *bridge;
1321     char **keys, **values;
1322     size_t n;
1323
1324     get_info(ctx, &info);
1325     bridge = find_bridge(&info, ctx->argv[1], true);
1326     if (bridge->br_cfg) {
1327         set_external_id(bridge->br_cfg->key_external_ids,
1328                         bridge->br_cfg->value_external_ids,
1329                         bridge->br_cfg->n_external_ids,
1330                         ctx->argv[2], ctx->argc >= 4 ? ctx->argv[3] : NULL,
1331                         &keys, &values, &n);
1332         ovsrec_bridge_verify_external_ids(bridge->br_cfg);
1333         ovsrec_bridge_set_external_ids(bridge->br_cfg, keys, values, n);
1334     } else {
1335         char *key = xasprintf("fake-bridge-%s", ctx->argv[2]);
1336         struct vsctl_port *port = shash_find_data(&info.ports, ctx->argv[1]);
1337         set_external_id(port->port_cfg->key_external_ids,
1338                         port->port_cfg->value_external_ids,
1339                         port->port_cfg->n_external_ids,
1340                         key, ctx->argc >= 4 ? ctx->argv[3] : NULL,
1341                         &keys, &values, &n);
1342         ovsrec_port_verify_external_ids(port->port_cfg);
1343         ovsrec_port_set_external_ids(port->port_cfg, keys, values, n);
1344         free(key);
1345     }
1346     free(keys);
1347     free(values);
1348
1349     free_info(&info);
1350 }
1351
1352 static void
1353 get_external_id(char **keys, char **values, size_t n,
1354                 const char *prefix, const char *key,
1355                 struct ds *output)
1356 {
1357     size_t prefix_len = strlen(prefix);
1358     struct svec svec;
1359     size_t i;
1360
1361     svec_init(&svec);
1362     for (i = 0; i < n; i++) {
1363         if (!key && !strncmp(keys[i], prefix, prefix_len)) {
1364             svec_add_nocopy(&svec, xasprintf("%s=%s",
1365                                              keys[i] + prefix_len, values[i]));
1366         } else if (key && key_matches(keys[i], prefix, prefix_len, key)) {
1367             svec_add(&svec, values[i]);
1368             break;
1369         }
1370     }
1371     output_sorted(&svec, output);
1372     svec_destroy(&svec);
1373 }
1374
1375 static void
1376 pre_cmd_br_get_external_id(struct vsctl_context *ctx)
1377 {
1378     pre_cmd_br_set_external_id(ctx);
1379 }
1380
1381 static void
1382 cmd_br_get_external_id(struct vsctl_context *ctx)
1383 {
1384     struct vsctl_info info;
1385     struct vsctl_bridge *bridge;
1386
1387     get_info(ctx, &info);
1388     bridge = find_bridge(&info, ctx->argv[1], true);
1389     if (bridge->br_cfg) {
1390         ovsrec_bridge_verify_external_ids(bridge->br_cfg);
1391         get_external_id(bridge->br_cfg->key_external_ids,
1392                         bridge->br_cfg->value_external_ids,
1393                         bridge->br_cfg->n_external_ids,
1394                         "", ctx->argc >= 3 ? ctx->argv[2] : NULL,
1395                         &ctx->output);
1396     } else {
1397         struct vsctl_port *port = shash_find_data(&info.ports, ctx->argv[1]);
1398         ovsrec_port_verify_external_ids(port->port_cfg);
1399         get_external_id(port->port_cfg->key_external_ids,
1400                         port->port_cfg->value_external_ids,
1401                         port->port_cfg->n_external_ids,
1402                         "fake-bridge-", ctx->argc >= 3 ? ctx->argv[2] : NULL, &ctx->output);
1403     }
1404     free_info(&info);
1405 }
1406
1407
1408 static void
1409 cmd_list_ports(struct vsctl_context *ctx)
1410 {
1411     struct vsctl_bridge *br;
1412     struct shash_node *node;
1413     struct vsctl_info info;
1414     struct svec ports;
1415
1416     get_info(ctx, &info);
1417     br = find_bridge(&info, ctx->argv[1], true);
1418     ovsrec_bridge_verify_ports(br->br_cfg ? br->br_cfg : br->parent->br_cfg);
1419
1420     svec_init(&ports);
1421     SHASH_FOR_EACH (node, &info.ports) {
1422         struct vsctl_port *port = node->data;
1423
1424         if (strcmp(port->port_cfg->name, br->name) && br == port->bridge) {
1425             svec_add(&ports, port->port_cfg->name);
1426         }
1427     }
1428     output_sorted(&ports, &ctx->output);
1429     svec_destroy(&ports);
1430
1431     free_info(&info);
1432 }
1433
1434 static void
1435 add_port(struct vsctl_context *ctx,
1436          const char *br_name, const char *port_name,
1437          bool may_exist, bool fake_iface,
1438          char *iface_names[], int n_ifaces,
1439          char *settings[], int n_settings)
1440 {
1441     struct vsctl_info info;
1442     struct vsctl_bridge *bridge;
1443     struct ovsrec_interface **ifaces;
1444     struct ovsrec_port *port;
1445     size_t i;
1446
1447     get_info(ctx, &info);
1448     if (may_exist) {
1449         struct vsctl_port *vsctl_port;
1450
1451         vsctl_port = find_port(&info, port_name, false);
1452         if (vsctl_port) {
1453             struct svec want_names, have_names;
1454
1455             svec_init(&want_names);
1456             for (i = 0; i < n_ifaces; i++) {
1457                 svec_add(&want_names, iface_names[i]);
1458             }
1459             svec_sort(&want_names);
1460
1461             svec_init(&have_names);
1462             for (i = 0; i < vsctl_port->port_cfg->n_interfaces; i++) {
1463                 svec_add(&have_names,
1464                          vsctl_port->port_cfg->interfaces[i]->name);
1465             }
1466             svec_sort(&have_names);
1467
1468             if (strcmp(vsctl_port->bridge->name, br_name)) {
1469                 char *command = vsctl_context_to_string(ctx);
1470                 vsctl_fatal("\"%s\" but %s is actually attached to bridge %s",
1471                             command, port_name, vsctl_port->bridge->name);
1472             }
1473
1474             if (!svec_equal(&want_names, &have_names)) {
1475                 char *have_names_string = svec_join(&have_names, ", ", "");
1476                 char *command = vsctl_context_to_string(ctx);
1477
1478                 vsctl_fatal("\"%s\" but %s actually has interface(s) %s",
1479                             command, port_name, have_names_string);
1480             }
1481
1482             svec_destroy(&want_names);
1483             svec_destroy(&have_names);
1484
1485             return;
1486         }
1487     }
1488     check_conflicts(&info, port_name,
1489                     xasprintf("cannot create a port named %s", port_name));
1490     for (i = 0; i < n_ifaces; i++) {
1491         check_conflicts(&info, iface_names[i],
1492                         xasprintf("cannot create an interface named %s",
1493                                   iface_names[i]));
1494     }
1495     bridge = find_bridge(&info, br_name, true);
1496
1497     ifaces = xmalloc(n_ifaces * sizeof *ifaces);
1498     for (i = 0; i < n_ifaces; i++) {
1499         ifaces[i] = ovsrec_interface_insert(ctx->txn);
1500         ovsrec_interface_set_name(ifaces[i], iface_names[i]);
1501     }
1502
1503     port = ovsrec_port_insert(ctx->txn);
1504     ovsrec_port_set_name(port, port_name);
1505     ovsrec_port_set_interfaces(port, ifaces, n_ifaces);
1506     ovsrec_port_set_bond_fake_iface(port, fake_iface);
1507     free(ifaces);
1508
1509     if (bridge->vlan) {
1510         int64_t tag = bridge->vlan;
1511         ovsrec_port_set_tag(port, &tag, 1);
1512     }
1513
1514     for (i = 0; i < n_settings; i++) {
1515         set_column(get_table("Port"), &port->header_, settings[i],
1516                    ctx->symtab);
1517     }
1518
1519     bridge_insert_port((bridge->parent ? bridge->parent->br_cfg
1520                         : bridge->br_cfg), port);
1521
1522     free_info(&info);
1523 }
1524
1525 static void
1526 cmd_add_port(struct vsctl_context *ctx)
1527 {
1528     bool may_exist = shash_find(&ctx->options, "--may-exist") != 0;
1529
1530     add_port(ctx, ctx->argv[1], ctx->argv[2], may_exist, false,
1531              &ctx->argv[2], 1, &ctx->argv[3], ctx->argc - 3);
1532 }
1533
1534 static void
1535 cmd_add_bond(struct vsctl_context *ctx)
1536 {
1537     bool may_exist = shash_find(&ctx->options, "--may-exist") != 0;
1538     bool fake_iface = shash_find(&ctx->options, "--fake-iface");
1539     int n_ifaces;
1540     int i;
1541
1542     n_ifaces = ctx->argc - 3;
1543     for (i = 3; i < ctx->argc; i++) {
1544         if (strchr(ctx->argv[i], '=')) {
1545             n_ifaces = i - 3;
1546             break;
1547         }
1548     }
1549     if (n_ifaces < 2) {
1550         vsctl_fatal("add-bond requires at least 2 interfaces, but only "
1551                     "%d were specified", n_ifaces);
1552     }
1553
1554     add_port(ctx, ctx->argv[1], ctx->argv[2], may_exist, fake_iface,
1555              &ctx->argv[3], n_ifaces,
1556              &ctx->argv[n_ifaces + 3], ctx->argc - 3 - n_ifaces);
1557 }
1558
1559 static void
1560 cmd_del_port(struct vsctl_context *ctx)
1561 {
1562     bool must_exist = !shash_find(&ctx->options, "--if-exists");
1563     bool with_iface = shash_find(&ctx->options, "--with-iface") != NULL;
1564     struct vsctl_port *port;
1565     struct vsctl_info info;
1566
1567     get_info(ctx, &info);
1568     if (!with_iface) {
1569         port = find_port(&info, ctx->argv[ctx->argc - 1], must_exist);
1570     } else {
1571         const char *target = ctx->argv[ctx->argc - 1];
1572         struct vsctl_iface *iface;
1573
1574         port = find_port(&info, target, false);
1575         if (!port) {
1576             iface = find_iface(&info, target, false);
1577             if (iface) {
1578                 port = iface->port;
1579             }
1580         }
1581         if (must_exist && !port) {
1582             vsctl_fatal("no port or interface named %s", target);
1583         }
1584     }
1585
1586     if (port) {
1587         if (ctx->argc == 3) {
1588             struct vsctl_bridge *bridge;
1589
1590             bridge = find_bridge(&info, ctx->argv[1], true);
1591             if (port->bridge != bridge) {
1592                 if (port->bridge->parent == bridge) {
1593                     vsctl_fatal("bridge %s does not have a port %s (although "
1594                                 "its parent bridge %s does)",
1595                                 ctx->argv[1], ctx->argv[2],
1596                                 bridge->parent->name);
1597                 } else {
1598                     vsctl_fatal("bridge %s does not have a port %s",
1599                                 ctx->argv[1], ctx->argv[2]);
1600                 }
1601             }
1602         }
1603
1604         del_port(port);
1605     }
1606
1607     free_info(&info);
1608 }
1609
1610 static void
1611 cmd_port_to_br(struct vsctl_context *ctx)
1612 {
1613     struct vsctl_port *port;
1614     struct vsctl_info info;
1615
1616     get_info(ctx, &info);
1617     port = find_port(&info, ctx->argv[1], true);
1618     ds_put_format(&ctx->output, "%s\n", port->bridge->name);
1619     free_info(&info);
1620 }
1621
1622 static void
1623 cmd_br_to_vlan(struct vsctl_context *ctx)
1624 {
1625     struct vsctl_bridge *bridge;
1626     struct vsctl_info info;
1627
1628     get_info(ctx, &info);
1629     bridge = find_bridge(&info, ctx->argv[1], true);
1630     ds_put_format(&ctx->output, "%d\n", bridge->vlan);
1631     free_info(&info);
1632 }
1633
1634 static void
1635 cmd_br_to_parent(struct vsctl_context *ctx)
1636 {
1637     struct vsctl_bridge *bridge;
1638     struct vsctl_info info;
1639
1640     get_info(ctx, &info);
1641     bridge = find_bridge(&info, ctx->argv[1], true);
1642     if (bridge->parent) {
1643         bridge = bridge->parent;
1644     }
1645     ds_put_format(&ctx->output, "%s\n", bridge->name);
1646     free_info(&info);
1647 }
1648
1649 static void
1650 cmd_list_ifaces(struct vsctl_context *ctx)
1651 {
1652     struct vsctl_bridge *br;
1653     struct shash_node *node;
1654     struct vsctl_info info;
1655     struct svec ifaces;
1656
1657     get_info(ctx, &info);
1658     br = find_bridge(&info, ctx->argv[1], true);
1659     verify_ports(ctx);
1660
1661     svec_init(&ifaces);
1662     SHASH_FOR_EACH (node, &info.ifaces) {
1663         struct vsctl_iface *iface = node->data;
1664
1665         if (strcmp(iface->iface_cfg->name, br->name)
1666             && br == iface->port->bridge) {
1667             svec_add(&ifaces, iface->iface_cfg->name);
1668         }
1669     }
1670     output_sorted(&ifaces, &ctx->output);
1671     svec_destroy(&ifaces);
1672
1673     free_info(&info);
1674 }
1675
1676 static void
1677 cmd_iface_to_br(struct vsctl_context *ctx)
1678 {
1679     struct vsctl_iface *iface;
1680     struct vsctl_info info;
1681
1682     get_info(ctx, &info);
1683     iface = find_iface(&info, ctx->argv[1], true);
1684     ds_put_format(&ctx->output, "%s\n", iface->port->bridge->name);
1685     free_info(&info);
1686 }
1687
1688 static void
1689 verify_controllers(struct ovsrec_bridge *bridge)
1690 {
1691     if (bridge) {
1692         size_t i;
1693
1694         ovsrec_bridge_verify_controller(bridge);
1695         for (i = 0; i < bridge->n_controller; i++) {
1696             ovsrec_controller_verify_target(bridge->controller[i]);
1697         }
1698     }
1699 }
1700
1701 static void
1702 pre_controller(struct vsctl_context *ctx)
1703 {
1704     pre_get_info(ctx);
1705
1706     ovsdb_idl_add_column(ctx->idl, &ovsrec_controller_col_target);
1707 }
1708
1709 static void
1710 cmd_get_controller(struct vsctl_context *ctx)
1711 {
1712     struct vsctl_info info;
1713     struct vsctl_bridge *br;
1714     struct svec targets;
1715     size_t i;
1716
1717     get_info(ctx, &info);
1718     br = find_bridge(&info, ctx->argv[1], true);
1719     verify_controllers(br->br_cfg);
1720
1721     /* Print the targets in sorted order for reproducibility. */
1722     svec_init(&targets);
1723     for (i = 0; i < br->n_ctrl; i++) {
1724         svec_add(&targets, br->ctrl[i]->target);
1725     }
1726
1727     svec_sort(&targets);
1728     for (i = 0; i < targets.n; i++) {
1729         ds_put_format(&ctx->output, "%s\n", targets.names[i]);
1730     }
1731     svec_destroy(&targets);
1732
1733     free_info(&info);
1734 }
1735
1736 static void
1737 cmd_del_controller(struct vsctl_context *ctx)
1738 {
1739     struct vsctl_info info;
1740     struct vsctl_bridge *br;
1741
1742     get_info(ctx, &info);
1743
1744     br = find_real_bridge(&info, ctx->argv[1], true);
1745     ovsrec_bridge_set_controller(br->br_cfg, NULL, 0);
1746
1747     free_info(&info);
1748 }
1749
1750 static struct ovsrec_controller **
1751 insert_controllers(struct ovsdb_idl_txn *txn, char *targets[], size_t n)
1752 {
1753     struct ovsrec_controller **controllers;
1754     size_t i;
1755
1756     controllers = xmalloc(n * sizeof *controllers);
1757     for (i = 0; i < n; i++) {
1758         controllers[i] = ovsrec_controller_insert(txn);
1759         ovsrec_controller_set_target(controllers[i], targets[i]);
1760     }
1761
1762     return controllers;
1763 }
1764
1765 static void
1766 cmd_set_controller(struct vsctl_context *ctx)
1767 {
1768     struct vsctl_info info;
1769     struct vsctl_bridge *br;
1770     struct ovsrec_controller **controllers;
1771     size_t n;
1772
1773     get_info(ctx, &info);
1774     br = find_real_bridge(&info, ctx->argv[1], true);
1775
1776     n = ctx->argc - 2;
1777     controllers = insert_controllers(ctx->txn, &ctx->argv[2], n);
1778     ovsrec_bridge_set_controller(br->br_cfg, controllers, n);
1779     free(controllers);
1780
1781     free_info(&info);
1782 }
1783
1784 static void
1785 cmd_get_fail_mode(struct vsctl_context *ctx)
1786 {
1787     struct vsctl_info info;
1788     struct vsctl_bridge *br;
1789
1790     get_info(ctx, &info);
1791     br = find_bridge(&info, ctx->argv[1], true);
1792
1793     if (br->br_cfg) {
1794         ovsrec_bridge_verify_fail_mode(br->br_cfg);
1795     }
1796     if (br->fail_mode && strlen(br->fail_mode)) {
1797         ds_put_format(&ctx->output, "%s\n", br->fail_mode);
1798     }
1799
1800     free_info(&info);
1801 }
1802
1803 static void
1804 cmd_del_fail_mode(struct vsctl_context *ctx)
1805 {
1806     struct vsctl_info info;
1807     struct vsctl_bridge *br;
1808
1809     get_info(ctx, &info);
1810     br = find_real_bridge(&info, ctx->argv[1], true);
1811
1812     ovsrec_bridge_set_fail_mode(br->br_cfg, NULL);
1813
1814     free_info(&info);
1815 }
1816
1817 static void
1818 cmd_set_fail_mode(struct vsctl_context *ctx)
1819 {
1820     struct vsctl_info info;
1821     struct vsctl_bridge *br;
1822     const char *fail_mode = ctx->argv[2];
1823
1824     get_info(ctx, &info);
1825     br = find_real_bridge(&info, ctx->argv[1], true);
1826
1827     if (strcmp(fail_mode, "standalone") && strcmp(fail_mode, "secure")) {
1828         vsctl_fatal("fail-mode must be \"standalone\" or \"secure\"");
1829     }
1830
1831     ovsrec_bridge_set_fail_mode(br->br_cfg, fail_mode);
1832
1833     free_info(&info);
1834 }
1835
1836 static void
1837 verify_managers(const struct ovsrec_open_vswitch *ovs)
1838 {
1839     size_t i;
1840
1841     ovsrec_open_vswitch_verify_manager_options(ovs);
1842
1843     for (i = 0; i < ovs->n_manager_options; ++i) {
1844         const struct ovsrec_manager *mgr = ovs->manager_options[i];
1845
1846         ovsrec_manager_verify_target(mgr);
1847     }
1848 }
1849
1850 static void
1851 pre_manager(struct vsctl_context *ctx)
1852 {
1853     ovsdb_idl_add_column(ctx->idl, &ovsrec_open_vswitch_col_manager_options);
1854     ovsdb_idl_add_column(ctx->idl, &ovsrec_manager_col_target);
1855 }
1856
1857 static void
1858 cmd_get_manager(struct vsctl_context *ctx)
1859 {
1860     const struct ovsrec_open_vswitch *ovs = ctx->ovs;
1861     struct svec targets;
1862     size_t i;
1863
1864     verify_managers(ovs);
1865
1866     /* Print the targets in sorted order for reproducibility. */
1867     svec_init(&targets);
1868
1869     for (i = 0; i < ovs->n_manager_options; i++) {
1870         svec_add(&targets, ovs->manager_options[i]->target);
1871     }
1872
1873     svec_sort_unique(&targets);
1874     for (i = 0; i < targets.n; i++) {
1875         ds_put_format(&ctx->output, "%s\n", targets.names[i]);
1876     }
1877     svec_destroy(&targets);
1878 }
1879
1880 static void
1881 cmd_del_manager(struct vsctl_context *ctx)
1882 {
1883     const struct ovsrec_open_vswitch *ovs = ctx->ovs;
1884
1885     ovsrec_open_vswitch_set_manager_options(ovs, NULL, 0);
1886 }
1887
1888 static void
1889 insert_managers(struct vsctl_context *ctx, char *targets[], size_t n)
1890 {
1891     struct ovsrec_manager **managers;
1892     size_t i;
1893
1894     /* Insert each manager in a new row in Manager table. */
1895     managers = xmalloc(n * sizeof *managers);
1896     for (i = 0; i < n; i++) {
1897         managers[i] = ovsrec_manager_insert(ctx->txn);
1898         ovsrec_manager_set_target(managers[i], targets[i]);
1899     }
1900
1901     /* Store uuids of new Manager rows in 'manager_options' column. */
1902     ovsrec_open_vswitch_set_manager_options(ctx->ovs, managers, n);
1903     free(managers);
1904 }
1905
1906 static void
1907 cmd_set_manager(struct vsctl_context *ctx)
1908 {
1909     const size_t n = ctx->argc - 1;
1910
1911     insert_managers(ctx, &ctx->argv[1], n);
1912 }
1913
1914 static void
1915 pre_cmd_get_ssl(struct vsctl_context *ctx)
1916 {
1917     ovsdb_idl_add_column(ctx->idl, &ovsrec_open_vswitch_col_ssl);
1918
1919     ovsdb_idl_add_column(ctx->idl, &ovsrec_ssl_col_private_key);
1920     ovsdb_idl_add_column(ctx->idl, &ovsrec_ssl_col_certificate);
1921     ovsdb_idl_add_column(ctx->idl, &ovsrec_ssl_col_ca_cert);
1922     ovsdb_idl_add_column(ctx->idl, &ovsrec_ssl_col_bootstrap_ca_cert);
1923 }
1924
1925 static void
1926 cmd_get_ssl(struct vsctl_context *ctx)
1927 {
1928     struct ovsrec_ssl *ssl = ctx->ovs->ssl;
1929
1930     ovsrec_open_vswitch_verify_ssl(ctx->ovs);
1931     if (ssl) {
1932         ovsrec_ssl_verify_private_key(ssl);
1933         ovsrec_ssl_verify_certificate(ssl);
1934         ovsrec_ssl_verify_ca_cert(ssl);
1935         ovsrec_ssl_verify_bootstrap_ca_cert(ssl);
1936
1937         ds_put_format(&ctx->output, "Private key: %s\n", ssl->private_key);
1938         ds_put_format(&ctx->output, "Certificate: %s\n", ssl->certificate);
1939         ds_put_format(&ctx->output, "CA Certificate: %s\n", ssl->ca_cert);
1940         ds_put_format(&ctx->output, "Bootstrap: %s\n",
1941                 ssl->bootstrap_ca_cert ? "true" : "false");
1942     }
1943 }
1944
1945 static void
1946 pre_cmd_del_ssl(struct vsctl_context *ctx)
1947 {
1948     ovsdb_idl_add_column(ctx->idl, &ovsrec_open_vswitch_col_ssl);
1949 }
1950
1951 static void
1952 cmd_del_ssl(struct vsctl_context *ctx)
1953 {
1954     ovsrec_open_vswitch_set_ssl(ctx->ovs, NULL);
1955 }
1956
1957 static void
1958 pre_cmd_set_ssl(struct vsctl_context *ctx)
1959 {
1960     ovsdb_idl_add_column(ctx->idl, &ovsrec_open_vswitch_col_ssl);
1961 }
1962
1963 static void
1964 cmd_set_ssl(struct vsctl_context *ctx)
1965 {
1966     bool bootstrap = shash_find(&ctx->options, "--bootstrap");
1967     struct ovsrec_ssl *ssl;
1968
1969     ssl = ovsrec_ssl_insert(ctx->txn);
1970
1971     ovsrec_ssl_set_private_key(ssl, ctx->argv[1]);
1972     ovsrec_ssl_set_certificate(ssl, ctx->argv[2]);
1973     ovsrec_ssl_set_ca_cert(ssl, ctx->argv[3]);
1974
1975     ovsrec_ssl_set_bootstrap_ca_cert(ssl, bootstrap);
1976
1977     ovsrec_open_vswitch_set_ssl(ctx->ovs, ssl);
1978 }
1979 \f
1980 /* Parameter commands. */
1981
1982 struct vsctl_row_id {
1983     const struct ovsdb_idl_table_class *table;
1984     const struct ovsdb_idl_column *name_column;
1985     const struct ovsdb_idl_column *uuid_column;
1986 };
1987
1988 struct vsctl_table_class {
1989     struct ovsdb_idl_table_class *class;
1990     struct vsctl_row_id row_ids[2];
1991 };
1992
1993 static const struct vsctl_table_class tables[] = {
1994     {&ovsrec_table_bridge,
1995      {{&ovsrec_table_bridge, &ovsrec_bridge_col_name, NULL},
1996       {NULL, NULL, NULL}}},
1997
1998     {&ovsrec_table_controller,
1999      {{&ovsrec_table_bridge,
2000        &ovsrec_bridge_col_name,
2001        &ovsrec_bridge_col_controller}}},
2002
2003     {&ovsrec_table_interface,
2004      {{&ovsrec_table_interface, &ovsrec_interface_col_name, NULL},
2005       {NULL, NULL, NULL}}},
2006
2007     {&ovsrec_table_mirror,
2008      {{&ovsrec_table_mirror, &ovsrec_mirror_col_name, NULL},
2009       {NULL, NULL, NULL}}},
2010
2011     {&ovsrec_table_manager,
2012      {{&ovsrec_table_manager, &ovsrec_manager_col_target, NULL},
2013       {NULL, NULL, NULL}}},
2014
2015     {&ovsrec_table_netflow,
2016      {{&ovsrec_table_bridge,
2017        &ovsrec_bridge_col_name,
2018        &ovsrec_bridge_col_netflow},
2019       {NULL, NULL, NULL}}},
2020
2021     {&ovsrec_table_open_vswitch,
2022      {{&ovsrec_table_open_vswitch, NULL, NULL},
2023       {NULL, NULL, NULL}}},
2024
2025     {&ovsrec_table_port,
2026      {{&ovsrec_table_port, &ovsrec_port_col_name, NULL},
2027       {NULL, NULL, NULL}}},
2028
2029     {&ovsrec_table_qos,
2030      {{&ovsrec_table_port, &ovsrec_port_col_name, &ovsrec_port_col_qos},
2031       {NULL, NULL, NULL}}},
2032
2033     {&ovsrec_table_monitor,
2034      {{&ovsrec_table_interface,
2035        &ovsrec_interface_col_name,
2036        &ovsrec_interface_col_monitor},
2037       {NULL, NULL, NULL}}},
2038
2039     {&ovsrec_table_maintenance_point,
2040      {{NULL, NULL, NULL},
2041       {NULL, NULL, NULL}}},
2042
2043     {&ovsrec_table_queue,
2044      {{NULL, NULL, NULL},
2045       {NULL, NULL, NULL}}},
2046
2047     {&ovsrec_table_ssl,
2048      {{&ovsrec_table_open_vswitch, NULL, &ovsrec_open_vswitch_col_ssl}}},
2049
2050     {&ovsrec_table_sflow,
2051      {{&ovsrec_table_bridge,
2052        &ovsrec_bridge_col_name,
2053        &ovsrec_bridge_col_sflow},
2054       {NULL, NULL, NULL}}},
2055
2056     {NULL, {{NULL, NULL, NULL}, {NULL, NULL, NULL}}}
2057 };
2058
2059 static void
2060 die_if_error(char *error)
2061 {
2062     if (error) {
2063         vsctl_fatal("%s", error);
2064     }
2065 }
2066
2067 static int
2068 to_lower_and_underscores(unsigned c)
2069 {
2070     return c == '-' ? '_' : tolower(c);
2071 }
2072
2073 static unsigned int
2074 score_partial_match(const char *name, const char *s)
2075 {
2076     int score;
2077
2078     if (!strcmp(name, s)) {
2079         return UINT_MAX;
2080     }
2081     for (score = 0; ; score++, name++, s++) {
2082         if (to_lower_and_underscores(*name) != to_lower_and_underscores(*s)) {
2083             break;
2084         } else if (*name == '\0') {
2085             return UINT_MAX - 1;
2086         }
2087     }
2088     return *s == '\0' ? score : 0;
2089 }
2090
2091 static const struct vsctl_table_class *
2092 get_table(const char *table_name)
2093 {
2094     const struct vsctl_table_class *table;
2095     const struct vsctl_table_class *best_match = NULL;
2096     unsigned int best_score = 0;
2097
2098     for (table = tables; table->class; table++) {
2099         unsigned int score = score_partial_match(table->class->name,
2100                                                  table_name);
2101         if (score > best_score) {
2102             best_match = table;
2103             best_score = score;
2104         } else if (score == best_score) {
2105             best_match = NULL;
2106         }
2107     }
2108     if (best_match) {
2109         return best_match;
2110     } else if (best_score) {
2111         vsctl_fatal("multiple table names match \"%s\"", table_name);
2112     } else {
2113         vsctl_fatal("unknown table \"%s\"", table_name);
2114     }
2115 }
2116
2117 static const struct vsctl_table_class *
2118 pre_get_table(struct vsctl_context *ctx, const char *table_name)
2119 {
2120     const struct vsctl_table_class *table_class;
2121     int i;
2122
2123     table_class = get_table(table_name);
2124     ovsdb_idl_add_table(ctx->idl, table_class->class);
2125
2126     for (i = 0; i < ARRAY_SIZE(table_class->row_ids); i++) {
2127         const struct vsctl_row_id *id = &table_class->row_ids[i];
2128         if (id->table) {
2129             ovsdb_idl_add_table(ctx->idl, id->table);
2130         }
2131         if (id->name_column) {
2132             ovsdb_idl_add_column(ctx->idl, id->name_column);
2133         }
2134         if (id->uuid_column) {
2135             ovsdb_idl_add_column(ctx->idl, id->uuid_column);
2136         }
2137     }
2138
2139     return table_class;
2140 }
2141
2142 static const struct ovsdb_idl_row *
2143 get_row_by_id(struct vsctl_context *ctx, const struct vsctl_table_class *table,
2144               const struct vsctl_row_id *id, const char *record_id)
2145 {
2146     const struct ovsdb_idl_row *referrer, *final;
2147
2148     if (!id->table) {
2149         return NULL;
2150     }
2151
2152     if (!id->name_column) {
2153         if (strcmp(record_id, ".")) {
2154             return NULL;
2155         }
2156         referrer = ovsdb_idl_first_row(ctx->idl, id->table);
2157         if (!referrer || ovsdb_idl_next_row(referrer)) {
2158             return NULL;
2159         }
2160     } else {
2161         const struct ovsdb_idl_row *row;
2162
2163         referrer = NULL;
2164         for (row = ovsdb_idl_first_row(ctx->idl, id->table);
2165              row != NULL;
2166              row = ovsdb_idl_next_row(row))
2167         {
2168             const struct ovsdb_datum *name;
2169
2170             name = ovsdb_idl_get(row, id->name_column,
2171                                  OVSDB_TYPE_STRING, OVSDB_TYPE_VOID);
2172             if (name->n == 1 && !strcmp(name->keys[0].string, record_id)) {
2173                 if (referrer) {
2174                     vsctl_fatal("multiple rows in %s match \"%s\"",
2175                                 table->class->name, record_id);
2176                 }
2177                 referrer = row;
2178             }
2179         }
2180     }
2181     if (!referrer) {
2182         return NULL;
2183     }
2184
2185     final = NULL;
2186     if (id->uuid_column) {
2187         const struct ovsdb_datum *uuid;
2188
2189         ovsdb_idl_txn_verify(referrer, id->uuid_column);
2190         uuid = ovsdb_idl_get(referrer, id->uuid_column,
2191                              OVSDB_TYPE_UUID, OVSDB_TYPE_VOID);
2192         if (uuid->n == 1) {
2193             final = ovsdb_idl_get_row_for_uuid(ctx->idl, table->class,
2194                                                &uuid->keys[0].uuid);
2195         }
2196     } else {
2197         final = referrer;
2198     }
2199
2200     return final;
2201 }
2202
2203 static const struct ovsdb_idl_row *
2204 get_row (struct vsctl_context *ctx,
2205          const struct vsctl_table_class *table, const char *record_id)
2206 {
2207     const struct ovsdb_idl_row *row;
2208     struct uuid uuid;
2209
2210     if (uuid_from_string(&uuid, record_id)) {
2211         row = ovsdb_idl_get_row_for_uuid(ctx->idl, table->class, &uuid);
2212     } else {
2213         int i;
2214
2215         for (i = 0; i < ARRAY_SIZE(table->row_ids); i++) {
2216             row = get_row_by_id(ctx, table, &table->row_ids[i], record_id);
2217             if (row) {
2218                 break;
2219             }
2220         }
2221     }
2222     return row;
2223 }
2224
2225 static const struct ovsdb_idl_row *
2226 must_get_row(struct vsctl_context *ctx,
2227              const struct vsctl_table_class *table, const char *record_id)
2228 {
2229     const struct ovsdb_idl_row *row = get_row(ctx, table, record_id);
2230     if (!row) {
2231         vsctl_fatal("no row \"%s\" in table %s",
2232                     record_id, table->class->name);
2233     }
2234     return row;
2235 }
2236
2237 static char *
2238 get_column(const struct vsctl_table_class *table, const char *column_name,
2239            const struct ovsdb_idl_column **columnp)
2240 {
2241     const struct ovsdb_idl_column *best_match = NULL;
2242     unsigned int best_score = 0;
2243     size_t i;
2244
2245     for (i = 0; i < table->class->n_columns; i++) {
2246         const struct ovsdb_idl_column *column = &table->class->columns[i];
2247         unsigned int score = score_partial_match(column->name, column_name);
2248         if (score > best_score) {
2249             best_match = column;
2250             best_score = score;
2251         } else if (score == best_score) {
2252             best_match = NULL;
2253         }
2254     }
2255
2256     *columnp = best_match;
2257     if (best_match) {
2258         return NULL;
2259     } else if (best_score) {
2260         return xasprintf("%s contains more than one column whose name "
2261                          "matches \"%s\"", table->class->name, column_name);
2262     } else {
2263         return xasprintf("%s does not contain a column whose name matches "
2264                          "\"%s\"", table->class->name, column_name);
2265     }
2266 }
2267
2268 static struct ovsdb_symbol *
2269 create_symbol(struct ovsdb_symbol_table *symtab, const char *id, bool *newp)
2270 {
2271     struct ovsdb_symbol *symbol;
2272
2273     if (id[0] != '@') {
2274         vsctl_fatal("row id \"%s\" does not begin with \"@\"", id);
2275     }
2276
2277     if (newp) {
2278         *newp = ovsdb_symbol_table_get(symtab, id) == NULL;
2279     }
2280
2281     symbol = ovsdb_symbol_table_insert(symtab, id);
2282     if (symbol->created) {
2283         vsctl_fatal("row id \"%s\" may only be specified on one --id option",
2284                     id);
2285     }
2286     symbol->created = true;
2287     return symbol;
2288 }
2289
2290 static void
2291 pre_get_column(struct vsctl_context *ctx,
2292                const struct vsctl_table_class *table, const char *column_name,
2293                const struct ovsdb_idl_column **columnp)
2294 {
2295     die_if_error(get_column(table, column_name, columnp));
2296     ovsdb_idl_add_column(ctx->idl, *columnp);
2297 }
2298
2299 static char *
2300 missing_operator_error(const char *arg, const char **allowed_operators,
2301                        size_t n_allowed)
2302 {
2303     struct ds s;
2304
2305     ds_init(&s);
2306     ds_put_format(&s, "%s: argument does not end in ", arg);
2307     ds_put_format(&s, "\"%s\"", allowed_operators[0]);
2308     if (n_allowed == 2) {
2309         ds_put_format(&s, " or \"%s\"", allowed_operators[1]);
2310     } else if (n_allowed > 2) {
2311         size_t i;
2312
2313         for (i = 1; i < n_allowed - 1; i++) {
2314             ds_put_format(&s, ", \"%s\"", allowed_operators[i]);
2315         }
2316         ds_put_format(&s, ", or \"%s\"", allowed_operators[i]);
2317     }
2318     ds_put_format(&s, " followed by a value.");
2319
2320     return ds_steal_cstr(&s);
2321 }
2322
2323 /* Breaks 'arg' apart into a number of fields in the following order:
2324  *
2325  *      - The name of a column in 'table', stored into '*columnp'.  The column
2326  *        name may be abbreviated.
2327  *
2328  *      - Optionally ':' followed by a key string.  The key is stored as a
2329  *        malloc()'d string into '*keyp', or NULL if no key is present in
2330  *        'arg'.
2331  *
2332  *      - If 'valuep' is nonnull, an operator followed by a value string.  The
2333  *        allowed operators are the 'n_allowed' string in 'allowed_operators',
2334  *        or just "=" if 'n_allowed' is 0.  If 'operatorp' is nonnull, then the
2335  *        operator is stored into '*operatorp' (one of the pointers from
2336  *        'allowed_operators' is stored; nothing is malloc()'d).  The value is
2337  *        stored as a malloc()'d string into '*valuep', or NULL if no value is
2338  *        present in 'arg'.
2339  *
2340  * On success, returns NULL.  On failure, returned a malloc()'d string error
2341  * message and stores NULL into all of the nonnull output arguments. */
2342 static char * WARN_UNUSED_RESULT
2343 parse_column_key_value(const char *arg,
2344                        const struct vsctl_table_class *table,
2345                        const struct ovsdb_idl_column **columnp, char **keyp,
2346                        const char **operatorp,
2347                        const char **allowed_operators, size_t n_allowed,
2348                        char **valuep)
2349 {
2350     const char *p = arg;
2351     char *column_name;
2352     char *error;
2353
2354     assert(!(operatorp && !valuep));
2355     *keyp = NULL;
2356     if (valuep) {
2357         *valuep = NULL;
2358     }
2359
2360     /* Parse column name. */
2361     error = ovsdb_token_parse(&p, &column_name);
2362     if (error) {
2363         goto error;
2364     }
2365     if (column_name[0] == '\0') {
2366         free(column_name);
2367         error = xasprintf("%s: missing column name", arg);
2368         goto error;
2369     }
2370     error = get_column(table, column_name, columnp);
2371     free(column_name);
2372     if (error) {
2373         goto error;
2374     }
2375
2376     /* Parse key string. */
2377     if (*p == ':') {
2378         p++;
2379         error = ovsdb_token_parse(&p, keyp);
2380         if (error) {
2381             goto error;
2382         }
2383     }
2384
2385     /* Parse value string. */
2386     if (valuep) {
2387         const char *best;
2388         size_t best_len;
2389         size_t i;
2390
2391         if (!allowed_operators) {
2392             static const char *equals = "=";
2393             allowed_operators = &equals;
2394             n_allowed = 1;
2395         }
2396
2397         best = NULL;
2398         best_len = 0;
2399         for (i = 0; i < n_allowed; i++) {
2400             const char *op = allowed_operators[i];
2401             size_t op_len = strlen(op);
2402
2403             if (op_len > best_len && !strncmp(op, p, op_len) && p[op_len]) {
2404                 best_len = op_len;
2405                 best = op;
2406             }
2407         }
2408         if (!best) {
2409             error = missing_operator_error(arg, allowed_operators, n_allowed);
2410             goto error;
2411         }
2412
2413         if (operatorp) {
2414             *operatorp = best;
2415         }
2416         *valuep = xstrdup(p + best_len);
2417     } else {
2418         if (valuep) {
2419             *valuep = NULL;
2420         }
2421         if (*p != '\0') {
2422             error = xasprintf("%s: trailing garbage \"%s\" in argument",
2423                               arg, p);
2424             goto error;
2425         }
2426     }
2427     return NULL;
2428
2429 error:
2430     *columnp = NULL;
2431     free(*keyp);
2432     *keyp = NULL;
2433     if (valuep) {
2434         free(*valuep);
2435         *valuep = NULL;
2436         if (operatorp) {
2437             *operatorp = NULL;
2438         }
2439     }
2440     return error;
2441 }
2442
2443 static void
2444 pre_parse_column_key_value(struct vsctl_context *ctx,
2445                            const char *arg,
2446                            const struct vsctl_table_class *table)
2447 {
2448     const struct ovsdb_idl_column *column;
2449     const char *p;
2450     char *column_name;
2451
2452     p = arg;
2453     die_if_error(ovsdb_token_parse(&p, &column_name));
2454     if (column_name[0] == '\0') {
2455         vsctl_fatal("%s: missing column name", arg);
2456     }
2457
2458     pre_get_column(ctx, table, column_name, &column);
2459     free(column_name);
2460 }
2461
2462 static void
2463 pre_cmd_get(struct vsctl_context *ctx)
2464 {
2465     const char *table_name = ctx->argv[1];
2466     const struct vsctl_table_class *table;
2467     int i;
2468
2469     table = pre_get_table(ctx, table_name);
2470     for (i = 3; i < ctx->argc; i++) {
2471         if (!strcasecmp(ctx->argv[i], "_uuid")
2472             || !strcasecmp(ctx->argv[i], "-uuid")) {
2473             continue;
2474         }
2475
2476         pre_parse_column_key_value(ctx, ctx->argv[i], table);
2477     }
2478 }
2479
2480 static void
2481 cmd_get(struct vsctl_context *ctx)
2482 {
2483     const char *id = shash_find_data(&ctx->options, "--id");
2484     bool if_exists = shash_find(&ctx->options, "--if-exists");
2485     const char *table_name = ctx->argv[1];
2486     const char *record_id = ctx->argv[2];
2487     const struct vsctl_table_class *table;
2488     const struct ovsdb_idl_row *row;
2489     struct ds *out = &ctx->output;
2490     int i;
2491
2492     table = get_table(table_name);
2493     row = must_get_row(ctx, table, record_id);
2494     if (id) {
2495         struct ovsdb_symbol *symbol;
2496         bool new;
2497
2498         symbol = create_symbol(ctx->symtab, id, &new);
2499         if (!new) {
2500             vsctl_fatal("row id \"%s\" specified on \"get\" command was used "
2501                         "before it was defined", id);
2502         }
2503         symbol->uuid = row->uuid;
2504
2505         /* This symbol refers to a row that already exists, so disable warnings
2506          * about it being unreferenced. */
2507         symbol->strong_ref = true;
2508     }
2509     for (i = 3; i < ctx->argc; i++) {
2510         const struct ovsdb_idl_column *column;
2511         const struct ovsdb_datum *datum;
2512         char *key_string;
2513
2514         /* Special case for obtaining the UUID of a row.  We can't just do this
2515          * through parse_column_key_value() below since it returns a "struct
2516          * ovsdb_idl_column" and the UUID column doesn't have one. */
2517         if (!strcasecmp(ctx->argv[i], "_uuid")
2518             || !strcasecmp(ctx->argv[i], "-uuid")) {
2519             ds_put_format(out, UUID_FMT"\n", UUID_ARGS(&row->uuid));
2520             continue;
2521         }
2522
2523         die_if_error(parse_column_key_value(ctx->argv[i], table,
2524                                             &column, &key_string,
2525                                             NULL, NULL, 0, NULL));
2526
2527         ovsdb_idl_txn_verify(row, column);
2528         datum = ovsdb_idl_read(row, column);
2529         if (key_string) {
2530             union ovsdb_atom key;
2531             unsigned int idx;
2532
2533             if (column->type.value.type == OVSDB_TYPE_VOID) {
2534                 vsctl_fatal("cannot specify key to get for non-map column %s",
2535                             column->name);
2536             }
2537
2538             die_if_error(ovsdb_atom_from_string(&key,
2539                                                 &column->type.key,
2540                                                 key_string, ctx->symtab));
2541
2542             idx = ovsdb_datum_find_key(datum, &key,
2543                                        column->type.key.type);
2544             if (idx == UINT_MAX) {
2545                 if (!if_exists) {
2546                     vsctl_fatal("no key \"%s\" in %s record \"%s\" column %s",
2547                                 key_string, table->class->name, record_id,
2548                                 column->name);
2549                 }
2550             } else {
2551                 ovsdb_atom_to_string(&datum->values[idx],
2552                                      column->type.value.type, out);
2553             }
2554             ovsdb_atom_destroy(&key, column->type.key.type);
2555         } else {
2556             ovsdb_datum_to_string(datum, &column->type, out);
2557         }
2558         ds_put_char(out, '\n');
2559
2560         free(key_string);
2561     }
2562 }
2563
2564 static void
2565 parse_column_names(const char *column_names,
2566                    const struct vsctl_table_class *table,
2567                    const struct ovsdb_idl_column ***columnsp,
2568                    size_t *n_columnsp)
2569 {
2570     const struct ovsdb_idl_column **columns;
2571     size_t n_columns;
2572
2573     if (!column_names) {
2574         size_t i;
2575
2576         n_columns = table->class->n_columns + 1;
2577         columns = xmalloc(n_columns * sizeof *columns);
2578         columns[0] = NULL;
2579         for (i = 0; i < table->class->n_columns; i++) {
2580             columns[i + 1] = &table->class->columns[i];
2581         }
2582     } else {
2583         char *s = xstrdup(column_names);
2584         size_t allocated_columns;
2585         char *save_ptr = NULL;
2586         char *column_name;
2587
2588         columns = NULL;
2589         allocated_columns = n_columns = 0;
2590         for (column_name = strtok_r(s, ", ", &save_ptr); column_name;
2591              column_name = strtok_r(NULL, ", ", &save_ptr)) {
2592             const struct ovsdb_idl_column *column;
2593
2594             if (!strcasecmp(column_name, "_uuid")) {
2595                 column = NULL;
2596             } else {
2597                 die_if_error(get_column(table, column_name, &column));
2598             }
2599             if (n_columns >= allocated_columns) {
2600                 columns = x2nrealloc(columns, &allocated_columns,
2601                                      sizeof *columns);
2602             }
2603             columns[n_columns++] = column;
2604         }
2605         free(s);
2606
2607         if (!n_columns) {
2608             vsctl_fatal("must specify at least one column name");
2609         }
2610     }
2611     *columnsp = columns;
2612     *n_columnsp = n_columns;
2613 }
2614
2615
2616 static void
2617 pre_list_columns(struct vsctl_context *ctx,
2618                  const struct vsctl_table_class *table,
2619                  const char *column_names)
2620 {
2621     const struct ovsdb_idl_column **columns;
2622     size_t n_columns;
2623     size_t i;
2624
2625     parse_column_names(column_names, table, &columns, &n_columns);
2626     for (i = 0; i < n_columns; i++) {
2627         if (columns[i]) {
2628             ovsdb_idl_add_column(ctx->idl, columns[i]);
2629         }
2630     }
2631     free(columns);
2632 }
2633
2634 static void
2635 pre_cmd_list(struct vsctl_context *ctx)
2636 {
2637     const char *column_names = shash_find_data(&ctx->options, "--columns");
2638     const char *table_name = ctx->argv[1];
2639     const struct vsctl_table_class *table;
2640
2641     table = pre_get_table(ctx, table_name);
2642     pre_list_columns(ctx, table, column_names);
2643 }
2644
2645 static struct table *
2646 list_make_table(const struct ovsdb_idl_column **columns, size_t n_columns)
2647 {
2648     struct table *out;
2649     size_t i;
2650
2651     out = xmalloc(sizeof *out);
2652     table_init(out);
2653
2654     for (i = 0; i < n_columns; i++) {
2655         const struct ovsdb_idl_column *column = columns[i];
2656         const char *column_name = column ? column->name : "_uuid";
2657
2658         table_add_column(out, "%s", column_name);
2659     }
2660
2661     return out;
2662 }
2663
2664 static void
2665 list_record(const struct ovsdb_idl_row *row,
2666             const struct ovsdb_idl_column **columns, size_t n_columns,
2667             struct table *out)
2668 {
2669     size_t i;
2670
2671     table_add_row(out);
2672     for (i = 0; i < n_columns; i++) {
2673         const struct ovsdb_idl_column *column = columns[i];
2674         struct cell *cell = table_add_cell(out);
2675
2676         if (!column) {
2677             struct ovsdb_datum datum;
2678             union ovsdb_atom atom;
2679
2680             atom.uuid = row->uuid;
2681
2682             datum.keys = &atom;
2683             datum.values = NULL;
2684             datum.n = 1;
2685
2686             cell->json = ovsdb_datum_to_json(&datum, &ovsdb_type_uuid);
2687             cell->type = &ovsdb_type_uuid;
2688         } else {
2689             const struct ovsdb_datum *datum = ovsdb_idl_read(row, column);
2690
2691             cell->json = ovsdb_datum_to_json(datum, &column->type);
2692             cell->type = &column->type;
2693         }
2694     }
2695 }
2696
2697 static void
2698 cmd_list(struct vsctl_context *ctx)
2699 {
2700     const char *column_names = shash_find_data(&ctx->options, "--columns");
2701     const struct ovsdb_idl_column **columns;
2702     const char *table_name = ctx->argv[1];
2703     const struct vsctl_table_class *table;
2704     struct table *out;
2705     size_t n_columns;
2706     int i;
2707
2708     table = get_table(table_name);
2709     parse_column_names(column_names, table, &columns, &n_columns);
2710     out = ctx->table = list_make_table(columns, n_columns);
2711     if (ctx->argc > 2) {
2712         for (i = 2; i < ctx->argc; i++) {
2713             list_record(must_get_row(ctx, table, ctx->argv[i]),
2714                         columns, n_columns, out);
2715         }
2716     } else {
2717         const struct ovsdb_idl_row *row;
2718         bool first;
2719
2720         for (row = ovsdb_idl_first_row(ctx->idl, table->class), first = true;
2721              row != NULL;
2722              row = ovsdb_idl_next_row(row), first = false) {
2723             list_record(row, columns, n_columns, out);
2724         }
2725     }
2726     free(columns);
2727 }
2728
2729 static void
2730 pre_cmd_find(struct vsctl_context *ctx)
2731 {
2732     const char *column_names = shash_find_data(&ctx->options, "--columns");
2733     const char *table_name = ctx->argv[1];
2734     const struct vsctl_table_class *table;
2735     int i;
2736
2737     table = pre_get_table(ctx, table_name);
2738     pre_list_columns(ctx, table, column_names);
2739     for (i = 2; i < ctx->argc; i++) {
2740         pre_parse_column_key_value(ctx, ctx->argv[i], table);
2741     }
2742 }
2743
2744 static void
2745 cmd_find(struct vsctl_context *ctx)
2746 {
2747     const char *column_names = shash_find_data(&ctx->options, "--columns");
2748     const struct ovsdb_idl_column **columns;
2749     const char *table_name = ctx->argv[1];
2750     const struct vsctl_table_class *table;
2751     const struct ovsdb_idl_row *row;
2752     struct table *out;
2753     size_t n_columns;
2754
2755     table = get_table(table_name);
2756     parse_column_names(column_names, table, &columns, &n_columns);
2757     out = ctx->table = list_make_table(columns, n_columns);
2758     for (row = ovsdb_idl_first_row(ctx->idl, table->class); row;
2759          row = ovsdb_idl_next_row(row)) {
2760         int i;
2761
2762         for (i = 2; i < ctx->argc; i++) {
2763             if (!is_condition_satisfied(table, row, ctx->argv[i],
2764                                         ctx->symtab)) {
2765                 goto next_row;
2766             }
2767         }
2768         list_record(row, columns, n_columns, out);
2769
2770     next_row: ;
2771     }
2772     free(columns);
2773 }
2774
2775 static void
2776 pre_cmd_set(struct vsctl_context *ctx)
2777 {
2778     const char *table_name = ctx->argv[1];
2779     const struct vsctl_table_class *table;
2780     int i;
2781
2782     table = pre_get_table(ctx, table_name);
2783     for (i = 3; i < ctx->argc; i++) {
2784         pre_parse_column_key_value(ctx, ctx->argv[i], table);
2785     }
2786 }
2787
2788 static void
2789 set_column(const struct vsctl_table_class *table,
2790            const struct ovsdb_idl_row *row, const char *arg,
2791            struct ovsdb_symbol_table *symtab)
2792 {
2793     const struct ovsdb_idl_column *column;
2794     char *key_string, *value_string;
2795     char *error;
2796
2797     error = parse_column_key_value(arg, table, &column, &key_string,
2798                                    NULL, NULL, 0, &value_string);
2799     die_if_error(error);
2800     if (!value_string) {
2801         vsctl_fatal("%s: missing value", arg);
2802     }
2803
2804     if (key_string) {
2805         union ovsdb_atom key, value;
2806         struct ovsdb_datum datum;
2807
2808         if (column->type.value.type == OVSDB_TYPE_VOID) {
2809             vsctl_fatal("cannot specify key to set for non-map column %s",
2810                         column->name);
2811         }
2812
2813         die_if_error(ovsdb_atom_from_string(&key, &column->type.key,
2814                                             key_string, symtab));
2815         die_if_error(ovsdb_atom_from_string(&value, &column->type.value,
2816                                             value_string, symtab));
2817
2818         ovsdb_datum_init_empty(&datum);
2819         ovsdb_datum_add_unsafe(&datum, &key, &value, &column->type);
2820
2821         ovsdb_atom_destroy(&key, column->type.key.type);
2822         ovsdb_atom_destroy(&value, column->type.value.type);
2823
2824         ovsdb_datum_union(&datum, ovsdb_idl_read(row, column),
2825                           &column->type, false);
2826         ovsdb_idl_txn_write(row, column, &datum);
2827     } else {
2828         struct ovsdb_datum datum;
2829
2830         die_if_error(ovsdb_datum_from_string(&datum, &column->type,
2831                                              value_string, symtab));
2832         ovsdb_idl_txn_write(row, column, &datum);
2833     }
2834
2835     free(key_string);
2836     free(value_string);
2837 }
2838
2839 static void
2840 cmd_set(struct vsctl_context *ctx)
2841 {
2842     const char *table_name = ctx->argv[1];
2843     const char *record_id = ctx->argv[2];
2844     const struct vsctl_table_class *table;
2845     const struct ovsdb_idl_row *row;
2846     int i;
2847
2848     table = get_table(table_name);
2849     row = must_get_row(ctx, table, record_id);
2850     for (i = 3; i < ctx->argc; i++) {
2851         set_column(table, row, ctx->argv[i], ctx->symtab);
2852     }
2853 }
2854
2855 static void
2856 pre_cmd_add(struct vsctl_context *ctx)
2857 {
2858     const char *table_name = ctx->argv[1];
2859     const char *column_name = ctx->argv[3];
2860     const struct vsctl_table_class *table;
2861     const struct ovsdb_idl_column *column;
2862
2863     table = pre_get_table(ctx, table_name);
2864     pre_get_column(ctx, table, column_name, &column);
2865 }
2866
2867 static void
2868 cmd_add(struct vsctl_context *ctx)
2869 {
2870     const char *table_name = ctx->argv[1];
2871     const char *record_id = ctx->argv[2];
2872     const char *column_name = ctx->argv[3];
2873     const struct vsctl_table_class *table;
2874     const struct ovsdb_idl_column *column;
2875     const struct ovsdb_idl_row *row;
2876     const struct ovsdb_type *type;
2877     struct ovsdb_datum old;
2878     int i;
2879
2880     table = get_table(table_name);
2881     row = must_get_row(ctx, table, record_id);
2882     die_if_error(get_column(table, column_name, &column));
2883
2884     type = &column->type;
2885     ovsdb_datum_clone(&old, ovsdb_idl_read(row, column), &column->type);
2886     for (i = 4; i < ctx->argc; i++) {
2887         struct ovsdb_type add_type;
2888         struct ovsdb_datum add;
2889
2890         add_type = *type;
2891         add_type.n_min = 1;
2892         add_type.n_max = UINT_MAX;
2893         die_if_error(ovsdb_datum_from_string(&add, &add_type, ctx->argv[i],
2894                                              ctx->symtab));
2895         ovsdb_datum_union(&old, &add, type, false);
2896         ovsdb_datum_destroy(&add, type);
2897     }
2898     if (old.n > type->n_max) {
2899         vsctl_fatal("\"add\" operation would put %u %s in column %s of "
2900                     "table %s but the maximum number is %u",
2901                     old.n,
2902                     type->value.type == OVSDB_TYPE_VOID ? "values" : "pairs",
2903                     column->name, table->class->name, type->n_max);
2904     }
2905     ovsdb_idl_txn_verify(row, column);
2906     ovsdb_idl_txn_write(row, column, &old);
2907 }
2908
2909 static void
2910 pre_cmd_remove(struct vsctl_context *ctx)
2911 {
2912     const char *table_name = ctx->argv[1];
2913     const char *column_name = ctx->argv[3];
2914     const struct vsctl_table_class *table;
2915     const struct ovsdb_idl_column *column;
2916
2917     table = pre_get_table(ctx, table_name);
2918     pre_get_column(ctx, table, column_name, &column);
2919 }
2920
2921 static void
2922 cmd_remove(struct vsctl_context *ctx)
2923 {
2924     const char *table_name = ctx->argv[1];
2925     const char *record_id = ctx->argv[2];
2926     const char *column_name = ctx->argv[3];
2927     const struct vsctl_table_class *table;
2928     const struct ovsdb_idl_column *column;
2929     const struct ovsdb_idl_row *row;
2930     const struct ovsdb_type *type;
2931     struct ovsdb_datum old;
2932     int i;
2933
2934     table = get_table(table_name);
2935     row = must_get_row(ctx, table, record_id);
2936     die_if_error(get_column(table, column_name, &column));
2937
2938     type = &column->type;
2939     ovsdb_datum_clone(&old, ovsdb_idl_read(row, column), &column->type);
2940     for (i = 4; i < ctx->argc; i++) {
2941         struct ovsdb_type rm_type;
2942         struct ovsdb_datum rm;
2943         char *error;
2944
2945         rm_type = *type;
2946         rm_type.n_min = 1;
2947         rm_type.n_max = UINT_MAX;
2948         error = ovsdb_datum_from_string(&rm, &rm_type,
2949                                         ctx->argv[i], ctx->symtab);
2950         if (error && ovsdb_type_is_map(&rm_type)) {
2951             free(error);
2952             rm_type.value.type = OVSDB_TYPE_VOID;
2953             die_if_error(ovsdb_datum_from_string(&rm, &rm_type,
2954                                                  ctx->argv[i], ctx->symtab));
2955         }
2956         ovsdb_datum_subtract(&old, type, &rm, &rm_type);
2957         ovsdb_datum_destroy(&rm, &rm_type);
2958     }
2959     if (old.n < type->n_min) {
2960         vsctl_fatal("\"remove\" operation would put %u %s in column %s of "
2961                     "table %s but the minimum number is %u",
2962                     old.n,
2963                     type->value.type == OVSDB_TYPE_VOID ? "values" : "pairs",
2964                     column->name, table->class->name, type->n_min);
2965     }
2966     ovsdb_idl_txn_verify(row, column);
2967     ovsdb_idl_txn_write(row, column, &old);
2968 }
2969
2970 static void
2971 pre_cmd_clear(struct vsctl_context *ctx)
2972 {
2973     const char *table_name = ctx->argv[1];
2974     const struct vsctl_table_class *table;
2975     int i;
2976
2977     table = pre_get_table(ctx, table_name);
2978     for (i = 3; i < ctx->argc; i++) {
2979         const struct ovsdb_idl_column *column;
2980
2981         pre_get_column(ctx, table, ctx->argv[i], &column);
2982     }
2983 }
2984
2985 static void
2986 cmd_clear(struct vsctl_context *ctx)
2987 {
2988     const char *table_name = ctx->argv[1];
2989     const char *record_id = ctx->argv[2];
2990     const struct vsctl_table_class *table;
2991     const struct ovsdb_idl_row *row;
2992     int i;
2993
2994     table = get_table(table_name);
2995     row = must_get_row(ctx, table, record_id);
2996     for (i = 3; i < ctx->argc; i++) {
2997         const struct ovsdb_idl_column *column;
2998         const struct ovsdb_type *type;
2999         struct ovsdb_datum datum;
3000
3001         die_if_error(get_column(table, ctx->argv[i], &column));
3002
3003         type = &column->type;
3004         if (type->n_min > 0) {
3005             vsctl_fatal("\"clear\" operation cannot be applied to column %s "
3006                         "of table %s, which is not allowed to be empty",
3007                         column->name, table->class->name);
3008         }
3009
3010         ovsdb_datum_init_empty(&datum);
3011         ovsdb_idl_txn_write(row, column, &datum);
3012     }
3013 }
3014
3015 static void
3016 pre_create(struct vsctl_context *ctx)
3017 {
3018     const char *id = shash_find_data(&ctx->options, "--id");
3019     const char *table_name = ctx->argv[1];
3020     const struct vsctl_table_class *table;
3021
3022     table = get_table(table_name);
3023     if (!id && !table->class->is_root) {
3024         VLOG_WARN("applying \"create\" command to table %s without --id "
3025                   "option will have no effect", table->class->name);
3026     }
3027 }
3028
3029 static void
3030 cmd_create(struct vsctl_context *ctx)
3031 {
3032     const char *id = shash_find_data(&ctx->options, "--id");
3033     const char *table_name = ctx->argv[1];
3034     const struct vsctl_table_class *table = get_table(table_name);
3035     const struct ovsdb_idl_row *row;
3036     const struct uuid *uuid;
3037     int i;
3038
3039     if (id) {
3040         struct ovsdb_symbol *symbol = create_symbol(ctx->symtab, id, NULL);
3041         if (table->class->is_root) {
3042             /* This table is in the root set, meaning that rows created in it
3043              * won't disappear even if they are unreferenced, so disable
3044              * warnings about that by pretending that there is a reference. */
3045             symbol->strong_ref = true;
3046         }
3047         uuid = &symbol->uuid;
3048     } else {
3049         uuid = NULL;
3050     }
3051
3052     row = ovsdb_idl_txn_insert(ctx->txn, table->class, uuid);
3053     for (i = 2; i < ctx->argc; i++) {
3054         set_column(table, row, ctx->argv[i], ctx->symtab);
3055     }
3056     ds_put_format(&ctx->output, UUID_FMT, UUID_ARGS(&row->uuid));
3057 }
3058
3059 /* This function may be used as the 'postprocess' function for commands that
3060  * insert new rows into the database.  It expects that the command's 'run'
3061  * function prints the UUID reported by ovsdb_idl_txn_insert() as the command's
3062  * sole output.  It replaces that output by the row's permanent UUID assigned
3063  * by the database server and appends a new-line.
3064  *
3065  * Currently we use this only for "create", because the higher-level commands
3066  * are supposed to be independent of the actual structure of the vswitch
3067  * configuration. */
3068 static void
3069 post_create(struct vsctl_context *ctx)
3070 {
3071     const struct uuid *real;
3072     struct uuid dummy;
3073
3074     if (!uuid_from_string(&dummy, ds_cstr(&ctx->output))) {
3075         NOT_REACHED();
3076     }
3077     real = ovsdb_idl_txn_get_insert_uuid(ctx->txn, &dummy);
3078     if (real) {
3079         ds_clear(&ctx->output);
3080         ds_put_format(&ctx->output, UUID_FMT, UUID_ARGS(real));
3081     }
3082     ds_put_char(&ctx->output, '\n');
3083 }
3084
3085 static void
3086 pre_cmd_destroy(struct vsctl_context *ctx)
3087 {
3088     const char *table_name = ctx->argv[1];
3089
3090     pre_get_table(ctx, table_name);
3091 }
3092
3093 static void
3094 cmd_destroy(struct vsctl_context *ctx)
3095 {
3096     bool must_exist = !shash_find(&ctx->options, "--if-exists");
3097     const char *table_name = ctx->argv[1];
3098     const struct vsctl_table_class *table;
3099     int i;
3100
3101     table = get_table(table_name);
3102     for (i = 2; i < ctx->argc; i++) {
3103         const struct ovsdb_idl_row *row;
3104
3105         row = (must_exist ? must_get_row : get_row)(ctx, table, ctx->argv[i]);
3106         if (row) {
3107             ovsdb_idl_txn_delete(row);
3108         }
3109     }
3110 }
3111
3112 static bool
3113 is_condition_satisfied(const struct vsctl_table_class *table,
3114                        const struct ovsdb_idl_row *row, const char *arg,
3115                        struct ovsdb_symbol_table *symtab)
3116 {
3117     static const char *operators[] = {
3118         "=", "!=", "<", ">", "<=", ">="
3119     };
3120
3121     const struct ovsdb_idl_column *column;
3122     const struct ovsdb_datum *have_datum;
3123     char *key_string, *value_string;
3124     const char *operator;
3125     unsigned int idx;
3126     char *error;
3127     int cmp = 0;
3128
3129     error = parse_column_key_value(arg, table, &column, &key_string,
3130                                    &operator, operators, ARRAY_SIZE(operators),
3131                                    &value_string);
3132     die_if_error(error);
3133     if (!value_string) {
3134         vsctl_fatal("%s: missing value", arg);
3135     }
3136
3137     have_datum = ovsdb_idl_read(row, column);
3138     if (key_string) {
3139         union ovsdb_atom want_key, want_value;
3140
3141         if (column->type.value.type == OVSDB_TYPE_VOID) {
3142             vsctl_fatal("cannot specify key to check for non-map column %s",
3143                         column->name);
3144         }
3145
3146         die_if_error(ovsdb_atom_from_string(&want_key, &column->type.key,
3147                                             key_string, symtab));
3148         die_if_error(ovsdb_atom_from_string(&want_value, &column->type.value,
3149                                             value_string, symtab));
3150
3151         idx = ovsdb_datum_find_key(have_datum,
3152                                    &want_key, column->type.key.type);
3153         if (idx != UINT_MAX) {
3154             cmp = ovsdb_atom_compare_3way(&have_datum->values[idx],
3155                                           &want_value,
3156                                           column->type.value.type);
3157         }
3158
3159         ovsdb_atom_destroy(&want_key, column->type.key.type);
3160         ovsdb_atom_destroy(&want_value, column->type.value.type);
3161     } else {
3162         struct ovsdb_datum want_datum;
3163
3164         die_if_error(ovsdb_datum_from_string(&want_datum, &column->type,
3165                                              value_string, symtab));
3166         idx = 0;
3167         cmp = ovsdb_datum_compare_3way(have_datum, &want_datum,
3168                                        &column->type);
3169         ovsdb_datum_destroy(&want_datum, &column->type);
3170     }
3171
3172     free(key_string);
3173     free(value_string);
3174
3175     return (idx == UINT_MAX ? false
3176             : !strcmp(operator, "=") ? cmp == 0
3177             : !strcmp(operator, "!=") ? cmp != 0
3178             : !strcmp(operator, "<") ? cmp < 0
3179             : !strcmp(operator, ">") ? cmp > 0
3180             : !strcmp(operator, "<=") ? cmp <= 0
3181             : !strcmp(operator, ">=") ? cmp >= 0
3182             : (abort(), 0));
3183 }
3184
3185 static void
3186 pre_cmd_wait_until(struct vsctl_context *ctx)
3187 {
3188     const char *table_name = ctx->argv[1];
3189     const struct vsctl_table_class *table;
3190     int i;
3191
3192     table = pre_get_table(ctx, table_name);
3193
3194     for (i = 3; i < ctx->argc; i++) {
3195         pre_parse_column_key_value(ctx, ctx->argv[i], table);
3196     }
3197 }
3198
3199 static void
3200 cmd_wait_until(struct vsctl_context *ctx)
3201 {
3202     const char *table_name = ctx->argv[1];
3203     const char *record_id = ctx->argv[2];
3204     const struct vsctl_table_class *table;
3205     const struct ovsdb_idl_row *row;
3206     int i;
3207
3208     table = get_table(table_name);
3209
3210     row = get_row(ctx, table, record_id);
3211     if (!row) {
3212         ctx->try_again = true;
3213         return;
3214     }
3215
3216     for (i = 3; i < ctx->argc; i++) {
3217         if (!is_condition_satisfied(table, row, ctx->argv[i], ctx->symtab)) {
3218             ctx->try_again = true;
3219             return;
3220         }
3221     }
3222 }
3223 \f
3224 static struct json *
3225 where_uuid_equals(const struct uuid *uuid)
3226 {
3227     return
3228         json_array_create_1(
3229             json_array_create_3(
3230                 json_string_create("_uuid"),
3231                 json_string_create("=="),
3232                 json_array_create_2(
3233                     json_string_create("uuid"),
3234                     json_string_create_nocopy(
3235                         xasprintf(UUID_FMT, UUID_ARGS(uuid))))));
3236 }
3237
3238 static void
3239 vsctl_context_init(struct vsctl_context *ctx, struct vsctl_command *command,
3240                    struct ovsdb_idl *idl, struct ovsdb_idl_txn *txn,
3241                    const struct ovsrec_open_vswitch *ovs,
3242                    struct ovsdb_symbol_table *symtab)
3243 {
3244     ctx->argc = command->argc;
3245     ctx->argv = command->argv;
3246     ctx->options = command->options;
3247
3248     ds_swap(&ctx->output, &command->output);
3249     ctx->table = command->table;
3250     ctx->idl = idl;
3251     ctx->txn = txn;
3252     ctx->ovs = ovs;
3253     ctx->symtab = symtab;
3254     ctx->verified_ports = false;
3255
3256     ctx->try_again = false;
3257 }
3258
3259 static void
3260 vsctl_context_done(struct vsctl_context *ctx, struct vsctl_command *command)
3261 {
3262     ds_swap(&ctx->output, &command->output);
3263     command->table = ctx->table;
3264 }
3265
3266 static void
3267 run_prerequisites(struct vsctl_command *commands, size_t n_commands,
3268                   struct ovsdb_idl *idl)
3269 {
3270     struct vsctl_command *c;
3271
3272     ovsdb_idl_add_table(idl, &ovsrec_table_open_vswitch);
3273     if (wait_for_reload) {
3274         ovsdb_idl_add_column(idl, &ovsrec_open_vswitch_col_cur_cfg);
3275     }
3276     for (c = commands; c < &commands[n_commands]; c++) {
3277         if (c->syntax->prerequisites) {
3278             struct vsctl_context ctx;
3279
3280             ds_init(&c->output);
3281             c->table = NULL;
3282
3283             vsctl_context_init(&ctx, c, idl, NULL, NULL, NULL);
3284             (c->syntax->prerequisites)(&ctx);
3285             vsctl_context_done(&ctx, c);
3286
3287             assert(!c->output.string);
3288             assert(!c->table);
3289         }
3290     }
3291 }
3292
3293 static void
3294 do_vsctl(const char *args, struct vsctl_command *commands, size_t n_commands,
3295          struct ovsdb_idl *idl)
3296 {
3297     struct ovsdb_idl_txn *txn;
3298     const struct ovsrec_open_vswitch *ovs;
3299     enum ovsdb_idl_txn_status status;
3300     struct ovsdb_symbol_table *symtab;
3301     struct vsctl_command *c;
3302     struct shash_node *node;
3303     int64_t next_cfg = 0;
3304     char *error = NULL;
3305
3306     txn = the_idl_txn = ovsdb_idl_txn_create(idl);
3307     if (dry_run) {
3308         ovsdb_idl_txn_set_dry_run(txn);
3309     }
3310
3311     ovsdb_idl_txn_add_comment(txn, "ovs-vsctl: %s", args);
3312
3313     ovs = ovsrec_open_vswitch_first(idl);
3314     if (!ovs) {
3315         /* XXX add verification that table is empty */
3316         ovs = ovsrec_open_vswitch_insert(txn);
3317     }
3318
3319     if (wait_for_reload) {
3320         struct json *where = where_uuid_equals(&ovs->header_.uuid);
3321         ovsdb_idl_txn_increment(txn, "Open_vSwitch", "next_cfg", where);
3322         json_destroy(where);
3323     }
3324
3325     symtab = ovsdb_symbol_table_create();
3326     for (c = commands; c < &commands[n_commands]; c++) {
3327         ds_init(&c->output);
3328         c->table = NULL;
3329     }
3330     for (c = commands; c < &commands[n_commands]; c++) {
3331         struct vsctl_context ctx;
3332
3333         vsctl_context_init(&ctx, c, idl, txn, ovs, symtab);
3334         (c->syntax->run)(&ctx);
3335         vsctl_context_done(&ctx, c);
3336
3337         if (ctx.try_again) {
3338             goto try_again;
3339         }
3340     }
3341
3342     SHASH_FOR_EACH (node, &symtab->sh) {
3343         struct ovsdb_symbol *symbol = node->data;
3344         if (!symbol->created) {
3345             vsctl_fatal("row id \"%s\" is referenced but never created (e.g. "
3346                         "with \"-- --id=%s create ...\")",
3347                         node->name, node->name);
3348         }
3349         if (!symbol->strong_ref) {
3350             if (!symbol->weak_ref) {
3351                 VLOG_WARN("row id \"%s\" was created but no reference to it "
3352                           "was inserted, so it will not actually appear in "
3353                           "the database", node->name);
3354             } else {
3355                 VLOG_WARN("row id \"%s\" was created but only a weak "
3356                           "reference to it was inserted, so it will not "
3357                           "actually appear in the database", node->name);
3358             }
3359         }
3360     }
3361
3362     status = ovsdb_idl_txn_commit_block(txn);
3363     if (wait_for_reload && status == TXN_SUCCESS) {
3364         next_cfg = ovsdb_idl_txn_get_increment_new_value(txn);
3365     }
3366     if (status == TXN_UNCHANGED || status == TXN_SUCCESS) {
3367         for (c = commands; c < &commands[n_commands]; c++) {
3368             if (c->syntax->postprocess) {
3369                 struct vsctl_context ctx;
3370
3371                 vsctl_context_init(&ctx, c, idl, txn, ovs, symtab);
3372                 (c->syntax->postprocess)(&ctx);
3373                 vsctl_context_done(&ctx, c);
3374             }
3375         }
3376     }
3377     error = xstrdup(ovsdb_idl_txn_get_error(txn));
3378     ovsdb_idl_txn_destroy(txn);
3379     txn = the_idl_txn = NULL;
3380
3381     switch (status) {
3382     case TXN_INCOMPLETE:
3383         NOT_REACHED();
3384
3385     case TXN_ABORTED:
3386         /* Should not happen--we never call ovsdb_idl_txn_abort(). */
3387         vsctl_fatal("transaction aborted");
3388
3389     case TXN_UNCHANGED:
3390     case TXN_SUCCESS:
3391         break;
3392
3393     case TXN_TRY_AGAIN:
3394         goto try_again;
3395
3396     case TXN_ERROR:
3397         vsctl_fatal("transaction error: %s", error);
3398
3399     default:
3400         NOT_REACHED();
3401     }
3402     free(error);
3403
3404     ovsdb_symbol_table_destroy(symtab);
3405
3406     for (c = commands; c < &commands[n_commands]; c++) {
3407         struct ds *ds = &c->output;
3408
3409         if (c->table) {
3410             table_print(c->table, &table_style);
3411         } else if (oneline) {
3412             size_t j;
3413
3414             ds_chomp(ds, '\n');
3415             for (j = 0; j < ds->length; j++) {
3416                 int ch = ds->string[j];
3417                 switch (ch) {
3418                 case '\n':
3419                     fputs("\\n", stdout);
3420                     break;
3421
3422                 case '\\':
3423                     fputs("\\\\", stdout);
3424                     break;
3425
3426                 default:
3427                     putchar(ch);
3428                 }
3429             }
3430             putchar('\n');
3431         } else {
3432             fputs(ds_cstr(ds), stdout);
3433         }
3434         ds_destroy(&c->output);
3435         table_destroy(c->table);
3436         free(c->table);
3437
3438         smap_destroy(&c->options);
3439     }
3440     free(commands);
3441
3442     if (wait_for_reload && status != TXN_UNCHANGED) {
3443         for (;;) {
3444             ovsdb_idl_run(idl);
3445             OVSREC_OPEN_VSWITCH_FOR_EACH (ovs, idl) {
3446                 if (ovs->cur_cfg >= next_cfg) {
3447                     goto done;
3448                 }
3449             }
3450             ovsdb_idl_wait(idl);
3451             poll_block();
3452         }
3453     done: ;
3454     }
3455     ovsdb_idl_destroy(idl);
3456
3457     exit(EXIT_SUCCESS);
3458
3459 try_again:
3460     /* Our transaction needs to be rerun, or a prerequisite was not met.  Free
3461      * resources and return so that the caller can try again. */
3462     if (txn) {
3463         ovsdb_idl_txn_abort(txn);
3464         ovsdb_idl_txn_destroy(txn);
3465     }
3466     ovsdb_symbol_table_destroy(symtab);
3467     for (c = commands; c < &commands[n_commands]; c++) {
3468         ds_destroy(&c->output);
3469         table_destroy(c->table);
3470         free(c->table);
3471     }
3472     free(error);
3473 }
3474
3475 static const struct vsctl_command_syntax all_commands[] = {
3476     /* Open vSwitch commands. */
3477     {"init", 0, 0, NULL, cmd_init, NULL, "", RW},
3478
3479     /* Bridge commands. */
3480     {"add-br", 1, 3, pre_get_info, cmd_add_br, NULL, "--may-exist", RW},
3481     {"del-br", 1, 1, pre_get_info, cmd_del_br, NULL, "--if-exists", RW},
3482     {"list-br", 0, 0, pre_get_info, cmd_list_br, NULL, "", RO},
3483     {"br-exists", 1, 1, pre_get_info, cmd_br_exists, NULL, "", RO},
3484     {"br-to-vlan", 1, 1, pre_get_info, cmd_br_to_vlan, NULL, "", RO},
3485     {"br-to-parent", 1, 1, pre_get_info, cmd_br_to_parent, NULL, "", RO},
3486     {"br-set-external-id", 2, 3, pre_cmd_br_set_external_id,
3487      cmd_br_set_external_id, NULL, "", RW},
3488     {"br-get-external-id", 1, 2, pre_cmd_br_get_external_id,
3489      cmd_br_get_external_id, NULL, "", RO},
3490
3491     /* Port commands. */
3492     {"list-ports", 1, 1, pre_get_info, cmd_list_ports, NULL, "", RO},
3493     {"add-port", 2, INT_MAX, pre_get_info, cmd_add_port, NULL, "--may-exist",
3494      RW},
3495     {"add-bond", 4, INT_MAX, pre_get_info, cmd_add_bond, NULL,
3496      "--may-exist,--fake-iface", RW},
3497     {"del-port", 1, 2, pre_get_info, cmd_del_port, NULL,
3498      "--if-exists,--with-iface", RW},
3499     {"port-to-br", 1, 1, pre_get_info, cmd_port_to_br, NULL, "", RO},
3500
3501     /* Interface commands. */
3502     {"list-ifaces", 1, 1, pre_get_info, cmd_list_ifaces, NULL, "", RO},
3503     {"iface-to-br", 1, 1, pre_get_info, cmd_iface_to_br, NULL, "", RO},
3504
3505     /* Controller commands. */
3506     {"get-controller", 1, 1, pre_controller, cmd_get_controller, NULL, "", RO},
3507     {"del-controller", 1, 1, pre_controller, cmd_del_controller, NULL, "", RW},
3508     {"set-controller", 1, INT_MAX, pre_controller, cmd_set_controller, NULL,
3509      "", RW},
3510     {"get-fail-mode", 1, 1, pre_get_info, cmd_get_fail_mode, NULL, "", RO},
3511     {"del-fail-mode", 1, 1, pre_get_info, cmd_del_fail_mode, NULL, "", RW},
3512     {"set-fail-mode", 2, 2, pre_get_info, cmd_set_fail_mode, NULL, "", RW},
3513
3514     /* Manager commands. */
3515     {"get-manager", 0, 0, pre_manager, cmd_get_manager, NULL, "", RO},
3516     {"del-manager", 0, INT_MAX, pre_manager, cmd_del_manager, NULL, "", RW},
3517     {"set-manager", 1, INT_MAX, pre_manager, cmd_set_manager, NULL, "", RW},
3518
3519     /* SSL commands. */
3520     {"get-ssl", 0, 0, pre_cmd_get_ssl, cmd_get_ssl, NULL, "", RO},
3521     {"del-ssl", 0, 0, pre_cmd_del_ssl, cmd_del_ssl, NULL, "", RW},
3522     {"set-ssl", 3, 3, pre_cmd_set_ssl, cmd_set_ssl, NULL, "--bootstrap", RW},
3523
3524     /* Switch commands. */
3525     {"emer-reset", 0, 0, pre_cmd_emer_reset, cmd_emer_reset, NULL, "", RW},
3526
3527     /* Parameter commands. */
3528     {"get", 2, INT_MAX, pre_cmd_get, cmd_get, NULL, "--if-exists,--id=", RO},
3529     {"list", 1, INT_MAX, pre_cmd_list, cmd_list, NULL, "--columns=", RO},
3530     {"find", 1, INT_MAX, pre_cmd_find, cmd_find, NULL, "--columns=", RO},
3531     {"set", 3, INT_MAX, pre_cmd_set, cmd_set, NULL, "", RW},
3532     {"add", 4, INT_MAX, pre_cmd_add, cmd_add, NULL, "", RW},
3533     {"remove", 4, INT_MAX, pre_cmd_remove, cmd_remove, NULL, "", RW},
3534     {"clear", 3, INT_MAX, pre_cmd_clear, cmd_clear, NULL, "", RW},
3535     {"create", 2, INT_MAX, pre_create, cmd_create, post_create, "--id=", RW},
3536     {"destroy", 1, INT_MAX, pre_cmd_destroy, cmd_destroy, NULL, "--if-exists",
3537      RW},
3538     {"wait-until", 2, INT_MAX, pre_cmd_wait_until, cmd_wait_until, NULL, "",
3539      RO},
3540
3541     {NULL, 0, 0, NULL, NULL, NULL, NULL, RO},
3542 };
3543