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