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