af1cfc0d5394be38a6fa3d76cf8b74488a9a4836
[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 = 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     ovsdb_idl_add_column(ctx->idl, &ovsrec_bridge_col_auto_attach);
1189
1190     ovsdb_idl_add_column(ctx->idl, &ovsrec_port_col_name);
1191     ovsdb_idl_add_column(ctx->idl, &ovsrec_port_col_fake_bridge);
1192     ovsdb_idl_add_column(ctx->idl, &ovsrec_port_col_tag);
1193     ovsdb_idl_add_column(ctx->idl, &ovsrec_port_col_interfaces);
1194
1195     ovsdb_idl_add_column(ctx->idl, &ovsrec_interface_col_name);
1196
1197     ovsdb_idl_add_column(ctx->idl, &ovsrec_autoattach_col_mappings);
1198     ovsdb_idl_add_column(ctx->idl, &ovsrec_interface_col_ofport);
1199 }
1200
1201 static void
1202 vsctl_context_populate_cache(struct vsctl_context *ctx)
1203 {
1204     const struct ovsrec_open_vswitch *ovs = ctx->ovs;
1205     struct sset bridges, ports;
1206     size_t i;
1207
1208     if (ctx->cache_valid) {
1209         /* Cache is already populated. */
1210         return;
1211     }
1212     ctx->cache_valid = true;
1213     shash_init(&ctx->bridges);
1214     shash_init(&ctx->ports);
1215     shash_init(&ctx->ifaces);
1216
1217     sset_init(&bridges);
1218     sset_init(&ports);
1219     for (i = 0; i < ovs->n_bridges; i++) {
1220         struct ovsrec_bridge *br_cfg = ovs->bridges[i];
1221         struct vsctl_bridge *br;
1222         size_t j;
1223
1224         if (!sset_add(&bridges, br_cfg->name)) {
1225             VLOG_WARN("%s: database contains duplicate bridge name",
1226                       br_cfg->name);
1227             continue;
1228         }
1229         br = add_bridge_to_cache(ctx, br_cfg, br_cfg->name, NULL, 0);
1230         if (!br) {
1231             continue;
1232         }
1233
1234         for (j = 0; j < br_cfg->n_ports; j++) {
1235             struct ovsrec_port *port_cfg = br_cfg->ports[j];
1236
1237             if (!sset_add(&ports, port_cfg->name)) {
1238                 /* Duplicate port name.  (We will warn about that later.) */
1239                 continue;
1240             }
1241
1242             if (port_is_fake_bridge(port_cfg)
1243                 && sset_add(&bridges, port_cfg->name)) {
1244                 add_bridge_to_cache(ctx, NULL, port_cfg->name, br,
1245                                     *port_cfg->tag);
1246             }
1247         }
1248     }
1249     sset_destroy(&bridges);
1250     sset_destroy(&ports);
1251
1252     sset_init(&bridges);
1253     for (i = 0; i < ovs->n_bridges; i++) {
1254         struct ovsrec_bridge *br_cfg = ovs->bridges[i];
1255         struct vsctl_bridge *br;
1256         size_t j;
1257
1258         if (!sset_add(&bridges, br_cfg->name)) {
1259             continue;
1260         }
1261         br = shash_find_data(&ctx->bridges, br_cfg->name);
1262         for (j = 0; j < br_cfg->n_ports; j++) {
1263             struct ovsrec_port *port_cfg = br_cfg->ports[j];
1264             struct vsctl_port *port;
1265             size_t k;
1266
1267             port = shash_find_data(&ctx->ports, port_cfg->name);
1268             if (port) {
1269                 if (port_cfg == port->port_cfg) {
1270                     VLOG_WARN("%s: port is in multiple bridges (%s and %s)",
1271                               port_cfg->name, br->name, port->bridge->name);
1272                 } else {
1273                     /* Log as an error because this violates the database's
1274                      * uniqueness constraints, so the database server shouldn't
1275                      * have allowed it. */
1276                     VLOG_ERR("%s: database contains duplicate port name",
1277                              port_cfg->name);
1278                 }
1279                 continue;
1280             }
1281
1282             if (port_is_fake_bridge(port_cfg)
1283                 && !sset_add(&bridges, port_cfg->name)) {
1284                 continue;
1285             }
1286
1287             port = add_port_to_cache(ctx, br, port_cfg);
1288             for (k = 0; k < port_cfg->n_interfaces; k++) {
1289                 struct ovsrec_interface *iface_cfg = port_cfg->interfaces[k];
1290                 struct vsctl_iface *iface;
1291
1292                 iface = shash_find_data(&ctx->ifaces, iface_cfg->name);
1293                 if (iface) {
1294                     if (iface_cfg == iface->iface_cfg) {
1295                         VLOG_WARN("%s: interface is in multiple ports "
1296                                   "(%s and %s)",
1297                                   iface_cfg->name,
1298                                   iface->port->port_cfg->name,
1299                                   port->port_cfg->name);
1300                     } else {
1301                         /* Log as an error because this violates the database's
1302                          * uniqueness constraints, so the database server
1303                          * shouldn't have allowed it. */
1304                         VLOG_ERR("%s: database contains duplicate interface "
1305                                  "name", iface_cfg->name);
1306                     }
1307                     continue;
1308                 }
1309
1310                 add_iface_to_cache(ctx, port, iface_cfg);
1311             }
1312         }
1313     }
1314     sset_destroy(&bridges);
1315 }
1316
1317 static void
1318 check_conflicts(struct vsctl_context *ctx, const char *name,
1319                 char *msg)
1320 {
1321     struct vsctl_iface *iface;
1322     struct vsctl_port *port;
1323
1324     verify_ports(ctx);
1325
1326     if (shash_find(&ctx->bridges, name)) {
1327         vsctl_fatal("%s because a bridge named %s already exists",
1328                     msg, name);
1329     }
1330
1331     port = shash_find_data(&ctx->ports, name);
1332     if (port) {
1333         vsctl_fatal("%s because a port named %s already exists on "
1334                     "bridge %s", msg, name, port->bridge->name);
1335     }
1336
1337     iface = shash_find_data(&ctx->ifaces, name);
1338     if (iface) {
1339         vsctl_fatal("%s because an interface named %s already exists "
1340                     "on bridge %s", msg, name, iface->port->bridge->name);
1341     }
1342
1343     free(msg);
1344 }
1345
1346 static struct vsctl_bridge *
1347 find_bridge(struct vsctl_context *ctx, const char *name, bool must_exist)
1348 {
1349     struct vsctl_bridge *br;
1350
1351     ovs_assert(ctx->cache_valid);
1352
1353     br = shash_find_data(&ctx->bridges, name);
1354     if (must_exist && !br) {
1355         vsctl_fatal("no bridge named %s", name);
1356     }
1357     ovsrec_open_vswitch_verify_bridges(ctx->ovs);
1358     return br;
1359 }
1360
1361 static struct vsctl_bridge *
1362 find_real_bridge(struct vsctl_context *ctx, const char *name, bool must_exist)
1363 {
1364     struct vsctl_bridge *br = find_bridge(ctx, name, must_exist);
1365     if (br && br->parent) {
1366         vsctl_fatal("%s is a fake bridge", name);
1367     }
1368     return br;
1369 }
1370
1371 static struct vsctl_port *
1372 find_port(struct vsctl_context *ctx, const char *name, bool must_exist)
1373 {
1374     struct vsctl_port *port;
1375
1376     ovs_assert(ctx->cache_valid);
1377
1378     port = shash_find_data(&ctx->ports, name);
1379     if (port && !strcmp(name, port->bridge->name)) {
1380         port = NULL;
1381     }
1382     if (must_exist && !port) {
1383         vsctl_fatal("no port named %s", name);
1384     }
1385     verify_ports(ctx);
1386     return port;
1387 }
1388
1389 static struct vsctl_iface *
1390 find_iface(struct vsctl_context *ctx, const char *name, bool must_exist)
1391 {
1392     struct vsctl_iface *iface;
1393
1394     ovs_assert(ctx->cache_valid);
1395
1396     iface = shash_find_data(&ctx->ifaces, name);
1397     if (iface && !strcmp(name, iface->port->bridge->name)) {
1398         iface = NULL;
1399     }
1400     if (must_exist && !iface) {
1401         vsctl_fatal("no interface named %s", name);
1402     }
1403     verify_ports(ctx);
1404     return iface;
1405 }
1406
1407 static void
1408 bridge_insert_port(struct ovsrec_bridge *br, struct ovsrec_port *port)
1409 {
1410     struct ovsrec_port **ports;
1411     size_t i;
1412
1413     ports = xmalloc(sizeof *br->ports * (br->n_ports + 1));
1414     for (i = 0; i < br->n_ports; i++) {
1415         ports[i] = br->ports[i];
1416     }
1417     ports[br->n_ports] = port;
1418     ovsrec_bridge_set_ports(br, ports, br->n_ports + 1);
1419     free(ports);
1420 }
1421
1422 static void
1423 bridge_delete_port(struct ovsrec_bridge *br, struct ovsrec_port *port)
1424 {
1425     struct ovsrec_port **ports;
1426     size_t i, n;
1427
1428     ports = xmalloc(sizeof *br->ports * br->n_ports);
1429     for (i = n = 0; i < br->n_ports; i++) {
1430         if (br->ports[i] != port) {
1431             ports[n++] = br->ports[i];
1432         }
1433     }
1434     ovsrec_bridge_set_ports(br, ports, n);
1435     free(ports);
1436 }
1437
1438 static void
1439 ovs_insert_bridge(const struct ovsrec_open_vswitch *ovs,
1440                   struct ovsrec_bridge *bridge)
1441 {
1442     struct ovsrec_bridge **bridges;
1443     size_t i;
1444
1445     bridges = xmalloc(sizeof *ovs->bridges * (ovs->n_bridges + 1));
1446     for (i = 0; i < ovs->n_bridges; i++) {
1447         bridges[i] = ovs->bridges[i];
1448     }
1449     bridges[ovs->n_bridges] = bridge;
1450     ovsrec_open_vswitch_set_bridges(ovs, bridges, ovs->n_bridges + 1);
1451     free(bridges);
1452 }
1453
1454 static void
1455 cmd_init(struct vsctl_context *ctx OVS_UNUSED)
1456 {
1457 }
1458
1459 struct cmd_show_table {
1460     const struct ovsdb_idl_table_class *table;
1461     const struct ovsdb_idl_column *name_column;
1462     const struct ovsdb_idl_column *columns[3];
1463     bool recurse;
1464 };
1465
1466 static struct cmd_show_table cmd_show_tables[] = {
1467     {&ovsrec_table_open_vswitch,
1468      NULL,
1469      {&ovsrec_open_vswitch_col_manager_options,
1470       &ovsrec_open_vswitch_col_bridges,
1471       &ovsrec_open_vswitch_col_ovs_version},
1472      false},
1473
1474     {&ovsrec_table_bridge,
1475      &ovsrec_bridge_col_name,
1476      {&ovsrec_bridge_col_controller,
1477       &ovsrec_bridge_col_fail_mode,
1478       &ovsrec_bridge_col_ports},
1479      false},
1480
1481     {&ovsrec_table_port,
1482      &ovsrec_port_col_name,
1483      {&ovsrec_port_col_tag,
1484       &ovsrec_port_col_trunks,
1485       &ovsrec_port_col_interfaces},
1486      false},
1487
1488     {&ovsrec_table_interface,
1489      &ovsrec_interface_col_name,
1490      {&ovsrec_interface_col_type,
1491       &ovsrec_interface_col_options,
1492       &ovsrec_interface_col_error},
1493      false},
1494
1495     {&ovsrec_table_controller,
1496      &ovsrec_controller_col_target,
1497      {&ovsrec_controller_col_is_connected,
1498       NULL,
1499       NULL},
1500      false},
1501
1502     {&ovsrec_table_manager,
1503      &ovsrec_manager_col_target,
1504      {&ovsrec_manager_col_is_connected,
1505       NULL,
1506       NULL},
1507      false},
1508 };
1509
1510 static void
1511 pre_cmd_show(struct vsctl_context *ctx)
1512 {
1513     struct cmd_show_table *show;
1514
1515     for (show = cmd_show_tables;
1516          show < &cmd_show_tables[ARRAY_SIZE(cmd_show_tables)];
1517          show++) {
1518         size_t i;
1519
1520         ovsdb_idl_add_table(ctx->idl, show->table);
1521         if (show->name_column) {
1522             ovsdb_idl_add_column(ctx->idl, show->name_column);
1523         }
1524         for (i = 0; i < ARRAY_SIZE(show->columns); i++) {
1525             const struct ovsdb_idl_column *column = show->columns[i];
1526             if (column) {
1527                 ovsdb_idl_add_column(ctx->idl, column);
1528             }
1529         }
1530     }
1531 }
1532
1533 static struct cmd_show_table *
1534 cmd_show_find_table_by_row(const struct ovsdb_idl_row *row)
1535 {
1536     struct cmd_show_table *show;
1537
1538     for (show = cmd_show_tables;
1539          show < &cmd_show_tables[ARRAY_SIZE(cmd_show_tables)];
1540          show++) {
1541         if (show->table == row->table->class) {
1542             return show;
1543         }
1544     }
1545     return NULL;
1546 }
1547
1548 static struct cmd_show_table *
1549 cmd_show_find_table_by_name(const char *name)
1550 {
1551     struct cmd_show_table *show;
1552
1553     for (show = cmd_show_tables;
1554          show < &cmd_show_tables[ARRAY_SIZE(cmd_show_tables)];
1555          show++) {
1556         if (!strcmp(show->table->name, name)) {
1557             return show;
1558         }
1559     }
1560     return NULL;
1561 }
1562
1563 static void
1564 cmd_show_row(struct vsctl_context *ctx, const struct ovsdb_idl_row *row,
1565              int level)
1566 {
1567     struct cmd_show_table *show = cmd_show_find_table_by_row(row);
1568     size_t i;
1569
1570     ds_put_char_multiple(&ctx->output, ' ', level * 4);
1571     if (show && show->name_column) {
1572         const struct ovsdb_datum *datum;
1573
1574         ds_put_format(&ctx->output, "%s ", show->table->name);
1575         datum = ovsdb_idl_read(row, show->name_column);
1576         ovsdb_datum_to_string(datum, &show->name_column->type, &ctx->output);
1577     } else {
1578         ds_put_format(&ctx->output, UUID_FMT, UUID_ARGS(&row->uuid));
1579     }
1580     ds_put_char(&ctx->output, '\n');
1581
1582     if (!show || show->recurse) {
1583         return;
1584     }
1585
1586     show->recurse = true;
1587     for (i = 0; i < ARRAY_SIZE(show->columns); i++) {
1588         const struct ovsdb_idl_column *column = show->columns[i];
1589         const struct ovsdb_datum *datum;
1590
1591         if (!column) {
1592             break;
1593         }
1594
1595         datum = ovsdb_idl_read(row, column);
1596         if (column->type.key.type == OVSDB_TYPE_UUID &&
1597             column->type.key.u.uuid.refTableName) {
1598             struct cmd_show_table *ref_show;
1599             size_t j;
1600
1601             ref_show = cmd_show_find_table_by_name(
1602                 column->type.key.u.uuid.refTableName);
1603             if (ref_show) {
1604                 for (j = 0; j < datum->n; j++) {
1605                     const struct ovsdb_idl_row *ref_row;
1606
1607                     ref_row = ovsdb_idl_get_row_for_uuid(ctx->idl,
1608                                                          ref_show->table,
1609                                                          &datum->keys[j].uuid);
1610                     if (ref_row) {
1611                         cmd_show_row(ctx, ref_row, level + 1);
1612                     }
1613                 }
1614                 continue;
1615             }
1616         }
1617
1618         if (!ovsdb_datum_is_default(datum, &column->type)) {
1619             ds_put_char_multiple(&ctx->output, ' ', (level + 1) * 4);
1620             ds_put_format(&ctx->output, "%s: ", column->name);
1621             ovsdb_datum_to_string(datum, &column->type, &ctx->output);
1622             ds_put_char(&ctx->output, '\n');
1623         }
1624     }
1625     show->recurse = false;
1626 }
1627
1628 static void
1629 cmd_show(struct vsctl_context *ctx)
1630 {
1631     const struct ovsdb_idl_row *row;
1632
1633     for (row = ovsdb_idl_first_row(ctx->idl, cmd_show_tables[0].table);
1634          row; row = ovsdb_idl_next_row(row)) {
1635         cmd_show_row(ctx, row, 0);
1636     }
1637 }
1638
1639 static void
1640 pre_cmd_emer_reset(struct vsctl_context *ctx)
1641 {
1642     ovsdb_idl_add_column(ctx->idl, &ovsrec_open_vswitch_col_manager_options);
1643     ovsdb_idl_add_column(ctx->idl, &ovsrec_open_vswitch_col_ssl);
1644
1645     ovsdb_idl_add_column(ctx->idl, &ovsrec_bridge_col_controller);
1646     ovsdb_idl_add_column(ctx->idl, &ovsrec_bridge_col_fail_mode);
1647     ovsdb_idl_add_column(ctx->idl, &ovsrec_bridge_col_mirrors);
1648     ovsdb_idl_add_column(ctx->idl, &ovsrec_bridge_col_netflow);
1649     ovsdb_idl_add_column(ctx->idl, &ovsrec_bridge_col_sflow);
1650     ovsdb_idl_add_column(ctx->idl, &ovsrec_bridge_col_ipfix);
1651     ovsdb_idl_add_column(ctx->idl, &ovsrec_bridge_col_flood_vlans);
1652     ovsdb_idl_add_column(ctx->idl, &ovsrec_bridge_col_other_config);
1653
1654     ovsdb_idl_add_column(ctx->idl, &ovsrec_port_col_other_config);
1655
1656     ovsdb_idl_add_column(ctx->idl,
1657                           &ovsrec_interface_col_ingress_policing_rate);
1658     ovsdb_idl_add_column(ctx->idl,
1659                           &ovsrec_interface_col_ingress_policing_burst);
1660 }
1661
1662 static void
1663 cmd_emer_reset(struct vsctl_context *ctx)
1664 {
1665     const struct ovsdb_idl *idl = ctx->idl;
1666     const struct ovsrec_bridge *br;
1667     const struct ovsrec_port *port;
1668     const struct ovsrec_interface *iface;
1669     const struct ovsrec_mirror *mirror, *next_mirror;
1670     const struct ovsrec_controller *ctrl, *next_ctrl;
1671     const struct ovsrec_manager *mgr, *next_mgr;
1672     const struct ovsrec_netflow *nf, *next_nf;
1673     const struct ovsrec_ssl *ssl, *next_ssl;
1674     const struct ovsrec_sflow *sflow, *next_sflow;
1675     const struct ovsrec_ipfix *ipfix, *next_ipfix;
1676     const struct ovsrec_flow_sample_collector_set *fscset, *next_fscset;
1677
1678     /* Reset the Open_vSwitch table. */
1679     ovsrec_open_vswitch_set_manager_options(ctx->ovs, NULL, 0);
1680     ovsrec_open_vswitch_set_ssl(ctx->ovs, NULL);
1681
1682     OVSREC_BRIDGE_FOR_EACH (br, idl) {
1683         const char *hwaddr;
1684
1685         ovsrec_bridge_set_controller(br, NULL, 0);
1686         ovsrec_bridge_set_fail_mode(br, NULL);
1687         ovsrec_bridge_set_mirrors(br, NULL, 0);
1688         ovsrec_bridge_set_netflow(br, NULL);
1689         ovsrec_bridge_set_sflow(br, NULL);
1690         ovsrec_bridge_set_ipfix(br, NULL);
1691         ovsrec_bridge_set_flood_vlans(br, NULL, 0);
1692
1693         /* We only want to save the "hwaddr" key from other_config. */
1694         hwaddr = smap_get(&br->other_config, "hwaddr");
1695         if (hwaddr) {
1696             struct smap smap = SMAP_INITIALIZER(&smap);
1697             smap_add(&smap, "hwaddr", hwaddr);
1698             ovsrec_bridge_set_other_config(br, &smap);
1699             smap_destroy(&smap);
1700         } else {
1701             ovsrec_bridge_set_other_config(br, NULL);
1702         }
1703     }
1704
1705     OVSREC_PORT_FOR_EACH (port, idl) {
1706         ovsrec_port_set_other_config(port, NULL);
1707     }
1708
1709     OVSREC_INTERFACE_FOR_EACH (iface, idl) {
1710         /* xxx What do we do about gre/patch devices created by mgr? */
1711
1712         ovsrec_interface_set_ingress_policing_rate(iface, 0);
1713         ovsrec_interface_set_ingress_policing_burst(iface, 0);
1714     }
1715
1716     OVSREC_MIRROR_FOR_EACH_SAFE (mirror, next_mirror, idl) {
1717         ovsrec_mirror_delete(mirror);
1718     }
1719
1720     OVSREC_CONTROLLER_FOR_EACH_SAFE (ctrl, next_ctrl, idl) {
1721         ovsrec_controller_delete(ctrl);
1722     }
1723
1724     OVSREC_MANAGER_FOR_EACH_SAFE (mgr, next_mgr, idl) {
1725         ovsrec_manager_delete(mgr);
1726     }
1727
1728     OVSREC_NETFLOW_FOR_EACH_SAFE (nf, next_nf, idl) {
1729         ovsrec_netflow_delete(nf);
1730     }
1731
1732     OVSREC_SSL_FOR_EACH_SAFE (ssl, next_ssl, idl) {
1733         ovsrec_ssl_delete(ssl);
1734     }
1735
1736     OVSREC_SFLOW_FOR_EACH_SAFE (sflow, next_sflow, idl) {
1737         ovsrec_sflow_delete(sflow);
1738     }
1739
1740     OVSREC_IPFIX_FOR_EACH_SAFE (ipfix, next_ipfix, idl) {
1741         ovsrec_ipfix_delete(ipfix);
1742     }
1743
1744     OVSREC_FLOW_SAMPLE_COLLECTOR_SET_FOR_EACH_SAFE (fscset, next_fscset, idl) {
1745         ovsrec_flow_sample_collector_set_delete(fscset);
1746     }
1747
1748     vsctl_context_invalidate_cache(ctx);
1749 }
1750
1751 static void
1752 cmd_add_br(struct vsctl_context *ctx)
1753 {
1754     bool may_exist = shash_find(&ctx->options, "--may-exist") != NULL;
1755     const char *br_name, *parent_name;
1756     struct ovsrec_interface *iface;
1757     int vlan;
1758
1759     br_name = ctx->argv[1];
1760     if (ctx->argc == 2) {
1761         parent_name = NULL;
1762         vlan = 0;
1763     } else if (ctx->argc == 4) {
1764         parent_name = ctx->argv[2];
1765         vlan = atoi(ctx->argv[3]);
1766         if (vlan < 0 || vlan > 4095) {
1767             vsctl_fatal("%s: vlan must be between 0 and 4095", ctx->argv[0]);
1768         }
1769     } else {
1770         vsctl_fatal("'%s' command takes exactly 1 or 3 arguments",
1771                     ctx->argv[0]);
1772     }
1773
1774     vsctl_context_populate_cache(ctx);
1775     if (may_exist) {
1776         struct vsctl_bridge *br;
1777
1778         br = find_bridge(ctx, br_name, false);
1779         if (br) {
1780             if (!parent_name) {
1781                 if (br->parent) {
1782                     vsctl_fatal("\"--may-exist add-br %s\" but %s is "
1783                                 "a VLAN bridge for VLAN %d",
1784                                 br_name, br_name, br->vlan);
1785                 }
1786             } else {
1787                 if (!br->parent) {
1788                     vsctl_fatal("\"--may-exist add-br %s %s %d\" but %s "
1789                                 "is not a VLAN bridge",
1790                                 br_name, parent_name, vlan, br_name);
1791                 } else if (strcmp(br->parent->name, parent_name)) {
1792                     vsctl_fatal("\"--may-exist add-br %s %s %d\" but %s "
1793                                 "has the wrong parent %s",
1794                                 br_name, parent_name, vlan,
1795                                 br_name, br->parent->name);
1796                 } else if (br->vlan != vlan) {
1797                     vsctl_fatal("\"--may-exist add-br %s %s %d\" but %s "
1798                                 "is a VLAN bridge for the wrong VLAN %d",
1799                                 br_name, parent_name, vlan, br_name, br->vlan);
1800                 }
1801             }
1802             return;
1803         }
1804     }
1805     check_conflicts(ctx, br_name,
1806                     xasprintf("cannot create a bridge named %s", br_name));
1807
1808     if (!parent_name) {
1809         struct ovsrec_port *port;
1810         struct ovsrec_autoattach *aa;
1811         struct ovsrec_bridge *br;
1812
1813         iface = ovsrec_interface_insert(ctx->txn);
1814         ovsrec_interface_set_name(iface, br_name);
1815         ovsrec_interface_set_type(iface, "internal");
1816
1817         port = ovsrec_port_insert(ctx->txn);
1818         ovsrec_port_set_name(port, br_name);
1819         ovsrec_port_set_interfaces(port, &iface, 1);
1820
1821         aa = ovsrec_autoattach_insert(ctx->txn);
1822
1823         br = ovsrec_bridge_insert(ctx->txn);
1824         ovsrec_bridge_set_name(br, br_name);
1825         ovsrec_bridge_set_ports(br, &port, 1);
1826         ovsrec_bridge_set_auto_attach(br, aa);
1827
1828         ovs_insert_bridge(ctx->ovs, br);
1829     } else {
1830         struct vsctl_bridge *conflict;
1831         struct vsctl_bridge *parent;
1832         struct ovsrec_port *port;
1833         struct ovsrec_bridge *br;
1834         int64_t tag = vlan;
1835
1836         parent = find_bridge(ctx, parent_name, false);
1837         if (parent && parent->parent) {
1838             vsctl_fatal("cannot create bridge with fake bridge as parent");
1839         }
1840         if (!parent) {
1841             vsctl_fatal("parent bridge %s does not exist", parent_name);
1842         }
1843         conflict = find_vlan_bridge(parent, vlan);
1844         if (conflict) {
1845             vsctl_fatal("bridge %s already has a child VLAN bridge %s "
1846                         "on VLAN %d", parent_name, conflict->name, vlan);
1847         }
1848         br = parent->br_cfg;
1849
1850         iface = ovsrec_interface_insert(ctx->txn);
1851         ovsrec_interface_set_name(iface, br_name);
1852         ovsrec_interface_set_type(iface, "internal");
1853
1854         port = ovsrec_port_insert(ctx->txn);
1855         ovsrec_port_set_name(port, br_name);
1856         ovsrec_port_set_interfaces(port, &iface, 1);
1857         ovsrec_port_set_fake_bridge(port, true);
1858         ovsrec_port_set_tag(port, &tag, 1);
1859
1860         bridge_insert_port(br, port);
1861     }
1862
1863     post_db_reload_expect_iface(iface);
1864     vsctl_context_invalidate_cache(ctx);
1865 }
1866
1867 static void
1868 del_port(struct vsctl_context *ctx, struct vsctl_port *port)
1869 {
1870     struct vsctl_iface *iface, *next_iface;
1871
1872     bridge_delete_port((port->bridge->parent
1873                         ? port->bridge->parent->br_cfg
1874                         : port->bridge->br_cfg), port->port_cfg);
1875
1876     LIST_FOR_EACH_SAFE (iface, next_iface, ifaces_node, &port->ifaces) {
1877         del_cached_iface(ctx, iface);
1878     }
1879     del_cached_port(ctx, port);
1880 }
1881
1882 static void
1883 del_bridge(struct vsctl_context *ctx, struct vsctl_bridge *br)
1884 {
1885     struct vsctl_bridge *child, *next_child;
1886     struct vsctl_port *port, *next_port;
1887     const struct ovsrec_flow_sample_collector_set *fscset, *next_fscset;
1888
1889     HMAP_FOR_EACH_SAFE (child, next_child, children_node, &br->children) {
1890         del_bridge(ctx, child);
1891     }
1892
1893     LIST_FOR_EACH_SAFE (port, next_port, ports_node, &br->ports) {
1894         del_port(ctx, port);
1895     }
1896
1897     OVSREC_FLOW_SAMPLE_COLLECTOR_SET_FOR_EACH_SAFE (fscset, next_fscset,
1898                                                     ctx->idl) {
1899         if (fscset->bridge == br->br_cfg) {
1900             ovsrec_flow_sample_collector_set_delete(fscset);
1901         }
1902     }
1903
1904     del_cached_bridge(ctx, br);
1905 }
1906
1907 static void
1908 cmd_del_br(struct vsctl_context *ctx)
1909 {
1910     bool must_exist = !shash_find(&ctx->options, "--if-exists");
1911     struct vsctl_bridge *bridge;
1912
1913     vsctl_context_populate_cache(ctx);
1914     bridge = find_bridge(ctx, ctx->argv[1], must_exist);
1915     if (bridge) {
1916         del_bridge(ctx, bridge);
1917     }
1918 }
1919
1920 static void
1921 output_sorted(struct svec *svec, struct ds *output)
1922 {
1923     const char *name;
1924     size_t i;
1925
1926     svec_sort(svec);
1927     SVEC_FOR_EACH (i, name, svec) {
1928         ds_put_format(output, "%s\n", name);
1929     }
1930 }
1931
1932 static void
1933 cmd_list_br(struct vsctl_context *ctx)
1934 {
1935     struct shash_node *node;
1936     struct svec bridges;
1937     bool real = shash_find(&ctx->options, "--real");
1938     bool fake = shash_find(&ctx->options, "--fake");
1939
1940     /* If neither fake nor real were requested, return both. */
1941     if (!real && !fake) {
1942         real = fake = true;
1943     }
1944
1945     vsctl_context_populate_cache(ctx);
1946
1947     svec_init(&bridges);
1948     SHASH_FOR_EACH (node, &ctx->bridges) {
1949         struct vsctl_bridge *br = node->data;
1950
1951         if (br->parent ? fake : real) {
1952             svec_add(&bridges, br->name);
1953         }
1954     }
1955     output_sorted(&bridges, &ctx->output);
1956     svec_destroy(&bridges);
1957 }
1958
1959 static void
1960 cmd_br_exists(struct vsctl_context *ctx)
1961 {
1962     vsctl_context_populate_cache(ctx);
1963     if (!find_bridge(ctx, ctx->argv[1], false)) {
1964         vsctl_exit(2);
1965     }
1966 }
1967
1968 static void
1969 set_external_id(struct smap *old, struct smap *new,
1970                 char *key, char *value)
1971 {
1972     smap_clone(new, old);
1973
1974     if (value) {
1975         smap_replace(new, key, value);
1976     } else {
1977         smap_remove(new, key);
1978     }
1979 }
1980
1981 static void
1982 pre_cmd_br_set_external_id(struct vsctl_context *ctx)
1983 {
1984     pre_get_info(ctx);
1985     ovsdb_idl_add_column(ctx->idl, &ovsrec_bridge_col_external_ids);
1986     ovsdb_idl_add_column(ctx->idl, &ovsrec_port_col_external_ids);
1987 }
1988
1989 static void
1990 cmd_br_set_external_id(struct vsctl_context *ctx)
1991 {
1992     struct vsctl_bridge *bridge;
1993     struct smap new;
1994
1995     vsctl_context_populate_cache(ctx);
1996     bridge = find_bridge(ctx, ctx->argv[1], true);
1997     if (bridge->br_cfg) {
1998
1999         set_external_id(&bridge->br_cfg->external_ids, &new, ctx->argv[2],
2000                         ctx->argc >= 4 ? ctx->argv[3] : NULL);
2001         ovsrec_bridge_verify_external_ids(bridge->br_cfg);
2002         ovsrec_bridge_set_external_ids(bridge->br_cfg, &new);
2003     } else {
2004         char *key = xasprintf("fake-bridge-%s", ctx->argv[2]);
2005         struct vsctl_port *port = shash_find_data(&ctx->ports, ctx->argv[1]);
2006         set_external_id(&port->port_cfg->external_ids, &new,
2007                         key, ctx->argc >= 4 ? ctx->argv[3] : NULL);
2008         ovsrec_port_verify_external_ids(port->port_cfg);
2009         ovsrec_port_set_external_ids(port->port_cfg, &new);
2010         free(key);
2011     }
2012     smap_destroy(&new);
2013 }
2014
2015 static void
2016 get_external_id(struct smap *smap, const char *prefix, const char *key,
2017                 struct ds *output)
2018 {
2019     if (key) {
2020         char *prefix_key = xasprintf("%s%s", prefix, key);
2021         const char *value = smap_get(smap, prefix_key);
2022
2023         if (value) {
2024             ds_put_format(output, "%s\n", value);
2025         }
2026         free(prefix_key);
2027     } else {
2028         const struct smap_node **sorted = smap_sort(smap);
2029         size_t prefix_len = strlen(prefix);
2030         size_t i;
2031
2032         for (i = 0; i < smap_count(smap); i++) {
2033             const struct smap_node *node = sorted[i];
2034             if (!strncmp(node->key, prefix, prefix_len)) {
2035                 ds_put_format(output, "%s=%s\n", node->key + prefix_len,
2036                               node->value);
2037             }
2038         }
2039         free(sorted);
2040     }
2041 }
2042
2043 static void
2044 pre_cmd_br_get_external_id(struct vsctl_context *ctx)
2045 {
2046     pre_cmd_br_set_external_id(ctx);
2047 }
2048
2049 static void
2050 cmd_br_get_external_id(struct vsctl_context *ctx)
2051 {
2052     struct vsctl_bridge *bridge;
2053
2054     vsctl_context_populate_cache(ctx);
2055
2056     bridge = find_bridge(ctx, ctx->argv[1], true);
2057     if (bridge->br_cfg) {
2058         ovsrec_bridge_verify_external_ids(bridge->br_cfg);
2059         get_external_id(&bridge->br_cfg->external_ids, "",
2060                         ctx->argc >= 3 ? ctx->argv[2] : NULL, &ctx->output);
2061     } else {
2062         struct vsctl_port *port = shash_find_data(&ctx->ports, ctx->argv[1]);
2063         ovsrec_port_verify_external_ids(port->port_cfg);
2064         get_external_id(&port->port_cfg->external_ids, "fake-bridge-",
2065                         ctx->argc >= 3 ? ctx->argv[2] : NULL, &ctx->output);
2066     }
2067 }
2068
2069 static void
2070 cmd_list_ports(struct vsctl_context *ctx)
2071 {
2072     struct vsctl_bridge *br;
2073     struct vsctl_port *port;
2074     struct svec ports;
2075
2076     vsctl_context_populate_cache(ctx);
2077     br = find_bridge(ctx, ctx->argv[1], true);
2078     ovsrec_bridge_verify_ports(br->br_cfg ? br->br_cfg : br->parent->br_cfg);
2079
2080     svec_init(&ports);
2081     LIST_FOR_EACH (port, ports_node, &br->ports) {
2082         if (strcmp(port->port_cfg->name, br->name)) {
2083             svec_add(&ports, port->port_cfg->name);
2084         }
2085     }
2086     output_sorted(&ports, &ctx->output);
2087     svec_destroy(&ports);
2088 }
2089
2090 static void
2091 add_port(struct vsctl_context *ctx,
2092          const char *br_name, const char *port_name,
2093          bool may_exist, bool fake_iface,
2094          char *iface_names[], int n_ifaces,
2095          char *settings[], int n_settings)
2096 {
2097     struct vsctl_port *vsctl_port;
2098     struct vsctl_bridge *bridge;
2099     struct ovsrec_interface **ifaces;
2100     struct ovsrec_port *port;
2101     size_t i;
2102
2103     vsctl_context_populate_cache(ctx);
2104     if (may_exist) {
2105         struct vsctl_port *vsctl_port;
2106
2107         vsctl_port = find_port(ctx, port_name, false);
2108         if (vsctl_port) {
2109             struct svec want_names, have_names;
2110
2111             svec_init(&want_names);
2112             for (i = 0; i < n_ifaces; i++) {
2113                 svec_add(&want_names, iface_names[i]);
2114             }
2115             svec_sort(&want_names);
2116
2117             svec_init(&have_names);
2118             for (i = 0; i < vsctl_port->port_cfg->n_interfaces; i++) {
2119                 svec_add(&have_names,
2120                          vsctl_port->port_cfg->interfaces[i]->name);
2121             }
2122             svec_sort(&have_names);
2123
2124             if (strcmp(vsctl_port->bridge->name, br_name)) {
2125                 char *command = vsctl_context_to_string(ctx);
2126                 vsctl_fatal("\"%s\" but %s is actually attached to bridge %s",
2127                             command, port_name, vsctl_port->bridge->name);
2128             }
2129
2130             if (!svec_equal(&want_names, &have_names)) {
2131                 char *have_names_string = svec_join(&have_names, ", ", "");
2132                 char *command = vsctl_context_to_string(ctx);
2133
2134                 vsctl_fatal("\"%s\" but %s actually has interface(s) %s",
2135                             command, port_name, have_names_string);
2136             }
2137
2138             svec_destroy(&want_names);
2139             svec_destroy(&have_names);
2140
2141             return;
2142         }
2143     }
2144     check_conflicts(ctx, port_name,
2145                     xasprintf("cannot create a port named %s", port_name));
2146     for (i = 0; i < n_ifaces; i++) {
2147         check_conflicts(ctx, iface_names[i],
2148                         xasprintf("cannot create an interface named %s",
2149                                   iface_names[i]));
2150     }
2151     bridge = find_bridge(ctx, br_name, true);
2152
2153     ifaces = xmalloc(n_ifaces * sizeof *ifaces);
2154     for (i = 0; i < n_ifaces; i++) {
2155         ifaces[i] = ovsrec_interface_insert(ctx->txn);
2156         ovsrec_interface_set_name(ifaces[i], iface_names[i]);
2157         post_db_reload_expect_iface(ifaces[i]);
2158     }
2159
2160     port = ovsrec_port_insert(ctx->txn);
2161     ovsrec_port_set_name(port, port_name);
2162     ovsrec_port_set_interfaces(port, ifaces, n_ifaces);
2163     ovsrec_port_set_bond_fake_iface(port, fake_iface);
2164
2165     if (bridge->parent) {
2166         int64_t tag = bridge->vlan;
2167         ovsrec_port_set_tag(port, &tag, 1);
2168     }
2169
2170     for (i = 0; i < n_settings; i++) {
2171         set_column(get_table("Port"), &port->header_, settings[i],
2172                    ctx->symtab);
2173     }
2174
2175     bridge_insert_port((bridge->parent ? bridge->parent->br_cfg
2176                         : bridge->br_cfg), port);
2177
2178     vsctl_port = add_port_to_cache(ctx, bridge, port);
2179     for (i = 0; i < n_ifaces; i++) {
2180         add_iface_to_cache(ctx, vsctl_port, ifaces[i]);
2181     }
2182     free(ifaces);
2183 }
2184
2185 static void
2186 cmd_add_port(struct vsctl_context *ctx)
2187 {
2188     bool may_exist = shash_find(&ctx->options, "--may-exist") != NULL;
2189
2190     add_port(ctx, ctx->argv[1], ctx->argv[2], may_exist, false,
2191              &ctx->argv[2], 1, &ctx->argv[3], ctx->argc - 3);
2192 }
2193
2194 static void
2195 cmd_add_bond(struct vsctl_context *ctx)
2196 {
2197     bool may_exist = shash_find(&ctx->options, "--may-exist") != NULL;
2198     bool fake_iface = shash_find(&ctx->options, "--fake-iface");
2199     int n_ifaces;
2200     int i;
2201
2202     n_ifaces = ctx->argc - 3;
2203     for (i = 3; i < ctx->argc; i++) {
2204         if (strchr(ctx->argv[i], '=')) {
2205             n_ifaces = i - 3;
2206             break;
2207         }
2208     }
2209     if (n_ifaces < 2) {
2210         vsctl_fatal("add-bond requires at least 2 interfaces, but only "
2211                     "%d were specified", n_ifaces);
2212     }
2213
2214     add_port(ctx, ctx->argv[1], ctx->argv[2], may_exist, fake_iface,
2215              &ctx->argv[3], n_ifaces,
2216              &ctx->argv[n_ifaces + 3], ctx->argc - 3 - n_ifaces);
2217 }
2218
2219 static void
2220 cmd_del_port(struct vsctl_context *ctx)
2221 {
2222     bool must_exist = !shash_find(&ctx->options, "--if-exists");
2223     bool with_iface = shash_find(&ctx->options, "--with-iface") != NULL;
2224     const char *target = ctx->argv[ctx->argc - 1];
2225     struct vsctl_port *port;
2226
2227     vsctl_context_populate_cache(ctx);
2228     if (find_bridge(ctx, target, false)) {
2229         if (must_exist) {
2230             vsctl_fatal("cannot delete port %s because it is the local port "
2231                         "for bridge %s (deleting this port requires deleting "
2232                         "the entire bridge)", target, target);
2233         }
2234         port = NULL;
2235     } else if (!with_iface) {
2236         port = find_port(ctx, target, must_exist);
2237     } else {
2238         struct vsctl_iface *iface;
2239
2240         port = find_port(ctx, target, false);
2241         if (!port) {
2242             iface = find_iface(ctx, target, false);
2243             if (iface) {
2244                 port = iface->port;
2245             }
2246         }
2247         if (must_exist && !port) {
2248             vsctl_fatal("no port or interface named %s", target);
2249         }
2250     }
2251
2252     if (port) {
2253         if (ctx->argc == 3) {
2254             struct vsctl_bridge *bridge;
2255
2256             bridge = find_bridge(ctx, ctx->argv[1], true);
2257             if (port->bridge != bridge) {
2258                 if (port->bridge->parent == bridge) {
2259                     vsctl_fatal("bridge %s does not have a port %s (although "
2260                                 "its parent bridge %s does)",
2261                                 ctx->argv[1], ctx->argv[2],
2262                                 bridge->parent->name);
2263                 } else {
2264                     vsctl_fatal("bridge %s does not have a port %s",
2265                                 ctx->argv[1], ctx->argv[2]);
2266                 }
2267             }
2268         }
2269
2270         del_port(ctx, port);
2271     }
2272 }
2273
2274 static void
2275 cmd_port_to_br(struct vsctl_context *ctx)
2276 {
2277     struct vsctl_port *port;
2278
2279     vsctl_context_populate_cache(ctx);
2280
2281     port = find_port(ctx, ctx->argv[1], true);
2282     ds_put_format(&ctx->output, "%s\n", port->bridge->name);
2283 }
2284
2285 static void
2286 cmd_br_to_vlan(struct vsctl_context *ctx)
2287 {
2288     struct vsctl_bridge *bridge;
2289
2290     vsctl_context_populate_cache(ctx);
2291
2292     bridge = find_bridge(ctx, ctx->argv[1], true);
2293     ds_put_format(&ctx->output, "%d\n", bridge->vlan);
2294 }
2295
2296 static void
2297 cmd_br_to_parent(struct vsctl_context *ctx)
2298 {
2299     struct vsctl_bridge *bridge;
2300
2301     vsctl_context_populate_cache(ctx);
2302
2303     bridge = find_bridge(ctx, ctx->argv[1], true);
2304     if (bridge->parent) {
2305         bridge = bridge->parent;
2306     }
2307     ds_put_format(&ctx->output, "%s\n", bridge->name);
2308 }
2309
2310 static void
2311 cmd_list_ifaces(struct vsctl_context *ctx)
2312 {
2313     struct vsctl_bridge *br;
2314     struct vsctl_port *port;
2315     struct svec ifaces;
2316
2317     vsctl_context_populate_cache(ctx);
2318
2319     br = find_bridge(ctx, ctx->argv[1], true);
2320     verify_ports(ctx);
2321
2322     svec_init(&ifaces);
2323     LIST_FOR_EACH (port, ports_node, &br->ports) {
2324         struct vsctl_iface *iface;
2325
2326         LIST_FOR_EACH (iface, ifaces_node, &port->ifaces) {
2327             if (strcmp(iface->iface_cfg->name, br->name)) {
2328                 svec_add(&ifaces, iface->iface_cfg->name);
2329             }
2330         }
2331     }
2332     output_sorted(&ifaces, &ctx->output);
2333     svec_destroy(&ifaces);
2334 }
2335
2336 static void
2337 cmd_iface_to_br(struct vsctl_context *ctx)
2338 {
2339     struct vsctl_iface *iface;
2340
2341     vsctl_context_populate_cache(ctx);
2342
2343     iface = find_iface(ctx, ctx->argv[1], true);
2344     ds_put_format(&ctx->output, "%s\n", iface->port->bridge->name);
2345 }
2346
2347 static void
2348 verify_controllers(struct ovsrec_bridge *bridge)
2349 {
2350     size_t i;
2351
2352     ovsrec_bridge_verify_controller(bridge);
2353     for (i = 0; i < bridge->n_controller; i++) {
2354         ovsrec_controller_verify_target(bridge->controller[i]);
2355     }
2356 }
2357
2358 static void
2359 pre_controller(struct vsctl_context *ctx)
2360 {
2361     pre_get_info(ctx);
2362
2363     ovsdb_idl_add_column(ctx->idl, &ovsrec_controller_col_target);
2364 }
2365
2366 static void
2367 cmd_get_controller(struct vsctl_context *ctx)
2368 {
2369     struct vsctl_bridge *br;
2370     struct svec targets;
2371     size_t i;
2372
2373     vsctl_context_populate_cache(ctx);
2374
2375     br = find_bridge(ctx, ctx->argv[1], true);
2376     if (br->parent) {
2377         br = br->parent;
2378     }
2379     verify_controllers(br->br_cfg);
2380
2381     /* Print the targets in sorted order for reproducibility. */
2382     svec_init(&targets);
2383     for (i = 0; i < br->br_cfg->n_controller; i++) {
2384         svec_add(&targets, br->br_cfg->controller[i]->target);
2385     }
2386
2387     svec_sort(&targets);
2388     for (i = 0; i < targets.n; i++) {
2389         ds_put_format(&ctx->output, "%s\n", targets.names[i]);
2390     }
2391     svec_destroy(&targets);
2392 }
2393
2394 static void
2395 delete_controllers(struct ovsrec_controller **controllers,
2396                    size_t n_controllers)
2397 {
2398     size_t i;
2399
2400     for (i = 0; i < n_controllers; i++) {
2401         ovsrec_controller_delete(controllers[i]);
2402     }
2403 }
2404
2405 static void
2406 cmd_del_controller(struct vsctl_context *ctx)
2407 {
2408     struct ovsrec_bridge *br;
2409
2410     vsctl_context_populate_cache(ctx);
2411
2412     br = find_real_bridge(ctx, ctx->argv[1], true)->br_cfg;
2413     verify_controllers(br);
2414
2415     if (br->controller) {
2416         delete_controllers(br->controller, br->n_controller);
2417         ovsrec_bridge_set_controller(br, NULL, 0);
2418     }
2419 }
2420
2421 static struct ovsrec_controller **
2422 insert_controllers(struct ovsdb_idl_txn *txn, char *targets[], size_t n)
2423 {
2424     struct ovsrec_controller **controllers;
2425     size_t i;
2426
2427     controllers = xmalloc(n * sizeof *controllers);
2428     for (i = 0; i < n; i++) {
2429         if (vconn_verify_name(targets[i]) && pvconn_verify_name(targets[i])) {
2430             VLOG_WARN("target type \"%s\" is possibly erroneous", targets[i]);
2431         }
2432         controllers[i] = ovsrec_controller_insert(txn);
2433         ovsrec_controller_set_target(controllers[i], targets[i]);
2434     }
2435
2436     return controllers;
2437 }
2438
2439 static void
2440 cmd_set_controller(struct vsctl_context *ctx)
2441 {
2442     struct ovsrec_controller **controllers;
2443     struct ovsrec_bridge *br;
2444     size_t n;
2445
2446     vsctl_context_populate_cache(ctx);
2447
2448     br = find_real_bridge(ctx, ctx->argv[1], true)->br_cfg;
2449     verify_controllers(br);
2450
2451     delete_controllers(br->controller, br->n_controller);
2452
2453     n = ctx->argc - 2;
2454     controllers = insert_controllers(ctx->txn, &ctx->argv[2], n);
2455     ovsrec_bridge_set_controller(br, controllers, n);
2456     free(controllers);
2457 }
2458
2459 static void
2460 cmd_get_fail_mode(struct vsctl_context *ctx)
2461 {
2462     struct vsctl_bridge *br;
2463     const char *fail_mode;
2464
2465     vsctl_context_populate_cache(ctx);
2466     br = find_bridge(ctx, ctx->argv[1], true);
2467
2468     if (br->parent) {
2469         br = br->parent;
2470     }
2471     ovsrec_bridge_verify_fail_mode(br->br_cfg);
2472
2473     fail_mode = br->br_cfg->fail_mode;
2474     if (fail_mode && strlen(fail_mode)) {
2475         ds_put_format(&ctx->output, "%s\n", fail_mode);
2476     }
2477 }
2478
2479 static void
2480 cmd_del_fail_mode(struct vsctl_context *ctx)
2481 {
2482     struct vsctl_bridge *br;
2483
2484     vsctl_context_populate_cache(ctx);
2485
2486     br = find_real_bridge(ctx, ctx->argv[1], true);
2487
2488     ovsrec_bridge_set_fail_mode(br->br_cfg, NULL);
2489 }
2490
2491 static void
2492 cmd_set_fail_mode(struct vsctl_context *ctx)
2493 {
2494     struct vsctl_bridge *br;
2495     const char *fail_mode = ctx->argv[2];
2496
2497     vsctl_context_populate_cache(ctx);
2498
2499     br = find_real_bridge(ctx, ctx->argv[1], true);
2500
2501     if (strcmp(fail_mode, "standalone") && strcmp(fail_mode, "secure")) {
2502         vsctl_fatal("fail-mode must be \"standalone\" or \"secure\"");
2503     }
2504
2505     ovsrec_bridge_set_fail_mode(br->br_cfg, fail_mode);
2506 }
2507
2508 static void
2509 verify_managers(const struct ovsrec_open_vswitch *ovs)
2510 {
2511     size_t i;
2512
2513     ovsrec_open_vswitch_verify_manager_options(ovs);
2514
2515     for (i = 0; i < ovs->n_manager_options; ++i) {
2516         const struct ovsrec_manager *mgr = ovs->manager_options[i];
2517
2518         ovsrec_manager_verify_target(mgr);
2519     }
2520 }
2521
2522 static void
2523 pre_manager(struct vsctl_context *ctx)
2524 {
2525     ovsdb_idl_add_column(ctx->idl, &ovsrec_open_vswitch_col_manager_options);
2526     ovsdb_idl_add_column(ctx->idl, &ovsrec_manager_col_target);
2527 }
2528
2529 static void
2530 cmd_get_manager(struct vsctl_context *ctx)
2531 {
2532     const struct ovsrec_open_vswitch *ovs = ctx->ovs;
2533     struct svec targets;
2534     size_t i;
2535
2536     verify_managers(ovs);
2537
2538     /* Print the targets in sorted order for reproducibility. */
2539     svec_init(&targets);
2540
2541     for (i = 0; i < ovs->n_manager_options; i++) {
2542         svec_add(&targets, ovs->manager_options[i]->target);
2543     }
2544
2545     svec_sort_unique(&targets);
2546     for (i = 0; i < targets.n; i++) {
2547         ds_put_format(&ctx->output, "%s\n", targets.names[i]);
2548     }
2549     svec_destroy(&targets);
2550 }
2551
2552 static void
2553 delete_managers(const struct vsctl_context *ctx)
2554 {
2555     const struct ovsrec_open_vswitch *ovs = ctx->ovs;
2556     size_t i;
2557
2558     /* Delete Manager rows pointed to by 'manager_options' column. */
2559     for (i = 0; i < ovs->n_manager_options; i++) {
2560         ovsrec_manager_delete(ovs->manager_options[i]);
2561     }
2562
2563     /* Delete 'Manager' row refs in 'manager_options' column. */
2564     ovsrec_open_vswitch_set_manager_options(ovs, NULL, 0);
2565 }
2566
2567 static void
2568 cmd_del_manager(struct vsctl_context *ctx)
2569 {
2570     const struct ovsrec_open_vswitch *ovs = ctx->ovs;
2571
2572     verify_managers(ovs);
2573     delete_managers(ctx);
2574 }
2575
2576 static void
2577 insert_managers(struct vsctl_context *ctx, char *targets[], size_t n)
2578 {
2579     struct ovsrec_manager **managers;
2580     size_t i;
2581
2582     /* Insert each manager in a new row in Manager table. */
2583     managers = xmalloc(n * sizeof *managers);
2584     for (i = 0; i < n; i++) {
2585         if (stream_verify_name(targets[i]) && pstream_verify_name(targets[i])) {
2586             VLOG_WARN("target type \"%s\" is possibly erroneous", targets[i]);
2587         }
2588         managers[i] = ovsrec_manager_insert(ctx->txn);
2589         ovsrec_manager_set_target(managers[i], targets[i]);
2590     }
2591
2592     /* Store uuids of new Manager rows in 'manager_options' column. */
2593     ovsrec_open_vswitch_set_manager_options(ctx->ovs, managers, n);
2594     free(managers);
2595 }
2596
2597 static void
2598 cmd_set_manager(struct vsctl_context *ctx)
2599 {
2600     const size_t n = ctx->argc - 1;
2601
2602     verify_managers(ctx->ovs);
2603     delete_managers(ctx);
2604     insert_managers(ctx, &ctx->argv[1], n);
2605 }
2606
2607 static void
2608 pre_cmd_get_ssl(struct vsctl_context *ctx)
2609 {
2610     ovsdb_idl_add_column(ctx->idl, &ovsrec_open_vswitch_col_ssl);
2611
2612     ovsdb_idl_add_column(ctx->idl, &ovsrec_ssl_col_private_key);
2613     ovsdb_idl_add_column(ctx->idl, &ovsrec_ssl_col_certificate);
2614     ovsdb_idl_add_column(ctx->idl, &ovsrec_ssl_col_ca_cert);
2615     ovsdb_idl_add_column(ctx->idl, &ovsrec_ssl_col_bootstrap_ca_cert);
2616 }
2617
2618 static void
2619 cmd_get_ssl(struct vsctl_context *ctx)
2620 {
2621     struct ovsrec_ssl *ssl = ctx->ovs->ssl;
2622
2623     ovsrec_open_vswitch_verify_ssl(ctx->ovs);
2624     if (ssl) {
2625         ovsrec_ssl_verify_private_key(ssl);
2626         ovsrec_ssl_verify_certificate(ssl);
2627         ovsrec_ssl_verify_ca_cert(ssl);
2628         ovsrec_ssl_verify_bootstrap_ca_cert(ssl);
2629
2630         ds_put_format(&ctx->output, "Private key: %s\n", ssl->private_key);
2631         ds_put_format(&ctx->output, "Certificate: %s\n", ssl->certificate);
2632         ds_put_format(&ctx->output, "CA Certificate: %s\n", ssl->ca_cert);
2633         ds_put_format(&ctx->output, "Bootstrap: %s\n",
2634                 ssl->bootstrap_ca_cert ? "true" : "false");
2635     }
2636 }
2637
2638 static void
2639 pre_cmd_del_ssl(struct vsctl_context *ctx)
2640 {
2641     ovsdb_idl_add_column(ctx->idl, &ovsrec_open_vswitch_col_ssl);
2642 }
2643
2644 static void
2645 cmd_del_ssl(struct vsctl_context *ctx)
2646 {
2647     struct ovsrec_ssl *ssl = ctx->ovs->ssl;
2648
2649     if (ssl) {
2650         ovsrec_open_vswitch_verify_ssl(ctx->ovs);
2651         ovsrec_ssl_delete(ssl);
2652         ovsrec_open_vswitch_set_ssl(ctx->ovs, NULL);
2653     }
2654 }
2655
2656 static void
2657 pre_cmd_set_ssl(struct vsctl_context *ctx)
2658 {
2659     ovsdb_idl_add_column(ctx->idl, &ovsrec_open_vswitch_col_ssl);
2660 }
2661
2662 static void
2663 cmd_set_ssl(struct vsctl_context *ctx)
2664 {
2665     bool bootstrap = shash_find(&ctx->options, "--bootstrap");
2666     struct ovsrec_ssl *ssl = ctx->ovs->ssl;
2667
2668     ovsrec_open_vswitch_verify_ssl(ctx->ovs);
2669     if (ssl) {
2670         ovsrec_ssl_delete(ssl);
2671     }
2672     ssl = ovsrec_ssl_insert(ctx->txn);
2673
2674     ovsrec_ssl_set_private_key(ssl, ctx->argv[1]);
2675     ovsrec_ssl_set_certificate(ssl, ctx->argv[2]);
2676     ovsrec_ssl_set_ca_cert(ssl, ctx->argv[3]);
2677
2678     ovsrec_ssl_set_bootstrap_ca_cert(ssl, bootstrap);
2679
2680     ovsrec_open_vswitch_set_ssl(ctx->ovs, ssl);
2681 }
2682
2683 static void
2684 autoattach_insert_mapping(struct ovsrec_autoattach *aa,
2685                           int64_t isid,
2686                           int64_t vlan)
2687 {
2688     int64_t *key_mappings, *value_mappings;
2689     size_t i;
2690
2691     key_mappings = xmalloc(sizeof *aa->key_mappings * (aa->n_mappings + 1));
2692     value_mappings = xmalloc(sizeof *aa->value_mappings * (aa->n_mappings + 1));
2693
2694     for (i = 0; i < aa->n_mappings; i++) {
2695         key_mappings[i] = aa->key_mappings[i];
2696         value_mappings[i] = aa->value_mappings[i];
2697     }
2698     key_mappings[aa->n_mappings] = isid;
2699     value_mappings[aa->n_mappings] = vlan;
2700
2701     ovsrec_autoattach_set_mappings(aa, key_mappings, value_mappings,
2702                                    aa->n_mappings + 1);
2703
2704     free(key_mappings);
2705     free(value_mappings);
2706 }
2707
2708 static void
2709 cmd_add_aa_mapping(struct vsctl_context *ctx)
2710 {
2711     struct vsctl_bridge *br;
2712     int64_t isid, vlan;
2713     char *nptr = NULL;
2714
2715     isid = strtoull(ctx->argv[2], &nptr, 10);
2716     if (nptr == ctx->argv[2] || nptr == NULL) {
2717         vsctl_fatal("Invalid argument %s", ctx->argv[2]);
2718         return;
2719     }
2720
2721     vlan = strtoull(ctx->argv[3], &nptr, 10);
2722     if (nptr == ctx->argv[3] || nptr == NULL) {
2723         vsctl_fatal("Invalid argument %s", ctx->argv[3]);
2724         return;
2725     }
2726
2727     vsctl_context_populate_cache(ctx);
2728
2729     br = find_bridge(ctx, ctx->argv[1], true);
2730     if (br->parent) {
2731         br = br->parent;
2732     }
2733
2734     if (br && br->br_cfg) {
2735         autoattach_insert_mapping(br->br_cfg->auto_attach, isid, vlan);
2736     }
2737 }
2738
2739 static void
2740 del_aa_mapping(struct ovsrec_autoattach *aa,
2741                int64_t isid,
2742                int64_t vlan)
2743 {
2744     int64_t *key_mappings, *value_mappings;
2745     size_t i, n;
2746
2747     key_mappings = xmalloc(sizeof *aa->key_mappings * (aa->n_mappings));
2748     value_mappings = xmalloc(sizeof *value_mappings * (aa->n_mappings));
2749
2750     for (i = n = 0; i < aa->n_mappings; i++) {
2751         if (aa->key_mappings[i] != isid && aa->value_mappings[i] != vlan) {
2752             key_mappings[n] = aa->key_mappings[i];
2753             value_mappings[n++] = aa->value_mappings[i];
2754         }
2755     }
2756
2757     ovsrec_autoattach_set_mappings(aa, key_mappings, value_mappings, n);
2758
2759     free(key_mappings);
2760     free(value_mappings);
2761 }
2762
2763 static void
2764 cmd_del_aa_mapping(struct vsctl_context *ctx)
2765 {
2766     struct vsctl_bridge *br;
2767     int64_t isid, vlan;
2768     char *nptr = NULL;
2769
2770     isid = strtoull(ctx->argv[2], &nptr, 10);
2771     if (nptr == ctx->argv[2] || nptr == NULL) {
2772         vsctl_fatal("Invalid argument %s", ctx->argv[2]);
2773         return;
2774     }
2775
2776     vlan = strtoull(ctx->argv[3], &nptr, 10);
2777     if (nptr == ctx->argv[3] || nptr == NULL) {
2778         vsctl_fatal("Invalid argument %s", ctx->argv[3]);
2779         return;
2780     }
2781
2782     vsctl_context_populate_cache(ctx);
2783
2784     br = find_bridge(ctx, ctx->argv[1], true);
2785     if (br->parent) {
2786         br = br->parent;
2787     }
2788
2789     if (br && br->br_cfg && br->br_cfg->auto_attach &&
2790         br->br_cfg->auto_attach->key_mappings &&
2791         br->br_cfg->auto_attach->value_mappings) {
2792         size_t i;
2793
2794         for (i = 0; i < br->br_cfg->auto_attach->n_mappings; i++) {
2795             if (br->br_cfg->auto_attach->key_mappings[i] == isid &&
2796                 br->br_cfg->auto_attach->value_mappings[i] == vlan) {
2797                 del_aa_mapping(br->br_cfg->auto_attach, isid, vlan);
2798                 break;
2799             }
2800         }
2801     }
2802 }
2803
2804 static void
2805 pre_aa_mapping(struct vsctl_context *ctx)
2806 {
2807     pre_get_info(ctx);
2808
2809     ovsdb_idl_add_column(ctx->idl, &ovsrec_autoattach_col_mappings);
2810 }
2811
2812 static void
2813 verify_auto_attach(struct ovsrec_bridge *bridge)
2814 {
2815     if (bridge) {
2816         ovsrec_bridge_verify_auto_attach(bridge);
2817
2818         if (bridge->auto_attach) {
2819             ovsrec_autoattach_verify_mappings(bridge->auto_attach);
2820         }
2821     }
2822 }
2823
2824 static void
2825 cmd_get_aa_mapping(struct vsctl_context *ctx)
2826 {
2827     struct vsctl_bridge *br;
2828
2829     vsctl_context_populate_cache(ctx);
2830
2831     br = find_bridge(ctx, ctx->argv[1], true);
2832     if (br->parent) {
2833         br = br->parent;
2834     }
2835
2836     verify_auto_attach(br->br_cfg);
2837
2838     if (br && br->br_cfg && br->br_cfg->auto_attach &&
2839         br->br_cfg->auto_attach->key_mappings &&
2840         br->br_cfg->auto_attach->value_mappings) {
2841         size_t i;
2842
2843         for (i = 0; i < br->br_cfg->auto_attach->n_mappings; i++) {
2844             ds_put_format(&ctx->output, "%"PRId64" %"PRId64"\n",
2845                           br->br_cfg->auto_attach->key_mappings[i],
2846                           br->br_cfg->auto_attach->value_mappings[i]);
2847         }
2848     }
2849 }
2850
2851 \f
2852 /* Parameter commands. */
2853
2854 struct vsctl_row_id {
2855     const struct ovsdb_idl_table_class *table;
2856     const struct ovsdb_idl_column *name_column;
2857     const struct ovsdb_idl_column *uuid_column;
2858 };
2859
2860 struct vsctl_table_class {
2861     struct ovsdb_idl_table_class *class;
2862     struct vsctl_row_id row_ids[2];
2863 };
2864
2865 static const struct vsctl_table_class tables[] = {
2866     {&ovsrec_table_bridge,
2867      {{&ovsrec_table_bridge, &ovsrec_bridge_col_name, NULL},
2868       {&ovsrec_table_flow_sample_collector_set, NULL,
2869        &ovsrec_flow_sample_collector_set_col_bridge}}},
2870
2871     {&ovsrec_table_controller,
2872      {{&ovsrec_table_bridge,
2873        &ovsrec_bridge_col_name,
2874        &ovsrec_bridge_col_controller}}},
2875
2876     {&ovsrec_table_interface,
2877      {{&ovsrec_table_interface, &ovsrec_interface_col_name, NULL},
2878       {NULL, NULL, NULL}}},
2879
2880     {&ovsrec_table_mirror,
2881      {{&ovsrec_table_mirror, &ovsrec_mirror_col_name, NULL},
2882       {NULL, NULL, NULL}}},
2883
2884     {&ovsrec_table_manager,
2885      {{&ovsrec_table_manager, &ovsrec_manager_col_target, NULL},
2886       {NULL, NULL, NULL}}},
2887
2888     {&ovsrec_table_netflow,
2889      {{&ovsrec_table_bridge,
2890        &ovsrec_bridge_col_name,
2891        &ovsrec_bridge_col_netflow},
2892       {NULL, NULL, NULL}}},
2893
2894     {&ovsrec_table_open_vswitch,
2895      {{&ovsrec_table_open_vswitch, NULL, NULL},
2896       {NULL, NULL, NULL}}},
2897
2898     {&ovsrec_table_port,
2899      {{&ovsrec_table_port, &ovsrec_port_col_name, NULL},
2900       {NULL, NULL, NULL}}},
2901
2902     {&ovsrec_table_qos,
2903      {{&ovsrec_table_port, &ovsrec_port_col_name, &ovsrec_port_col_qos},
2904       {NULL, NULL, NULL}}},
2905
2906     {&ovsrec_table_queue,
2907      {{NULL, NULL, NULL},
2908       {NULL, NULL, NULL}}},
2909
2910     {&ovsrec_table_ssl,
2911      {{&ovsrec_table_open_vswitch, NULL, &ovsrec_open_vswitch_col_ssl}}},
2912
2913     {&ovsrec_table_sflow,
2914      {{&ovsrec_table_bridge,
2915        &ovsrec_bridge_col_name,
2916        &ovsrec_bridge_col_sflow},
2917       {NULL, NULL, NULL}}},
2918
2919     {&ovsrec_table_flow_table,
2920      {{&ovsrec_table_flow_table, &ovsrec_flow_table_col_name, NULL},
2921       {NULL, NULL, NULL}}},
2922
2923     {&ovsrec_table_ipfix,
2924      {{&ovsrec_table_bridge,
2925        &ovsrec_bridge_col_name,
2926        &ovsrec_bridge_col_ipfix},
2927       {&ovsrec_table_flow_sample_collector_set, NULL,
2928        &ovsrec_flow_sample_collector_set_col_ipfix}}},
2929
2930     {&ovsrec_table_autoattach,
2931      {{&ovsrec_table_bridge,
2932        &ovsrec_bridge_col_name,
2933        &ovsrec_bridge_col_auto_attach},
2934       {NULL, NULL, NULL}}},
2935
2936     {&ovsrec_table_flow_sample_collector_set,
2937      {{NULL, NULL, NULL},
2938       {NULL, NULL, NULL}}},
2939
2940     {NULL, {{NULL, NULL, NULL}, {NULL, NULL, NULL}}}
2941 };
2942
2943 static void
2944 die_if_error(char *error)
2945 {
2946     if (error) {
2947         vsctl_fatal("%s", error);
2948     }
2949 }
2950
2951 static int
2952 to_lower_and_underscores(unsigned c)
2953 {
2954     return c == '-' ? '_' : tolower(c);
2955 }
2956
2957 static unsigned int
2958 score_partial_match(const char *name, const char *s)
2959 {
2960     int score;
2961
2962     if (!strcmp(name, s)) {
2963         return UINT_MAX;
2964     }
2965     for (score = 0; ; score++, name++, s++) {
2966         if (to_lower_and_underscores(*name) != to_lower_and_underscores(*s)) {
2967             break;
2968         } else if (*name == '\0') {
2969             return UINT_MAX - 1;
2970         }
2971     }
2972     return *s == '\0' ? score : 0;
2973 }
2974
2975 static const struct vsctl_table_class *
2976 get_table(const char *table_name)
2977 {
2978     const struct vsctl_table_class *table;
2979     const struct vsctl_table_class *best_match = NULL;
2980     unsigned int best_score = 0;
2981
2982     for (table = tables; table->class; table++) {
2983         unsigned int score = score_partial_match(table->class->name,
2984                                                  table_name);
2985         if (score > best_score) {
2986             best_match = table;
2987             best_score = score;
2988         } else if (score == best_score) {
2989             best_match = NULL;
2990         }
2991     }
2992     if (best_match) {
2993         return best_match;
2994     } else if (best_score) {
2995         vsctl_fatal("multiple table names match \"%s\"", table_name);
2996     } else {
2997         vsctl_fatal("unknown table \"%s\"", table_name);
2998     }
2999 }
3000
3001 static const struct vsctl_table_class *
3002 pre_get_table(struct vsctl_context *ctx, const char *table_name)
3003 {
3004     const struct vsctl_table_class *table_class;
3005     int i;
3006
3007     table_class = get_table(table_name);
3008     ovsdb_idl_add_table(ctx->idl, table_class->class);
3009
3010     for (i = 0; i < ARRAY_SIZE(table_class->row_ids); i++) {
3011         const struct vsctl_row_id *id = &table_class->row_ids[i];
3012         if (id->table) {
3013             ovsdb_idl_add_table(ctx->idl, id->table);
3014         }
3015         if (id->name_column) {
3016             ovsdb_idl_add_column(ctx->idl, id->name_column);
3017         }
3018         if (id->uuid_column) {
3019             ovsdb_idl_add_column(ctx->idl, id->uuid_column);
3020         }
3021     }
3022
3023     return table_class;
3024 }
3025
3026 static const struct ovsdb_idl_row *
3027 get_row_by_id(struct vsctl_context *ctx, const struct vsctl_table_class *table,
3028               const struct vsctl_row_id *id, const char *record_id)
3029 {
3030     const struct ovsdb_idl_row *referrer, *final;
3031
3032     if (!id->table) {
3033         return NULL;
3034     }
3035
3036     if (!id->name_column) {
3037         if (strcmp(record_id, ".")) {
3038             return NULL;
3039         }
3040         referrer = ovsdb_idl_first_row(ctx->idl, id->table);
3041         if (!referrer || ovsdb_idl_next_row(referrer)) {
3042             return NULL;
3043         }
3044     } else {
3045         const struct ovsdb_idl_row *row;
3046
3047         referrer = NULL;
3048         for (row = ovsdb_idl_first_row(ctx->idl, id->table);
3049              row != NULL;
3050              row = ovsdb_idl_next_row(row))
3051         {
3052             const struct ovsdb_datum *name;
3053
3054             name = ovsdb_idl_get(row, id->name_column,
3055                                  OVSDB_TYPE_STRING, OVSDB_TYPE_VOID);
3056             if (name->n == 1 && !strcmp(name->keys[0].string, record_id)) {
3057                 if (referrer) {
3058                     vsctl_fatal("multiple rows in %s match \"%s\"",
3059                                 table->class->name, record_id);
3060                 }
3061                 referrer = row;
3062             }
3063         }
3064     }
3065     if (!referrer) {
3066         return NULL;
3067     }
3068
3069     final = NULL;
3070     if (id->uuid_column) {
3071         const struct ovsdb_datum *uuid;
3072
3073         ovsdb_idl_txn_verify(referrer, id->uuid_column);
3074         uuid = ovsdb_idl_get(referrer, id->uuid_column,
3075                              OVSDB_TYPE_UUID, OVSDB_TYPE_VOID);
3076         if (uuid->n == 1) {
3077             final = ovsdb_idl_get_row_for_uuid(ctx->idl, table->class,
3078                                                &uuid->keys[0].uuid);
3079         }
3080     } else {
3081         final = referrer;
3082     }
3083
3084     return final;
3085 }
3086
3087 static const struct ovsdb_idl_row *
3088 get_row (struct vsctl_context *ctx,
3089          const struct vsctl_table_class *table, const char *record_id,
3090          bool must_exist)
3091 {
3092     const struct ovsdb_idl_row *row;
3093     struct uuid uuid;
3094
3095     row = NULL;
3096     if (uuid_from_string(&uuid, record_id)) {
3097         row = ovsdb_idl_get_row_for_uuid(ctx->idl, table->class, &uuid);
3098     }
3099     if (!row) {
3100         int i;
3101
3102         for (i = 0; i < ARRAY_SIZE(table->row_ids); i++) {
3103             row = get_row_by_id(ctx, table, &table->row_ids[i], record_id);
3104             if (row) {
3105                 break;
3106             }
3107         }
3108     }
3109     if (must_exist && !row) {
3110         vsctl_fatal("no row \"%s\" in table %s",
3111                     record_id, table->class->name);
3112     }
3113     return row;
3114 }
3115
3116 static char *
3117 get_column(const struct vsctl_table_class *table, const char *column_name,
3118            const struct ovsdb_idl_column **columnp)
3119 {
3120     const struct ovsdb_idl_column *best_match = NULL;
3121     unsigned int best_score = 0;
3122     size_t i;
3123
3124     for (i = 0; i < table->class->n_columns; i++) {
3125         const struct ovsdb_idl_column *column = &table->class->columns[i];
3126         unsigned int score = score_partial_match(column->name, column_name);
3127         if (score > best_score) {
3128             best_match = column;
3129             best_score = score;
3130         } else if (score == best_score) {
3131             best_match = NULL;
3132         }
3133     }
3134
3135     *columnp = best_match;
3136     if (best_match) {
3137         return NULL;
3138     } else if (best_score) {
3139         return xasprintf("%s contains more than one column whose name "
3140                          "matches \"%s\"", table->class->name, column_name);
3141     } else {
3142         return xasprintf("%s does not contain a column whose name matches "
3143                          "\"%s\"", table->class->name, column_name);
3144     }
3145 }
3146
3147 static struct ovsdb_symbol *
3148 create_symbol(struct ovsdb_symbol_table *symtab, const char *id, bool *newp)
3149 {
3150     struct ovsdb_symbol *symbol;
3151
3152     if (id[0] != '@') {
3153         vsctl_fatal("row id \"%s\" does not begin with \"@\"", id);
3154     }
3155
3156     if (newp) {
3157         *newp = ovsdb_symbol_table_get(symtab, id) == NULL;
3158     }
3159
3160     symbol = ovsdb_symbol_table_insert(symtab, id);
3161     if (symbol->created) {
3162         vsctl_fatal("row id \"%s\" may only be specified on one --id option",
3163                     id);
3164     }
3165     symbol->created = true;
3166     return symbol;
3167 }
3168
3169 static void
3170 pre_get_column(struct vsctl_context *ctx,
3171                const struct vsctl_table_class *table, const char *column_name,
3172                const struct ovsdb_idl_column **columnp)
3173 {
3174     die_if_error(get_column(table, column_name, columnp));
3175     ovsdb_idl_add_column(ctx->idl, *columnp);
3176 }
3177
3178 static char *
3179 missing_operator_error(const char *arg, const char **allowed_operators,
3180                        size_t n_allowed)
3181 {
3182     struct ds s;
3183
3184     ds_init(&s);
3185     ds_put_format(&s, "%s: argument does not end in ", arg);
3186     ds_put_format(&s, "\"%s\"", allowed_operators[0]);
3187     if (n_allowed == 2) {
3188         ds_put_format(&s, " or \"%s\"", allowed_operators[1]);
3189     } else if (n_allowed > 2) {
3190         size_t i;
3191
3192         for (i = 1; i < n_allowed - 1; i++) {
3193             ds_put_format(&s, ", \"%s\"", allowed_operators[i]);
3194         }
3195         ds_put_format(&s, ", or \"%s\"", allowed_operators[i]);
3196     }
3197     ds_put_format(&s, " followed by a value.");
3198
3199     return ds_steal_cstr(&s);
3200 }
3201
3202 /* Breaks 'arg' apart into a number of fields in the following order:
3203  *
3204  *      - The name of a column in 'table', stored into '*columnp'.  The column
3205  *        name may be abbreviated.
3206  *
3207  *      - Optionally ':' followed by a key string.  The key is stored as a
3208  *        malloc()'d string into '*keyp', or NULL if no key is present in
3209  *        'arg'.
3210  *
3211  *      - If 'valuep' is nonnull, an operator followed by a value string.  The
3212  *        allowed operators are the 'n_allowed' string in 'allowed_operators',
3213  *        or just "=" if 'n_allowed' is 0.  If 'operatorp' is nonnull, then the
3214  *        index of the operator within 'allowed_operators' is stored into
3215  *        '*operatorp'.  The value is stored as a malloc()'d string into
3216  *        '*valuep', or NULL if no value is present in 'arg'.
3217  *
3218  * On success, returns NULL.  On failure, returned a malloc()'d string error
3219  * message and stores NULL into all of the nonnull output arguments. */
3220 static char * OVS_WARN_UNUSED_RESULT
3221 parse_column_key_value(const char *arg,
3222                        const struct vsctl_table_class *table,
3223                        const struct ovsdb_idl_column **columnp, char **keyp,
3224                        int *operatorp,
3225                        const char **allowed_operators, size_t n_allowed,
3226                        char **valuep)
3227 {
3228     const char *p = arg;
3229     char *column_name;
3230     char *error;
3231
3232     ovs_assert(!(operatorp && !valuep));
3233     *keyp = NULL;
3234     if (valuep) {
3235         *valuep = NULL;
3236     }
3237
3238     /* Parse column name. */
3239     error = ovsdb_token_parse(&p, &column_name);
3240     if (error) {
3241         goto error;
3242     }
3243     if (column_name[0] == '\0') {
3244         free(column_name);
3245         error = xasprintf("%s: missing column name", arg);
3246         goto error;
3247     }
3248     error = get_column(table, column_name, columnp);
3249     free(column_name);
3250     if (error) {
3251         goto error;
3252     }
3253
3254     /* Parse key string. */
3255     if (*p == ':') {
3256         p++;
3257         error = ovsdb_token_parse(&p, keyp);
3258         if (error) {
3259             goto error;
3260         }
3261     }
3262
3263     /* Parse value string. */
3264     if (valuep) {
3265         size_t best_len;
3266         size_t i;
3267         int best;
3268
3269         if (!allowed_operators) {
3270             static const char *equals = "=";
3271             allowed_operators = &equals;
3272             n_allowed = 1;
3273         }
3274
3275         best = -1;
3276         best_len = 0;
3277         for (i = 0; i < n_allowed; i++) {
3278             const char *op = allowed_operators[i];
3279             size_t op_len = strlen(op);
3280
3281             if (op_len > best_len && !strncmp(op, p, op_len) && p[op_len]) {
3282                 best_len = op_len;
3283                 best = i;
3284             }
3285         }
3286         if (best < 0) {
3287             error = missing_operator_error(arg, allowed_operators, n_allowed);
3288             goto error;
3289         }
3290
3291         if (operatorp) {
3292             *operatorp = best;
3293         }
3294         *valuep = xstrdup(p + best_len);
3295     } else {
3296         if (*p != '\0') {
3297             error = xasprintf("%s: trailing garbage \"%s\" in argument",
3298                               arg, p);
3299             goto error;
3300         }
3301     }
3302     return NULL;
3303
3304 error:
3305     *columnp = NULL;
3306     free(*keyp);
3307     *keyp = NULL;
3308     if (valuep) {
3309         free(*valuep);
3310         *valuep = NULL;
3311         if (operatorp) {
3312             *operatorp = -1;
3313         }
3314     }
3315     return error;
3316 }
3317
3318 static const struct ovsdb_idl_column *
3319 pre_parse_column_key_value(struct vsctl_context *ctx,
3320                            const char *arg,
3321                            const struct vsctl_table_class *table)
3322 {
3323     const struct ovsdb_idl_column *column;
3324     const char *p;
3325     char *column_name;
3326
3327     p = arg;
3328     die_if_error(ovsdb_token_parse(&p, &column_name));
3329     if (column_name[0] == '\0') {
3330         vsctl_fatal("%s: missing column name", arg);
3331     }
3332
3333     pre_get_column(ctx, table, column_name, &column);
3334     free(column_name);
3335
3336     return column;
3337 }
3338
3339 static void
3340 check_mutable(const struct ovsdb_idl_row *row,
3341               const struct ovsdb_idl_column *column)
3342 {
3343     if (!ovsdb_idl_is_mutable(row, column)) {
3344         vsctl_fatal("cannot modify read-only column %s in table %s",
3345                     column->name, row->table->class->name);
3346     }
3347 }
3348
3349 static void
3350 pre_cmd_get(struct vsctl_context *ctx)
3351 {
3352     const char *id = shash_find_data(&ctx->options, "--id");
3353     const char *table_name = ctx->argv[1];
3354     const struct vsctl_table_class *table;
3355     int i;
3356
3357     /* Using "get" without --id or a column name could possibly make sense.
3358      * Maybe, for example, a ovs-vsctl run wants to assert that a row exists.
3359      * But it is unlikely that an interactive user would want to do that, so
3360      * issue a warning if we're running on a terminal. */
3361     if (!id && ctx->argc <= 3 && isatty(STDOUT_FILENO)) {
3362         VLOG_WARN("\"get\" command without row arguments or \"--id\" is "
3363                   "possibly erroneous");
3364     }
3365
3366     table = pre_get_table(ctx, table_name);
3367     for (i = 3; i < ctx->argc; i++) {
3368         if (!strcasecmp(ctx->argv[i], "_uuid")
3369             || !strcasecmp(ctx->argv[i], "-uuid")) {
3370             continue;
3371         }
3372
3373         pre_parse_column_key_value(ctx, ctx->argv[i], table);
3374     }
3375 }
3376
3377 static void
3378 cmd_get(struct vsctl_context *ctx)
3379 {
3380     const char *id = shash_find_data(&ctx->options, "--id");
3381     bool must_exist = !shash_find(&ctx->options, "--if-exists");
3382     const char *table_name = ctx->argv[1];
3383     const char *record_id = ctx->argv[2];
3384     const struct vsctl_table_class *table;
3385     const struct ovsdb_idl_row *row;
3386     struct ds *out = &ctx->output;
3387     int i;
3388
3389     if (id && !must_exist) {
3390         vsctl_fatal("--if-exists and --id may not be specified together");
3391     }
3392
3393     table = get_table(table_name);
3394     row = get_row(ctx, table, record_id, must_exist);
3395     if (!row) {
3396         return;
3397     }
3398
3399     if (id) {
3400         struct ovsdb_symbol *symbol;
3401         bool new;
3402
3403         symbol = create_symbol(ctx->symtab, id, &new);
3404         if (!new) {
3405             vsctl_fatal("row id \"%s\" specified on \"get\" command was used "
3406                         "before it was defined", id);
3407         }
3408         symbol->uuid = row->uuid;
3409
3410         /* This symbol refers to a row that already exists, so disable warnings
3411          * about it being unreferenced. */
3412         symbol->strong_ref = true;
3413     }
3414     for (i = 3; i < ctx->argc; i++) {
3415         const struct ovsdb_idl_column *column;
3416         const struct ovsdb_datum *datum;
3417         char *key_string;
3418
3419         /* Special case for obtaining the UUID of a row.  We can't just do this
3420          * through parse_column_key_value() below since it returns a "struct
3421          * ovsdb_idl_column" and the UUID column doesn't have one. */
3422         if (!strcasecmp(ctx->argv[i], "_uuid")
3423             || !strcasecmp(ctx->argv[i], "-uuid")) {
3424             ds_put_format(out, UUID_FMT"\n", UUID_ARGS(&row->uuid));
3425             continue;
3426         }
3427
3428         die_if_error(parse_column_key_value(ctx->argv[i], table,
3429                                             &column, &key_string,
3430                                             NULL, NULL, 0, NULL));
3431
3432         ovsdb_idl_txn_verify(row, column);
3433         datum = ovsdb_idl_read(row, column);
3434         if (key_string) {
3435             union ovsdb_atom key;
3436             unsigned int idx;
3437
3438             if (column->type.value.type == OVSDB_TYPE_VOID) {
3439                 vsctl_fatal("cannot specify key to get for non-map column %s",
3440                             column->name);
3441             }
3442
3443             die_if_error(ovsdb_atom_from_string(&key,
3444                                                 &column->type.key,
3445                                                 key_string, ctx->symtab));
3446
3447             idx = ovsdb_datum_find_key(datum, &key,
3448                                        column->type.key.type);
3449             if (idx == UINT_MAX) {
3450                 if (must_exist) {
3451                     vsctl_fatal("no key \"%s\" in %s record \"%s\" column %s",
3452                                 key_string, table->class->name, record_id,
3453                                 column->name);
3454                 }
3455             } else {
3456                 ovsdb_atom_to_string(&datum->values[idx],
3457                                      column->type.value.type, out);
3458             }
3459             ovsdb_atom_destroy(&key, column->type.key.type);
3460         } else {
3461             ovsdb_datum_to_string(datum, &column->type, out);
3462         }
3463         ds_put_char(out, '\n');
3464
3465         free(key_string);
3466     }
3467 }
3468
3469 static void
3470 parse_column_names(const char *column_names,
3471                    const struct vsctl_table_class *table,
3472                    const struct ovsdb_idl_column ***columnsp,
3473                    size_t *n_columnsp)
3474 {
3475     const struct ovsdb_idl_column **columns;
3476     size_t n_columns;
3477
3478     if (!column_names) {
3479         size_t i;
3480
3481         n_columns = table->class->n_columns + 1;
3482         columns = xmalloc(n_columns * sizeof *columns);
3483         columns[0] = NULL;
3484         for (i = 0; i < table->class->n_columns; i++) {
3485             columns[i + 1] = &table->class->columns[i];
3486         }
3487     } else {
3488         char *s = xstrdup(column_names);
3489         size_t allocated_columns;
3490         char *save_ptr = NULL;
3491         char *column_name;
3492
3493         columns = NULL;
3494         allocated_columns = n_columns = 0;
3495         for (column_name = strtok_r(s, ", ", &save_ptr); column_name;
3496              column_name = strtok_r(NULL, ", ", &save_ptr)) {
3497             const struct ovsdb_idl_column *column;
3498
3499             if (!strcasecmp(column_name, "_uuid")) {
3500                 column = NULL;
3501             } else {
3502                 die_if_error(get_column(table, column_name, &column));
3503             }
3504             if (n_columns >= allocated_columns) {
3505                 columns = x2nrealloc(columns, &allocated_columns,
3506                                      sizeof *columns);
3507             }
3508             columns[n_columns++] = column;
3509         }
3510         free(s);
3511
3512         if (!n_columns) {
3513             vsctl_fatal("must specify at least one column name");
3514         }
3515     }
3516     *columnsp = columns;
3517     *n_columnsp = n_columns;
3518 }
3519
3520
3521 static void
3522 pre_list_columns(struct vsctl_context *ctx,
3523                  const struct vsctl_table_class *table,
3524                  const char *column_names)
3525 {
3526     const struct ovsdb_idl_column **columns;
3527     size_t n_columns;
3528     size_t i;
3529
3530     parse_column_names(column_names, table, &columns, &n_columns);
3531     for (i = 0; i < n_columns; i++) {
3532         if (columns[i]) {
3533             ovsdb_idl_add_column(ctx->idl, columns[i]);
3534         }
3535     }
3536     free(columns);
3537 }
3538
3539 static void
3540 pre_cmd_list(struct vsctl_context *ctx)
3541 {
3542     const char *column_names = shash_find_data(&ctx->options, "--columns");
3543     const char *table_name = ctx->argv[1];
3544     const struct vsctl_table_class *table;
3545
3546     table = pre_get_table(ctx, table_name);
3547     pre_list_columns(ctx, table, column_names);
3548 }
3549
3550 static struct table *
3551 list_make_table(const struct ovsdb_idl_column **columns, size_t n_columns)
3552 {
3553     struct table *out;
3554     size_t i;
3555
3556     out = xmalloc(sizeof *out);
3557     table_init(out);
3558
3559     for (i = 0; i < n_columns; i++) {
3560         const struct ovsdb_idl_column *column = columns[i];
3561         const char *column_name = column ? column->name : "_uuid";
3562
3563         table_add_column(out, "%s", column_name);
3564     }
3565
3566     return out;
3567 }
3568
3569 static void
3570 list_record(const struct ovsdb_idl_row *row,
3571             const struct ovsdb_idl_column **columns, size_t n_columns,
3572             struct table *out)
3573 {
3574     size_t i;
3575
3576     if (!row) {
3577         return;
3578     }
3579
3580     table_add_row(out);
3581     for (i = 0; i < n_columns; i++) {
3582         const struct ovsdb_idl_column *column = columns[i];
3583         struct cell *cell = table_add_cell(out);
3584
3585         if (!column) {
3586             struct ovsdb_datum datum;
3587             union ovsdb_atom atom;
3588
3589             atom.uuid = row->uuid;
3590
3591             datum.keys = &atom;
3592             datum.values = NULL;
3593             datum.n = 1;
3594
3595             cell->json = ovsdb_datum_to_json(&datum, &ovsdb_type_uuid);
3596             cell->type = &ovsdb_type_uuid;
3597         } else {
3598             const struct ovsdb_datum *datum = ovsdb_idl_read(row, column);
3599
3600             cell->json = ovsdb_datum_to_json(datum, &column->type);
3601             cell->type = &column->type;
3602         }
3603     }
3604 }
3605
3606 static void
3607 cmd_list(struct vsctl_context *ctx)
3608 {
3609     const char *column_names = shash_find_data(&ctx->options, "--columns");
3610     bool must_exist = !shash_find(&ctx->options, "--if-exists");
3611     const struct ovsdb_idl_column **columns;
3612     const char *table_name = ctx->argv[1];
3613     const struct vsctl_table_class *table;
3614     struct table *out;
3615     size_t n_columns;
3616     int i;
3617
3618     table = get_table(table_name);
3619     parse_column_names(column_names, table, &columns, &n_columns);
3620     out = ctx->table = list_make_table(columns, n_columns);
3621     if (ctx->argc > 2) {
3622         for (i = 2; i < ctx->argc; i++) {
3623             list_record(get_row(ctx, table, ctx->argv[i], must_exist),
3624                         columns, n_columns, out);
3625         }
3626     } else {
3627         const struct ovsdb_idl_row *row;
3628
3629         for (row = ovsdb_idl_first_row(ctx->idl, table->class); row != NULL;
3630              row = ovsdb_idl_next_row(row)) {
3631             list_record(row, columns, n_columns, out);
3632         }
3633     }
3634     free(columns);
3635 }
3636
3637 static void
3638 pre_cmd_find(struct vsctl_context *ctx)
3639 {
3640     const char *column_names = shash_find_data(&ctx->options, "--columns");
3641     const char *table_name = ctx->argv[1];
3642     const struct vsctl_table_class *table;
3643     int i;
3644
3645     table = pre_get_table(ctx, table_name);
3646     pre_list_columns(ctx, table, column_names);
3647     for (i = 2; i < ctx->argc; i++) {
3648         pre_parse_column_key_value(ctx, ctx->argv[i], table);
3649     }
3650 }
3651
3652 static void
3653 cmd_find(struct vsctl_context *ctx)
3654 {
3655     const char *column_names = shash_find_data(&ctx->options, "--columns");
3656     const struct ovsdb_idl_column **columns;
3657     const char *table_name = ctx->argv[1];
3658     const struct vsctl_table_class *table;
3659     const struct ovsdb_idl_row *row;
3660     struct table *out;
3661     size_t n_columns;
3662
3663     table = get_table(table_name);
3664     parse_column_names(column_names, table, &columns, &n_columns);
3665     out = ctx->table = list_make_table(columns, n_columns);
3666     for (row = ovsdb_idl_first_row(ctx->idl, table->class); row;
3667          row = ovsdb_idl_next_row(row)) {
3668         int i;
3669
3670         for (i = 2; i < ctx->argc; i++) {
3671             if (!is_condition_satisfied(table, row, ctx->argv[i],
3672                                         ctx->symtab)) {
3673                 goto next_row;
3674             }
3675         }
3676         list_record(row, columns, n_columns, out);
3677
3678     next_row: ;
3679     }
3680     free(columns);
3681 }
3682
3683 static void
3684 pre_cmd_set(struct vsctl_context *ctx)
3685 {
3686     const char *table_name = ctx->argv[1];
3687     const struct vsctl_table_class *table;
3688     int i;
3689
3690     table = pre_get_table(ctx, table_name);
3691     for (i = 3; i < ctx->argc; i++) {
3692         pre_parse_column_key_value(ctx, ctx->argv[i], table);
3693     }
3694 }
3695
3696 static void
3697 set_column(const struct vsctl_table_class *table,
3698            const struct ovsdb_idl_row *row, const char *arg,
3699            struct ovsdb_symbol_table *symtab)
3700 {
3701     const struct ovsdb_idl_column *column;
3702     char *key_string, *value_string;
3703     char *error;
3704
3705     error = parse_column_key_value(arg, table, &column, &key_string,
3706                                    NULL, NULL, 0, &value_string);
3707     die_if_error(error);
3708     if (!value_string) {
3709         vsctl_fatal("%s: missing value", arg);
3710     }
3711     check_mutable(row, column);
3712
3713     if (key_string) {
3714         union ovsdb_atom key, value;
3715         struct ovsdb_datum datum;
3716
3717         if (column->type.value.type == OVSDB_TYPE_VOID) {
3718             vsctl_fatal("cannot specify key to set for non-map column %s",
3719                         column->name);
3720         }
3721
3722         die_if_error(ovsdb_atom_from_string(&key, &column->type.key,
3723                                             key_string, symtab));
3724         die_if_error(ovsdb_atom_from_string(&value, &column->type.value,
3725                                             value_string, symtab));
3726
3727         ovsdb_datum_init_empty(&datum);
3728         ovsdb_datum_add_unsafe(&datum, &key, &value, &column->type);
3729
3730         ovsdb_atom_destroy(&key, column->type.key.type);
3731         ovsdb_atom_destroy(&value, column->type.value.type);
3732
3733         ovsdb_datum_union(&datum, ovsdb_idl_read(row, column),
3734                           &column->type, false);
3735         ovsdb_idl_txn_verify(row, column);
3736         ovsdb_idl_txn_write(row, column, &datum);
3737     } else {
3738         struct ovsdb_datum datum;
3739
3740         die_if_error(ovsdb_datum_from_string(&datum, &column->type,
3741                                              value_string, symtab));
3742         ovsdb_idl_txn_write(row, column, &datum);
3743     }
3744
3745     free(key_string);
3746     free(value_string);
3747 }
3748
3749 static void
3750 cmd_set(struct vsctl_context *ctx)
3751 {
3752     bool must_exist = !shash_find(&ctx->options, "--if-exists");
3753     const char *table_name = ctx->argv[1];
3754     const char *record_id = ctx->argv[2];
3755     const struct vsctl_table_class *table;
3756     const struct ovsdb_idl_row *row;
3757     int i;
3758
3759     table = get_table(table_name);
3760     row = get_row(ctx, table, record_id, must_exist);
3761     if (!row) {
3762         return;
3763     }
3764
3765     for (i = 3; i < ctx->argc; i++) {
3766         set_column(table, row, ctx->argv[i], ctx->symtab);
3767     }
3768
3769     vsctl_context_invalidate_cache(ctx);
3770 }
3771
3772 static void
3773 pre_cmd_add(struct vsctl_context *ctx)
3774 {
3775     const char *table_name = ctx->argv[1];
3776     const char *column_name = ctx->argv[3];
3777     const struct vsctl_table_class *table;
3778     const struct ovsdb_idl_column *column;
3779
3780     table = pre_get_table(ctx, table_name);
3781     pre_get_column(ctx, table, column_name, &column);
3782 }
3783
3784 static void
3785 cmd_add(struct vsctl_context *ctx)
3786 {
3787     bool must_exist = !shash_find(&ctx->options, "--if-exists");
3788     const char *table_name = ctx->argv[1];
3789     const char *record_id = ctx->argv[2];
3790     const char *column_name = ctx->argv[3];
3791     const struct vsctl_table_class *table;
3792     const struct ovsdb_idl_column *column;
3793     const struct ovsdb_idl_row *row;
3794     const struct ovsdb_type *type;
3795     struct ovsdb_datum old;
3796     int i;
3797
3798     table = get_table(table_name);
3799     die_if_error(get_column(table, column_name, &column));
3800     row = get_row(ctx, table, record_id, must_exist);
3801     if (!row) {
3802         return;
3803     }
3804     check_mutable(row, column);
3805
3806     type = &column->type;
3807     ovsdb_datum_clone(&old, ovsdb_idl_read(row, column), &column->type);
3808     for (i = 4; i < ctx->argc; i++) {
3809         struct ovsdb_type add_type;
3810         struct ovsdb_datum add;
3811
3812         add_type = *type;
3813         add_type.n_min = 1;
3814         add_type.n_max = UINT_MAX;
3815         die_if_error(ovsdb_datum_from_string(&add, &add_type, ctx->argv[i],
3816                                              ctx->symtab));
3817         ovsdb_datum_union(&old, &add, type, false);
3818         ovsdb_datum_destroy(&add, type);
3819     }
3820     if (old.n > type->n_max) {
3821         vsctl_fatal("\"add\" operation would put %u %s in column %s of "
3822                     "table %s but the maximum number is %u",
3823                     old.n,
3824                     type->value.type == OVSDB_TYPE_VOID ? "values" : "pairs",
3825                     column->name, table->class->name, type->n_max);
3826     }
3827     ovsdb_idl_txn_verify(row, column);
3828     ovsdb_idl_txn_write(row, column, &old);
3829
3830     vsctl_context_invalidate_cache(ctx);
3831 }
3832
3833 static void
3834 pre_cmd_remove(struct vsctl_context *ctx)
3835 {
3836     const char *table_name = ctx->argv[1];
3837     const char *column_name = ctx->argv[3];
3838     const struct vsctl_table_class *table;
3839     const struct ovsdb_idl_column *column;
3840
3841     table = pre_get_table(ctx, table_name);
3842     pre_get_column(ctx, table, column_name, &column);
3843 }
3844
3845 static void
3846 cmd_remove(struct vsctl_context *ctx)
3847 {
3848     bool must_exist = !shash_find(&ctx->options, "--if-exists");
3849     const char *table_name = ctx->argv[1];
3850     const char *record_id = ctx->argv[2];
3851     const char *column_name = ctx->argv[3];
3852     const struct vsctl_table_class *table;
3853     const struct ovsdb_idl_column *column;
3854     const struct ovsdb_idl_row *row;
3855     const struct ovsdb_type *type;
3856     struct ovsdb_datum old;
3857     int i;
3858
3859     table = get_table(table_name);
3860     die_if_error(get_column(table, column_name, &column));
3861     row = get_row(ctx, table, record_id, must_exist);
3862     if (!row) {
3863         return;
3864     }
3865     check_mutable(row, column);
3866
3867     type = &column->type;
3868     ovsdb_datum_clone(&old, ovsdb_idl_read(row, column), &column->type);
3869     for (i = 4; i < ctx->argc; i++) {
3870         struct ovsdb_type rm_type;
3871         struct ovsdb_datum rm;
3872         char *error;
3873
3874         rm_type = *type;
3875         rm_type.n_min = 1;
3876         rm_type.n_max = UINT_MAX;
3877         error = ovsdb_datum_from_string(&rm, &rm_type,
3878                                         ctx->argv[i], ctx->symtab);
3879
3880         if (error) {
3881             if (ovsdb_type_is_map(&rm_type)) {
3882                 rm_type.value.type = OVSDB_TYPE_VOID;
3883                 free(error);
3884                 die_if_error(ovsdb_datum_from_string(
3885                                  &rm, &rm_type, ctx->argv[i], ctx->symtab));
3886             } else {
3887                 vsctl_fatal("%s", error);
3888             }
3889         }
3890         ovsdb_datum_subtract(&old, type, &rm, &rm_type);
3891         ovsdb_datum_destroy(&rm, &rm_type);
3892     }
3893     if (old.n < type->n_min) {
3894         vsctl_fatal("\"remove\" operation would put %u %s in column %s of "
3895                     "table %s but the minimum number is %u",
3896                     old.n,
3897                     type->value.type == OVSDB_TYPE_VOID ? "values" : "pairs",
3898                     column->name, table->class->name, type->n_min);
3899     }
3900     ovsdb_idl_txn_verify(row, column);
3901     ovsdb_idl_txn_write(row, column, &old);
3902
3903     vsctl_context_invalidate_cache(ctx);
3904 }
3905
3906 static void
3907 pre_cmd_clear(struct vsctl_context *ctx)
3908 {
3909     const char *table_name = ctx->argv[1];
3910     const struct vsctl_table_class *table;
3911     int i;
3912
3913     table = pre_get_table(ctx, table_name);
3914     for (i = 3; i < ctx->argc; i++) {
3915         const struct ovsdb_idl_column *column;
3916
3917         pre_get_column(ctx, table, ctx->argv[i], &column);
3918     }
3919 }
3920
3921 static void
3922 cmd_clear(struct vsctl_context *ctx)
3923 {
3924     bool must_exist = !shash_find(&ctx->options, "--if-exists");
3925     const char *table_name = ctx->argv[1];
3926     const char *record_id = ctx->argv[2];
3927     const struct vsctl_table_class *table;
3928     const struct ovsdb_idl_row *row;
3929     int i;
3930
3931     table = get_table(table_name);
3932     row = get_row(ctx, table, record_id, must_exist);
3933     if (!row) {
3934         return;
3935     }
3936
3937     for (i = 3; i < ctx->argc; i++) {
3938         const struct ovsdb_idl_column *column;
3939         const struct ovsdb_type *type;
3940         struct ovsdb_datum datum;
3941
3942         die_if_error(get_column(table, ctx->argv[i], &column));
3943         check_mutable(row, column);
3944
3945         type = &column->type;
3946         if (type->n_min > 0) {
3947             vsctl_fatal("\"clear\" operation cannot be applied to column %s "
3948                         "of table %s, which is not allowed to be empty",
3949                         column->name, table->class->name);
3950         }
3951
3952         ovsdb_datum_init_empty(&datum);
3953         ovsdb_idl_txn_write(row, column, &datum);
3954     }
3955
3956     vsctl_context_invalidate_cache(ctx);
3957 }
3958
3959 static void
3960 pre_create(struct vsctl_context *ctx)
3961 {
3962     const char *id = shash_find_data(&ctx->options, "--id");
3963     const char *table_name = ctx->argv[1];
3964     const struct vsctl_table_class *table;
3965
3966     table = get_table(table_name);
3967     if (!id && !table->class->is_root) {
3968         VLOG_WARN("applying \"create\" command to table %s without --id "
3969                   "option will have no effect", table->class->name);
3970     }
3971 }
3972
3973 static void
3974 cmd_create(struct vsctl_context *ctx)
3975 {
3976     const char *id = shash_find_data(&ctx->options, "--id");
3977     const char *table_name = ctx->argv[1];
3978     const struct vsctl_table_class *table = get_table(table_name);
3979     const struct ovsdb_idl_row *row;
3980     const struct uuid *uuid;
3981     int i;
3982
3983     if (id) {
3984         struct ovsdb_symbol *symbol = create_symbol(ctx->symtab, id, NULL);
3985         if (table->class->is_root) {
3986             /* This table is in the root set, meaning that rows created in it
3987              * won't disappear even if they are unreferenced, so disable
3988              * warnings about that by pretending that there is a reference. */
3989             symbol->strong_ref = true;
3990         }
3991         uuid = &symbol->uuid;
3992     } else {
3993         uuid = NULL;
3994     }
3995
3996     row = ovsdb_idl_txn_insert(ctx->txn, table->class, uuid);
3997     for (i = 2; i < ctx->argc; i++) {
3998         set_column(table, row, ctx->argv[i], ctx->symtab);
3999     }
4000     ds_put_format(&ctx->output, UUID_FMT, UUID_ARGS(&row->uuid));
4001 }
4002
4003 /* This function may be used as the 'postprocess' function for commands that
4004  * insert new rows into the database.  It expects that the command's 'run'
4005  * function prints the UUID reported by ovsdb_idl_txn_insert() as the command's
4006  * sole output.  It replaces that output by the row's permanent UUID assigned
4007  * by the database server and appends a new-line.
4008  *
4009  * Currently we use this only for "create", because the higher-level commands
4010  * are supposed to be independent of the actual structure of the vswitch
4011  * configuration. */
4012 static void
4013 post_create(struct vsctl_context *ctx)
4014 {
4015     const struct uuid *real;
4016     struct uuid dummy;
4017
4018     if (!uuid_from_string(&dummy, ds_cstr(&ctx->output))) {
4019         OVS_NOT_REACHED();
4020     }
4021     real = ovsdb_idl_txn_get_insert_uuid(ctx->txn, &dummy);
4022     if (real) {
4023         ds_clear(&ctx->output);
4024         ds_put_format(&ctx->output, UUID_FMT, UUID_ARGS(real));
4025     }
4026     ds_put_char(&ctx->output, '\n');
4027 }
4028
4029 static void
4030 post_db_reload_check_init(void)
4031 {
4032     n_neoteric_ifaces = 0;
4033 }
4034
4035 static void
4036 post_db_reload_expect_iface(const struct ovsrec_interface *iface)
4037 {
4038     if (n_neoteric_ifaces >= allocated_neoteric_ifaces) {
4039         neoteric_ifaces = x2nrealloc(neoteric_ifaces,
4040                                      &allocated_neoteric_ifaces,
4041                                      sizeof *neoteric_ifaces);
4042     }
4043     neoteric_ifaces[n_neoteric_ifaces++] = iface->header_.uuid;
4044 }
4045
4046 static void
4047 post_db_reload_do_checks(const struct vsctl_context *ctx)
4048 {
4049     struct ds dead_ifaces = DS_EMPTY_INITIALIZER;
4050     size_t i;
4051
4052     for (i = 0; i < n_neoteric_ifaces; i++) {
4053         const struct uuid *uuid;
4054
4055         uuid = ovsdb_idl_txn_get_insert_uuid(ctx->txn, &neoteric_ifaces[i]);
4056         if (uuid) {
4057             const struct ovsrec_interface *iface;
4058
4059             iface = ovsrec_interface_get_for_uuid(ctx->idl, uuid);
4060             if (iface && (!iface->ofport || *iface->ofport == -1)) {
4061                 ds_put_format(&dead_ifaces, "'%s', ", iface->name);
4062             }
4063         }
4064     }
4065
4066     if (dead_ifaces.length) {
4067         dead_ifaces.length -= 2; /* Strip off trailing comma and space. */
4068         ovs_error(0, "Error detected while setting up %s.  See ovs-vswitchd "
4069                   "log for details.", ds_cstr(&dead_ifaces));
4070     }
4071
4072     ds_destroy(&dead_ifaces);
4073 }
4074
4075 static void
4076 pre_cmd_destroy(struct vsctl_context *ctx)
4077 {
4078     const char *table_name = ctx->argv[1];
4079
4080     pre_get_table(ctx, table_name);
4081 }
4082
4083 static void
4084 cmd_destroy(struct vsctl_context *ctx)
4085 {
4086     bool must_exist = !shash_find(&ctx->options, "--if-exists");
4087     bool delete_all = shash_find(&ctx->options, "--all");
4088     const char *table_name = ctx->argv[1];
4089     const struct vsctl_table_class *table;
4090     int i;
4091
4092     table = get_table(table_name);
4093
4094     if (delete_all && ctx->argc > 2) {
4095         vsctl_fatal("--all and records argument should not be specified together");
4096     }
4097
4098     if (delete_all && !must_exist) {
4099         vsctl_fatal("--all and --if-exists should not be specified together");
4100     }
4101
4102     if (delete_all) {
4103         const struct ovsdb_idl_row *row;
4104         const struct ovsdb_idl_row *next_row;
4105
4106         for (row = ovsdb_idl_first_row(ctx->idl, table->class);
4107              row;) {
4108              next_row = ovsdb_idl_next_row(row);
4109              ovsdb_idl_txn_delete(row);
4110              row = next_row;
4111         }
4112     } else {
4113         for (i = 2; i < ctx->argc; i++) {
4114             const struct ovsdb_idl_row *row;
4115
4116             row = get_row(ctx, table, ctx->argv[i], must_exist);
4117             if (row) {
4118                 ovsdb_idl_txn_delete(row);
4119             }
4120         }
4121     }
4122     vsctl_context_invalidate_cache(ctx);
4123 }
4124
4125 #define RELOPS                                  \
4126     RELOP(RELOP_EQ,     "=")                    \
4127     RELOP(RELOP_NE,     "!=")                   \
4128     RELOP(RELOP_LT,     "<")                    \
4129     RELOP(RELOP_GT,     ">")                    \
4130     RELOP(RELOP_LE,     "<=")                   \
4131     RELOP(RELOP_GE,     ">=")                   \
4132     RELOP(RELOP_SET_EQ, "{=}")                  \
4133     RELOP(RELOP_SET_NE, "{!=}")                 \
4134     RELOP(RELOP_SET_LT, "{<}")                  \
4135     RELOP(RELOP_SET_GT, "{>}")                  \
4136     RELOP(RELOP_SET_LE, "{<=}")                 \
4137     RELOP(RELOP_SET_GE, "{>=}")
4138
4139 enum relop {
4140 #define RELOP(ENUM, STRING) ENUM,
4141     RELOPS
4142 #undef RELOP
4143 };
4144
4145 static bool
4146 is_set_operator(enum relop op)
4147 {
4148     return (op == RELOP_SET_EQ || op == RELOP_SET_NE ||
4149             op == RELOP_SET_LT || op == RELOP_SET_GT ||
4150             op == RELOP_SET_LE || op == RELOP_SET_GE);
4151 }
4152
4153 static bool
4154 evaluate_relop(const struct ovsdb_datum *a, const struct ovsdb_datum *b,
4155                const struct ovsdb_type *type, enum relop op)
4156 {
4157     switch (op) {
4158     case RELOP_EQ:
4159     case RELOP_SET_EQ:
4160         return ovsdb_datum_compare_3way(a, b, type) == 0;
4161     case RELOP_NE:
4162     case RELOP_SET_NE:
4163         return ovsdb_datum_compare_3way(a, b, type) != 0;
4164     case RELOP_LT:
4165         return ovsdb_datum_compare_3way(a, b, type) < 0;
4166     case RELOP_GT:
4167         return ovsdb_datum_compare_3way(a, b, type) > 0;
4168     case RELOP_LE:
4169         return ovsdb_datum_compare_3way(a, b, type) <= 0;
4170     case RELOP_GE:
4171         return ovsdb_datum_compare_3way(a, b, type) >= 0;
4172
4173     case RELOP_SET_LT:
4174         return b->n > a->n && ovsdb_datum_includes_all(a, b, type);
4175     case RELOP_SET_GT:
4176         return a->n > b->n && ovsdb_datum_includes_all(b, a, type);
4177     case RELOP_SET_LE:
4178         return ovsdb_datum_includes_all(a, b, type);
4179     case RELOP_SET_GE:
4180         return ovsdb_datum_includes_all(b, a, type);
4181
4182     default:
4183         OVS_NOT_REACHED();
4184     }
4185 }
4186
4187 static bool
4188 is_condition_satisfied(const struct vsctl_table_class *table,
4189                        const struct ovsdb_idl_row *row, const char *arg,
4190                        struct ovsdb_symbol_table *symtab)
4191 {
4192     static const char *operators[] = {
4193 #define RELOP(ENUM, STRING) STRING,
4194         RELOPS
4195 #undef RELOP
4196     };
4197
4198     const struct ovsdb_idl_column *column;
4199     const struct ovsdb_datum *have_datum;
4200     char *key_string, *value_string;
4201     struct ovsdb_type type;
4202     int operator;
4203     bool retval;
4204     char *error;
4205
4206     error = parse_column_key_value(arg, table, &column, &key_string,
4207                                    &operator, operators, ARRAY_SIZE(operators),
4208                                    &value_string);
4209     die_if_error(error);
4210     if (!value_string) {
4211         vsctl_fatal("%s: missing value", arg);
4212     }
4213
4214     type = column->type;
4215     type.n_max = UINT_MAX;
4216
4217     have_datum = ovsdb_idl_read(row, column);
4218     if (key_string) {
4219         union ovsdb_atom want_key;
4220         struct ovsdb_datum b;
4221         unsigned int idx;
4222
4223         if (column->type.value.type == OVSDB_TYPE_VOID) {
4224             vsctl_fatal("cannot specify key to check for non-map column %s",
4225                         column->name);
4226         }
4227
4228         die_if_error(ovsdb_atom_from_string(&want_key, &column->type.key,
4229                                             key_string, symtab));
4230
4231         type.key = type.value;
4232         type.value.type = OVSDB_TYPE_VOID;
4233         die_if_error(ovsdb_datum_from_string(&b, &type, value_string, symtab));
4234
4235         idx = ovsdb_datum_find_key(have_datum,
4236                                    &want_key, column->type.key.type);
4237         if (idx == UINT_MAX && !is_set_operator(operator)) {
4238             retval = false;
4239         } else {
4240             struct ovsdb_datum a;
4241
4242             if (idx != UINT_MAX) {
4243                 a.n = 1;
4244                 a.keys = &have_datum->values[idx];
4245                 a.values = NULL;
4246             } else {
4247                 a.n = 0;
4248                 a.keys = NULL;
4249                 a.values = NULL;
4250             }
4251
4252             retval = evaluate_relop(&a, &b, &type, operator);
4253         }
4254
4255         ovsdb_atom_destroy(&want_key, column->type.key.type);
4256         ovsdb_datum_destroy(&b, &type);
4257     } else {
4258         struct ovsdb_datum want_datum;
4259
4260         die_if_error(ovsdb_datum_from_string(&want_datum, &column->type,
4261                                              value_string, symtab));
4262         retval = evaluate_relop(have_datum, &want_datum, &type, operator);
4263         ovsdb_datum_destroy(&want_datum, &column->type);
4264     }
4265
4266     free(key_string);
4267     free(value_string);
4268
4269     return retval;
4270 }
4271
4272 static void
4273 pre_cmd_wait_until(struct vsctl_context *ctx)
4274 {
4275     const char *table_name = ctx->argv[1];
4276     const struct vsctl_table_class *table;
4277     int i;
4278
4279     table = pre_get_table(ctx, table_name);
4280
4281     for (i = 3; i < ctx->argc; i++) {
4282         pre_parse_column_key_value(ctx, ctx->argv[i], table);
4283     }
4284 }
4285
4286 static void
4287 cmd_wait_until(struct vsctl_context *ctx)
4288 {
4289     const char *table_name = ctx->argv[1];
4290     const char *record_id = ctx->argv[2];
4291     const struct vsctl_table_class *table;
4292     const struct ovsdb_idl_row *row;
4293     int i;
4294
4295     table = get_table(table_name);
4296
4297     row = get_row(ctx, table, record_id, false);
4298     if (!row) {
4299         ctx->try_again = true;
4300         return;
4301     }
4302
4303     for (i = 3; i < ctx->argc; i++) {
4304         if (!is_condition_satisfied(table, row, ctx->argv[i], ctx->symtab)) {
4305             ctx->try_again = true;
4306             return;
4307         }
4308     }
4309 }
4310 \f
4311 /* Prepares 'ctx', which has already been initialized with
4312  * vsctl_context_init(), for processing 'command'. */
4313 static void
4314 vsctl_context_init_command(struct vsctl_context *ctx,
4315                            struct vsctl_command *command)
4316 {
4317     ctx->argc = command->argc;
4318     ctx->argv = command->argv;
4319     ctx->options = command->options;
4320
4321     ds_swap(&ctx->output, &command->output);
4322     ctx->table = command->table;
4323
4324     ctx->verified_ports = false;
4325
4326     ctx->try_again = false;
4327 }
4328
4329 /* Prepares 'ctx' for processing commands, initializing its members with the
4330  * values passed in as arguments.
4331  *
4332  * If 'command' is nonnull, calls vsctl_context_init_command() to prepare for
4333  * that particular command. */
4334 static void
4335 vsctl_context_init(struct vsctl_context *ctx, struct vsctl_command *command,
4336                    struct ovsdb_idl *idl, struct ovsdb_idl_txn *txn,
4337                    const struct ovsrec_open_vswitch *ovs,
4338                    struct ovsdb_symbol_table *symtab)
4339 {
4340     if (command) {
4341         vsctl_context_init_command(ctx, command);
4342     }
4343     ctx->idl = idl;
4344     ctx->txn = txn;
4345     ctx->ovs = ovs;
4346     ctx->symtab = symtab;
4347     ctx->cache_valid = false;
4348 }
4349
4350 /* Completes processing of 'command' within 'ctx'. */
4351 static void
4352 vsctl_context_done_command(struct vsctl_context *ctx,
4353                            struct vsctl_command *command)
4354 {
4355     ds_swap(&ctx->output, &command->output);
4356     command->table = ctx->table;
4357 }
4358
4359 /* Finishes up with 'ctx'.
4360  *
4361  * If command is nonnull, first calls vsctl_context_done_command() to complete
4362  * processing that command within 'ctx'. */
4363 static void
4364 vsctl_context_done(struct vsctl_context *ctx, struct vsctl_command *command)
4365 {
4366     if (command) {
4367         vsctl_context_done_command(ctx, command);
4368     }
4369     vsctl_context_invalidate_cache(ctx);
4370 }
4371
4372 static void
4373 run_prerequisites(struct vsctl_command *commands, size_t n_commands,
4374                   struct ovsdb_idl *idl)
4375 {
4376     struct vsctl_command *c;
4377
4378     ovsdb_idl_add_table(idl, &ovsrec_table_open_vswitch);
4379     if (wait_for_reload) {
4380         ovsdb_idl_add_column(idl, &ovsrec_open_vswitch_col_cur_cfg);
4381     }
4382     for (c = commands; c < &commands[n_commands]; c++) {
4383         if (c->syntax->prerequisites) {
4384             struct vsctl_context ctx;
4385
4386             ds_init(&c->output);
4387             c->table = NULL;
4388
4389             vsctl_context_init(&ctx, c, idl, NULL, NULL, NULL);
4390             (c->syntax->prerequisites)(&ctx);
4391             vsctl_context_done(&ctx, c);
4392
4393             ovs_assert(!c->output.string);
4394             ovs_assert(!c->table);
4395         }
4396     }
4397 }
4398
4399 static void
4400 do_vsctl(const char *args, struct vsctl_command *commands, size_t n_commands,
4401          struct ovsdb_idl *idl)
4402 {
4403     struct ovsdb_idl_txn *txn;
4404     const struct ovsrec_open_vswitch *ovs;
4405     enum ovsdb_idl_txn_status status;
4406     struct ovsdb_symbol_table *symtab;
4407     struct vsctl_context ctx;
4408     struct vsctl_command *c;
4409     struct shash_node *node;
4410     int64_t next_cfg = 0;
4411     char *error = NULL;
4412
4413     txn = the_idl_txn = ovsdb_idl_txn_create(idl);
4414     if (dry_run) {
4415         ovsdb_idl_txn_set_dry_run(txn);
4416     }
4417
4418     ovsdb_idl_txn_add_comment(txn, "ovs-vsctl: %s", args);
4419
4420     ovs = ovsrec_open_vswitch_first(idl);
4421     if (!ovs) {
4422         /* XXX add verification that table is empty */
4423         ovs = ovsrec_open_vswitch_insert(txn);
4424     }
4425
4426     if (wait_for_reload) {
4427         ovsdb_idl_txn_increment(txn, &ovs->header_,
4428                                 &ovsrec_open_vswitch_col_next_cfg);
4429     }
4430
4431     post_db_reload_check_init();
4432     symtab = ovsdb_symbol_table_create();
4433     for (c = commands; c < &commands[n_commands]; c++) {
4434         ds_init(&c->output);
4435         c->table = NULL;
4436     }
4437     vsctl_context_init(&ctx, NULL, idl, txn, ovs, symtab);
4438     for (c = commands; c < &commands[n_commands]; c++) {
4439         vsctl_context_init_command(&ctx, c);
4440         if (c->syntax->run) {
4441             (c->syntax->run)(&ctx);
4442         }
4443         vsctl_context_done_command(&ctx, c);
4444
4445         if (ctx.try_again) {
4446             vsctl_context_done(&ctx, NULL);
4447             goto try_again;
4448         }
4449     }
4450     vsctl_context_done(&ctx, NULL);
4451
4452     SHASH_FOR_EACH (node, &symtab->sh) {
4453         struct ovsdb_symbol *symbol = node->data;
4454         if (!symbol->created) {
4455             vsctl_fatal("row id \"%s\" is referenced but never created (e.g. "
4456                         "with \"-- --id=%s create ...\")",
4457                         node->name, node->name);
4458         }
4459         if (!symbol->strong_ref) {
4460             if (!symbol->weak_ref) {
4461                 VLOG_WARN("row id \"%s\" was created but no reference to it "
4462                           "was inserted, so it will not actually appear in "
4463                           "the database", node->name);
4464             } else {
4465                 VLOG_WARN("row id \"%s\" was created but only a weak "
4466                           "reference to it was inserted, so it will not "
4467                           "actually appear in the database", node->name);
4468             }
4469         }
4470     }
4471
4472     status = ovsdb_idl_txn_commit_block(txn);
4473     if (wait_for_reload && status == TXN_SUCCESS) {
4474         next_cfg = ovsdb_idl_txn_get_increment_new_value(txn);
4475     }
4476     if (status == TXN_UNCHANGED || status == TXN_SUCCESS) {
4477         for (c = commands; c < &commands[n_commands]; c++) {
4478             if (c->syntax->postprocess) {
4479                 struct vsctl_context ctx;
4480
4481                 vsctl_context_init(&ctx, c, idl, txn, ovs, symtab);
4482                 (c->syntax->postprocess)(&ctx);
4483                 vsctl_context_done(&ctx, c);
4484             }
4485         }
4486     }
4487     error = xstrdup(ovsdb_idl_txn_get_error(txn));
4488
4489     switch (status) {
4490     case TXN_UNCOMMITTED:
4491     case TXN_INCOMPLETE:
4492         OVS_NOT_REACHED();
4493
4494     case TXN_ABORTED:
4495         /* Should not happen--we never call ovsdb_idl_txn_abort(). */
4496         vsctl_fatal("transaction aborted");
4497
4498     case TXN_UNCHANGED:
4499     case TXN_SUCCESS:
4500         break;
4501
4502     case TXN_TRY_AGAIN:
4503         goto try_again;
4504
4505     case TXN_ERROR:
4506         vsctl_fatal("transaction error: %s", error);
4507
4508     case TXN_NOT_LOCKED:
4509         /* Should not happen--we never call ovsdb_idl_set_lock(). */
4510         vsctl_fatal("database not locked");
4511
4512     default:
4513         OVS_NOT_REACHED();
4514     }
4515     free(error);
4516
4517     ovsdb_symbol_table_destroy(symtab);
4518
4519     for (c = commands; c < &commands[n_commands]; c++) {
4520         struct ds *ds = &c->output;
4521
4522         if (c->table) {
4523             table_print(c->table, &table_style);
4524         } else if (oneline) {
4525             size_t j;
4526
4527             ds_chomp(ds, '\n');
4528             for (j = 0; j < ds->length; j++) {
4529                 int ch = ds->string[j];
4530                 switch (ch) {
4531                 case '\n':
4532                     fputs("\\n", stdout);
4533                     break;
4534
4535                 case '\\':
4536                     fputs("\\\\", stdout);
4537                     break;
4538
4539                 default:
4540                     putchar(ch);
4541                 }
4542             }
4543             putchar('\n');
4544         } else {
4545             fputs(ds_cstr(ds), stdout);
4546         }
4547         ds_destroy(&c->output);
4548         table_destroy(c->table);
4549         free(c->table);
4550
4551         shash_destroy_free_data(&c->options);
4552     }
4553     free(commands);
4554
4555     if (wait_for_reload && status != TXN_UNCHANGED) {
4556         /* Even, if --retry flag was not specified, ovs-vsctl still
4557          * has to retry to establish OVSDB connection, if wait_for_reload
4558          * was set.  Otherwise, ovs-vsctl would end up waiting forever
4559          * until cur_cfg would be updated. */
4560         ovsdb_idl_enable_reconnect(idl);
4561         for (;;) {
4562             ovsdb_idl_run(idl);
4563             OVSREC_OPEN_VSWITCH_FOR_EACH (ovs, idl) {
4564                 if (ovs->cur_cfg >= next_cfg) {
4565                     post_db_reload_do_checks(&ctx);
4566                     goto done;
4567                 }
4568             }
4569             ovsdb_idl_wait(idl);
4570             poll_block();
4571         }
4572     done: ;
4573     }
4574     ovsdb_idl_txn_destroy(txn);
4575     ovsdb_idl_destroy(idl);
4576
4577     exit(EXIT_SUCCESS);
4578
4579 try_again:
4580     /* Our transaction needs to be rerun, or a prerequisite was not met.  Free
4581      * resources and return so that the caller can try again. */
4582     if (txn) {
4583         ovsdb_idl_txn_abort(txn);
4584         ovsdb_idl_txn_destroy(txn);
4585         the_idl_txn = NULL;
4586     }
4587     ovsdb_symbol_table_destroy(symtab);
4588     for (c = commands; c < &commands[n_commands]; c++) {
4589         ds_destroy(&c->output);
4590         table_destroy(c->table);
4591         free(c->table);
4592     }
4593     free(error);
4594 }
4595
4596 /*
4597  * Developers who add new commands to the 'struct vsctl_command_syntax' must
4598  * define the 'arguments' member of the struct.  The following keywords are
4599  * available for composing the argument format:
4600  *
4601  *    TABLE     RECORD       BRIDGE       PARENT         PORT
4602  *    KEY       VALUE        ARG          KEY=VALUE      ?KEY=VALUE
4603  *    IFACE     SYSIFACE     COLUMN       COLUMN?:KEY    COLUMN?:KEY=VALUE
4604  *    MODE      CA-CERT      CERTIFICATE  PRIVATE-KEY
4605  *    TARGET    NEW-* (e.g. NEW-PORT)
4606  *
4607  * For argument types not listed above, just uses 'ARG' as place holder.
4608  *
4609  * Encloses the keyword with '[]' if it is optional.  Appends '...' to
4610  * keyword or enclosed keyword to indicate that the argument can be specified
4611  * multiple times.
4612  *
4613  * */
4614 static const struct vsctl_command_syntax all_commands[] = {
4615     /* Open vSwitch commands. */
4616     {"init", 0, 0, "", NULL, cmd_init, NULL, "", RW},
4617     {"show", 0, 0, "", pre_cmd_show, cmd_show, NULL, "", RO},
4618
4619     /* Bridge commands. */
4620     {"add-br", 1, 3, "NEW-BRIDGE [PARENT] [NEW-VLAN]", pre_get_info,
4621      cmd_add_br, NULL, "--may-exist", RW},
4622     {"del-br", 1, 1, "BRIDGE", pre_get_info, cmd_del_br,
4623      NULL, "--if-exists", RW},
4624     {"list-br", 0, 0, "", pre_get_info, cmd_list_br, NULL, "--real,--fake",
4625      RO},
4626     {"br-exists", 1, 1, "BRIDGE", pre_get_info, cmd_br_exists, NULL, "", RO},
4627     {"br-to-vlan", 1, 1, "BRIDGE", pre_get_info, cmd_br_to_vlan, NULL, "",
4628      RO},
4629     {"br-to-parent", 1, 1, "BRIDGE", pre_get_info, cmd_br_to_parent, NULL,
4630      "", RO},
4631     {"br-set-external-id", 2, 3, "BRIDGE KEY [VALUE]",
4632      pre_cmd_br_set_external_id, cmd_br_set_external_id, NULL, "", RW},
4633     {"br-get-external-id", 1, 2, "BRIDGE [KEY]", pre_cmd_br_get_external_id,
4634      cmd_br_get_external_id, NULL, "", RO},
4635
4636     /* Port commands. */
4637     {"list-ports", 1, 1, "BRIDGE", pre_get_info, cmd_list_ports, NULL, "",
4638      RO},
4639     {"add-port", 2, INT_MAX, "BRIDGE NEW-PORT [COLUMN[:KEY]=VALUE]...",
4640      pre_get_info, cmd_add_port, NULL, "--may-exist", RW},
4641     {"add-bond", 4, INT_MAX,
4642      "BRIDGE NEW-BOND-PORT SYSIFACE... [COLUMN[:KEY]=VALUE]...", pre_get_info,
4643      cmd_add_bond, NULL, "--may-exist,--fake-iface", RW},
4644     {"del-port", 1, 2, "[BRIDGE] PORT|IFACE", pre_get_info, cmd_del_port, NULL,
4645      "--if-exists,--with-iface", RW},
4646     {"port-to-br", 1, 1, "PORT", pre_get_info, cmd_port_to_br, NULL, "", RO},
4647
4648     /* Interface commands. */
4649     {"list-ifaces", 1, 1, "BRIDGE", pre_get_info, cmd_list_ifaces, NULL, "",
4650      RO},
4651     {"iface-to-br", 1, 1, "IFACE", pre_get_info, cmd_iface_to_br, NULL, "",
4652      RO},
4653
4654     /* Controller commands. */
4655     {"get-controller", 1, 1, "BRIDGE", pre_controller, cmd_get_controller,
4656      NULL, "", RO},
4657     {"del-controller", 1, 1, "BRIDGE", pre_controller, cmd_del_controller,
4658      NULL, "", RW},
4659     {"set-controller", 1, INT_MAX, "BRIDGE TARGET...", pre_controller,
4660      cmd_set_controller, NULL, "", RW},
4661     {"get-fail-mode", 1, 1, "BRIDGE", pre_get_info, cmd_get_fail_mode, NULL,
4662      "", RO},
4663     {"del-fail-mode", 1, 1, "BRIDGE", pre_get_info, cmd_del_fail_mode, NULL,
4664      "", RW},
4665     {"set-fail-mode", 2, 2, "BRIDGE MODE", pre_get_info, cmd_set_fail_mode,
4666      NULL, "", RW},
4667
4668     /* Manager commands. */
4669     {"get-manager", 0, 0, "", pre_manager, cmd_get_manager, NULL, "", RO},
4670     {"del-manager", 0, 0, "", pre_manager, cmd_del_manager, NULL, "", RW},
4671     {"set-manager", 1, INT_MAX, "TARGET...", pre_manager, cmd_set_manager,
4672      NULL, "", RW},
4673
4674     /* SSL commands. */
4675     {"get-ssl", 0, 0, "", pre_cmd_get_ssl, cmd_get_ssl, NULL, "", RO},
4676     {"del-ssl", 0, 0, "", pre_cmd_del_ssl, cmd_del_ssl, NULL, "", RW},
4677     {"set-ssl", 3, 3, "PRIVATE-KEY CERTIFICATE CA-CERT", pre_cmd_set_ssl,
4678      cmd_set_ssl, NULL, "--bootstrap", RW},
4679
4680     /* Auto Attach commands. */
4681     {"add-aa-mapping", 3, 3, "BRIDGE ARG ARG", pre_get_info, cmd_add_aa_mapping,
4682      NULL, "", RW},
4683     {"del-aa-mapping", 3, 3, "BRIDGE ARG ARG", pre_aa_mapping, cmd_del_aa_mapping,
4684      NULL, "", RW},
4685     {"get-aa-mapping", 1, 1, "BRIDGE", pre_aa_mapping, cmd_get_aa_mapping,
4686      NULL, "", RO},
4687
4688     /* Switch commands. */
4689     {"emer-reset", 0, 0, "", pre_cmd_emer_reset, cmd_emer_reset, NULL, "", RW},
4690
4691     /* Database commands. */
4692     {"comment", 0, INT_MAX, "[ARG]...", NULL, NULL, NULL, "", RO},
4693     {"get", 2, INT_MAX, "TABLE RECORD [COLUMN[:KEY]]...",pre_cmd_get, cmd_get,
4694      NULL, "--if-exists,--id=", RO},
4695     {"list", 1, INT_MAX, "TABLE [RECORD]...", pre_cmd_list, cmd_list, NULL,
4696      "--if-exists,--columns=", RO},
4697     {"find", 1, INT_MAX, "TABLE [COLUMN[:KEY]=VALUE]...", pre_cmd_find,
4698      cmd_find, NULL, "--columns=", RO},
4699     {"set", 3, INT_MAX, "TABLE RECORD COLUMN[:KEY]=VALUE...", pre_cmd_set,
4700      cmd_set, NULL, "--if-exists", RW},
4701     {"add", 4, INT_MAX, "TABLE RECORD COLUMN [KEY=]VALUE...", pre_cmd_add,
4702      cmd_add, NULL, "--if-exists", RW},
4703     {"remove", 4, INT_MAX, "TABLE RECORD COLUMN KEY|VALUE|KEY=VALUE...",
4704      pre_cmd_remove, cmd_remove, NULL, "--if-exists", RW},
4705     {"clear", 3, INT_MAX, "TABLE RECORD COLUMN...", pre_cmd_clear, cmd_clear,
4706      NULL, "--if-exists", RW},
4707     {"create", 2, INT_MAX, "TABLE COLUMN[:KEY]=VALUE...", pre_create,
4708      cmd_create, post_create, "--id=", RW},
4709     {"destroy", 1, INT_MAX, "TABLE [RECORD]...", pre_cmd_destroy, cmd_destroy,
4710      NULL, "--if-exists,--all", RW},
4711     {"wait-until", 2, INT_MAX, "TABLE RECORD [COLUMN[:KEY]=VALUE]...",
4712      pre_cmd_wait_until, cmd_wait_until, NULL, "", RO},
4713
4714     {NULL, 0, 0, NULL, NULL, NULL, NULL, NULL, RO},
4715 };
4716
4717 static const struct vsctl_command_syntax *get_all_commands(void)
4718 {
4719     return all_commands;
4720 }