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