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