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