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