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