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