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