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