fe78387677e92b54657cb07470b09e5ce6ffb1ab
[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 Database commands:\n\
443   list TBL [REC]              list RECord (or all records) in TBL\n\
444   get TBL REC COL[:KEY]       print values of COLumns in RECORD in TBL\n\
445   set TBL REC COL[:KEY]=VALUE set COLumn values in RECord in TBL\n\
446   add TBL REC COL [KEY=]VALUE add (KEY=)VALUE to COLumn in RECord in TBL\n\
447   remove TBL REC COL [KEY=]VALUE  remove (KEY=)VALUE from COLumn\n\
448   clear TBL REC COL           clear values from COLumn in RECord in TBL\n\
449   create TBL COL[:KEY]=VALUE  create and initialize new record\n\
450   destroy TBL REC             delete REC from TBL\n\
451 Potentially unsafe database commands require --force option.\n\
452 \n\
453 Options:\n\
454   --db=DATABASE               connect to DATABASE\n\
455                               (default: %s)\n\
456   --oneline                   print exactly one line of output per command\n",
457            program_name, program_name, default_db());
458     vlog_usage();
459     printf("\n\
460 Other options:\n\
461   -h, --help                  display this help message\n\
462   -V, --version               display version information\n");
463     exit(EXIT_SUCCESS);
464 }
465
466 static char *
467 default_db(void)
468 {
469     static char *def;
470     if (!def) {
471         def = xasprintf("unix:%s/db.sock", ovs_rundir);
472     }
473     return def;
474 }
475 \f
476 struct vsctl_context {
477     /* Read-only. */
478     int argc;
479     char **argv;
480     struct shash options;
481
482     /* Modifiable state. */
483     struct ds output;
484     struct ovsdb_idl *idl;
485     struct ovsdb_idl_txn *txn;
486     const struct ovsrec_open_vswitch *ovs;
487 };
488
489 struct vsctl_bridge {
490     struct ovsrec_bridge *br_cfg;
491     char *name;
492     struct ovsrec_controller *ctrl;
493     struct vsctl_bridge *parent;
494     int vlan;
495 };
496
497 struct vsctl_port {
498     struct ovsrec_port *port_cfg;
499     struct vsctl_bridge *bridge;
500 };
501
502 struct vsctl_iface {
503     struct ovsrec_interface *iface_cfg;
504     struct vsctl_port *port;
505 };
506
507 struct vsctl_info {
508     struct shash bridges;
509     struct shash ports;
510     struct shash ifaces;
511     struct ovsrec_controller *ctrl;
512 };
513
514 static char *
515 vsctl_context_to_string(const struct vsctl_context *ctx)
516 {
517     const struct shash_node *node;
518     struct svec words;
519     char *s;
520     int i;
521
522     svec_init(&words);
523     SHASH_FOR_EACH (node, &ctx->options) {
524         svec_add(&words, node->name);
525     }
526     for (i = 0; i < ctx->argc; i++) {
527         svec_add(&words, ctx->argv[i]);
528     }
529     svec_terminate(&words);
530
531     s = process_escape_args(words.names);
532
533     svec_destroy(&words);
534
535     return s;
536 }
537
538 static struct vsctl_bridge *
539 add_bridge(struct vsctl_info *b,
540            struct ovsrec_bridge *br_cfg, const char *name,
541            struct vsctl_bridge *parent, int vlan)
542 {
543     struct vsctl_bridge *br = xmalloc(sizeof *br);
544     br->br_cfg = br_cfg;
545     br->name = xstrdup(name);
546     br->parent = parent;
547     br->vlan = vlan;
548     br->ctrl = parent ? parent->br_cfg->controller : br_cfg->controller;
549     shash_add(&b->bridges, br->name, br);
550     return br;
551 }
552
553 static bool
554 port_is_fake_bridge(const struct ovsrec_port *port_cfg)
555 {
556     return (port_cfg->fake_bridge
557             && port_cfg->tag
558             && *port_cfg->tag >= 1 && *port_cfg->tag <= 4095);
559 }
560
561 static struct vsctl_bridge *
562 find_vlan_bridge(struct vsctl_info *info,
563                  struct vsctl_bridge *parent, int vlan)
564 {
565     struct shash_node *node;
566
567     SHASH_FOR_EACH (node, &info->bridges) {
568         struct vsctl_bridge *br = node->data;
569         if (br->parent == parent && br->vlan == vlan) {
570             return br;
571         }
572     }
573
574     return NULL;
575 }
576
577 static void
578 free_info(struct vsctl_info *info)
579 {
580     struct shash_node *node;
581
582     SHASH_FOR_EACH (node, &info->bridges) {
583         struct vsctl_bridge *bridge = node->data;
584         free(bridge->name);
585         free(bridge);
586     }
587     shash_destroy(&info->bridges);
588
589     SHASH_FOR_EACH (node, &info->ports) {
590         struct vsctl_port *port = node->data;
591         free(port);
592     }
593     shash_destroy(&info->ports);
594
595     SHASH_FOR_EACH (node, &info->ifaces) {
596         struct vsctl_iface *iface = node->data;
597         free(iface);
598     }
599     shash_destroy(&info->ifaces);
600 }
601
602 static void
603 get_info(const struct ovsrec_open_vswitch *ovs, struct vsctl_info *info)
604 {
605     struct shash bridges, ports;
606     size_t i;
607
608     shash_init(&info->bridges);
609     shash_init(&info->ports);
610     shash_init(&info->ifaces);
611
612     info->ctrl = ovs->controller;
613
614     shash_init(&bridges);
615     shash_init(&ports);
616     for (i = 0; i < ovs->n_bridges; i++) {
617         struct ovsrec_bridge *br_cfg = ovs->bridges[i];
618         struct vsctl_bridge *br;
619         size_t j;
620
621         if (!shash_add_once(&bridges, br_cfg->name, NULL)) {
622             VLOG_WARN("%s: database contains duplicate bridge name",
623                       br_cfg->name);
624             continue;
625         }
626         br = add_bridge(info, br_cfg, br_cfg->name, NULL, 0);
627         if (!br) {
628             continue;
629         }
630
631         for (j = 0; j < br_cfg->n_ports; j++) {
632             struct ovsrec_port *port_cfg = br_cfg->ports[j];
633
634             if (!shash_add_once(&ports, port_cfg->name, NULL)) {
635                 VLOG_WARN("%s: database contains duplicate port name",
636                           port_cfg->name);
637                 continue;
638             }
639
640             if (port_is_fake_bridge(port_cfg)
641                 && shash_add_once(&bridges, port_cfg->name, NULL)) {
642                 add_bridge(info, NULL, port_cfg->name, br, *port_cfg->tag);
643             }
644         }
645     }
646     shash_destroy(&bridges);
647     shash_destroy(&ports);
648
649     shash_init(&bridges);
650     shash_init(&ports);
651     for (i = 0; i < ovs->n_bridges; i++) {
652         struct ovsrec_bridge *br_cfg = ovs->bridges[i];
653         struct vsctl_bridge *br;
654         size_t j;
655
656         if (!shash_add_once(&bridges, br_cfg->name, NULL)) {
657             continue;
658         }
659         br = shash_find_data(&info->bridges, br_cfg->name);
660         for (j = 0; j < br_cfg->n_ports; j++) {
661             struct ovsrec_port *port_cfg = br_cfg->ports[j];
662             struct vsctl_port *port;
663             size_t k;
664
665             if (!shash_add_once(&ports, port_cfg->name, NULL)) {
666                 continue;
667             }
668
669             if (port_is_fake_bridge(port_cfg)
670                 && !shash_add_once(&bridges, port_cfg->name, NULL)) {
671                 continue;
672             }
673
674             port = xmalloc(sizeof *port);
675             port->port_cfg = port_cfg;
676             if (port_cfg->tag
677                 && *port_cfg->tag >= 1 && *port_cfg->tag <= 4095) {
678                 port->bridge = find_vlan_bridge(info, br, *port_cfg->tag);
679                 if (!port->bridge) {
680                     port->bridge = br;
681                 }
682             } else {
683                 port->bridge = br;
684             }
685             shash_add(&info->ports, port_cfg->name, port);
686
687             for (k = 0; k < port_cfg->n_interfaces; k++) {
688                 struct ovsrec_interface *iface_cfg = port_cfg->interfaces[k];
689                 struct vsctl_iface *iface;
690
691                 if (shash_find(&info->ifaces, iface_cfg->name)) {
692                     VLOG_WARN("%s: database contains duplicate interface name",
693                               iface_cfg->name);
694                     continue;
695                 }
696
697                 iface = xmalloc(sizeof *iface);
698                 iface->iface_cfg = iface_cfg;
699                 iface->port = port;
700                 shash_add(&info->ifaces, iface_cfg->name, iface);
701             }
702         }
703     }
704     shash_destroy(&bridges);
705     shash_destroy(&ports);
706 }
707
708 static void
709 check_conflicts(struct vsctl_info *info, const char *name,
710                 char *msg)
711 {
712     struct vsctl_iface *iface;
713     struct vsctl_port *port;
714
715     if (shash_find(&info->bridges, name)) {
716         vsctl_fatal("%s because a bridge named %s already exists",
717                     msg, name);
718     }
719
720     port = shash_find_data(&info->ports, name);
721     if (port) {
722         vsctl_fatal("%s because a port named %s already exists on "
723                     "bridge %s", msg, name, port->bridge->name);
724     }
725
726     iface = shash_find_data(&info->ifaces, name);
727     if (iface) {
728         vsctl_fatal("%s because an interface named %s already exists "
729                     "on bridge %s", msg, name, iface->port->bridge->name);
730     }
731
732     free(msg);
733 }
734
735 static struct vsctl_bridge *
736 find_bridge(struct vsctl_info *info, const char *name, bool must_exist)
737 {
738     struct vsctl_bridge *br = shash_find_data(&info->bridges, name);
739     if (must_exist && !br) {
740         vsctl_fatal("no bridge named %s", name);
741     }
742     return br;
743 }
744
745 static struct vsctl_bridge *
746 find_real_bridge(struct vsctl_info *info, const char *name, bool must_exist)
747 {
748     struct vsctl_bridge *br = find_bridge(info, name, must_exist);
749     if (br && br->parent) {
750         vsctl_fatal("%s is a fake bridge", name);
751     }
752     return br;
753 }
754
755 static struct vsctl_port *
756 find_port(struct vsctl_info *info, const char *name, bool must_exist)
757 {
758     struct vsctl_port *port = shash_find_data(&info->ports, name);
759     if (port && !strcmp(name, port->bridge->name)) {
760         port = NULL;
761     }
762     if (must_exist && !port) {
763         vsctl_fatal("no port named %s", name);
764     }
765     return port;
766 }
767
768 static struct vsctl_iface *
769 find_iface(struct vsctl_info *info, const char *name, bool must_exist)
770 {
771     struct vsctl_iface *iface = shash_find_data(&info->ifaces, name);
772     if (iface && !strcmp(name, iface->port->bridge->name)) {
773         iface = NULL;
774     }
775     if (must_exist && !iface) {
776         vsctl_fatal("no interface named %s", name);
777     }
778     return iface;
779 }
780
781 static void
782 bridge_insert_port(struct ovsrec_bridge *br, struct ovsrec_port *port)
783 {
784     struct ovsrec_port **ports;
785     size_t i;
786
787     ports = xmalloc(sizeof *br->ports * (br->n_ports + 1));
788     for (i = 0; i < br->n_ports; i++) {
789         ports[i] = br->ports[i];
790     }
791     ports[br->n_ports] = port;
792     ovsrec_bridge_set_ports(br, ports, br->n_ports + 1);
793     free(ports);
794 }
795
796 static void
797 bridge_delete_port(struct ovsrec_bridge *br, struct ovsrec_port *port)
798 {
799     struct ovsrec_port **ports;
800     size_t i, n;
801
802     ports = xmalloc(sizeof *br->ports * br->n_ports);
803     for (i = n = 0; i < br->n_ports; i++) {
804         if (br->ports[i] != port) {
805             ports[n++] = br->ports[i];
806         }
807     }
808     ovsrec_bridge_set_ports(br, ports, n);
809     free(ports);
810 }
811
812 static void
813 ovs_insert_bridge(const struct ovsrec_open_vswitch *ovs,
814                   struct ovsrec_bridge *bridge)
815 {
816     struct ovsrec_bridge **bridges;
817     size_t i;
818
819     bridges = xmalloc(sizeof *ovs->bridges * (ovs->n_bridges + 1));
820     for (i = 0; i < ovs->n_bridges; i++) {
821         bridges[i] = ovs->bridges[i];
822     }
823     bridges[ovs->n_bridges] = bridge;
824     ovsrec_open_vswitch_set_bridges(ovs, bridges, ovs->n_bridges + 1);
825     free(bridges);
826 }
827
828 static void
829 ovs_delete_bridge(const struct ovsrec_open_vswitch *ovs,
830                   struct ovsrec_bridge *bridge)
831 {
832     struct ovsrec_bridge **bridges;
833     size_t i, n;
834
835     bridges = xmalloc(sizeof *ovs->bridges * ovs->n_bridges);
836     for (i = n = 0; i < ovs->n_bridges; i++) {
837         if (ovs->bridges[i] != bridge) {
838             bridges[n++] = ovs->bridges[i];
839         }
840     }
841     ovsrec_open_vswitch_set_bridges(ovs, bridges, n);
842     free(bridges);
843 }
844
845 static void
846 cmd_init(struct vsctl_context *ctx OVS_UNUSED)
847 {
848 }
849
850 static void
851 cmd_add_br(struct vsctl_context *ctx)
852 {
853     bool may_exist = shash_find(&ctx->options, "--may-exist") != 0;
854     const char *br_name, *parent_name;
855     struct vsctl_info info;
856     int vlan;
857
858     br_name = ctx->argv[1];
859     if (ctx->argc == 2) {
860         parent_name = NULL;
861         vlan = 0;
862     } else if (ctx->argc == 4) {
863         parent_name = ctx->argv[2];
864         vlan = atoi(ctx->argv[3]);
865         if (vlan < 1 || vlan > 4095) {
866             vsctl_fatal("%s: vlan must be between 1 and 4095", ctx->argv[0]);
867         }
868     } else {
869         vsctl_fatal("'%s' command takes exactly 1 or 3 arguments",
870                     ctx->argv[0]);
871     }
872
873     get_info(ctx->ovs, &info);
874     if (may_exist) {
875         struct vsctl_bridge *br;
876
877         br = find_bridge(&info, br_name, false);
878         if (br) {
879             if (!parent_name) {
880                 if (br->parent) {
881                     vsctl_fatal("\"--may-exist add-br %s\" but %s is "
882                                 "a VLAN bridge for VLAN %d",
883                                 br_name, br_name, br->vlan);
884                 }
885             } else {
886                 if (!br->parent) {
887                     vsctl_fatal("\"--may-exist add-br %s %s %d\" but %s "
888                                 "is not a VLAN bridge",
889                                 br_name, parent_name, vlan, br_name);
890                 } else if (strcmp(br->parent->name, parent_name)) {
891                     vsctl_fatal("\"--may-exist add-br %s %s %d\" but %s "
892                                 "has the wrong parent %s",
893                                 br_name, parent_name, vlan,
894                                 br_name, br->parent->name);
895                 } else if (br->vlan != vlan) {
896                     vsctl_fatal("\"--may-exist add-br %s %s %d\" but %s "
897                                 "is a VLAN bridge for the wrong VLAN %d",
898                                 br_name, parent_name, vlan, br_name, br->vlan);
899                 }
900             }
901             return;
902         }
903     }
904     check_conflicts(&info, br_name,
905                     xasprintf("cannot create a bridge named %s", br_name));
906
907     if (!parent_name) {
908         struct ovsrec_port *port;
909         struct ovsrec_interface *iface;
910         struct ovsrec_bridge *br;
911
912         iface = ovsrec_interface_insert(ctx->txn);
913         ovsrec_interface_set_name(iface, br_name);
914
915         port = ovsrec_port_insert(ctx->txn);
916         ovsrec_port_set_name(port, br_name);
917         ovsrec_port_set_interfaces(port, &iface, 1);
918
919         br = ovsrec_bridge_insert(ctx->txn);
920         ovsrec_bridge_set_name(br, br_name);
921         ovsrec_bridge_set_ports(br, &port, 1);
922
923         ovs_insert_bridge(ctx->ovs, br);
924     } else {
925         struct vsctl_bridge *parent;
926         struct ovsrec_port *port;
927         struct ovsrec_interface *iface;
928         struct ovsrec_bridge *br;
929         int64_t tag = vlan;
930
931         parent = find_bridge(&info, parent_name, false);
932         if (parent && parent->vlan) {
933             vsctl_fatal("cannot create bridge with fake bridge as parent");
934         }
935         if (!parent) {
936             vsctl_fatal("parent bridge %s does not exist", parent_name);
937         }
938         br = parent->br_cfg;
939
940         iface = ovsrec_interface_insert(ctx->txn);
941         ovsrec_interface_set_name(iface, br_name);
942         ovsrec_interface_set_type(iface, "internal");
943
944         port = ovsrec_port_insert(ctx->txn);
945         ovsrec_port_set_name(port, br_name);
946         ovsrec_port_set_interfaces(port, &iface, 1);
947         ovsrec_port_set_fake_bridge(port, true);
948         ovsrec_port_set_tag(port, &tag, 1);
949
950         bridge_insert_port(br, port);
951     }
952
953     free_info(&info);
954 }
955
956 static void
957 del_port(struct vsctl_info *info, struct vsctl_port *port)
958 {
959     struct shash_node *node;
960
961     SHASH_FOR_EACH (node, &info->ifaces) {
962         struct vsctl_iface *iface = node->data;
963         if (iface->port == port) {
964             ovsrec_interface_delete(iface->iface_cfg);
965         }
966     }
967     ovsrec_port_delete(port->port_cfg);
968
969     bridge_delete_port((port->bridge->parent
970                         ? port->bridge->parent->br_cfg
971                         : port->bridge->br_cfg), port->port_cfg);
972 }
973
974 static void
975 cmd_del_br(struct vsctl_context *ctx)
976 {
977     bool must_exist = !shash_find(&ctx->options, "--if-exists");
978     struct vsctl_bridge *bridge;
979     struct vsctl_info info;
980
981     get_info(ctx->ovs, &info);
982     bridge = find_bridge(&info, ctx->argv[1], must_exist);
983     if (bridge) {
984         struct shash_node *node;
985
986         SHASH_FOR_EACH (node, &info.ports) {
987             struct vsctl_port *port = node->data;
988             if (port->bridge == bridge || port->bridge->parent == bridge
989                 || !strcmp(port->port_cfg->name, bridge->name)) {
990                 del_port(&info, port);
991             }
992         }
993         if (bridge->br_cfg) {
994             ovsrec_bridge_delete(bridge->br_cfg);
995             ovs_delete_bridge(ctx->ovs, bridge->br_cfg);
996         }
997     }
998     free_info(&info);
999 }
1000
1001 static void
1002 output_sorted(struct svec *svec, struct ds *output)
1003 {
1004     const char *name;
1005     size_t i;
1006
1007     svec_sort(svec);
1008     SVEC_FOR_EACH (i, name, svec) {
1009         ds_put_format(output, "%s\n", name);
1010     }
1011 }
1012
1013 static void
1014 cmd_list_br(struct vsctl_context *ctx)
1015 {
1016     struct shash_node *node;
1017     struct vsctl_info info;
1018     struct svec bridges;
1019
1020     get_info(ctx->ovs, &info);
1021
1022     svec_init(&bridges);
1023     SHASH_FOR_EACH (node, &info.bridges) {
1024         struct vsctl_bridge *br = node->data;
1025         svec_add(&bridges, br->name);
1026     }
1027     output_sorted(&bridges, &ctx->output);
1028     svec_destroy(&bridges);
1029
1030     free_info(&info);
1031 }
1032
1033 static void
1034 cmd_br_exists(struct vsctl_context *ctx)
1035 {
1036     struct vsctl_info info;
1037
1038     get_info(ctx->ovs, &info);
1039     if (!find_bridge(&info, ctx->argv[1], false)) {
1040         vsctl_exit(2);
1041     }
1042     free_info(&info);
1043 }
1044
1045 /* Returns true if 'b_prefix' (of length 'b_prefix_len') concatenated with 'b'
1046  * equals 'a', false otherwise. */
1047 static bool
1048 key_matches(const char *a,
1049             const char *b_prefix, size_t b_prefix_len, const char *b)
1050 {
1051     return !strncmp(a, b_prefix, b_prefix_len) && !strcmp(a + b_prefix_len, b);
1052 }
1053
1054 static void
1055 set_external_id(char **old_keys, char **old_values, size_t old_n,
1056                 char *key, char *value,
1057                 char ***new_keysp, char ***new_valuesp, size_t *new_np)
1058 {
1059     char **new_keys;
1060     char **new_values;
1061     size_t new_n;
1062     size_t i;
1063
1064     new_keys = xmalloc(sizeof *new_keys * (old_n + 1));
1065     new_values = xmalloc(sizeof *new_values * (old_n + 1));
1066     new_n = 0;
1067     for (i = 0; i < old_n; i++) {
1068         if (strcmp(key, old_keys[i])) {
1069             new_keys[new_n] = old_keys[i];
1070             new_values[new_n] = old_values[i];
1071             new_n++;
1072         }
1073     }
1074     if (value) {
1075         new_keys[new_n] = key;
1076         new_values[new_n] = value;
1077         new_n++;
1078     }
1079     *new_keysp = new_keys;
1080     *new_valuesp = new_values;
1081     *new_np = new_n;
1082 }
1083
1084 static void
1085 cmd_br_set_external_id(struct vsctl_context *ctx)
1086 {
1087     struct vsctl_info info;
1088     struct vsctl_bridge *bridge;
1089     char **keys, **values;
1090     size_t n;
1091
1092     get_info(ctx->ovs, &info);
1093     bridge = find_bridge(&info, ctx->argv[1], true);
1094     if (bridge->br_cfg) {
1095         set_external_id(bridge->br_cfg->key_external_ids,
1096                         bridge->br_cfg->value_external_ids,
1097                         bridge->br_cfg->n_external_ids,
1098                         ctx->argv[2], ctx->argc >= 4 ? ctx->argv[3] : NULL,
1099                         &keys, &values, &n);
1100         ovsrec_bridge_set_external_ids(bridge->br_cfg, keys, values, n);
1101     } else {
1102         char *key = xasprintf("fake-bridge-%s", ctx->argv[2]);
1103         struct vsctl_port *port = shash_find_data(&info.ports, ctx->argv[1]);
1104         set_external_id(port->port_cfg->key_external_ids,
1105                         port->port_cfg->value_external_ids,
1106                         port->port_cfg->n_external_ids,
1107                         key, ctx->argc >= 4 ? ctx->argv[3] : NULL,
1108                         &keys, &values, &n);
1109         ovsrec_port_set_external_ids(port->port_cfg, keys, values, n);
1110         free(key);
1111     }
1112     free(keys);
1113     free(values);
1114
1115     free_info(&info);
1116 }
1117
1118 static void
1119 get_external_id(char **keys, char **values, size_t n,
1120                 const char *prefix, const char *key,
1121                 struct ds *output)
1122 {
1123     size_t prefix_len = strlen(prefix);
1124     struct svec svec;
1125     size_t i;
1126
1127     svec_init(&svec);
1128     for (i = 0; i < n; i++) {
1129         if (!key && !strncmp(keys[i], prefix, prefix_len)) {
1130             svec_add_nocopy(&svec, xasprintf("%s=%s",
1131                                              keys[i] + prefix_len, values[i]));
1132         } else if (key_matches(keys[i], prefix, prefix_len, key)) {
1133             svec_add(&svec, values[i]);
1134             break;
1135         }
1136     }
1137     output_sorted(&svec, output);
1138     svec_destroy(&svec);
1139 }
1140
1141 static void
1142 cmd_br_get_external_id(struct vsctl_context *ctx)
1143 {
1144     struct vsctl_info info;
1145     struct vsctl_bridge *bridge;
1146
1147     get_info(ctx->ovs, &info);
1148     bridge = find_bridge(&info, ctx->argv[1], true);
1149     if (bridge->br_cfg) {
1150         get_external_id(bridge->br_cfg->key_external_ids,
1151                         bridge->br_cfg->value_external_ids,
1152                         bridge->br_cfg->n_external_ids,
1153                         "", ctx->argc >= 3 ? ctx->argv[2] : NULL,
1154                         &ctx->output);
1155     } else {
1156         struct vsctl_port *port = shash_find_data(&info.ports, ctx->argv[1]);
1157         get_external_id(port->port_cfg->key_external_ids,
1158                         port->port_cfg->value_external_ids,
1159                         port->port_cfg->n_external_ids,
1160                         "fake-bridge-", ctx->argc >= 3 ? ctx->argv[2] : NULL, &ctx->output);
1161     }
1162     free_info(&info);
1163 }
1164
1165
1166 static void
1167 cmd_list_ports(struct vsctl_context *ctx)
1168 {
1169     struct vsctl_bridge *br;
1170     struct shash_node *node;
1171     struct vsctl_info info;
1172     struct svec ports;
1173
1174     get_info(ctx->ovs, &info);
1175     br = find_bridge(&info, ctx->argv[1], true);
1176
1177     svec_init(&ports);
1178     SHASH_FOR_EACH (node, &info.ports) {
1179         struct vsctl_port *port = node->data;
1180
1181         if (strcmp(port->port_cfg->name, br->name) && br == port->bridge) {
1182             svec_add(&ports, port->port_cfg->name);
1183         }
1184     }
1185     output_sorted(&ports, &ctx->output);
1186     svec_destroy(&ports);
1187
1188     free_info(&info);
1189 }
1190
1191 static void
1192 add_port(struct vsctl_context *ctx,
1193          const char *br_name, const char *port_name,
1194          bool may_exist, bool fake_iface,
1195          char *iface_names[], int n_ifaces,
1196          char *settings[], int n_settings)
1197 {
1198     struct vsctl_info info;
1199     struct vsctl_bridge *bridge;
1200     struct ovsrec_interface **ifaces;
1201     struct ovsrec_port *port;
1202     size_t i;
1203
1204     get_info(ctx->ovs, &info);
1205     if (may_exist) {
1206         struct vsctl_port *port;
1207
1208         port = find_port(&info, port_name, false);
1209         if (port) {
1210             struct svec want_names, have_names;
1211             size_t i;
1212
1213             svec_init(&want_names);
1214             for (i = 0; i < n_ifaces; i++) {
1215                 svec_add(&want_names, iface_names[i]);
1216             }
1217             svec_sort(&want_names);
1218
1219             svec_init(&have_names);
1220             for (i = 0; i < port->port_cfg->n_interfaces; i++) {
1221                 svec_add(&have_names, port->port_cfg->interfaces[i]->name);
1222             }
1223             svec_sort(&have_names);
1224
1225             if (strcmp(port->bridge->name, br_name)) {
1226                 char *command = vsctl_context_to_string(ctx);
1227                 vsctl_fatal("\"%s\" but %s is actually attached to bridge %s",
1228                             command, port_name, port->bridge->name);
1229             }
1230
1231             if (!svec_equal(&want_names, &have_names)) {
1232                 char *have_names_string = svec_join(&have_names, ", ", "");
1233                 char *command = vsctl_context_to_string(ctx);
1234
1235                 vsctl_fatal("\"%s\" but %s actually has interface(s) %s",
1236                             command, port_name, have_names_string);
1237             }
1238
1239             svec_destroy(&want_names);
1240             svec_destroy(&have_names);
1241
1242             return;
1243         }
1244     }
1245     check_conflicts(&info, port_name,
1246                     xasprintf("cannot create a port named %s", port_name));
1247     for (i = 0; i < n_ifaces; i++) {
1248         check_conflicts(&info, iface_names[i],
1249                         xasprintf("cannot create an interface named %s",
1250                                   iface_names[i]));
1251     }
1252     bridge = find_bridge(&info, br_name, true);
1253
1254     ifaces = xmalloc(n_ifaces * sizeof *ifaces);
1255     for (i = 0; i < n_ifaces; i++) {
1256         ifaces[i] = ovsrec_interface_insert(ctx->txn);
1257         ovsrec_interface_set_name(ifaces[i], iface_names[i]);
1258     }
1259
1260     port = ovsrec_port_insert(ctx->txn);
1261     ovsrec_port_set_name(port, port_name);
1262     ovsrec_port_set_interfaces(port, ifaces, n_ifaces);
1263     ovsrec_port_set_bond_fake_iface(port, fake_iface);
1264     free(ifaces);
1265
1266     if (bridge->vlan) {
1267         int64_t tag = bridge->vlan;
1268         ovsrec_port_set_tag(port, &tag, 1);
1269     }
1270
1271     for (i = 0; i < n_settings; i++) {
1272         set_column(get_table("Port"), &port->header_, settings[i]);
1273     }
1274
1275     bridge_insert_port((bridge->parent ? bridge->parent->br_cfg
1276                         : bridge->br_cfg), port);
1277
1278     free_info(&info);
1279 }
1280
1281 static void
1282 cmd_add_port(struct vsctl_context *ctx)
1283 {
1284     bool may_exist = shash_find(&ctx->options, "--may-exist") != 0;
1285
1286     add_port(ctx, ctx->argv[1], ctx->argv[2], may_exist, false,
1287              &ctx->argv[2], 1, &ctx->argv[3], ctx->argc - 3);
1288 }
1289
1290 static void
1291 cmd_add_bond(struct vsctl_context *ctx)
1292 {
1293     bool may_exist = shash_find(&ctx->options, "--may-exist") != 0;
1294     bool fake_iface = shash_find(&ctx->options, "--fake-iface");
1295     int n_ifaces;
1296     int i;
1297
1298     n_ifaces = ctx->argc - 3;
1299     for (i = 3; i < ctx->argc; i++) {
1300         if (strchr(ctx->argv[i], '=')) {
1301             n_ifaces = i - 3;
1302             break;
1303         }
1304     }
1305     if (n_ifaces < 2) {
1306         vsctl_fatal("add-bond requires at least 2 interfaces, but only "
1307                     "%d were specified", n_ifaces);
1308     }
1309
1310     add_port(ctx, ctx->argv[1], ctx->argv[2], may_exist, fake_iface,
1311              &ctx->argv[3], n_ifaces,
1312              &ctx->argv[n_ifaces + 3], ctx->argc - 3 - n_ifaces);
1313 }
1314
1315 static void
1316 cmd_del_port(struct vsctl_context *ctx)
1317 {
1318     bool must_exist = !shash_find(&ctx->options, "--if-exists");
1319     bool with_iface = shash_find(&ctx->options, "--with-iface") != NULL;
1320     struct vsctl_port *port;
1321     struct vsctl_info info;
1322
1323     get_info(ctx->ovs, &info);
1324     if (!with_iface) {
1325         port = find_port(&info, ctx->argv[ctx->argc - 1], must_exist);
1326     } else {
1327         const char *target = ctx->argv[ctx->argc - 1];
1328         struct vsctl_iface *iface;
1329
1330         port = find_port(&info, target, false);
1331         if (!port) {
1332             iface = find_iface(&info, target, false);
1333             if (iface) {
1334                 port = iface->port;
1335             }
1336         }
1337         if (must_exist && !port) {
1338             vsctl_fatal("no port or interface named %s", target);
1339         }
1340     }
1341
1342     if (port) {
1343         if (ctx->argc == 3) {
1344             struct vsctl_bridge *bridge;
1345
1346             bridge = find_bridge(&info, ctx->argv[1], true);
1347             if (port->bridge != bridge) {
1348                 if (port->bridge->parent == bridge) {
1349                     vsctl_fatal("bridge %s does not have a port %s (although "
1350                                 "its parent bridge %s does)",
1351                                 ctx->argv[1], ctx->argv[2],
1352                                 bridge->parent->name);
1353                 } else {
1354                     vsctl_fatal("bridge %s does not have a port %s",
1355                                 ctx->argv[1], ctx->argv[2]);
1356                 }
1357             }
1358         }
1359
1360         del_port(&info, port);
1361     }
1362
1363     free_info(&info);
1364 }
1365
1366 static void
1367 cmd_port_to_br(struct vsctl_context *ctx)
1368 {
1369     struct vsctl_port *port;
1370     struct vsctl_info info;
1371
1372     get_info(ctx->ovs, &info);
1373     port = find_port(&info, ctx->argv[1], true);
1374     ds_put_format(&ctx->output, "%s\n", port->bridge->name);
1375     free_info(&info);
1376 }
1377
1378 static void
1379 cmd_br_to_vlan(struct vsctl_context *ctx)
1380 {
1381     struct vsctl_bridge *bridge;
1382     struct vsctl_info info;
1383
1384     get_info(ctx->ovs, &info);
1385     bridge = find_bridge(&info, ctx->argv[1], true);
1386     ds_put_format(&ctx->output, "%d\n", bridge->vlan);
1387     free_info(&info);
1388 }
1389
1390 static void
1391 cmd_br_to_parent(struct vsctl_context *ctx)
1392 {
1393     struct vsctl_bridge *bridge;
1394     struct vsctl_info info;
1395
1396     get_info(ctx->ovs, &info);
1397     bridge = find_bridge(&info, ctx->argv[1], true);
1398     if (bridge->parent) {
1399         bridge = bridge->parent;
1400     }
1401     ds_put_format(&ctx->output, "%s\n", bridge->name);
1402     free_info(&info);
1403 }
1404
1405 static void
1406 cmd_list_ifaces(struct vsctl_context *ctx)
1407 {
1408     struct vsctl_bridge *br;
1409     struct shash_node *node;
1410     struct vsctl_info info;
1411     struct svec ifaces;
1412
1413     get_info(ctx->ovs, &info);
1414     br = find_bridge(&info, ctx->argv[1], true);
1415
1416     svec_init(&ifaces);
1417     SHASH_FOR_EACH (node, &info.ifaces) {
1418         struct vsctl_iface *iface = node->data;
1419
1420         if (strcmp(iface->iface_cfg->name, br->name)
1421             && br == iface->port->bridge) {
1422             svec_add(&ifaces, iface->iface_cfg->name);
1423         }
1424     }
1425     output_sorted(&ifaces, &ctx->output);
1426     svec_destroy(&ifaces);
1427
1428     free_info(&info);
1429 }
1430
1431 static void
1432 cmd_iface_to_br(struct vsctl_context *ctx)
1433 {
1434     struct vsctl_iface *iface;
1435     struct vsctl_info info;
1436
1437     get_info(ctx->ovs, &info);
1438     iface = find_iface(&info, ctx->argv[1], true);
1439     ds_put_format(&ctx->output, "%s\n", iface->port->bridge->name);
1440     free_info(&info);
1441 }
1442
1443 static void
1444 cmd_get_controller(struct vsctl_context *ctx)
1445 {
1446     struct vsctl_info info;
1447
1448     get_info(ctx->ovs, &info);
1449
1450     if (ctx->argc == 1) {
1451         /* Return the controller from the "Open_vSwitch" table */
1452         if (info.ctrl) {
1453             ds_put_format(&ctx->output, "%s\n", info.ctrl->target);
1454         }
1455     } else {
1456         /* Return the controller for a particular bridge. */
1457         struct vsctl_bridge *br = find_bridge(&info, ctx->argv[1], true);
1458
1459         /* If no controller is explicitly defined for the requested
1460          * bridge, fallback to the "Open_vSwitch" table's controller. */
1461         if (br->ctrl) {
1462             ds_put_format(&ctx->output, "%s\n", br->ctrl->target);
1463         } else if (info.ctrl) {
1464             ds_put_format(&ctx->output, "%s\n", info.ctrl->target);
1465         }
1466     }
1467
1468     free_info(&info);
1469 }
1470
1471 static void
1472 cmd_del_controller(struct vsctl_context *ctx)
1473 {
1474     struct vsctl_info info;
1475
1476     get_info(ctx->ovs, &info);
1477
1478     if (ctx->argc == 1) {
1479         if (info.ctrl) {
1480             ovsrec_controller_delete(info.ctrl);
1481             ovsrec_open_vswitch_set_controller(ctx->ovs, NULL);
1482         }
1483     } else {
1484         struct vsctl_bridge *br = find_real_bridge(&info, ctx->argv[1], true);
1485
1486         if (br->ctrl) {
1487             ovsrec_controller_delete(br->ctrl);
1488             ovsrec_bridge_set_controller(br->br_cfg, NULL);
1489         }
1490     }
1491
1492     free_info(&info);
1493 }
1494
1495 static void
1496 cmd_set_controller(struct vsctl_context *ctx)
1497 {
1498     struct vsctl_info info;
1499     struct ovsrec_controller *ctrl;
1500
1501     get_info(ctx->ovs, &info);
1502
1503     if (ctx->argc == 2) {
1504         /* Set the controller in the "Open_vSwitch" table. */
1505         if (info.ctrl) {
1506             ovsrec_controller_delete(info.ctrl);
1507         }
1508         ctrl = ovsrec_controller_insert(ctx->txn);
1509         ovsrec_controller_set_target(ctrl, ctx->argv[1]);
1510         ovsrec_open_vswitch_set_controller(ctx->ovs, ctrl);
1511     } else {
1512         /* Set the controller for a particular bridge. */
1513         struct vsctl_bridge *br = find_real_bridge(&info, ctx->argv[1], true);
1514
1515         if (br->ctrl) {
1516             ovsrec_controller_delete(br->ctrl);
1517         }
1518         ctrl = ovsrec_controller_insert(ctx->txn);
1519         ovsrec_controller_set_target(ctrl, ctx->argv[2]);
1520         ovsrec_bridge_set_controller(br->br_cfg, ctrl);
1521     }
1522
1523     free_info(&info);
1524 }
1525
1526 static void
1527 cmd_get_fail_mode(struct vsctl_context *ctx)
1528 {
1529     struct vsctl_info info;
1530     const char *fail_mode = NULL;
1531
1532     get_info(ctx->ovs, &info);
1533
1534     if (ctx->argc == 1) {
1535         /* Return the fail-mode from the "Open_vSwitch" table */
1536         if (info.ctrl && info.ctrl->fail_mode) {
1537             fail_mode = info.ctrl->fail_mode;
1538         }
1539     } else {
1540         /* Return the fail-mode for a particular bridge. */
1541         struct vsctl_bridge *br = find_bridge(&info, ctx->argv[1], true);
1542
1543         /* If no controller or fail-mode is explicitly defined for the 
1544          * requested bridge, fallback to the "Open_vSwitch" table's 
1545          * setting. */
1546         if (br->ctrl && br->ctrl->fail_mode) {
1547             fail_mode = br->ctrl->fail_mode;
1548         } else if (info.ctrl && info.ctrl->fail_mode) {
1549             fail_mode = info.ctrl->fail_mode;
1550         }
1551     }
1552
1553     if (fail_mode && strlen(fail_mode)) {
1554         ds_put_format(&ctx->output, "%s\n", fail_mode);
1555     }
1556
1557     free_info(&info);
1558 }
1559
1560 static void
1561 cmd_del_fail_mode(struct vsctl_context *ctx)
1562 {
1563     struct vsctl_info info;
1564
1565     get_info(ctx->ovs, &info);
1566
1567     if (ctx->argc == 1) {
1568         if (info.ctrl && info.ctrl->fail_mode) {
1569             ovsrec_controller_set_fail_mode(info.ctrl, NULL);
1570         }
1571     } else {
1572         struct vsctl_bridge *br = find_real_bridge(&info, ctx->argv[1], true);
1573
1574         if (br->ctrl && br->ctrl->fail_mode) {
1575             ovsrec_controller_set_fail_mode(br->ctrl, NULL);
1576         }
1577     }
1578
1579     free_info(&info);
1580 }
1581
1582 static void
1583 cmd_set_fail_mode(struct vsctl_context *ctx)
1584 {
1585     struct vsctl_info info;
1586     const char *fail_mode;
1587
1588     get_info(ctx->ovs, &info);
1589
1590     fail_mode = (ctx->argc == 2) ? ctx->argv[1] : ctx->argv[2];
1591
1592     if (strcmp(fail_mode, "standalone") && strcmp(fail_mode, "secure")) {
1593         vsctl_fatal("fail-mode must be \"standalone\" or \"secure\"");
1594     }
1595
1596     if (ctx->argc == 2) {
1597         /* Set the fail-mode in the "Open_vSwitch" table. */
1598         if (!info.ctrl) {
1599             vsctl_fatal("no controller declared");
1600         }
1601         ovsrec_controller_set_fail_mode(info.ctrl, fail_mode);
1602     } else {
1603         struct vsctl_bridge *br = find_real_bridge(&info, ctx->argv[1], true);
1604
1605         if (!br->ctrl) {
1606             vsctl_fatal("no controller declared for %s", br->name);
1607         }
1608         ovsrec_controller_set_fail_mode(br->ctrl, fail_mode);
1609     }
1610
1611     free_info(&info);
1612 }
1613
1614 static void
1615 cmd_get_ssl(struct vsctl_context *ctx)
1616 {
1617     struct ovsrec_ssl *ssl = ctx->ovs->ssl;
1618
1619     if (ssl) {
1620         ds_put_format(&ctx->output, "Private key: %s\n", ssl->private_key);
1621         ds_put_format(&ctx->output, "Certificate: %s\n", ssl->certificate);
1622         ds_put_format(&ctx->output, "CA Certificate: %s\n", ssl->ca_cert);
1623         ds_put_format(&ctx->output, "Bootstrap: %s\n",
1624                 ssl->bootstrap_ca_cert ? "true" : "false");
1625     }
1626 }
1627
1628 static void
1629 cmd_del_ssl(struct vsctl_context *ctx)
1630 {
1631     struct ovsrec_ssl *ssl = ctx->ovs->ssl;
1632
1633     if (ssl) {
1634         ovsrec_ssl_delete(ssl);
1635         ovsrec_open_vswitch_set_ssl(ctx->ovs, NULL);
1636     }
1637 }
1638
1639 static void
1640 cmd_set_ssl(struct vsctl_context *ctx)
1641 {
1642     bool bootstrap = shash_find(&ctx->options, "--bootstrap");
1643     struct ovsrec_ssl *ssl = ctx->ovs->ssl;
1644
1645     if (ssl) {
1646         ovsrec_ssl_delete(ssl);
1647     }
1648     ssl = ovsrec_ssl_insert(ctx->txn);
1649
1650     ovsrec_ssl_set_private_key(ssl, ctx->argv[1]);
1651     ovsrec_ssl_set_certificate(ssl, ctx->argv[2]);
1652     ovsrec_ssl_set_ca_cert(ssl, ctx->argv[3]);
1653
1654     ovsrec_ssl_set_bootstrap_ca_cert(ssl, bootstrap);
1655
1656     ovsrec_open_vswitch_set_ssl(ctx->ovs, ssl);
1657 }
1658 \f
1659 /* Parameter commands. */
1660
1661 struct vsctl_row_id {
1662     const struct ovsdb_idl_table_class *table;
1663     const struct ovsdb_idl_column *name_column;
1664     const struct ovsdb_idl_column *uuid_column;
1665 };
1666
1667 struct vsctl_table_class {
1668     struct ovsdb_idl_table_class *class;
1669     struct vsctl_row_id row_ids[2];
1670 };
1671
1672 static const struct vsctl_table_class tables[] = {
1673     {&ovsrec_table_bridge,
1674      {{&ovsrec_table_bridge, &ovsrec_bridge_col_name, NULL},
1675       {NULL, NULL, NULL}}},
1676
1677     {&ovsrec_table_controller,
1678      {{&ovsrec_table_bridge,
1679        &ovsrec_bridge_col_name,
1680        &ovsrec_bridge_col_controller},
1681       {&ovsrec_table_open_vswitch,
1682        NULL,
1683        &ovsrec_open_vswitch_col_controller}}},
1684
1685     {&ovsrec_table_interface,
1686      {{&ovsrec_table_interface, &ovsrec_interface_col_name, NULL},
1687       {NULL, NULL, NULL}}},
1688
1689     {&ovsrec_table_mirror,
1690      {{&ovsrec_table_mirror, &ovsrec_mirror_col_name, NULL},
1691       {NULL, NULL, NULL}}},
1692
1693     {&ovsrec_table_netflow,
1694      {{&ovsrec_table_bridge,
1695        &ovsrec_bridge_col_name,
1696        &ovsrec_bridge_col_netflow},
1697       {NULL, NULL, NULL}}},
1698
1699     {&ovsrec_table_open_vswitch,
1700      {{&ovsrec_table_open_vswitch, NULL, NULL},
1701       {NULL, NULL, NULL}}},
1702
1703     {&ovsrec_table_port,
1704      {{&ovsrec_table_port, &ovsrec_port_col_name, NULL},
1705       {NULL, NULL, NULL}}},
1706
1707     {&ovsrec_table_ssl,
1708      {{&ovsrec_table_open_vswitch, NULL, &ovsrec_open_vswitch_col_ssl}}},
1709
1710     {NULL, {{NULL, NULL, NULL}, {NULL, NULL, NULL}}}
1711 };
1712
1713 static void
1714 die_if_error(char *error)
1715 {
1716     if (error) {
1717         vsctl_fatal("%s", error);
1718     }
1719 }
1720
1721 static int
1722 to_lower_and_underscores(unsigned c)
1723 {
1724     return c == '-' ? '_' : tolower(c);
1725 }
1726
1727 static unsigned int
1728 score_partial_match(const char *name, const char *s)
1729 {
1730     int score;
1731
1732     if (!strcmp(name, s)) {
1733         return UINT_MAX;
1734     }
1735     for (score = 0; ; score++, name++, s++) {
1736         if (to_lower_and_underscores(*name) != to_lower_and_underscores(*s)) {
1737             break;
1738         } else if (*name == '\0') {
1739             return UINT_MAX - 1;
1740         }
1741     }
1742     return *s == '\0' ? score : 0;
1743 }
1744
1745 static const struct vsctl_table_class *
1746 get_table(const char *table_name)
1747 {
1748     const struct vsctl_table_class *table;
1749     const struct vsctl_table_class *best_match = NULL;
1750     unsigned int best_score = 0;
1751
1752     for (table = tables; table->class; table++) {
1753         unsigned int score = score_partial_match(table->class->name,
1754                                                  table_name);
1755         if (score > best_score) {
1756             best_match = table;
1757             best_score = score;
1758         } else if (score == best_score) {
1759             best_match = NULL;
1760         }
1761     }
1762     if (best_match) {
1763         return best_match;
1764     } else if (best_score) {
1765         vsctl_fatal("multiple table names match \"%s\"", table_name);
1766     } else {
1767         vsctl_fatal("unknown table \"%s\"", table_name);
1768     }
1769 }
1770
1771 static const struct ovsdb_idl_row *
1772 get_row_by_id(struct vsctl_context *ctx, const struct vsctl_table_class *table,
1773               const struct vsctl_row_id *id, const char *record_id)
1774 {
1775     const struct ovsdb_idl_row *referrer, *final;
1776
1777     if (!id->table) {
1778         return NULL;
1779     }
1780
1781     if (!id->name_column) {
1782         if (strcmp(record_id, ".")) {
1783             return NULL;
1784         }
1785         referrer = ovsdb_idl_first_row(ctx->idl, id->table);
1786         if (!referrer || ovsdb_idl_next_row(referrer)) {
1787             return NULL;
1788         }
1789     } else {
1790         const struct ovsdb_idl_row *row;
1791         unsigned int best_score = 0;
1792
1793         /* It might make sense to relax this assertion. */
1794         assert(id->name_column->type.key.type == OVSDB_TYPE_STRING);
1795
1796         referrer = NULL;
1797         for (row = ovsdb_idl_first_row(ctx->idl, id->table);
1798              row != NULL && best_score != UINT_MAX;
1799              row = ovsdb_idl_next_row(row))
1800         {
1801             struct ovsdb_datum name;
1802
1803             ovsdb_idl_txn_read(row, id->name_column, &name);
1804             if (name.n == 1) {
1805                 unsigned int score = score_partial_match(name.keys[0].string,
1806                                                          record_id);
1807                 if (score > best_score) {
1808                     referrer = row;
1809                     best_score = score;
1810                 } else if (score == best_score) {
1811                     referrer = NULL;
1812                 }
1813             }
1814             ovsdb_datum_destroy(&name, &id->name_column->type);
1815         }
1816         if (best_score && !referrer) {
1817             vsctl_fatal("multiple rows in %s match \"%s\"",
1818                         table->class->name, record_id);
1819         }
1820     }
1821     if (!referrer) {
1822         return NULL;
1823     }
1824
1825     final = NULL;
1826     if (id->uuid_column) {
1827         struct ovsdb_datum uuid;
1828
1829         assert(id->uuid_column->type.key.type == OVSDB_TYPE_UUID);
1830         assert(id->uuid_column->type.value.type == OVSDB_TYPE_VOID);
1831
1832         ovsdb_idl_txn_read(referrer, id->uuid_column, &uuid);
1833         if (uuid.n == 1) {
1834             final = ovsdb_idl_get_row_for_uuid(ctx->idl, table->class,
1835                                                &uuid.keys[0].uuid);
1836         }
1837         ovsdb_datum_destroy(&uuid, &id->uuid_column->type);
1838     } else {
1839         final = referrer;
1840     }
1841
1842     return final;
1843 }
1844
1845 static const struct ovsdb_idl_row *
1846 get_row(struct vsctl_context *ctx,
1847         const struct vsctl_table_class *table, const char *record_id)
1848 {
1849     const struct ovsdb_idl_row *row;
1850     struct uuid uuid;
1851
1852     if (uuid_from_string(&uuid, record_id)) {
1853         row = ovsdb_idl_get_row_for_uuid(ctx->idl, table->class, &uuid);
1854     } else {
1855         int i;
1856
1857         for (i = 0; i < ARRAY_SIZE(table->row_ids); i++) {
1858             row = get_row_by_id(ctx, table, &table->row_ids[i], record_id);
1859             if (row) {
1860                 break;
1861             }
1862         }
1863     }
1864     return row;
1865 }
1866
1867 static const struct ovsdb_idl_row *
1868 must_get_row(struct vsctl_context *ctx,
1869              const struct vsctl_table_class *table, const char *record_id)
1870 {
1871     const struct ovsdb_idl_row *row = get_row(ctx, table, record_id);
1872     if (!row) {
1873         vsctl_fatal("no row \"%s\" in table %s",
1874                     record_id, table->class->name);
1875     }
1876     return row;
1877 }
1878
1879 static char *
1880 get_column(const struct vsctl_table_class *table, const char *column_name,
1881            const struct ovsdb_idl_column **columnp)
1882 {
1883     const struct ovsdb_idl_column *best_match = NULL;
1884     unsigned int best_score = 0;
1885     size_t i;
1886
1887     for (i = 0; i < table->class->n_columns; i++) {
1888         const struct ovsdb_idl_column *column = &table->class->columns[i];
1889         unsigned int score = score_partial_match(column->name, column_name);
1890         if (score > best_score) {
1891             best_match = column;
1892             best_score = score;
1893         } else if (score == best_score) {
1894             best_match = NULL;
1895         }
1896     }
1897
1898     *columnp = best_match;
1899     if (best_match) {
1900         return NULL;
1901     } else if (best_score) {
1902         return xasprintf("%s contains more than one column whose name "
1903                          "matches \"%s\"", table->class->name, column_name);
1904     } else {
1905         return xasprintf("%s does not contain a column whose name matches "
1906                          "\"%s\"", table->class->name, column_name);
1907     }
1908 }
1909
1910 static char * WARN_UNUSED_RESULT
1911 parse_column_key_value(const char *arg, const struct vsctl_table_class *table,
1912                        const struct ovsdb_idl_column **columnp,
1913                        char **keyp, char **valuep)
1914 {
1915     const char *p = arg;
1916     char *error;
1917
1918     assert(columnp || keyp);
1919     if (keyp) {
1920         *keyp = NULL;
1921     }
1922     if (valuep) {
1923         *valuep = NULL;
1924     }
1925
1926     /* Parse column name. */
1927     if (columnp) {
1928         char *column_name;
1929
1930         error = ovsdb_token_parse(&p, &column_name);
1931         if (error) {
1932             goto error;
1933         }
1934         if (column_name[0] == '\0') {
1935             free(column_name);
1936             error = xasprintf("%s: missing column name", arg);
1937             goto error;
1938         }
1939         error = get_column(table, column_name, columnp);
1940         free(column_name);
1941         if (error) {
1942             goto error;
1943         }
1944     }
1945
1946     /* Parse key string. */
1947     if (*p == ':' || !columnp) {
1948         if (columnp) {
1949             p++;
1950         } else if (!keyp) {
1951             error = xasprintf("%s: key not accepted here", arg);
1952             goto error;
1953         }
1954         error = ovsdb_token_parse(&p, keyp);
1955         if (error) {
1956             goto error;
1957         }
1958     } else if (keyp) {
1959         *keyp = NULL;
1960     }
1961
1962     /* Parse value string. */
1963     if (*p == '=') {
1964         if (!valuep) {
1965             error = xasprintf("%s: value not accepted here", arg);
1966             goto error;
1967         }
1968         *valuep = xstrdup(p + 1);
1969     } else {
1970         if (valuep) {
1971             *valuep = NULL;
1972         }
1973         if (*p != '\0') {
1974             error = xasprintf("%s: trailing garbage \"%s\" in argument",
1975                               arg, p);
1976             goto error;
1977         }
1978     }
1979     return NULL;
1980
1981 error:
1982     if (columnp) {
1983         *columnp = NULL;
1984     }
1985     if (keyp) {
1986         free(*keyp);
1987         *keyp = NULL;
1988     }
1989     if (valuep) {
1990         free(*valuep);
1991         *valuep = NULL;
1992     }
1993     return error;
1994 }
1995
1996 static void
1997 cmd_get(struct vsctl_context *ctx)
1998 {
1999     bool if_exists = shash_find(&ctx->options, "--if-exists");
2000     const char *table_name = ctx->argv[1];
2001     const char *record_id = ctx->argv[2];
2002     const struct vsctl_table_class *table;
2003     const struct ovsdb_idl_row *row;
2004     struct ds *out = &ctx->output;
2005     int i;
2006
2007     table = get_table(table_name);
2008     row = must_get_row(ctx, table, record_id);
2009     for (i = 3; i < ctx->argc; i++) {
2010         const struct ovsdb_idl_column *column;
2011         struct ovsdb_datum datum;
2012         char *key_string;
2013
2014         die_if_error(parse_column_key_value(ctx->argv[i], table,
2015                                             &column, &key_string, NULL));
2016
2017         ovsdb_idl_txn_read(row, column, &datum);
2018         if (key_string) {
2019             union ovsdb_atom key;
2020             unsigned int idx;
2021
2022             if (column->type.value.type == OVSDB_TYPE_VOID) {
2023                 vsctl_fatal("cannot specify key to get for non-map column %s",
2024                             column->name);
2025             }
2026
2027             die_if_error(ovsdb_atom_from_string(&key,
2028                                                 &column->type.key,
2029                                                 key_string));
2030
2031             idx = ovsdb_datum_find_key(&datum, &key,
2032                                        column->type.key.type);
2033             if (idx == UINT_MAX) {
2034                 if (!if_exists) {
2035                     vsctl_fatal("no key \"%s\" in %s record \"%s\" column %s",
2036                                 key_string, table->class->name, record_id,
2037                                 column->name);
2038                 }
2039             } else {
2040                 ovsdb_atom_to_string(&datum.values[idx],
2041                                      column->type.value.type, out);
2042             }
2043             ovsdb_atom_destroy(&key, column->type.key.type);
2044         } else {
2045             ovsdb_datum_to_string(&datum, &column->type, out);
2046         }
2047         ds_put_char(out, '\n');
2048         ovsdb_datum_destroy(&datum, &column->type);
2049
2050         free(key_string);
2051     }
2052 }
2053
2054 static void
2055 list_record(const struct vsctl_table_class *table,
2056             const struct ovsdb_idl_row *row, struct ds *out)
2057 {
2058     size_t i;
2059
2060     ds_put_format(out, "%-20s: "UUID_FMT"\n", "_uuid",
2061                   UUID_ARGS(&row->uuid));
2062     for (i = 0; i < table->class->n_columns; i++) {
2063         const struct ovsdb_idl_column *column = &table->class->columns[i];
2064         struct ovsdb_datum datum;
2065
2066         ovsdb_idl_txn_read(row, column, &datum);
2067
2068         ds_put_format(out, "%-20s: ", column->name);
2069         ovsdb_datum_to_string(&datum, &column->type, out);
2070         ds_put_char(out, '\n');
2071
2072         ovsdb_datum_destroy(&datum, &column->type);
2073     }
2074 }
2075
2076 static void
2077 cmd_list(struct vsctl_context *ctx)
2078 {
2079     const char *table_name = ctx->argv[1];
2080     const struct vsctl_table_class *table;
2081     struct ds *out = &ctx->output;
2082     int i;
2083
2084     table = get_table(table_name);
2085     if (ctx->argc > 2) {
2086         for (i = 2; i < ctx->argc; i++) {
2087             if (i > 2) {
2088                 ds_put_char(out, '\n');
2089             }
2090             list_record(table, must_get_row(ctx, table, ctx->argv[i]), out);
2091         }
2092     } else {
2093         const struct ovsdb_idl_row *row;
2094         bool first;
2095
2096         for (row = ovsdb_idl_first_row(ctx->idl, table->class), first = true;
2097              row != NULL;
2098              row = ovsdb_idl_next_row(row), first = false) {
2099             if (!first) {
2100                 ds_put_char(out, '\n');
2101             }
2102             list_record(table, row, out);
2103         }
2104     }
2105 }
2106
2107 static void
2108 set_column(const struct vsctl_table_class *table,
2109            const struct ovsdb_idl_row *row, const char *arg)
2110 {
2111     const struct ovsdb_idl_column *column;
2112     char *key_string, *value_string;
2113     char *error;
2114
2115     error = parse_column_key_value(arg, table, &column, &key_string,
2116                                    &value_string);
2117     die_if_error(error);
2118     if (!value_string) {
2119         vsctl_fatal("%s: missing value", arg);
2120     }
2121
2122     if (key_string) {
2123         union ovsdb_atom key, value;
2124         struct ovsdb_datum old, new;
2125
2126         if (column->type.value.type == OVSDB_TYPE_VOID) {
2127             vsctl_fatal("cannot specify key to set for non-map column %s",
2128                         column->name);
2129         }
2130
2131         die_if_error(ovsdb_atom_from_string(&key, &column->type.key,
2132                                             key_string));
2133         die_if_error(ovsdb_atom_from_string(&value, &column->type.value,
2134                                             value_string));
2135
2136         ovsdb_datum_init_empty(&new);
2137         ovsdb_datum_add_unsafe(&new, &key, &value, &column->type);
2138
2139         ovsdb_atom_destroy(&key, column->type.key.type);
2140         ovsdb_atom_destroy(&value, column->type.value.type);
2141
2142         ovsdb_idl_txn_read(row, column, &old);
2143         ovsdb_datum_union(&old, &new, &column->type, true);
2144         ovsdb_idl_txn_write(row, column, &old);
2145
2146         ovsdb_datum_destroy(&new, &column->type);
2147     } else {
2148         struct ovsdb_datum datum;
2149
2150         die_if_error(ovsdb_datum_from_string(&datum, &column->type,
2151                                              value_string));
2152         ovsdb_idl_txn_write(row, column, &datum);
2153     }
2154
2155     free(key_string);
2156     free(value_string);
2157 }
2158
2159 static void
2160 cmd_set(struct vsctl_context *ctx)
2161 {
2162     const char *table_name = ctx->argv[1];
2163     const char *record_id = ctx->argv[2];
2164     const struct vsctl_table_class *table;
2165     const struct ovsdb_idl_row *row;
2166     int i;
2167
2168     table = get_table(table_name);
2169     row = must_get_row(ctx, table, record_id);
2170     for (i = 3; i < ctx->argc; i++) {
2171         set_column(table, row, ctx->argv[i]);
2172     }
2173 }
2174
2175 static void
2176 cmd_add(struct vsctl_context *ctx)
2177 {
2178     const char *table_name = ctx->argv[1];
2179     const char *record_id = ctx->argv[2];
2180     const char *column_name = ctx->argv[3];
2181     const struct vsctl_table_class *table;
2182     const struct ovsdb_idl_column *column;
2183     const struct ovsdb_idl_row *row;
2184     const struct ovsdb_type *type;
2185     struct ovsdb_datum old;
2186     int i;
2187
2188     table = get_table(table_name);
2189     row = must_get_row(ctx, table, record_id);
2190     die_if_error(get_column(table, column_name, &column));
2191
2192     type = &column->type;
2193     ovsdb_idl_txn_read(row, column, &old);
2194     for (i = 4; i < ctx->argc; i++) {
2195         struct ovsdb_type add_type;
2196         struct ovsdb_datum add;
2197
2198         add_type = *type;
2199         add_type.n_min = 1;
2200         add_type.n_max = UINT_MAX;
2201         die_if_error(ovsdb_datum_from_string(&add, &add_type, ctx->argv[i]));
2202         ovsdb_datum_union(&old, &add, type, false);
2203         ovsdb_datum_destroy(&add, type);
2204     }
2205     if (old.n > type->n_max) {
2206         vsctl_fatal("\"add\" operation would put %u %s in column %s of "
2207                     "table %s but the maximum number is %u",
2208                     old.n,
2209                     type->value.type == OVSDB_TYPE_VOID ? "values" : "pairs",
2210                     column->name, table->class->name, type->n_max);
2211     }
2212     ovsdb_idl_txn_write(row, column, &old);
2213 }
2214
2215 static void
2216 cmd_remove(struct vsctl_context *ctx)
2217 {
2218     const char *table_name = ctx->argv[1];
2219     const char *record_id = ctx->argv[2];
2220     const char *column_name = ctx->argv[3];
2221     const struct vsctl_table_class *table;
2222     const struct ovsdb_idl_column *column;
2223     const struct ovsdb_idl_row *row;
2224     const struct ovsdb_type *type;
2225     struct ovsdb_datum old;
2226     int i;
2227
2228     table = get_table(table_name);
2229     row = must_get_row(ctx, table, record_id);
2230     die_if_error(get_column(table, column_name, &column));
2231
2232     type = &column->type;
2233     ovsdb_idl_txn_read(row, column, &old);
2234     for (i = 4; i < ctx->argc; i++) {
2235         struct ovsdb_type rm_type;
2236         struct ovsdb_datum rm;
2237         char *error;
2238
2239         rm_type = *type;
2240         rm_type.n_min = 1;
2241         rm_type.n_max = UINT_MAX;
2242         error = ovsdb_datum_from_string(&rm, &rm_type, ctx->argv[i]);
2243         if (error && ovsdb_type_is_map(&rm_type)) {
2244             free(error);
2245             rm_type.value.type = OVSDB_TYPE_VOID;
2246             die_if_error(ovsdb_datum_from_string(&rm, &rm_type, ctx->argv[i]));
2247         }
2248         ovsdb_datum_subtract(&old, type, &rm, &rm_type);
2249         ovsdb_datum_destroy(&rm, &rm_type);
2250     }
2251     if (old.n < type->n_min) {
2252         vsctl_fatal("\"remove\" operation would put %u %s in column %s of "
2253                     "table %s but the minimun number is %u",
2254                     old.n,
2255                     type->value.type == OVSDB_TYPE_VOID ? "values" : "pairs",
2256                     column->name, table->class->name, type->n_min);
2257     }
2258     ovsdb_idl_txn_write(row, column, &old);
2259 }
2260
2261 static void
2262 cmd_clear(struct vsctl_context *ctx)
2263 {
2264     const char *table_name = ctx->argv[1];
2265     const char *record_id = ctx->argv[2];
2266     const struct vsctl_table_class *table;
2267     const struct ovsdb_idl_row *row;
2268     int i;
2269
2270     table = get_table(table_name);
2271     row = must_get_row(ctx, table, record_id);
2272     for (i = 3; i < ctx->argc; i++) {
2273         const struct ovsdb_idl_column *column;
2274         const struct ovsdb_type *type;
2275         struct ovsdb_datum datum;
2276
2277         die_if_error(get_column(table, ctx->argv[i], &column));
2278
2279         type = &column->type;
2280         if (type->n_min > 0) {
2281             vsctl_fatal("\"clear\" operation cannot be applied to column %s "
2282                         "of table %s, which is not allowed to be empty",
2283                         column->name, table->class->name);
2284         }
2285
2286         ovsdb_datum_init_empty(&datum);
2287         ovsdb_idl_txn_write(row, column, &datum);
2288     }
2289 }
2290
2291 static void
2292 cmd_create(struct vsctl_context *ctx)
2293 {
2294     const char *table_name = ctx->argv[1];
2295     const struct vsctl_table_class *table;
2296     const struct ovsdb_idl_row *row;
2297     int i;
2298
2299     table = get_table(table_name);
2300     row = ovsdb_idl_txn_insert(ctx->txn, table->class);
2301     for (i = 2; i < ctx->argc; i++) {
2302         set_column(table, row, ctx->argv[i]);
2303     }
2304     ds_put_format(&ctx->output, UUID_FMT, UUID_ARGS(&row->uuid));
2305 }
2306
2307 /* This function may be used as the 'postprocess' function for commands that
2308  * insert new rows into the database.  It expects that the command's 'run'
2309  * function prints the UUID reported by ovsdb_idl_txn_insert() as the command's
2310  * sole output.  It replaces that output by the row's permanent UUID assigned
2311  * by the database server and appends a new-line.
2312  *
2313  * Currently we use this only for "create", because the higher-level commands
2314  * are supposed to be independent of the actual structure of the vswitch
2315  * configuration. */
2316 static void
2317 post_create(struct vsctl_context *ctx)
2318 {
2319     const struct uuid *real;
2320     struct uuid dummy;
2321
2322     uuid_from_string(&dummy, ds_cstr(&ctx->output));
2323     real = ovsdb_idl_txn_get_insert_uuid(ctx->txn, &dummy);
2324     if (real) {
2325         ds_clear(&ctx->output);
2326         ds_put_format(&ctx->output, UUID_FMT, UUID_ARGS(real));
2327     }
2328     ds_put_char(&ctx->output, '\n');
2329 }
2330
2331 static void
2332 cmd_destroy(struct vsctl_context *ctx)
2333 {
2334     bool must_exist = !shash_find(&ctx->options, "--if-exists");
2335     const char *table_name = ctx->argv[1];
2336     const struct vsctl_table_class *table;
2337     int i;
2338
2339     table = get_table(table_name);
2340     for (i = 2; i < ctx->argc; i++) {
2341         const struct ovsdb_idl_row *row;
2342
2343         row = (must_exist ? must_get_row : get_row)(ctx, table, ctx->argv[i]);
2344         if (row) {
2345             ovsdb_idl_txn_delete(row);
2346         }
2347     }
2348 }
2349 \f
2350 static struct json *
2351 where_uuid_equals(const struct uuid *uuid)
2352 {
2353     return
2354         json_array_create_1(
2355             json_array_create_3(
2356                 json_string_create("_uuid"),
2357                 json_string_create("=="),
2358                 json_array_create_2(
2359                     json_string_create("uuid"),
2360                     json_string_create_nocopy(
2361                         xasprintf(UUID_FMT, UUID_ARGS(uuid))))));
2362 }
2363
2364 static void
2365 vsctl_context_init(struct vsctl_context *ctx, struct vsctl_command *command,
2366                    struct ovsdb_idl *idl, struct ovsdb_idl_txn *txn,
2367                    const struct ovsrec_open_vswitch *ovs)
2368 {
2369     ctx->argc = command->argc;
2370     ctx->argv = command->argv;
2371     ctx->options = command->options;
2372
2373     ds_swap(&ctx->output, &command->output);
2374     ctx->idl = idl;
2375     ctx->txn = txn;
2376     ctx->ovs = ovs;
2377
2378 }
2379
2380 static void
2381 vsctl_context_done(struct vsctl_context *ctx, struct vsctl_command *command)
2382 {
2383     ds_swap(&ctx->output, &command->output);
2384 }
2385
2386 static void
2387 do_vsctl(const char *args, struct vsctl_command *commands, size_t n_commands,
2388          struct ovsdb_idl *idl)
2389 {
2390     struct ovsdb_idl_txn *txn;
2391     const struct ovsrec_open_vswitch *ovs;
2392     enum ovsdb_idl_txn_status status;
2393     struct vsctl_command *c;
2394     int64_t next_cfg = 0;
2395     char *error;
2396
2397     txn = the_idl_txn = ovsdb_idl_txn_create(idl);
2398     if (dry_run) {
2399         ovsdb_idl_txn_set_dry_run(txn);
2400     }
2401
2402     ovsdb_idl_txn_add_comment(txn, "ovs-vsctl: %s", args);
2403
2404     ovs = ovsrec_open_vswitch_first(idl);
2405     if (!ovs) {
2406         /* XXX add verification that table is empty */
2407         ovs = ovsrec_open_vswitch_insert(txn);
2408     }
2409
2410     if (wait_for_reload) {
2411         struct json *where = where_uuid_equals(&ovs->header_.uuid);
2412         ovsdb_idl_txn_increment(txn, "Open_vSwitch", "next_cfg", where);
2413         json_destroy(where);
2414     }
2415
2416     for (c = commands; c < &commands[n_commands]; c++) {
2417         struct vsctl_context ctx;
2418
2419         ds_init(&c->output);
2420         vsctl_context_init(&ctx, c, idl, txn, ovs);
2421         (c->syntax->run)(&ctx);
2422         vsctl_context_done(&ctx, c);
2423     }
2424
2425     status = ovsdb_idl_txn_commit_block(txn);
2426     if (wait_for_reload && status == TXN_SUCCESS) {
2427         next_cfg = ovsdb_idl_txn_get_increment_new_value(txn);
2428     }
2429     for (c = commands; c < &commands[n_commands]; c++) {
2430         if (c->syntax->postprocess) {
2431             struct vsctl_context ctx;
2432
2433             vsctl_context_init(&ctx, c, idl, txn, ovs);
2434             (c->syntax->postprocess)(&ctx);
2435             vsctl_context_done(&ctx, c);
2436         }
2437     }
2438     error = xstrdup(ovsdb_idl_txn_get_error(txn));
2439     ovsdb_idl_txn_destroy(txn);
2440     the_idl_txn = NULL;
2441
2442     switch (status) {
2443     case TXN_INCOMPLETE:
2444         NOT_REACHED();
2445
2446     case TXN_ABORTED:
2447         /* Should not happen--we never call ovsdb_idl_txn_abort(). */
2448         vsctl_fatal("transaction aborted");
2449
2450     case TXN_UNCHANGED:
2451     case TXN_SUCCESS:
2452         break;
2453
2454     case TXN_TRY_AGAIN:
2455         for (c = commands; c < &commands[n_commands]; c++) {
2456             ds_destroy(&c->output);
2457         }
2458         free(error);
2459         return;
2460
2461     case TXN_ERROR:
2462         vsctl_fatal("transaction error: %s", error);
2463
2464     default:
2465         NOT_REACHED();
2466     }
2467     free(error);
2468
2469     for (c = commands; c < &commands[n_commands]; c++) {
2470         struct ds *ds = &c->output;
2471         if (oneline) {
2472             size_t j;
2473
2474             ds_chomp(ds, '\n');
2475             for (j = 0; j < ds->length; j++) {
2476                 int c = ds->string[j];
2477                 switch (c) {
2478                 case '\n':
2479                     fputs("\\n", stdout);
2480                     break;
2481
2482                 case '\\':
2483                     fputs("\\\\", stdout);
2484                     break;
2485
2486                 default:
2487                     putchar(c);
2488                 }
2489             }
2490             putchar('\n');
2491         } else {
2492             fputs(ds_cstr(ds), stdout);
2493         }
2494         ds_destroy(&c->output);
2495         shash_destroy(&c->options);
2496     }
2497     free(commands);
2498
2499     if (wait_for_reload && status != TXN_UNCHANGED) {
2500         for (;;) {
2501             const struct ovsrec_open_vswitch *ovs;
2502
2503             ovsdb_idl_run(idl);
2504             OVSREC_OPEN_VSWITCH_FOR_EACH (ovs, idl) {
2505                 if (ovs->cur_cfg >= next_cfg) {
2506                     goto done;
2507                 }
2508             }
2509             ovsdb_idl_wait(idl);
2510             poll_block();
2511         }
2512     done: ;
2513     }
2514     ovsdb_idl_destroy(idl);
2515
2516     exit(EXIT_SUCCESS);
2517 }
2518
2519 static const struct vsctl_command_syntax all_commands[] = {
2520     /* Open vSwitch commands. */
2521     {"init", 0, 0, cmd_init, NULL, ""},
2522
2523     /* Bridge commands. */
2524     {"add-br", 1, 3, cmd_add_br, NULL, "--may-exist"},
2525     {"del-br", 1, 1, cmd_del_br, NULL, "--if-exists"},
2526     {"list-br", 0, 0, cmd_list_br, NULL, ""},
2527     {"br-exists", 1, 1, cmd_br_exists, NULL, ""},
2528     {"br-to-vlan", 1, 1, cmd_br_to_vlan, NULL, ""},
2529     {"br-to-parent", 1, 1, cmd_br_to_parent, NULL, ""},
2530     {"br-set-external-id", 2, 3, cmd_br_set_external_id, NULL, ""},
2531     {"br-get-external-id", 1, 2, cmd_br_get_external_id, NULL, ""},
2532
2533     /* Port commands. */
2534     {"list-ports", 1, 1, cmd_list_ports, NULL, ""},
2535     {"add-port", 2, INT_MAX, cmd_add_port, NULL, "--may-exist"},
2536     {"add-bond", 4, INT_MAX, cmd_add_bond, NULL, "--may-exist,--fake-iface"},
2537     {"del-port", 1, 2, cmd_del_port, NULL, "--if-exists,--with-iface"},
2538     {"port-to-br", 1, 1, cmd_port_to_br, NULL, ""},
2539
2540     /* Interface commands. */
2541     {"list-ifaces", 1, 1, cmd_list_ifaces, NULL, ""},
2542     {"iface-to-br", 1, 1, cmd_iface_to_br, NULL, ""},
2543
2544     /* Controller commands. */
2545     {"get-controller", 0, 1, cmd_get_controller, NULL, ""},
2546     {"del-controller", 0, 1, cmd_del_controller, NULL, ""},
2547     {"set-controller", 1, 2, cmd_set_controller, NULL, ""},
2548     {"get-fail-mode", 0, 1, cmd_get_fail_mode, NULL, ""},
2549     {"del-fail-mode", 0, 1, cmd_del_fail_mode, NULL, ""},
2550     {"set-fail-mode", 1, 2, cmd_set_fail_mode, NULL, ""},
2551
2552     /* SSL commands. */
2553     {"get-ssl", 0, 0, cmd_get_ssl, NULL, ""},
2554     {"del-ssl", 0, 0, cmd_del_ssl, NULL, ""},
2555     {"set-ssl", 3, 3, cmd_set_ssl, NULL, "--bootstrap"},
2556
2557     /* Parameter commands. */
2558     {"get", 3, INT_MAX, cmd_get, NULL, "--if-exists"},
2559     {"list", 1, INT_MAX, cmd_list, NULL, ""},
2560     {"set", 3, INT_MAX, cmd_set, NULL, ""},
2561     {"add", 4, INT_MAX, cmd_add, NULL, ""},
2562     {"remove", 4, INT_MAX, cmd_remove, NULL, ""},
2563     {"clear", 3, INT_MAX, cmd_clear, NULL, ""},
2564     {"create", 2, INT_MAX, cmd_create, post_create, ""},
2565     {"destroy", 1, INT_MAX, cmd_destroy, NULL, "--if-exists"},
2566
2567     {NULL, 0, 0, NULL, NULL, NULL},
2568 };
2569