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