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