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