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