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