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