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