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