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