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