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