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