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