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