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