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