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