vlog: Add a new log level "off".
[sliver-openvswitch.git] / utilities / ovs-vsctl.c
1 /*
2  * Copyright (c) 2009, 2010, 2011 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 #include <unistd.h>
30
31 #include "command-line.h"
32 #include "compiler.h"
33 #include "dirs.h"
34 #include "dynamic-string.h"
35 #include "json.h"
36 #include "ovsdb-data.h"
37 #include "ovsdb-idl.h"
38 #include "poll-loop.h"
39 #include "process.h"
40 #include "stream.h"
41 #include "stream-ssl.h"
42 #include "sset.h"
43 #include "svec.h"
44 #include "vswitchd/vswitch-idl.h"
45 #include "table.h"
46 #include "timeval.h"
47 #include "util.h"
48 #include "vlog.h"
49
50 VLOG_DEFINE_THIS_MODULE(vsctl);
51
52 /* vsctl_fatal() also logs the error, so it is preferred in this file. */
53 #define ovs_fatal please_use_vsctl_fatal_instead_of_ovs_fatal
54
55 struct vsctl_context;
56
57 /* A command supported by ovs-vsctl. */
58 struct vsctl_command_syntax {
59     const char *name;           /* e.g. "add-br" */
60     int min_args;               /* Min number of arguments following name. */
61     int max_args;               /* Max number of arguments following name. */
62
63     /* If nonnull, calls ovsdb_idl_add_column() or ovsdb_idl_add_table() for
64      * each column or table in ctx->idl that it uses. */
65     void (*prerequisites)(struct vsctl_context *ctx);
66
67     /* Does the actual work of the command and puts the command's output, if
68      * any, in ctx->output or ctx->table.
69      *
70      * Alternatively, if some prerequisite of the command is not met and the
71      * caller should wait for something to change and then retry, it may set
72      * ctx->try_again to true.  (Only the "wait-until" command currently does
73      * this.) */
74     void (*run)(struct vsctl_context *ctx);
75
76     /* If nonnull, called after the transaction has been successfully
77      * committed.  ctx->output is the output from the "run" function, which
78      * this function may modify and otherwise postprocess as needed.  (Only the
79      * "create" command currently does any postprocessing.) */
80     void (*postprocess)(struct vsctl_context *ctx);
81
82     /* A comma-separated list of supported options, e.g. "--a,--b", or the
83      * empty string if the command does not support any options. */
84     const char *options;
85     enum { RO, RW } mode;       /* Does this command modify the database? */
86 };
87
88 struct vsctl_command {
89     /* Data that remains constant after initialization. */
90     const struct vsctl_command_syntax *syntax;
91     int argc;
92     char **argv;
93     struct shash options;
94
95     /* Data modified by commands. */
96     struct ds output;
97     struct table *table;
98 };
99
100 /* --db: The database server to contact. */
101 static const char *db;
102
103 /* --oneline: Write each command's output as a single line? */
104 static bool oneline;
105
106 /* --dry-run: Do not commit any changes. */
107 static bool dry_run;
108
109 /* --no-wait: Wait for ovs-vswitchd to reload its configuration? */
110 static bool wait_for_reload = true;
111
112 /* --timeout: Time to wait for a connection to 'db'. */
113 static int timeout;
114
115 /* Format for table output. */
116 static struct table_style table_style = TABLE_STYLE_DEFAULT;
117
118 /* All supported commands. */
119 static const struct vsctl_command_syntax all_commands[];
120
121 /* The IDL we're using and the current transaction, if any.
122  * This is for use by vsctl_exit() only, to allow it to clean up.
123  * Other code should use its context arguments. */
124 static struct ovsdb_idl *the_idl;
125 static struct ovsdb_idl_txn *the_idl_txn;
126
127 static void vsctl_exit(int status) NO_RETURN;
128 static void vsctl_fatal(const char *, ...) PRINTF_FORMAT(1, 2) NO_RETURN;
129 static char *default_db(void);
130 static void usage(void) NO_RETURN;
131 static void parse_options(int argc, char *argv[]);
132 static bool might_write_to_db(char **argv);
133
134 static struct vsctl_command *parse_commands(int argc, char *argv[],
135                                             size_t *n_commandsp);
136 static void parse_command(int argc, char *argv[], struct vsctl_command *);
137 static const struct vsctl_command_syntax *find_command(const char *name);
138 static void run_prerequisites(struct vsctl_command[], size_t n_commands,
139                               struct ovsdb_idl *);
140 static void do_vsctl(const char *args,
141                      struct vsctl_command *, size_t n_commands,
142                      struct ovsdb_idl *);
143
144 static const struct vsctl_table_class *get_table(const char *table_name);
145 static void set_column(const struct vsctl_table_class *,
146                        const struct ovsdb_idl_row *, const char *arg,
147                        struct ovsdb_symbol_table *);
148
149 static bool is_condition_satisfied(const struct vsctl_table_class *,
150                                    const struct ovsdb_idl_row *,
151                                    const char *arg,
152                                    struct ovsdb_symbol_table *);
153
154 int
155 main(int argc, char *argv[])
156 {
157     extern struct vlog_module VLM_reconnect;
158     struct ovsdb_idl *idl;
159     struct vsctl_command *commands;
160     size_t n_commands;
161     char *args;
162
163     set_program_name(argv[0]);
164     signal(SIGPIPE, SIG_IGN);
165     vlog_set_levels(NULL, VLF_CONSOLE, VLL_WARN);
166     vlog_set_levels(&VLM_reconnect, VLF_ANY_FACILITY, VLL_WARN);
167     ovsrec_init();
168
169     /* Log our arguments.  This is often valuable for debugging systems. */
170     args = process_escape_args(argv);
171     VLOG(might_write_to_db(argv) ? VLL_INFO : VLL_DBG, "Called as %s", args);
172
173     /* Parse command line. */
174     parse_options(argc, argv);
175     commands = parse_commands(argc - optind, argv + optind, &n_commands);
176
177     if (timeout) {
178         time_alarm(timeout);
179     }
180
181     /* Initialize IDL. */
182     idl = the_idl = ovsdb_idl_create(db, &ovsrec_idl_class, false);
183     run_prerequisites(commands, n_commands, idl);
184
185     /* Now execute the commands. */
186     for (;;) {
187         if (ovsdb_idl_run(idl)) {
188             do_vsctl(args, commands, n_commands, idl);
189         }
190
191         ovsdb_idl_wait(idl);
192         poll_block();
193     }
194 }
195
196 static void
197 parse_options(int argc, char *argv[])
198 {
199     enum {
200         OPT_DB = UCHAR_MAX + 1,
201         OPT_ONELINE,
202         OPT_NO_SYSLOG,
203         OPT_NO_WAIT,
204         OPT_DRY_RUN,
205         OPT_PEER_CA_CERT,
206         VLOG_OPTION_ENUMS,
207         TABLE_OPTION_ENUMS
208     };
209     static struct option long_options[] = {
210         {"db", required_argument, NULL, OPT_DB},
211         {"no-syslog", no_argument, NULL, OPT_NO_SYSLOG},
212         {"no-wait", no_argument, NULL, OPT_NO_WAIT},
213         {"dry-run", no_argument, NULL, OPT_DRY_RUN},
214         {"oneline", no_argument, NULL, OPT_ONELINE},
215         {"timeout", required_argument, NULL, 't'},
216         {"help", no_argument, NULL, 'h'},
217         {"version", no_argument, NULL, 'V'},
218         VLOG_LONG_OPTIONS,
219         TABLE_LONG_OPTIONS,
220         STREAM_SSL_LONG_OPTIONS,
221         {"peer-ca-cert", required_argument, NULL, OPT_PEER_CA_CERT},
222         {NULL, 0, NULL, 0},
223     };
224     char *tmp, *short_options;
225
226     tmp = long_options_to_short_options(long_options);
227     short_options = xasprintf("+%s", tmp);
228     free(tmp);
229
230     table_style.format = TF_LIST;
231
232     for (;;) {
233         int c;
234
235         c = getopt_long(argc, argv, short_options, long_options, NULL);
236         if (c == -1) {
237             break;
238         }
239
240         switch (c) {
241         case OPT_DB:
242             db = optarg;
243             break;
244
245         case OPT_ONELINE:
246             oneline = true;
247             break;
248
249         case OPT_NO_SYSLOG:
250             vlog_set_levels(&VLM_vsctl, VLF_SYSLOG, VLL_WARN);
251             break;
252
253         case OPT_NO_WAIT:
254             wait_for_reload = false;
255             break;
256
257         case OPT_DRY_RUN:
258             dry_run = true;
259             break;
260
261         case 'h':
262             usage();
263
264         case 'V':
265             OVS_PRINT_VERSION(0, 0);
266             exit(EXIT_SUCCESS);
267
268         case 't':
269             timeout = strtoul(optarg, NULL, 10);
270             if (timeout < 0) {
271                 vsctl_fatal("value %s on -t or --timeout is invalid",
272                             optarg);
273             }
274             break;
275
276         VLOG_OPTION_HANDLERS
277         TABLE_OPTION_HANDLERS(&table_style)
278
279         STREAM_SSL_OPTION_HANDLERS
280
281         case OPT_PEER_CA_CERT:
282             stream_ssl_set_peer_ca_cert_file(optarg);
283             break;
284
285         case '?':
286             exit(EXIT_FAILURE);
287
288         default:
289             abort();
290         }
291     }
292     free(short_options);
293
294     if (!db) {
295         db = default_db();
296     }
297 }
298
299 static struct vsctl_command *
300 parse_commands(int argc, char *argv[], size_t *n_commandsp)
301 {
302     struct vsctl_command *commands;
303     size_t n_commands, allocated_commands;
304     int i, start;
305
306     commands = NULL;
307     n_commands = allocated_commands = 0;
308
309     for (start = i = 0; i <= argc; i++) {
310         if (i == argc || !strcmp(argv[i], "--")) {
311             if (i > start) {
312                 if (n_commands >= allocated_commands) {
313                     struct vsctl_command *c;
314
315                     commands = x2nrealloc(commands, &allocated_commands,
316                                           sizeof *commands);
317                     for (c = commands; c < &commands[n_commands]; c++) {
318                         shash_moved(&c->options);
319                     }
320                 }
321                 parse_command(i - start, &argv[start],
322                               &commands[n_commands++]);
323             }
324             start = i + 1;
325         }
326     }
327     if (!n_commands) {
328         vsctl_fatal("missing command name (use --help for help)");
329     }
330     *n_commandsp = n_commands;
331     return commands;
332 }
333
334 static void
335 parse_command(int argc, char *argv[], struct vsctl_command *command)
336 {
337     const struct vsctl_command_syntax *p;
338     struct shash_node *node;
339     int n_arg;
340     int i;
341
342     shash_init(&command->options);
343     for (i = 0; i < argc; i++) {
344         const char *option = argv[i];
345         const char *equals;
346         char *key, *value;
347
348         if (option[0] != '-') {
349             break;
350         }
351
352         equals = strchr(option, '=');
353         if (equals) {
354             key = xmemdup0(option, equals - option);
355             value = xstrdup(equals + 1);
356         } else {
357             key = xstrdup(option);
358             value = NULL;
359         }
360
361         if (shash_find(&command->options, key)) {
362             vsctl_fatal("'%s' option specified multiple times", argv[i]);
363         }
364         shash_add_nocopy(&command->options, key, value);
365     }
366     if (i == argc) {
367         vsctl_fatal("missing command name");
368     }
369
370     p = find_command(argv[i]);
371     if (!p) {
372         vsctl_fatal("unknown command '%s'; use --help for help", argv[i]);
373     }
374
375     SHASH_FOR_EACH (node, &command->options) {
376         const char *s = strstr(p->options, node->name);
377         int end = s ? s[strlen(node->name)] : EOF;
378
379         if (end != '=' && end != ',' && end != ' ' && end != '\0') {
380             vsctl_fatal("'%s' command has no '%s' option",
381                         argv[i], node->name);
382         }
383         if ((end == '=') != (node->data != NULL)) {
384             if (end == '=') {
385                 vsctl_fatal("missing argument to '%s' option on '%s' "
386                             "command", node->name, argv[i]);
387             } else {
388                 vsctl_fatal("'%s' option on '%s' does not accept an "
389                             "argument", node->name, argv[i]);
390             }
391         }
392     }
393
394     n_arg = argc - i - 1;
395     if (n_arg < p->min_args) {
396         vsctl_fatal("'%s' command requires at least %d arguments",
397                     p->name, p->min_args);
398     } else if (n_arg > p->max_args) {
399         int j;
400
401         for (j = i + 1; j < argc; j++) {
402             if (argv[j][0] == '-') {
403                 vsctl_fatal("'%s' command takes at most %d arguments "
404                             "(note that options must precede command "
405                             "names and follow a \"--\" argument)",
406                             p->name, p->max_args);
407             }
408         }
409
410         vsctl_fatal("'%s' command takes at most %d arguments",
411                     p->name, p->max_args);
412     }
413
414     command->syntax = p;
415     command->argc = n_arg + 1;
416     command->argv = &argv[i];
417 }
418
419 /* Returns the "struct vsctl_command_syntax" for a given command 'name', or a
420  * null pointer if there is none. */
421 static const struct vsctl_command_syntax *
422 find_command(const char *name)
423 {
424     static struct shash commands = SHASH_INITIALIZER(&commands);
425
426     if (shash_is_empty(&commands)) {
427         const struct vsctl_command_syntax *p;
428
429         for (p = all_commands; p->name; p++) {
430             shash_add_assert(&commands, p->name, p);
431         }
432     }
433
434     return shash_find_data(&commands, name);
435 }
436
437 static void
438 vsctl_fatal(const char *format, ...)
439 {
440     char *message;
441     va_list args;
442
443     va_start(args, format);
444     message = xvasprintf(format, args);
445     va_end(args);
446
447     vlog_set_levels(&VLM_vsctl, VLF_CONSOLE, VLL_OFF);
448     VLOG_ERR("%s", message);
449     ovs_error(0, "%s", message);
450     vsctl_exit(EXIT_FAILURE);
451 }
452
453 /* Frees the current transaction and the underlying IDL and then calls
454  * exit(status).
455  *
456  * Freeing the transaction and the IDL is not strictly necessary, but it makes
457  * for a clean memory leak report from valgrind in the normal case.  That makes
458  * it easier to notice real memory leaks. */
459 static void
460 vsctl_exit(int status)
461 {
462     if (the_idl_txn) {
463         ovsdb_idl_txn_abort(the_idl_txn);
464         ovsdb_idl_txn_destroy(the_idl_txn);
465     }
466     ovsdb_idl_destroy(the_idl);
467     exit(status);
468 }
469
470 static void
471 usage(void)
472 {
473     printf("\
474 %s: ovs-vswitchd management utility\n\
475 usage: %s [OPTIONS] COMMAND [ARG...]\n\
476 \n\
477 Open vSwitch commands:\n\
478   init                        initialize database, if not yet initialized\n\
479   show                        print overview of database contents\n\
480   emer-reset                  reset configuration to clean state\n\
481 \n\
482 Bridge commands:\n\
483   add-br BRIDGE               create a new bridge named BRIDGE\n\
484   add-br BRIDGE PARENT VLAN   create new fake BRIDGE in PARENT on VLAN\n\
485   del-br BRIDGE               delete BRIDGE and all of its ports\n\
486   list-br                     print the names of all the bridges\n\
487   br-exists BRIDGE            test whether BRIDGE exists\n\
488   br-to-vlan BRIDGE           print the VLAN which BRIDGE is on\n\
489   br-to-parent BRIDGE         print the parent of BRIDGE\n\
490   br-set-external-id BRIDGE KEY VALUE  set KEY on BRIDGE to VALUE\n\
491   br-set-external-id BRIDGE KEY  unset KEY on BRIDGE\n\
492   br-get-external-id BRIDGE KEY  print value of KEY on BRIDGE\n\
493   br-get-external-id BRIDGE  list key-value pairs on BRIDGE\n\
494 \n\
495 Port commands (a bond is considered to be a single port):\n\
496   list-ports BRIDGE           print the names of all the ports on BRIDGE\n\
497   add-port BRIDGE PORT        add network device PORT to BRIDGE\n\
498   add-bond BRIDGE PORT IFACE...  add bonded port PORT in BRIDGE from IFACES\n\
499   del-port [BRIDGE] PORT      delete PORT (which may be bonded) from BRIDGE\n\
500   port-to-br PORT             print name of bridge that contains PORT\n\
501 \n\
502 Interface commands (a bond consists of multiple interfaces):\n\
503   list-ifaces BRIDGE          print the names of all interfaces on BRIDGE\n\
504   iface-to-br IFACE           print name of bridge that contains IFACE\n\
505 \n\
506 Controller commands:\n\
507   get-controller BRIDGE      print the controller for BRIDGE\n\
508   del-controller BRIDGE      delete the controller for BRIDGE\n\
509   set-controller BRIDGE TARGET  set the controller for BRIDGE to TARGET\n\
510   get-fail-mode BRIDGE       print the fail-mode for BRIDGE\n\
511   del-fail-mode BRIDGE       delete the fail-mode for BRIDGE\n\
512   set-fail-mode BRIDGE MODE  set the fail-mode for BRIDGE to MODE\n\
513 \n\
514 Manager commands:\n\
515   get-manager                print all manager(s)\n\
516   del-manager                delete all manager(s)\n\
517   set-manager TARGET...      set the list of manager(s) to TARGET(s)\n\
518 \n\
519 SSL commands:\n\
520   get-ssl                     print the SSL configuration\n\
521   del-ssl                     delete the SSL configuration\n\
522   set-ssl PRIV-KEY CERT CA-CERT  set the SSL configuration\n\
523 \n\
524 Switch commands:\n\
525   emer-reset                  reset switch to known good state\n\
526 \n\
527 Database commands:\n\
528   list TBL [REC]              list RECord (or all records) in TBL\n\
529   find TBL CONDITION...       list records satisfying CONDITION in TBL\n\
530   get TBL REC COL[:KEY]       print values of COLumns in RECord in TBL\n\
531   set TBL REC COL[:KEY]=VALUE set COLumn values in RECord in TBL\n\
532   add TBL REC COL [KEY=]VALUE add (KEY=)VALUE to COLumn in RECord in TBL\n\
533   remove TBL REC COL [KEY=]VALUE  remove (KEY=)VALUE from COLumn\n\
534   clear TBL REC COL           clear values from COLumn in RECord in TBL\n\
535   create TBL COL[:KEY]=VALUE  create and initialize new record\n\
536   destroy TBL REC             delete RECord from TBL\n\
537   wait-until TBL REC [COL[:KEY]=VALUE]  wait until condition is true\n\
538 Potentially unsafe database commands require --force option.\n\
539 \n\
540 Options:\n\
541   --db=DATABASE               connect to DATABASE\n\
542                               (default: %s)\n\
543   --no-wait                   do not wait for ovs-vswitchd to reconfigure\n\
544   -t, --timeout=SECS          wait at most SECS seconds for ovs-vswitchd\n\
545   --dry-run                   do not commit changes to database\n\
546   --oneline                   print exactly one line of output per command\n",
547            program_name, program_name, default_db());
548     vlog_usage();
549     printf("\
550   --no-syslog             equivalent to --verbose=vsctl:syslog:warn\n");
551     stream_usage("database", true, true, false);
552     printf("\n\
553 Other options:\n\
554   -h, --help                  display this help message\n\
555   -V, --version               display version information\n");
556     exit(EXIT_SUCCESS);
557 }
558
559 static char *
560 default_db(void)
561 {
562     static char *def;
563     if (!def) {
564         def = xasprintf("unix:%s/db.sock", ovs_rundir());
565     }
566     return def;
567 }
568
569 /* Returns true if it looks like this set of arguments might modify the
570  * database, otherwise false.  (Not very smart, so it's prone to false
571  * positives.) */
572 static bool
573 might_write_to_db(char **argv)
574 {
575     for (; *argv; argv++) {
576         const struct vsctl_command_syntax *p = find_command(*argv);
577         if (p && p->mode == RW) {
578             return true;
579         }
580     }
581     return false;
582 }
583 \f
584 struct vsctl_context {
585     /* Read-only. */
586     int argc;
587     char **argv;
588     struct shash options;
589
590     /* Modifiable state. */
591     struct ds output;
592     struct table *table;
593     struct ovsdb_idl *idl;
594     struct ovsdb_idl_txn *txn;
595     struct ovsdb_symbol_table *symtab;
596     const struct ovsrec_open_vswitch *ovs;
597     bool verified_ports;
598
599     /* A command may set this member to true if some prerequisite is not met
600      * and the caller should wait for something to change and then retry. */
601     bool try_again;
602 };
603
604 struct vsctl_bridge {
605     struct ovsrec_bridge *br_cfg;
606     char *name;
607     struct ovsrec_controller **ctrl;
608     char *fail_mode;
609     size_t n_ctrl;
610     struct vsctl_bridge *parent;
611     int vlan;
612 };
613
614 struct vsctl_port {
615     struct ovsrec_port *port_cfg;
616     struct vsctl_bridge *bridge;
617 };
618
619 struct vsctl_iface {
620     struct ovsrec_interface *iface_cfg;
621     struct vsctl_port *port;
622 };
623
624 struct vsctl_info {
625     struct vsctl_context *ctx;
626     struct shash bridges;   /* Maps from bridge name to struct vsctl_bridge. */
627     struct shash ports;     /* Maps from port name to struct vsctl_port. */
628     struct shash ifaces;    /* Maps from port name to struct vsctl_iface. */
629 };
630
631 static char *
632 vsctl_context_to_string(const struct vsctl_context *ctx)
633 {
634     const struct shash_node *node;
635     struct svec words;
636     char *s;
637     int i;
638
639     svec_init(&words);
640     SHASH_FOR_EACH (node, &ctx->options) {
641         svec_add(&words, node->name);
642     }
643     for (i = 0; i < ctx->argc; i++) {
644         svec_add(&words, ctx->argv[i]);
645     }
646     svec_terminate(&words);
647
648     s = process_escape_args(words.names);
649
650     svec_destroy(&words);
651
652     return s;
653 }
654
655 static void
656 verify_ports(struct vsctl_context *ctx)
657 {
658     if (!ctx->verified_ports) {
659         const struct ovsrec_bridge *bridge;
660         const struct ovsrec_port *port;
661
662         ovsrec_open_vswitch_verify_bridges(ctx->ovs);
663         OVSREC_BRIDGE_FOR_EACH (bridge, ctx->idl) {
664             ovsrec_bridge_verify_ports(bridge);
665         }
666         OVSREC_PORT_FOR_EACH (port, ctx->idl) {
667             ovsrec_port_verify_interfaces(port);
668         }
669
670         ctx->verified_ports = true;
671     }
672 }
673
674 static struct vsctl_bridge *
675 add_bridge(struct vsctl_info *b,
676            struct ovsrec_bridge *br_cfg, const char *name,
677            struct vsctl_bridge *parent, int vlan)
678 {
679     struct vsctl_bridge *br = xmalloc(sizeof *br);
680     br->br_cfg = br_cfg;
681     br->name = xstrdup(name);
682     br->parent = parent;
683     br->vlan = vlan;
684     if (parent) {
685         br->ctrl = parent->br_cfg->controller;
686         br->n_ctrl = parent->br_cfg->n_controller;
687         br->fail_mode = parent->br_cfg->fail_mode;
688     } else {
689         br->ctrl = br_cfg->controller;
690         br->n_ctrl = br_cfg->n_controller;
691         br->fail_mode = br_cfg->fail_mode;
692     }
693     shash_add(&b->bridges, br->name, br);
694     return br;
695 }
696
697 static bool
698 port_is_fake_bridge(const struct ovsrec_port *port_cfg)
699 {
700     return (port_cfg->fake_bridge
701             && port_cfg->tag
702             && *port_cfg->tag >= 1 && *port_cfg->tag <= 4095);
703 }
704
705 static struct vsctl_bridge *
706 find_vlan_bridge(struct vsctl_info *info,
707                  struct vsctl_bridge *parent, int vlan)
708 {
709     struct shash_node *node;
710
711     SHASH_FOR_EACH (node, &info->bridges) {
712         struct vsctl_bridge *br = node->data;
713         if (br->parent == parent && br->vlan == vlan) {
714             return br;
715         }
716     }
717
718     return NULL;
719 }
720
721 static void
722 free_info(struct vsctl_info *info)
723 {
724     struct shash_node *node;
725
726     SHASH_FOR_EACH (node, &info->bridges) {
727         struct vsctl_bridge *bridge = node->data;
728         free(bridge->name);
729         free(bridge);
730     }
731     shash_destroy(&info->bridges);
732
733     shash_destroy_free_data(&info->ports);
734     shash_destroy_free_data(&info->ifaces);
735 }
736
737 static void
738 pre_get_info(struct vsctl_context *ctx)
739 {
740     ovsdb_idl_add_column(ctx->idl, &ovsrec_open_vswitch_col_bridges);
741
742     ovsdb_idl_add_column(ctx->idl, &ovsrec_bridge_col_name);
743     ovsdb_idl_add_column(ctx->idl, &ovsrec_bridge_col_controller);
744     ovsdb_idl_add_column(ctx->idl, &ovsrec_bridge_col_fail_mode);
745     ovsdb_idl_add_column(ctx->idl, &ovsrec_bridge_col_ports);
746
747     ovsdb_idl_add_column(ctx->idl, &ovsrec_port_col_name);
748     ovsdb_idl_add_column(ctx->idl, &ovsrec_port_col_fake_bridge);
749     ovsdb_idl_add_column(ctx->idl, &ovsrec_port_col_tag);
750     ovsdb_idl_add_column(ctx->idl, &ovsrec_port_col_interfaces);
751
752     ovsdb_idl_add_column(ctx->idl, &ovsrec_interface_col_name);
753 }
754
755 static void
756 get_info(struct vsctl_context *ctx, struct vsctl_info *info)
757 {
758     const struct ovsrec_open_vswitch *ovs = ctx->ovs;
759     struct sset bridges, ports;
760     size_t i;
761
762     info->ctx = ctx;
763     shash_init(&info->bridges);
764     shash_init(&info->ports);
765     shash_init(&info->ifaces);
766
767     sset_init(&bridges);
768     sset_init(&ports);
769     for (i = 0; i < ovs->n_bridges; i++) {
770         struct ovsrec_bridge *br_cfg = ovs->bridges[i];
771         struct vsctl_bridge *br;
772         size_t j;
773
774         if (!sset_add(&bridges, br_cfg->name)) {
775             VLOG_WARN("%s: database contains duplicate bridge name",
776                       br_cfg->name);
777             continue;
778         }
779         br = add_bridge(info, br_cfg, br_cfg->name, NULL, 0);
780         if (!br) {
781             continue;
782         }
783
784         for (j = 0; j < br_cfg->n_ports; j++) {
785             struct ovsrec_port *port_cfg = br_cfg->ports[j];
786
787             if (!sset_add(&ports, port_cfg->name)) {
788                 /* Duplicate port name.  (We will warn about that later.) */
789                 continue;
790             }
791
792             if (port_is_fake_bridge(port_cfg)
793                 && sset_add(&bridges, port_cfg->name)) {
794                 add_bridge(info, NULL, port_cfg->name, br, *port_cfg->tag);
795             }
796         }
797     }
798     sset_destroy(&bridges);
799     sset_destroy(&ports);
800
801     sset_init(&bridges);
802     for (i = 0; i < ovs->n_bridges; i++) {
803         struct ovsrec_bridge *br_cfg = ovs->bridges[i];
804         struct vsctl_bridge *br;
805         size_t j;
806
807         if (!sset_add(&bridges, br_cfg->name)) {
808             continue;
809         }
810         br = shash_find_data(&info->bridges, br_cfg->name);
811         for (j = 0; j < br_cfg->n_ports; j++) {
812             struct ovsrec_port *port_cfg = br_cfg->ports[j];
813             struct vsctl_port *port;
814             size_t k;
815
816             port = shash_find_data(&info->ports, port_cfg->name);
817             if (port) {
818                 if (port_cfg == port->port_cfg) {
819                     VLOG_WARN("%s: port is in multiple bridges (%s and %s)",
820                               port_cfg->name, br->name, port->bridge->name);
821                 } else {
822                     /* Log as an error because this violates the database's
823                      * uniqueness constraints, so the database server shouldn't
824                      * have allowed it. */
825                     VLOG_ERR("%s: database contains duplicate port name",
826                              port_cfg->name);
827                 }
828                 continue;
829             }
830
831             if (port_is_fake_bridge(port_cfg)
832                 && !sset_add(&bridges, port_cfg->name)) {
833                 continue;
834             }
835
836             port = xmalloc(sizeof *port);
837             port->port_cfg = port_cfg;
838             if (port_cfg->tag
839                 && *port_cfg->tag >= 1 && *port_cfg->tag <= 4095) {
840                 port->bridge = find_vlan_bridge(info, br, *port_cfg->tag);
841                 if (!port->bridge) {
842                     port->bridge = br;
843                 }
844             } else {
845                 port->bridge = br;
846             }
847             shash_add(&info->ports, port_cfg->name, port);
848
849             for (k = 0; k < port_cfg->n_interfaces; k++) {
850                 struct ovsrec_interface *iface_cfg = port_cfg->interfaces[k];
851                 struct vsctl_iface *iface;
852
853                 iface = shash_find_data(&info->ifaces, iface_cfg->name);
854                 if (iface) {
855                     if (iface_cfg == iface->iface_cfg) {
856                         VLOG_WARN("%s: interface is in multiple ports "
857                                   "(%s and %s)",
858                                   iface_cfg->name,
859                                   iface->port->port_cfg->name,
860                                   port->port_cfg->name);
861                     } else {
862                         /* Log as an error because this violates the database's
863                          * uniqueness constraints, so the database server
864                          * shouldn't have allowed it. */
865                         VLOG_ERR("%s: database contains duplicate interface "
866                                  "name", iface_cfg->name);
867                     }
868                     continue;
869                 }
870
871                 iface = xmalloc(sizeof *iface);
872                 iface->iface_cfg = iface_cfg;
873                 iface->port = port;
874                 shash_add(&info->ifaces, iface_cfg->name, iface);
875             }
876         }
877     }
878     sset_destroy(&bridges);
879 }
880
881 static void
882 check_conflicts(struct vsctl_info *info, const char *name,
883                 char *msg)
884 {
885     struct vsctl_iface *iface;
886     struct vsctl_port *port;
887
888     verify_ports(info->ctx);
889
890     if (shash_find(&info->bridges, name)) {
891         vsctl_fatal("%s because a bridge named %s already exists",
892                     msg, name);
893     }
894
895     port = shash_find_data(&info->ports, name);
896     if (port) {
897         vsctl_fatal("%s because a port named %s already exists on "
898                     "bridge %s", msg, name, port->bridge->name);
899     }
900
901     iface = shash_find_data(&info->ifaces, name);
902     if (iface) {
903         vsctl_fatal("%s because an interface named %s already exists "
904                     "on bridge %s", msg, name, iface->port->bridge->name);
905     }
906
907     free(msg);
908 }
909
910 static struct vsctl_bridge *
911 find_bridge(struct vsctl_info *info, const char *name, bool must_exist)
912 {
913     struct vsctl_bridge *br = shash_find_data(&info->bridges, name);
914     if (must_exist && !br) {
915         vsctl_fatal("no bridge named %s", name);
916     }
917     ovsrec_open_vswitch_verify_bridges(info->ctx->ovs);
918     return br;
919 }
920
921 static struct vsctl_bridge *
922 find_real_bridge(struct vsctl_info *info, const char *name, bool must_exist)
923 {
924     struct vsctl_bridge *br = find_bridge(info, name, must_exist);
925     if (br && br->parent) {
926         vsctl_fatal("%s is a fake bridge", name);
927     }
928     return br;
929 }
930
931 static struct vsctl_port *
932 find_port(struct vsctl_info *info, const char *name, bool must_exist)
933 {
934     struct vsctl_port *port = shash_find_data(&info->ports, name);
935     if (port && !strcmp(name, port->bridge->name)) {
936         port = NULL;
937     }
938     if (must_exist && !port) {
939         vsctl_fatal("no port named %s", name);
940     }
941     verify_ports(info->ctx);
942     return port;
943 }
944
945 static struct vsctl_iface *
946 find_iface(struct vsctl_info *info, const char *name, bool must_exist)
947 {
948     struct vsctl_iface *iface = shash_find_data(&info->ifaces, name);
949     if (iface && !strcmp(name, iface->port->bridge->name)) {
950         iface = NULL;
951     }
952     if (must_exist && !iface) {
953         vsctl_fatal("no interface named %s", name);
954     }
955     verify_ports(info->ctx);
956     return iface;
957 }
958
959 static void
960 bridge_insert_port(struct ovsrec_bridge *br, struct ovsrec_port *port)
961 {
962     struct ovsrec_port **ports;
963     size_t i;
964
965     ports = xmalloc(sizeof *br->ports * (br->n_ports + 1));
966     for (i = 0; i < br->n_ports; i++) {
967         ports[i] = br->ports[i];
968     }
969     ports[br->n_ports] = port;
970     ovsrec_bridge_set_ports(br, ports, br->n_ports + 1);
971     free(ports);
972 }
973
974 static void
975 bridge_delete_port(struct ovsrec_bridge *br, struct ovsrec_port *port)
976 {
977     struct ovsrec_port **ports;
978     size_t i, n;
979
980     ports = xmalloc(sizeof *br->ports * br->n_ports);
981     for (i = n = 0; i < br->n_ports; i++) {
982         if (br->ports[i] != port) {
983             ports[n++] = br->ports[i];
984         }
985     }
986     ovsrec_bridge_set_ports(br, ports, n);
987     free(ports);
988 }
989
990 static void
991 ovs_insert_bridge(const struct ovsrec_open_vswitch *ovs,
992                   struct ovsrec_bridge *bridge)
993 {
994     struct ovsrec_bridge **bridges;
995     size_t i;
996
997     bridges = xmalloc(sizeof *ovs->bridges * (ovs->n_bridges + 1));
998     for (i = 0; i < ovs->n_bridges; i++) {
999         bridges[i] = ovs->bridges[i];
1000     }
1001     bridges[ovs->n_bridges] = bridge;
1002     ovsrec_open_vswitch_set_bridges(ovs, bridges, ovs->n_bridges + 1);
1003     free(bridges);
1004 }
1005
1006 static void
1007 ovs_delete_bridge(const struct ovsrec_open_vswitch *ovs,
1008                   struct ovsrec_bridge *bridge)
1009 {
1010     struct ovsrec_bridge **bridges;
1011     size_t i, n;
1012
1013     bridges = xmalloc(sizeof *ovs->bridges * ovs->n_bridges);
1014     for (i = n = 0; i < ovs->n_bridges; i++) {
1015         if (ovs->bridges[i] != bridge) {
1016             bridges[n++] = ovs->bridges[i];
1017         }
1018     }
1019     ovsrec_open_vswitch_set_bridges(ovs, bridges, n);
1020     free(bridges);
1021 }
1022
1023 static void
1024 cmd_init(struct vsctl_context *ctx OVS_UNUSED)
1025 {
1026 }
1027
1028 struct cmd_show_table {
1029     const struct ovsdb_idl_table_class *table;
1030     const struct ovsdb_idl_column *name_column;
1031     const struct ovsdb_idl_column *columns[3];
1032     bool recurse;
1033 };
1034
1035 static struct cmd_show_table cmd_show_tables[] = {
1036     {&ovsrec_table_open_vswitch,
1037      NULL,
1038      {&ovsrec_open_vswitch_col_manager_options,
1039       &ovsrec_open_vswitch_col_bridges,
1040       &ovsrec_open_vswitch_col_ovs_version},
1041      false},
1042
1043     {&ovsrec_table_bridge,
1044      &ovsrec_bridge_col_name,
1045      {&ovsrec_bridge_col_controller,
1046       &ovsrec_bridge_col_fail_mode,
1047       &ovsrec_bridge_col_ports},
1048      false},
1049
1050     {&ovsrec_table_port,
1051      &ovsrec_port_col_name,
1052      {&ovsrec_port_col_tag,
1053       &ovsrec_port_col_trunks,
1054       &ovsrec_port_col_interfaces},
1055      false},
1056
1057     {&ovsrec_table_interface,
1058      &ovsrec_interface_col_name,
1059      {&ovsrec_interface_col_type,
1060       &ovsrec_interface_col_options,
1061       NULL},
1062      false},
1063
1064     {&ovsrec_table_controller,
1065      &ovsrec_controller_col_target,
1066      {&ovsrec_controller_col_is_connected,
1067       NULL,
1068       NULL},
1069      false},
1070
1071     {&ovsrec_table_manager,
1072      &ovsrec_manager_col_target,
1073      {&ovsrec_manager_col_is_connected,
1074       NULL,
1075       NULL},
1076      false},
1077 };
1078
1079 static void
1080 pre_cmd_show(struct vsctl_context *ctx)
1081 {
1082     struct cmd_show_table *show;
1083
1084     for (show = cmd_show_tables;
1085          show < &cmd_show_tables[ARRAY_SIZE(cmd_show_tables)];
1086          show++) {
1087         size_t i;
1088
1089         ovsdb_idl_add_table(ctx->idl, show->table);
1090         if (show->name_column) {
1091             ovsdb_idl_add_column(ctx->idl, show->name_column);
1092         }
1093         for (i = 0; i < ARRAY_SIZE(show->columns); i++) {
1094             const struct ovsdb_idl_column *column = show->columns[i];
1095             if (column) {
1096                 ovsdb_idl_add_column(ctx->idl, column);
1097             }
1098         }
1099     }
1100 }
1101
1102 static struct cmd_show_table *
1103 cmd_show_find_table_by_row(const struct ovsdb_idl_row *row)
1104 {
1105     struct cmd_show_table *show;
1106
1107     for (show = cmd_show_tables;
1108          show < &cmd_show_tables[ARRAY_SIZE(cmd_show_tables)];
1109          show++) {
1110         if (show->table == row->table->class) {
1111             return show;
1112         }
1113     }
1114     return NULL;
1115 }
1116
1117 static struct cmd_show_table *
1118 cmd_show_find_table_by_name(const char *name)
1119 {
1120     struct cmd_show_table *show;
1121
1122     for (show = cmd_show_tables;
1123          show < &cmd_show_tables[ARRAY_SIZE(cmd_show_tables)];
1124          show++) {
1125         if (!strcmp(show->table->name, name)) {
1126             return show;
1127         }
1128     }
1129     return NULL;
1130 }
1131
1132 static void
1133 cmd_show_row(struct vsctl_context *ctx, const struct ovsdb_idl_row *row,
1134              int level)
1135 {
1136     struct cmd_show_table *show = cmd_show_find_table_by_row(row);
1137     size_t i;
1138
1139     ds_put_char_multiple(&ctx->output, ' ', level * 4);
1140     if (show && show->name_column) {
1141         const struct ovsdb_datum *datum;
1142
1143         ds_put_format(&ctx->output, "%s ", show->table->name);
1144         datum = ovsdb_idl_read(row, show->name_column);
1145         ovsdb_datum_to_string(datum, &show->name_column->type, &ctx->output);
1146     } else {
1147         ds_put_format(&ctx->output, UUID_FMT, UUID_ARGS(&row->uuid));
1148     }
1149     ds_put_char(&ctx->output, '\n');
1150
1151     if (!show || show->recurse) {
1152         return;
1153     }
1154
1155     show->recurse = true;
1156     for (i = 0; i < ARRAY_SIZE(show->columns); i++) {
1157         const struct ovsdb_idl_column *column = show->columns[i];
1158         const struct ovsdb_datum *datum;
1159
1160         if (!column) {
1161             break;
1162         }
1163
1164         datum = ovsdb_idl_read(row, column);
1165         if (column->type.key.type == OVSDB_TYPE_UUID &&
1166             column->type.key.u.uuid.refTableName) {
1167             struct cmd_show_table *ref_show;
1168             size_t j;
1169
1170             ref_show = cmd_show_find_table_by_name(
1171                 column->type.key.u.uuid.refTableName);
1172             if (ref_show) {
1173                 for (j = 0; j < datum->n; j++) {
1174                     const struct ovsdb_idl_row *ref_row;
1175
1176                     ref_row = ovsdb_idl_get_row_for_uuid(ctx->idl,
1177                                                          ref_show->table,
1178                                                          &datum->keys[j].uuid);
1179                     if (ref_row) {
1180                         cmd_show_row(ctx, ref_row, level + 1);
1181                     }
1182                 }
1183                 continue;
1184             }
1185         }
1186
1187         if (!ovsdb_datum_is_default(datum, &column->type)) {
1188             ds_put_char_multiple(&ctx->output, ' ', (level + 1) * 4);
1189             ds_put_format(&ctx->output, "%s: ", column->name);
1190             ovsdb_datum_to_string(datum, &column->type, &ctx->output);
1191             ds_put_char(&ctx->output, '\n');
1192         }
1193     }
1194     show->recurse = false;
1195 }
1196
1197 static void
1198 cmd_show(struct vsctl_context *ctx)
1199 {
1200     const struct ovsdb_idl_row *row;
1201
1202     for (row = ovsdb_idl_first_row(ctx->idl, cmd_show_tables[0].table);
1203          row; row = ovsdb_idl_next_row(row)) {
1204         cmd_show_row(ctx, row, 0);
1205     }
1206 }
1207
1208 static void
1209 pre_cmd_emer_reset(struct vsctl_context *ctx)
1210 {
1211     ovsdb_idl_add_column(ctx->idl, &ovsrec_open_vswitch_col_manager_options);
1212     ovsdb_idl_add_column(ctx->idl, &ovsrec_open_vswitch_col_ssl);
1213
1214     ovsdb_idl_add_column(ctx->idl, &ovsrec_bridge_col_controller);
1215     ovsdb_idl_add_column(ctx->idl, &ovsrec_bridge_col_fail_mode);
1216     ovsdb_idl_add_column(ctx->idl, &ovsrec_bridge_col_mirrors);
1217     ovsdb_idl_add_column(ctx->idl, &ovsrec_bridge_col_netflow);
1218     ovsdb_idl_add_column(ctx->idl, &ovsrec_bridge_col_sflow);
1219     ovsdb_idl_add_column(ctx->idl, &ovsrec_bridge_col_flood_vlans);
1220     ovsdb_idl_add_column(ctx->idl, &ovsrec_bridge_col_other_config);
1221
1222     ovsdb_idl_add_column(ctx->idl, &ovsrec_port_col_other_config);
1223
1224     ovsdb_idl_add_column(ctx->idl,
1225                           &ovsrec_interface_col_ingress_policing_rate);
1226     ovsdb_idl_add_column(ctx->idl,
1227                           &ovsrec_interface_col_ingress_policing_burst);
1228 }
1229
1230 static void
1231 cmd_emer_reset(struct vsctl_context *ctx)
1232 {
1233     const struct ovsdb_idl *idl = ctx->idl;
1234     const struct ovsrec_bridge *br;
1235     const struct ovsrec_port *port;
1236     const struct ovsrec_interface *iface;
1237     const struct ovsrec_mirror *mirror, *next_mirror;
1238     const struct ovsrec_controller *ctrl, *next_ctrl;
1239     const struct ovsrec_manager *mgr, *next_mgr;
1240     const struct ovsrec_netflow *nf, *next_nf;
1241     const struct ovsrec_ssl *ssl, *next_ssl;
1242     const struct ovsrec_sflow *sflow, *next_sflow;
1243
1244     /* Reset the Open_vSwitch table. */
1245     ovsrec_open_vswitch_set_manager_options(ctx->ovs, NULL, 0);
1246     ovsrec_open_vswitch_set_ssl(ctx->ovs, NULL);
1247
1248     OVSREC_BRIDGE_FOR_EACH (br, idl) {
1249         int i;
1250         char *hw_key = "hwaddr";
1251         char *hw_val = NULL;
1252
1253         ovsrec_bridge_set_controller(br, NULL, 0);
1254         ovsrec_bridge_set_fail_mode(br, NULL);
1255         ovsrec_bridge_set_mirrors(br, NULL, 0);
1256         ovsrec_bridge_set_netflow(br, NULL);
1257         ovsrec_bridge_set_sflow(br, NULL);
1258         ovsrec_bridge_set_flood_vlans(br, NULL, 0);
1259
1260         /* We only want to save the "hwaddr" key from other_config. */
1261         for (i=0; i < br->n_other_config; i++) {
1262             if (!strcmp(br->key_other_config[i], hw_key)) {
1263                 hw_val = br->value_other_config[i];
1264                 break;
1265             }
1266         }
1267         if (hw_val) {
1268             char *val = xstrdup(hw_val);
1269             ovsrec_bridge_set_other_config(br, &hw_key, &val, 1);
1270             free(val);
1271         } else {
1272             ovsrec_bridge_set_other_config(br, NULL, NULL, 0);
1273         }
1274     }
1275
1276     OVSREC_PORT_FOR_EACH (port, idl) {
1277         ovsrec_port_set_other_config(port, NULL, NULL, 0);
1278     }
1279
1280     OVSREC_INTERFACE_FOR_EACH (iface, idl) {
1281         /* xxx What do we do about gre/patch devices created by mgr? */
1282
1283         ovsrec_interface_set_ingress_policing_rate(iface, 0);
1284         ovsrec_interface_set_ingress_policing_burst(iface, 0);
1285     }
1286
1287     OVSREC_MIRROR_FOR_EACH_SAFE (mirror, next_mirror, idl) {
1288         ovsrec_mirror_delete(mirror);
1289     }
1290
1291     OVSREC_CONTROLLER_FOR_EACH_SAFE (ctrl, next_ctrl, idl) {
1292         ovsrec_controller_delete(ctrl);
1293     }
1294
1295     OVSREC_MANAGER_FOR_EACH_SAFE (mgr, next_mgr, idl) {
1296         ovsrec_manager_delete(mgr);
1297     }
1298
1299     OVSREC_NETFLOW_FOR_EACH_SAFE (nf, next_nf, idl) {
1300         ovsrec_netflow_delete(nf);
1301     }
1302
1303     OVSREC_SSL_FOR_EACH_SAFE (ssl, next_ssl, idl) {
1304         ovsrec_ssl_delete(ssl);
1305     }
1306
1307     OVSREC_SFLOW_FOR_EACH_SAFE (sflow, next_sflow, idl) {
1308         ovsrec_sflow_delete(sflow);
1309     }
1310 }
1311
1312 static void
1313 cmd_add_br(struct vsctl_context *ctx)
1314 {
1315     bool may_exist = shash_find(&ctx->options, "--may-exist") != NULL;
1316     const char *br_name, *parent_name;
1317     struct vsctl_info info;
1318     int vlan;
1319
1320     br_name = ctx->argv[1];
1321     if (ctx->argc == 2) {
1322         parent_name = NULL;
1323         vlan = 0;
1324     } else if (ctx->argc == 4) {
1325         parent_name = ctx->argv[2];
1326         vlan = atoi(ctx->argv[3]);
1327         if (vlan < 1 || vlan > 4095) {
1328             vsctl_fatal("%s: vlan must be between 1 and 4095", ctx->argv[0]);
1329         }
1330     } else {
1331         vsctl_fatal("'%s' command takes exactly 1 or 3 arguments",
1332                     ctx->argv[0]);
1333     }
1334
1335     get_info(ctx, &info);
1336     if (may_exist) {
1337         struct vsctl_bridge *br;
1338
1339         br = find_bridge(&info, br_name, false);
1340         if (br) {
1341             if (!parent_name) {
1342                 if (br->parent) {
1343                     vsctl_fatal("\"--may-exist add-br %s\" but %s is "
1344                                 "a VLAN bridge for VLAN %d",
1345                                 br_name, br_name, br->vlan);
1346                 }
1347             } else {
1348                 if (!br->parent) {
1349                     vsctl_fatal("\"--may-exist add-br %s %s %d\" but %s "
1350                                 "is not a VLAN bridge",
1351                                 br_name, parent_name, vlan, br_name);
1352                 } else if (strcmp(br->parent->name, parent_name)) {
1353                     vsctl_fatal("\"--may-exist add-br %s %s %d\" but %s "
1354                                 "has the wrong parent %s",
1355                                 br_name, parent_name, vlan,
1356                                 br_name, br->parent->name);
1357                 } else if (br->vlan != vlan) {
1358                     vsctl_fatal("\"--may-exist add-br %s %s %d\" but %s "
1359                                 "is a VLAN bridge for the wrong VLAN %d",
1360                                 br_name, parent_name, vlan, br_name, br->vlan);
1361                 }
1362             }
1363             return;
1364         }
1365     }
1366     check_conflicts(&info, br_name,
1367                     xasprintf("cannot create a bridge named %s", br_name));
1368
1369     if (!parent_name) {
1370         struct ovsrec_port *port;
1371         struct ovsrec_interface *iface;
1372         struct ovsrec_bridge *br;
1373
1374         iface = ovsrec_interface_insert(ctx->txn);
1375         ovsrec_interface_set_name(iface, br_name);
1376         ovsrec_interface_set_type(iface, "internal");
1377
1378         port = ovsrec_port_insert(ctx->txn);
1379         ovsrec_port_set_name(port, br_name);
1380         ovsrec_port_set_interfaces(port, &iface, 1);
1381
1382         br = ovsrec_bridge_insert(ctx->txn);
1383         ovsrec_bridge_set_name(br, br_name);
1384         ovsrec_bridge_set_ports(br, &port, 1);
1385
1386         ovs_insert_bridge(ctx->ovs, br);
1387     } else {
1388         struct vsctl_bridge *parent;
1389         struct ovsrec_port *port;
1390         struct ovsrec_interface *iface;
1391         struct ovsrec_bridge *br;
1392         int64_t tag = vlan;
1393
1394         parent = find_bridge(&info, parent_name, false);
1395         if (parent && parent->vlan) {
1396             vsctl_fatal("cannot create bridge with fake bridge as parent");
1397         }
1398         if (!parent) {
1399             vsctl_fatal("parent bridge %s does not exist", parent_name);
1400         }
1401         br = parent->br_cfg;
1402
1403         iface = ovsrec_interface_insert(ctx->txn);
1404         ovsrec_interface_set_name(iface, br_name);
1405         ovsrec_interface_set_type(iface, "internal");
1406
1407         port = ovsrec_port_insert(ctx->txn);
1408         ovsrec_port_set_name(port, br_name);
1409         ovsrec_port_set_interfaces(port, &iface, 1);
1410         ovsrec_port_set_fake_bridge(port, true);
1411         ovsrec_port_set_tag(port, &tag, 1);
1412
1413         bridge_insert_port(br, port);
1414     }
1415
1416     free_info(&info);
1417 }
1418
1419 static void
1420 del_port(struct vsctl_info *info, struct vsctl_port *port)
1421 {
1422     struct shash_node *node;
1423
1424     SHASH_FOR_EACH (node, &info->ifaces) {
1425         struct vsctl_iface *iface = node->data;
1426         if (iface->port == port) {
1427             ovsrec_interface_delete(iface->iface_cfg);
1428         }
1429     }
1430     ovsrec_port_delete(port->port_cfg);
1431
1432     bridge_delete_port((port->bridge->parent
1433                         ? port->bridge->parent->br_cfg
1434                         : port->bridge->br_cfg), port->port_cfg);
1435 }
1436
1437 static void
1438 cmd_del_br(struct vsctl_context *ctx)
1439 {
1440     bool must_exist = !shash_find(&ctx->options, "--if-exists");
1441     struct vsctl_bridge *bridge;
1442     struct vsctl_info info;
1443
1444     get_info(ctx, &info);
1445     bridge = find_bridge(&info, ctx->argv[1], must_exist);
1446     if (bridge) {
1447         struct shash_node *node;
1448
1449         SHASH_FOR_EACH (node, &info.ports) {
1450             struct vsctl_port *port = node->data;
1451             if (port->bridge == bridge || port->bridge->parent == bridge
1452                 || !strcmp(port->port_cfg->name, bridge->name)) {
1453                 del_port(&info, port);
1454             }
1455         }
1456         if (bridge->br_cfg) {
1457             ovsrec_bridge_delete(bridge->br_cfg);
1458             ovs_delete_bridge(ctx->ovs, bridge->br_cfg);
1459         }
1460     }
1461     free_info(&info);
1462 }
1463
1464 static void
1465 output_sorted(struct svec *svec, struct ds *output)
1466 {
1467     const char *name;
1468     size_t i;
1469
1470     svec_sort(svec);
1471     SVEC_FOR_EACH (i, name, svec) {
1472         ds_put_format(output, "%s\n", name);
1473     }
1474 }
1475
1476 static void
1477 cmd_list_br(struct vsctl_context *ctx)
1478 {
1479     struct shash_node *node;
1480     struct vsctl_info info;
1481     struct svec bridges;
1482
1483     get_info(ctx, &info);
1484
1485     svec_init(&bridges);
1486     SHASH_FOR_EACH (node, &info.bridges) {
1487         struct vsctl_bridge *br = node->data;
1488         svec_add(&bridges, br->name);
1489     }
1490     output_sorted(&bridges, &ctx->output);
1491     svec_destroy(&bridges);
1492
1493     free_info(&info);
1494 }
1495
1496 static void
1497 cmd_br_exists(struct vsctl_context *ctx)
1498 {
1499     struct vsctl_info info;
1500
1501     get_info(ctx, &info);
1502     if (!find_bridge(&info, ctx->argv[1], false)) {
1503         vsctl_exit(2);
1504     }
1505     free_info(&info);
1506 }
1507
1508 /* Returns true if 'b_prefix' (of length 'b_prefix_len') concatenated with 'b'
1509  * equals 'a', false otherwise. */
1510 static bool
1511 key_matches(const char *a,
1512             const char *b_prefix, size_t b_prefix_len, const char *b)
1513 {
1514     return !strncmp(a, b_prefix, b_prefix_len) && !strcmp(a + b_prefix_len, b);
1515 }
1516
1517 static void
1518 set_external_id(char **old_keys, char **old_values, size_t old_n,
1519                 char *key, char *value,
1520                 char ***new_keysp, char ***new_valuesp, size_t *new_np)
1521 {
1522     char **new_keys;
1523     char **new_values;
1524     size_t new_n;
1525     size_t i;
1526
1527     new_keys = xmalloc(sizeof *new_keys * (old_n + 1));
1528     new_values = xmalloc(sizeof *new_values * (old_n + 1));
1529     new_n = 0;
1530     for (i = 0; i < old_n; i++) {
1531         if (strcmp(key, old_keys[i])) {
1532             new_keys[new_n] = old_keys[i];
1533             new_values[new_n] = old_values[i];
1534             new_n++;
1535         }
1536     }
1537     if (value) {
1538         new_keys[new_n] = key;
1539         new_values[new_n] = value;
1540         new_n++;
1541     }
1542     *new_keysp = new_keys;
1543     *new_valuesp = new_values;
1544     *new_np = new_n;
1545 }
1546
1547 static void
1548 pre_cmd_br_set_external_id(struct vsctl_context *ctx)
1549 {
1550     pre_get_info(ctx);
1551     ovsdb_idl_add_column(ctx->idl, &ovsrec_bridge_col_external_ids);
1552     ovsdb_idl_add_column(ctx->idl, &ovsrec_port_col_external_ids);
1553 }
1554
1555 static void
1556 cmd_br_set_external_id(struct vsctl_context *ctx)
1557 {
1558     struct vsctl_info info;
1559     struct vsctl_bridge *bridge;
1560     char **keys, **values;
1561     size_t n;
1562
1563     get_info(ctx, &info);
1564     bridge = find_bridge(&info, ctx->argv[1], true);
1565     if (bridge->br_cfg) {
1566         set_external_id(bridge->br_cfg->key_external_ids,
1567                         bridge->br_cfg->value_external_ids,
1568                         bridge->br_cfg->n_external_ids,
1569                         ctx->argv[2], ctx->argc >= 4 ? ctx->argv[3] : NULL,
1570                         &keys, &values, &n);
1571         ovsrec_bridge_verify_external_ids(bridge->br_cfg);
1572         ovsrec_bridge_set_external_ids(bridge->br_cfg, keys, values, n);
1573     } else {
1574         char *key = xasprintf("fake-bridge-%s", ctx->argv[2]);
1575         struct vsctl_port *port = shash_find_data(&info.ports, ctx->argv[1]);
1576         set_external_id(port->port_cfg->key_external_ids,
1577                         port->port_cfg->value_external_ids,
1578                         port->port_cfg->n_external_ids,
1579                         key, ctx->argc >= 4 ? ctx->argv[3] : NULL,
1580                         &keys, &values, &n);
1581         ovsrec_port_verify_external_ids(port->port_cfg);
1582         ovsrec_port_set_external_ids(port->port_cfg, keys, values, n);
1583         free(key);
1584     }
1585     free(keys);
1586     free(values);
1587
1588     free_info(&info);
1589 }
1590
1591 static void
1592 get_external_id(char **keys, char **values, size_t n,
1593                 const char *prefix, const char *key,
1594                 struct ds *output)
1595 {
1596     size_t prefix_len = strlen(prefix);
1597     struct svec svec;
1598     size_t i;
1599
1600     svec_init(&svec);
1601     for (i = 0; i < n; i++) {
1602         if (!key && !strncmp(keys[i], prefix, prefix_len)) {
1603             svec_add_nocopy(&svec, xasprintf("%s=%s",
1604                                              keys[i] + prefix_len, values[i]));
1605         } else if (key && key_matches(keys[i], prefix, prefix_len, key)) {
1606             svec_add(&svec, values[i]);
1607             break;
1608         }
1609     }
1610     output_sorted(&svec, output);
1611     svec_destroy(&svec);
1612 }
1613
1614 static void
1615 pre_cmd_br_get_external_id(struct vsctl_context *ctx)
1616 {
1617     pre_cmd_br_set_external_id(ctx);
1618 }
1619
1620 static void
1621 cmd_br_get_external_id(struct vsctl_context *ctx)
1622 {
1623     struct vsctl_info info;
1624     struct vsctl_bridge *bridge;
1625
1626     get_info(ctx, &info);
1627     bridge = find_bridge(&info, ctx->argv[1], true);
1628     if (bridge->br_cfg) {
1629         ovsrec_bridge_verify_external_ids(bridge->br_cfg);
1630         get_external_id(bridge->br_cfg->key_external_ids,
1631                         bridge->br_cfg->value_external_ids,
1632                         bridge->br_cfg->n_external_ids,
1633                         "", ctx->argc >= 3 ? ctx->argv[2] : NULL,
1634                         &ctx->output);
1635     } else {
1636         struct vsctl_port *port = shash_find_data(&info.ports, ctx->argv[1]);
1637         ovsrec_port_verify_external_ids(port->port_cfg);
1638         get_external_id(port->port_cfg->key_external_ids,
1639                         port->port_cfg->value_external_ids,
1640                         port->port_cfg->n_external_ids,
1641                         "fake-bridge-", ctx->argc >= 3 ? ctx->argv[2] : NULL, &ctx->output);
1642     }
1643     free_info(&info);
1644 }
1645
1646
1647 static void
1648 cmd_list_ports(struct vsctl_context *ctx)
1649 {
1650     struct vsctl_bridge *br;
1651     struct shash_node *node;
1652     struct vsctl_info info;
1653     struct svec ports;
1654
1655     get_info(ctx, &info);
1656     br = find_bridge(&info, ctx->argv[1], true);
1657     ovsrec_bridge_verify_ports(br->br_cfg ? br->br_cfg : br->parent->br_cfg);
1658
1659     svec_init(&ports);
1660     SHASH_FOR_EACH (node, &info.ports) {
1661         struct vsctl_port *port = node->data;
1662
1663         if (strcmp(port->port_cfg->name, br->name) && br == port->bridge) {
1664             svec_add(&ports, port->port_cfg->name);
1665         }
1666     }
1667     output_sorted(&ports, &ctx->output);
1668     svec_destroy(&ports);
1669
1670     free_info(&info);
1671 }
1672
1673 static void
1674 add_port(struct vsctl_context *ctx,
1675          const char *br_name, const char *port_name,
1676          bool may_exist, bool fake_iface,
1677          char *iface_names[], int n_ifaces,
1678          char *settings[], int n_settings)
1679 {
1680     struct vsctl_info info;
1681     struct vsctl_bridge *bridge;
1682     struct ovsrec_interface **ifaces;
1683     struct ovsrec_port *port;
1684     size_t i;
1685
1686     get_info(ctx, &info);
1687     if (may_exist) {
1688         struct vsctl_port *vsctl_port;
1689
1690         vsctl_port = find_port(&info, port_name, false);
1691         if (vsctl_port) {
1692             struct svec want_names, have_names;
1693
1694             svec_init(&want_names);
1695             for (i = 0; i < n_ifaces; i++) {
1696                 svec_add(&want_names, iface_names[i]);
1697             }
1698             svec_sort(&want_names);
1699
1700             svec_init(&have_names);
1701             for (i = 0; i < vsctl_port->port_cfg->n_interfaces; i++) {
1702                 svec_add(&have_names,
1703                          vsctl_port->port_cfg->interfaces[i]->name);
1704             }
1705             svec_sort(&have_names);
1706
1707             if (strcmp(vsctl_port->bridge->name, br_name)) {
1708                 char *command = vsctl_context_to_string(ctx);
1709                 vsctl_fatal("\"%s\" but %s is actually attached to bridge %s",
1710                             command, port_name, vsctl_port->bridge->name);
1711             }
1712
1713             if (!svec_equal(&want_names, &have_names)) {
1714                 char *have_names_string = svec_join(&have_names, ", ", "");
1715                 char *command = vsctl_context_to_string(ctx);
1716
1717                 vsctl_fatal("\"%s\" but %s actually has interface(s) %s",
1718                             command, port_name, have_names_string);
1719             }
1720
1721             svec_destroy(&want_names);
1722             svec_destroy(&have_names);
1723
1724             return;
1725         }
1726     }
1727     check_conflicts(&info, port_name,
1728                     xasprintf("cannot create a port named %s", port_name));
1729     for (i = 0; i < n_ifaces; i++) {
1730         check_conflicts(&info, iface_names[i],
1731                         xasprintf("cannot create an interface named %s",
1732                                   iface_names[i]));
1733     }
1734     bridge = find_bridge(&info, br_name, true);
1735
1736     ifaces = xmalloc(n_ifaces * sizeof *ifaces);
1737     for (i = 0; i < n_ifaces; i++) {
1738         ifaces[i] = ovsrec_interface_insert(ctx->txn);
1739         ovsrec_interface_set_name(ifaces[i], iface_names[i]);
1740     }
1741
1742     port = ovsrec_port_insert(ctx->txn);
1743     ovsrec_port_set_name(port, port_name);
1744     ovsrec_port_set_interfaces(port, ifaces, n_ifaces);
1745     ovsrec_port_set_bond_fake_iface(port, fake_iface);
1746     free(ifaces);
1747
1748     if (bridge->vlan) {
1749         int64_t tag = bridge->vlan;
1750         ovsrec_port_set_tag(port, &tag, 1);
1751     }
1752
1753     for (i = 0; i < n_settings; i++) {
1754         set_column(get_table("Port"), &port->header_, settings[i],
1755                    ctx->symtab);
1756     }
1757
1758     bridge_insert_port((bridge->parent ? bridge->parent->br_cfg
1759                         : bridge->br_cfg), port);
1760
1761     free_info(&info);
1762 }
1763
1764 static void
1765 cmd_add_port(struct vsctl_context *ctx)
1766 {
1767     bool may_exist = shash_find(&ctx->options, "--may-exist") != NULL;
1768
1769     add_port(ctx, ctx->argv[1], ctx->argv[2], may_exist, false,
1770              &ctx->argv[2], 1, &ctx->argv[3], ctx->argc - 3);
1771 }
1772
1773 static void
1774 cmd_add_bond(struct vsctl_context *ctx)
1775 {
1776     bool may_exist = shash_find(&ctx->options, "--may-exist") != NULL;
1777     bool fake_iface = shash_find(&ctx->options, "--fake-iface");
1778     int n_ifaces;
1779     int i;
1780
1781     n_ifaces = ctx->argc - 3;
1782     for (i = 3; i < ctx->argc; i++) {
1783         if (strchr(ctx->argv[i], '=')) {
1784             n_ifaces = i - 3;
1785             break;
1786         }
1787     }
1788     if (n_ifaces < 2) {
1789         vsctl_fatal("add-bond requires at least 2 interfaces, but only "
1790                     "%d were specified", n_ifaces);
1791     }
1792
1793     add_port(ctx, ctx->argv[1], ctx->argv[2], may_exist, fake_iface,
1794              &ctx->argv[3], n_ifaces,
1795              &ctx->argv[n_ifaces + 3], ctx->argc - 3 - n_ifaces);
1796 }
1797
1798 static void
1799 cmd_del_port(struct vsctl_context *ctx)
1800 {
1801     bool must_exist = !shash_find(&ctx->options, "--if-exists");
1802     bool with_iface = shash_find(&ctx->options, "--with-iface") != NULL;
1803     struct vsctl_port *port;
1804     struct vsctl_info info;
1805
1806     get_info(ctx, &info);
1807     if (!with_iface) {
1808         port = find_port(&info, ctx->argv[ctx->argc - 1], must_exist);
1809     } else {
1810         const char *target = ctx->argv[ctx->argc - 1];
1811         struct vsctl_iface *iface;
1812
1813         port = find_port(&info, target, false);
1814         if (!port) {
1815             iface = find_iface(&info, target, false);
1816             if (iface) {
1817                 port = iface->port;
1818             }
1819         }
1820         if (must_exist && !port) {
1821             vsctl_fatal("no port or interface named %s", target);
1822         }
1823     }
1824
1825     if (port) {
1826         if (ctx->argc == 3) {
1827             struct vsctl_bridge *bridge;
1828
1829             bridge = find_bridge(&info, ctx->argv[1], true);
1830             if (port->bridge != bridge) {
1831                 if (port->bridge->parent == bridge) {
1832                     vsctl_fatal("bridge %s does not have a port %s (although "
1833                                 "its parent bridge %s does)",
1834                                 ctx->argv[1], ctx->argv[2],
1835                                 bridge->parent->name);
1836                 } else {
1837                     vsctl_fatal("bridge %s does not have a port %s",
1838                                 ctx->argv[1], ctx->argv[2]);
1839                 }
1840             }
1841         }
1842
1843         del_port(&info, port);
1844     }
1845
1846     free_info(&info);
1847 }
1848
1849 static void
1850 cmd_port_to_br(struct vsctl_context *ctx)
1851 {
1852     struct vsctl_port *port;
1853     struct vsctl_info info;
1854
1855     get_info(ctx, &info);
1856     port = find_port(&info, ctx->argv[1], true);
1857     ds_put_format(&ctx->output, "%s\n", port->bridge->name);
1858     free_info(&info);
1859 }
1860
1861 static void
1862 cmd_br_to_vlan(struct vsctl_context *ctx)
1863 {
1864     struct vsctl_bridge *bridge;
1865     struct vsctl_info info;
1866
1867     get_info(ctx, &info);
1868     bridge = find_bridge(&info, ctx->argv[1], true);
1869     ds_put_format(&ctx->output, "%d\n", bridge->vlan);
1870     free_info(&info);
1871 }
1872
1873 static void
1874 cmd_br_to_parent(struct vsctl_context *ctx)
1875 {
1876     struct vsctl_bridge *bridge;
1877     struct vsctl_info info;
1878
1879     get_info(ctx, &info);
1880     bridge = find_bridge(&info, ctx->argv[1], true);
1881     if (bridge->parent) {
1882         bridge = bridge->parent;
1883     }
1884     ds_put_format(&ctx->output, "%s\n", bridge->name);
1885     free_info(&info);
1886 }
1887
1888 static void
1889 cmd_list_ifaces(struct vsctl_context *ctx)
1890 {
1891     struct vsctl_bridge *br;
1892     struct shash_node *node;
1893     struct vsctl_info info;
1894     struct svec ifaces;
1895
1896     get_info(ctx, &info);
1897     br = find_bridge(&info, ctx->argv[1], true);
1898     verify_ports(ctx);
1899
1900     svec_init(&ifaces);
1901     SHASH_FOR_EACH (node, &info.ifaces) {
1902         struct vsctl_iface *iface = node->data;
1903
1904         if (strcmp(iface->iface_cfg->name, br->name)
1905             && br == iface->port->bridge) {
1906             svec_add(&ifaces, iface->iface_cfg->name);
1907         }
1908     }
1909     output_sorted(&ifaces, &ctx->output);
1910     svec_destroy(&ifaces);
1911
1912     free_info(&info);
1913 }
1914
1915 static void
1916 cmd_iface_to_br(struct vsctl_context *ctx)
1917 {
1918     struct vsctl_iface *iface;
1919     struct vsctl_info info;
1920
1921     get_info(ctx, &info);
1922     iface = find_iface(&info, ctx->argv[1], true);
1923     ds_put_format(&ctx->output, "%s\n", iface->port->bridge->name);
1924     free_info(&info);
1925 }
1926
1927 static void
1928 verify_controllers(struct ovsrec_bridge *bridge)
1929 {
1930     if (bridge) {
1931         size_t i;
1932
1933         ovsrec_bridge_verify_controller(bridge);
1934         for (i = 0; i < bridge->n_controller; i++) {
1935             ovsrec_controller_verify_target(bridge->controller[i]);
1936         }
1937     }
1938 }
1939
1940 static void
1941 pre_controller(struct vsctl_context *ctx)
1942 {
1943     pre_get_info(ctx);
1944
1945     ovsdb_idl_add_column(ctx->idl, &ovsrec_controller_col_target);
1946 }
1947
1948 static void
1949 cmd_get_controller(struct vsctl_context *ctx)
1950 {
1951     struct vsctl_info info;
1952     struct vsctl_bridge *br;
1953     struct svec targets;
1954     size_t i;
1955
1956     get_info(ctx, &info);
1957     br = find_bridge(&info, ctx->argv[1], true);
1958     verify_controllers(br->br_cfg);
1959
1960     /* Print the targets in sorted order for reproducibility. */
1961     svec_init(&targets);
1962     for (i = 0; i < br->n_ctrl; i++) {
1963         svec_add(&targets, br->ctrl[i]->target);
1964     }
1965
1966     svec_sort(&targets);
1967     for (i = 0; i < targets.n; i++) {
1968         ds_put_format(&ctx->output, "%s\n", targets.names[i]);
1969     }
1970     svec_destroy(&targets);
1971
1972     free_info(&info);
1973 }
1974
1975 static void
1976 delete_controllers(struct ovsrec_controller **controllers,
1977                    size_t n_controllers)
1978 {
1979     size_t i;
1980
1981     for (i = 0; i < n_controllers; i++) {
1982         ovsrec_controller_delete(controllers[i]);
1983     }
1984 }
1985
1986 static void
1987 cmd_del_controller(struct vsctl_context *ctx)
1988 {
1989     struct vsctl_info info;
1990     struct vsctl_bridge *br;
1991
1992     get_info(ctx, &info);
1993
1994     br = find_real_bridge(&info, ctx->argv[1], true);
1995     verify_controllers(br->br_cfg);
1996
1997     if (br->ctrl) {
1998         delete_controllers(br->ctrl, br->n_ctrl);
1999         ovsrec_bridge_set_controller(br->br_cfg, NULL, 0);
2000     }
2001
2002     free_info(&info);
2003 }
2004
2005 static struct ovsrec_controller **
2006 insert_controllers(struct ovsdb_idl_txn *txn, char *targets[], size_t n)
2007 {
2008     struct ovsrec_controller **controllers;
2009     size_t i;
2010
2011     controllers = xmalloc(n * sizeof *controllers);
2012     for (i = 0; i < n; i++) {
2013         controllers[i] = ovsrec_controller_insert(txn);
2014         ovsrec_controller_set_target(controllers[i], targets[i]);
2015     }
2016
2017     return controllers;
2018 }
2019
2020 static void
2021 cmd_set_controller(struct vsctl_context *ctx)
2022 {
2023     struct vsctl_info info;
2024     struct vsctl_bridge *br;
2025     struct ovsrec_controller **controllers;
2026     size_t n;
2027
2028     get_info(ctx, &info);
2029     br = find_real_bridge(&info, ctx->argv[1], true);
2030     verify_controllers(br->br_cfg);
2031
2032     delete_controllers(br->ctrl, br->n_ctrl);
2033
2034     n = ctx->argc - 2;
2035     controllers = insert_controllers(ctx->txn, &ctx->argv[2], n);
2036     ovsrec_bridge_set_controller(br->br_cfg, controllers, n);
2037     free(controllers);
2038
2039     free_info(&info);
2040 }
2041
2042 static void
2043 cmd_get_fail_mode(struct vsctl_context *ctx)
2044 {
2045     struct vsctl_info info;
2046     struct vsctl_bridge *br;
2047
2048     get_info(ctx, &info);
2049     br = find_bridge(&info, ctx->argv[1], true);
2050
2051     if (br->br_cfg) {
2052         ovsrec_bridge_verify_fail_mode(br->br_cfg);
2053     }
2054     if (br->fail_mode && strlen(br->fail_mode)) {
2055         ds_put_format(&ctx->output, "%s\n", br->fail_mode);
2056     }
2057
2058     free_info(&info);
2059 }
2060
2061 static void
2062 cmd_del_fail_mode(struct vsctl_context *ctx)
2063 {
2064     struct vsctl_info info;
2065     struct vsctl_bridge *br;
2066
2067     get_info(ctx, &info);
2068     br = find_real_bridge(&info, ctx->argv[1], true);
2069
2070     ovsrec_bridge_set_fail_mode(br->br_cfg, NULL);
2071
2072     free_info(&info);
2073 }
2074
2075 static void
2076 cmd_set_fail_mode(struct vsctl_context *ctx)
2077 {
2078     struct vsctl_info info;
2079     struct vsctl_bridge *br;
2080     const char *fail_mode = ctx->argv[2];
2081
2082     get_info(ctx, &info);
2083     br = find_real_bridge(&info, ctx->argv[1], true);
2084
2085     if (strcmp(fail_mode, "standalone") && strcmp(fail_mode, "secure")) {
2086         vsctl_fatal("fail-mode must be \"standalone\" or \"secure\"");
2087     }
2088
2089     ovsrec_bridge_set_fail_mode(br->br_cfg, fail_mode);
2090
2091     free_info(&info);
2092 }
2093
2094 static void
2095 verify_managers(const struct ovsrec_open_vswitch *ovs)
2096 {
2097     size_t i;
2098
2099     ovsrec_open_vswitch_verify_manager_options(ovs);
2100
2101     for (i = 0; i < ovs->n_manager_options; ++i) {
2102         const struct ovsrec_manager *mgr = ovs->manager_options[i];
2103
2104         ovsrec_manager_verify_target(mgr);
2105     }
2106 }
2107
2108 static void
2109 pre_manager(struct vsctl_context *ctx)
2110 {
2111     ovsdb_idl_add_column(ctx->idl, &ovsrec_open_vswitch_col_manager_options);
2112     ovsdb_idl_add_column(ctx->idl, &ovsrec_manager_col_target);
2113 }
2114
2115 static void
2116 cmd_get_manager(struct vsctl_context *ctx)
2117 {
2118     const struct ovsrec_open_vswitch *ovs = ctx->ovs;
2119     struct svec targets;
2120     size_t i;
2121
2122     verify_managers(ovs);
2123
2124     /* Print the targets in sorted order for reproducibility. */
2125     svec_init(&targets);
2126
2127     for (i = 0; i < ovs->n_manager_options; i++) {
2128         svec_add(&targets, ovs->manager_options[i]->target);
2129     }
2130
2131     svec_sort_unique(&targets);
2132     for (i = 0; i < targets.n; i++) {
2133         ds_put_format(&ctx->output, "%s\n", targets.names[i]);
2134     }
2135     svec_destroy(&targets);
2136 }
2137
2138 static void
2139 delete_managers(const struct vsctl_context *ctx)
2140 {
2141     const struct ovsrec_open_vswitch *ovs = ctx->ovs;
2142     size_t i;
2143
2144     /* Delete Manager rows pointed to by 'manager_options' column. */
2145     for (i = 0; i < ovs->n_manager_options; i++) {
2146         ovsrec_manager_delete(ovs->manager_options[i]);
2147     }
2148
2149     /* Delete 'Manager' row refs in 'manager_options' column. */
2150     ovsrec_open_vswitch_set_manager_options(ovs, NULL, 0);
2151 }
2152
2153 static void
2154 cmd_del_manager(struct vsctl_context *ctx)
2155 {
2156     const struct ovsrec_open_vswitch *ovs = ctx->ovs;
2157
2158     verify_managers(ovs);
2159     delete_managers(ctx);
2160 }
2161
2162 static void
2163 insert_managers(struct vsctl_context *ctx, char *targets[], size_t n)
2164 {
2165     struct ovsrec_manager **managers;
2166     size_t i;
2167
2168     /* Insert each manager in a new row in Manager table. */
2169     managers = xmalloc(n * sizeof *managers);
2170     for (i = 0; i < n; i++) {
2171         managers[i] = ovsrec_manager_insert(ctx->txn);
2172         ovsrec_manager_set_target(managers[i], targets[i]);
2173     }
2174
2175     /* Store uuids of new Manager rows in 'manager_options' column. */
2176     ovsrec_open_vswitch_set_manager_options(ctx->ovs, managers, n);
2177     free(managers);
2178 }
2179
2180 static void
2181 cmd_set_manager(struct vsctl_context *ctx)
2182 {
2183     const size_t n = ctx->argc - 1;
2184
2185     verify_managers(ctx->ovs);
2186     delete_managers(ctx);
2187     insert_managers(ctx, &ctx->argv[1], n);
2188 }
2189
2190 static void
2191 pre_cmd_get_ssl(struct vsctl_context *ctx)
2192 {
2193     ovsdb_idl_add_column(ctx->idl, &ovsrec_open_vswitch_col_ssl);
2194
2195     ovsdb_idl_add_column(ctx->idl, &ovsrec_ssl_col_private_key);
2196     ovsdb_idl_add_column(ctx->idl, &ovsrec_ssl_col_certificate);
2197     ovsdb_idl_add_column(ctx->idl, &ovsrec_ssl_col_ca_cert);
2198     ovsdb_idl_add_column(ctx->idl, &ovsrec_ssl_col_bootstrap_ca_cert);
2199 }
2200
2201 static void
2202 cmd_get_ssl(struct vsctl_context *ctx)
2203 {
2204     struct ovsrec_ssl *ssl = ctx->ovs->ssl;
2205
2206     ovsrec_open_vswitch_verify_ssl(ctx->ovs);
2207     if (ssl) {
2208         ovsrec_ssl_verify_private_key(ssl);
2209         ovsrec_ssl_verify_certificate(ssl);
2210         ovsrec_ssl_verify_ca_cert(ssl);
2211         ovsrec_ssl_verify_bootstrap_ca_cert(ssl);
2212
2213         ds_put_format(&ctx->output, "Private key: %s\n", ssl->private_key);
2214         ds_put_format(&ctx->output, "Certificate: %s\n", ssl->certificate);
2215         ds_put_format(&ctx->output, "CA Certificate: %s\n", ssl->ca_cert);
2216         ds_put_format(&ctx->output, "Bootstrap: %s\n",
2217                 ssl->bootstrap_ca_cert ? "true" : "false");
2218     }
2219 }
2220
2221 static void
2222 pre_cmd_del_ssl(struct vsctl_context *ctx)
2223 {
2224     ovsdb_idl_add_column(ctx->idl, &ovsrec_open_vswitch_col_ssl);
2225 }
2226
2227 static void
2228 cmd_del_ssl(struct vsctl_context *ctx)
2229 {
2230     struct ovsrec_ssl *ssl = ctx->ovs->ssl;
2231
2232     if (ssl) {
2233         ovsrec_open_vswitch_verify_ssl(ctx->ovs);
2234         ovsrec_ssl_delete(ssl);
2235         ovsrec_open_vswitch_set_ssl(ctx->ovs, NULL);
2236     }
2237 }
2238
2239 static void
2240 pre_cmd_set_ssl(struct vsctl_context *ctx)
2241 {
2242     ovsdb_idl_add_column(ctx->idl, &ovsrec_open_vswitch_col_ssl);
2243 }
2244
2245 static void
2246 cmd_set_ssl(struct vsctl_context *ctx)
2247 {
2248     bool bootstrap = shash_find(&ctx->options, "--bootstrap");
2249     struct ovsrec_ssl *ssl = ctx->ovs->ssl;
2250
2251     ovsrec_open_vswitch_verify_ssl(ctx->ovs);
2252     if (ssl) {
2253         ovsrec_ssl_delete(ssl);
2254     }
2255     ssl = ovsrec_ssl_insert(ctx->txn);
2256
2257     ovsrec_ssl_set_private_key(ssl, ctx->argv[1]);
2258     ovsrec_ssl_set_certificate(ssl, ctx->argv[2]);
2259     ovsrec_ssl_set_ca_cert(ssl, ctx->argv[3]);
2260
2261     ovsrec_ssl_set_bootstrap_ca_cert(ssl, bootstrap);
2262
2263     ovsrec_open_vswitch_set_ssl(ctx->ovs, ssl);
2264 }
2265 \f
2266 /* Parameter commands. */
2267
2268 struct vsctl_row_id {
2269     const struct ovsdb_idl_table_class *table;
2270     const struct ovsdb_idl_column *name_column;
2271     const struct ovsdb_idl_column *uuid_column;
2272 };
2273
2274 struct vsctl_table_class {
2275     struct ovsdb_idl_table_class *class;
2276     struct vsctl_row_id row_ids[2];
2277 };
2278
2279 static const struct vsctl_table_class tables[] = {
2280     {&ovsrec_table_bridge,
2281      {{&ovsrec_table_bridge, &ovsrec_bridge_col_name, NULL},
2282       {NULL, NULL, NULL}}},
2283
2284     {&ovsrec_table_controller,
2285      {{&ovsrec_table_bridge,
2286        &ovsrec_bridge_col_name,
2287        &ovsrec_bridge_col_controller}}},
2288
2289     {&ovsrec_table_interface,
2290      {{&ovsrec_table_interface, &ovsrec_interface_col_name, NULL},
2291       {NULL, NULL, NULL}}},
2292
2293     {&ovsrec_table_mirror,
2294      {{&ovsrec_table_mirror, &ovsrec_mirror_col_name, NULL},
2295       {NULL, NULL, NULL}}},
2296
2297     {&ovsrec_table_manager,
2298      {{&ovsrec_table_manager, &ovsrec_manager_col_target, NULL},
2299       {NULL, NULL, NULL}}},
2300
2301     {&ovsrec_table_netflow,
2302      {{&ovsrec_table_bridge,
2303        &ovsrec_bridge_col_name,
2304        &ovsrec_bridge_col_netflow},
2305       {NULL, NULL, NULL}}},
2306
2307     {&ovsrec_table_open_vswitch,
2308      {{&ovsrec_table_open_vswitch, NULL, NULL},
2309       {NULL, NULL, NULL}}},
2310
2311     {&ovsrec_table_port,
2312      {{&ovsrec_table_port, &ovsrec_port_col_name, NULL},
2313       {NULL, NULL, NULL}}},
2314
2315     {&ovsrec_table_qos,
2316      {{&ovsrec_table_port, &ovsrec_port_col_name, &ovsrec_port_col_qos},
2317       {NULL, NULL, NULL}}},
2318
2319     {&ovsrec_table_queue,
2320      {{NULL, NULL, NULL},
2321       {NULL, NULL, NULL}}},
2322
2323     {&ovsrec_table_ssl,
2324      {{&ovsrec_table_open_vswitch, NULL, &ovsrec_open_vswitch_col_ssl}}},
2325
2326     {&ovsrec_table_sflow,
2327      {{&ovsrec_table_bridge,
2328        &ovsrec_bridge_col_name,
2329        &ovsrec_bridge_col_sflow},
2330       {NULL, NULL, NULL}}},
2331
2332     {NULL, {{NULL, NULL, NULL}, {NULL, NULL, NULL}}}
2333 };
2334
2335 static void
2336 die_if_error(char *error)
2337 {
2338     if (error) {
2339         vsctl_fatal("%s", error);
2340     }
2341 }
2342
2343 static int
2344 to_lower_and_underscores(unsigned c)
2345 {
2346     return c == '-' ? '_' : tolower(c);
2347 }
2348
2349 static unsigned int
2350 score_partial_match(const char *name, const char *s)
2351 {
2352     int score;
2353
2354     if (!strcmp(name, s)) {
2355         return UINT_MAX;
2356     }
2357     for (score = 0; ; score++, name++, s++) {
2358         if (to_lower_and_underscores(*name) != to_lower_and_underscores(*s)) {
2359             break;
2360         } else if (*name == '\0') {
2361             return UINT_MAX - 1;
2362         }
2363     }
2364     return *s == '\0' ? score : 0;
2365 }
2366
2367 static const struct vsctl_table_class *
2368 get_table(const char *table_name)
2369 {
2370     const struct vsctl_table_class *table;
2371     const struct vsctl_table_class *best_match = NULL;
2372     unsigned int best_score = 0;
2373
2374     for (table = tables; table->class; table++) {
2375         unsigned int score = score_partial_match(table->class->name,
2376                                                  table_name);
2377         if (score > best_score) {
2378             best_match = table;
2379             best_score = score;
2380         } else if (score == best_score) {
2381             best_match = NULL;
2382         }
2383     }
2384     if (best_match) {
2385         return best_match;
2386     } else if (best_score) {
2387         vsctl_fatal("multiple table names match \"%s\"", table_name);
2388     } else {
2389         vsctl_fatal("unknown table \"%s\"", table_name);
2390     }
2391 }
2392
2393 static const struct vsctl_table_class *
2394 pre_get_table(struct vsctl_context *ctx, const char *table_name)
2395 {
2396     const struct vsctl_table_class *table_class;
2397     int i;
2398
2399     table_class = get_table(table_name);
2400     ovsdb_idl_add_table(ctx->idl, table_class->class);
2401
2402     for (i = 0; i < ARRAY_SIZE(table_class->row_ids); i++) {
2403         const struct vsctl_row_id *id = &table_class->row_ids[i];
2404         if (id->table) {
2405             ovsdb_idl_add_table(ctx->idl, id->table);
2406         }
2407         if (id->name_column) {
2408             ovsdb_idl_add_column(ctx->idl, id->name_column);
2409         }
2410         if (id->uuid_column) {
2411             ovsdb_idl_add_column(ctx->idl, id->uuid_column);
2412         }
2413     }
2414
2415     return table_class;
2416 }
2417
2418 static const struct ovsdb_idl_row *
2419 get_row_by_id(struct vsctl_context *ctx, const struct vsctl_table_class *table,
2420               const struct vsctl_row_id *id, const char *record_id)
2421 {
2422     const struct ovsdb_idl_row *referrer, *final;
2423
2424     if (!id->table) {
2425         return NULL;
2426     }
2427
2428     if (!id->name_column) {
2429         if (strcmp(record_id, ".")) {
2430             return NULL;
2431         }
2432         referrer = ovsdb_idl_first_row(ctx->idl, id->table);
2433         if (!referrer || ovsdb_idl_next_row(referrer)) {
2434             return NULL;
2435         }
2436     } else {
2437         const struct ovsdb_idl_row *row;
2438
2439         referrer = NULL;
2440         for (row = ovsdb_idl_first_row(ctx->idl, id->table);
2441              row != NULL;
2442              row = ovsdb_idl_next_row(row))
2443         {
2444             const struct ovsdb_datum *name;
2445
2446             name = ovsdb_idl_get(row, id->name_column,
2447                                  OVSDB_TYPE_STRING, OVSDB_TYPE_VOID);
2448             if (name->n == 1 && !strcmp(name->keys[0].string, record_id)) {
2449                 if (referrer) {
2450                     vsctl_fatal("multiple rows in %s match \"%s\"",
2451                                 table->class->name, record_id);
2452                 }
2453                 referrer = row;
2454             }
2455         }
2456     }
2457     if (!referrer) {
2458         return NULL;
2459     }
2460
2461     final = NULL;
2462     if (id->uuid_column) {
2463         const struct ovsdb_datum *uuid;
2464
2465         ovsdb_idl_txn_verify(referrer, id->uuid_column);
2466         uuid = ovsdb_idl_get(referrer, id->uuid_column,
2467                              OVSDB_TYPE_UUID, OVSDB_TYPE_VOID);
2468         if (uuid->n == 1) {
2469             final = ovsdb_idl_get_row_for_uuid(ctx->idl, table->class,
2470                                                &uuid->keys[0].uuid);
2471         }
2472     } else {
2473         final = referrer;
2474     }
2475
2476     return final;
2477 }
2478
2479 static const struct ovsdb_idl_row *
2480 get_row (struct vsctl_context *ctx,
2481          const struct vsctl_table_class *table, const char *record_id)
2482 {
2483     const struct ovsdb_idl_row *row;
2484     struct uuid uuid;
2485
2486     if (uuid_from_string(&uuid, record_id)) {
2487         row = ovsdb_idl_get_row_for_uuid(ctx->idl, table->class, &uuid);
2488     } else {
2489         int i;
2490
2491         for (i = 0; i < ARRAY_SIZE(table->row_ids); i++) {
2492             row = get_row_by_id(ctx, table, &table->row_ids[i], record_id);
2493             if (row) {
2494                 break;
2495             }
2496         }
2497     }
2498     return row;
2499 }
2500
2501 static const struct ovsdb_idl_row *
2502 must_get_row(struct vsctl_context *ctx,
2503              const struct vsctl_table_class *table, const char *record_id)
2504 {
2505     const struct ovsdb_idl_row *row = get_row(ctx, table, record_id);
2506     if (!row) {
2507         vsctl_fatal("no row \"%s\" in table %s",
2508                     record_id, table->class->name);
2509     }
2510     return row;
2511 }
2512
2513 static char *
2514 get_column(const struct vsctl_table_class *table, const char *column_name,
2515            const struct ovsdb_idl_column **columnp)
2516 {
2517     const struct ovsdb_idl_column *best_match = NULL;
2518     unsigned int best_score = 0;
2519     size_t i;
2520
2521     for (i = 0; i < table->class->n_columns; i++) {
2522         const struct ovsdb_idl_column *column = &table->class->columns[i];
2523         unsigned int score = score_partial_match(column->name, column_name);
2524         if (score > best_score) {
2525             best_match = column;
2526             best_score = score;
2527         } else if (score == best_score) {
2528             best_match = NULL;
2529         }
2530     }
2531
2532     *columnp = best_match;
2533     if (best_match) {
2534         return NULL;
2535     } else if (best_score) {
2536         return xasprintf("%s contains more than one column whose name "
2537                          "matches \"%s\"", table->class->name, column_name);
2538     } else {
2539         return xasprintf("%s does not contain a column whose name matches "
2540                          "\"%s\"", table->class->name, column_name);
2541     }
2542 }
2543
2544 static struct ovsdb_symbol *
2545 create_symbol(struct ovsdb_symbol_table *symtab, const char *id, bool *newp)
2546 {
2547     struct ovsdb_symbol *symbol;
2548
2549     if (id[0] != '@') {
2550         vsctl_fatal("row id \"%s\" does not begin with \"@\"", id);
2551     }
2552
2553     if (newp) {
2554         *newp = ovsdb_symbol_table_get(symtab, id) == NULL;
2555     }
2556
2557     symbol = ovsdb_symbol_table_insert(symtab, id);
2558     if (symbol->created) {
2559         vsctl_fatal("row id \"%s\" may only be specified on one --id option",
2560                     id);
2561     }
2562     symbol->created = true;
2563     return symbol;
2564 }
2565
2566 static void
2567 pre_get_column(struct vsctl_context *ctx,
2568                const struct vsctl_table_class *table, const char *column_name,
2569                const struct ovsdb_idl_column **columnp)
2570 {
2571     die_if_error(get_column(table, column_name, columnp));
2572     ovsdb_idl_add_column(ctx->idl, *columnp);
2573 }
2574
2575 static char *
2576 missing_operator_error(const char *arg, const char **allowed_operators,
2577                        size_t n_allowed)
2578 {
2579     struct ds s;
2580
2581     ds_init(&s);
2582     ds_put_format(&s, "%s: argument does not end in ", arg);
2583     ds_put_format(&s, "\"%s\"", allowed_operators[0]);
2584     if (n_allowed == 2) {
2585         ds_put_format(&s, " or \"%s\"", allowed_operators[1]);
2586     } else if (n_allowed > 2) {
2587         size_t i;
2588
2589         for (i = 1; i < n_allowed - 1; i++) {
2590             ds_put_format(&s, ", \"%s\"", allowed_operators[i]);
2591         }
2592         ds_put_format(&s, ", or \"%s\"", allowed_operators[i]);
2593     }
2594     ds_put_format(&s, " followed by a value.");
2595
2596     return ds_steal_cstr(&s);
2597 }
2598
2599 /* Breaks 'arg' apart into a number of fields in the following order:
2600  *
2601  *      - The name of a column in 'table', stored into '*columnp'.  The column
2602  *        name may be abbreviated.
2603  *
2604  *      - Optionally ':' followed by a key string.  The key is stored as a
2605  *        malloc()'d string into '*keyp', or NULL if no key is present in
2606  *        'arg'.
2607  *
2608  *      - If 'valuep' is nonnull, an operator followed by a value string.  The
2609  *        allowed operators are the 'n_allowed' string in 'allowed_operators',
2610  *        or just "=" if 'n_allowed' is 0.  If 'operatorp' is nonnull, then the
2611  *        operator is stored into '*operatorp' (one of the pointers from
2612  *        'allowed_operators' is stored; nothing is malloc()'d).  The value is
2613  *        stored as a malloc()'d string into '*valuep', or NULL if no value is
2614  *        present in 'arg'.
2615  *
2616  * On success, returns NULL.  On failure, returned a malloc()'d string error
2617  * message and stores NULL into all of the nonnull output arguments. */
2618 static char * WARN_UNUSED_RESULT
2619 parse_column_key_value(const char *arg,
2620                        const struct vsctl_table_class *table,
2621                        const struct ovsdb_idl_column **columnp, char **keyp,
2622                        const char **operatorp,
2623                        const char **allowed_operators, size_t n_allowed,
2624                        char **valuep)
2625 {
2626     const char *p = arg;
2627     char *column_name;
2628     char *error;
2629
2630     assert(!(operatorp && !valuep));
2631     *keyp = NULL;
2632     if (valuep) {
2633         *valuep = NULL;
2634     }
2635
2636     /* Parse column name. */
2637     error = ovsdb_token_parse(&p, &column_name);
2638     if (error) {
2639         goto error;
2640     }
2641     if (column_name[0] == '\0') {
2642         free(column_name);
2643         error = xasprintf("%s: missing column name", arg);
2644         goto error;
2645     }
2646     error = get_column(table, column_name, columnp);
2647     free(column_name);
2648     if (error) {
2649         goto error;
2650     }
2651
2652     /* Parse key string. */
2653     if (*p == ':') {
2654         p++;
2655         error = ovsdb_token_parse(&p, keyp);
2656         if (error) {
2657             goto error;
2658         }
2659     }
2660
2661     /* Parse value string. */
2662     if (valuep) {
2663         const char *best;
2664         size_t best_len;
2665         size_t i;
2666
2667         if (!allowed_operators) {
2668             static const char *equals = "=";
2669             allowed_operators = &equals;
2670             n_allowed = 1;
2671         }
2672
2673         best = NULL;
2674         best_len = 0;
2675         for (i = 0; i < n_allowed; i++) {
2676             const char *op = allowed_operators[i];
2677             size_t op_len = strlen(op);
2678
2679             if (op_len > best_len && !strncmp(op, p, op_len) && p[op_len]) {
2680                 best_len = op_len;
2681                 best = op;
2682             }
2683         }
2684         if (!best) {
2685             error = missing_operator_error(arg, allowed_operators, n_allowed);
2686             goto error;
2687         }
2688
2689         if (operatorp) {
2690             *operatorp = best;
2691         }
2692         *valuep = xstrdup(p + best_len);
2693     } else {
2694         if (*p != '\0') {
2695             error = xasprintf("%s: trailing garbage \"%s\" in argument",
2696                               arg, p);
2697             goto error;
2698         }
2699     }
2700     return NULL;
2701
2702 error:
2703     *columnp = NULL;
2704     free(*keyp);
2705     *keyp = NULL;
2706     if (valuep) {
2707         free(*valuep);
2708         *valuep = NULL;
2709         if (operatorp) {
2710             *operatorp = NULL;
2711         }
2712     }
2713     return error;
2714 }
2715
2716 static void
2717 pre_parse_column_key_value(struct vsctl_context *ctx,
2718                            const char *arg,
2719                            const struct vsctl_table_class *table)
2720 {
2721     const struct ovsdb_idl_column *column;
2722     const char *p;
2723     char *column_name;
2724
2725     p = arg;
2726     die_if_error(ovsdb_token_parse(&p, &column_name));
2727     if (column_name[0] == '\0') {
2728         vsctl_fatal("%s: missing column name", arg);
2729     }
2730
2731     pre_get_column(ctx, table, column_name, &column);
2732     free(column_name);
2733 }
2734
2735 static void
2736 pre_cmd_get(struct vsctl_context *ctx)
2737 {
2738     const char *id = shash_find_data(&ctx->options, "--id");
2739     const char *table_name = ctx->argv[1];
2740     const struct vsctl_table_class *table;
2741     int i;
2742
2743     /* Using "get" without --id or a column name could possibly make sense.
2744      * Maybe, for example, a ovs-vsctl run wants to assert that a row exists.
2745      * But it is unlikely that an interactive user would want to do that, so
2746      * issue a warning if we're running on a terminal. */
2747     if (!id && ctx->argc <= 3 && isatty(STDOUT_FILENO)) {
2748         VLOG_WARN("\"get\" command without row arguments or \"--id\" is "
2749                   "possibly erroneous");
2750     }
2751
2752     table = pre_get_table(ctx, table_name);
2753     for (i = 3; i < ctx->argc; i++) {
2754         if (!strcasecmp(ctx->argv[i], "_uuid")
2755             || !strcasecmp(ctx->argv[i], "-uuid")) {
2756             continue;
2757         }
2758
2759         pre_parse_column_key_value(ctx, ctx->argv[i], table);
2760     }
2761 }
2762
2763 static void
2764 cmd_get(struct vsctl_context *ctx)
2765 {
2766     const char *id = shash_find_data(&ctx->options, "--id");
2767     bool if_exists = shash_find(&ctx->options, "--if-exists");
2768     const char *table_name = ctx->argv[1];
2769     const char *record_id = ctx->argv[2];
2770     const struct vsctl_table_class *table;
2771     const struct ovsdb_idl_row *row;
2772     struct ds *out = &ctx->output;
2773     int i;
2774
2775     table = get_table(table_name);
2776     row = must_get_row(ctx, table, record_id);
2777     if (id) {
2778         struct ovsdb_symbol *symbol;
2779         bool new;
2780
2781         symbol = create_symbol(ctx->symtab, id, &new);
2782         if (!new) {
2783             vsctl_fatal("row id \"%s\" specified on \"get\" command was used "
2784                         "before it was defined", id);
2785         }
2786         symbol->uuid = row->uuid;
2787
2788         /* This symbol refers to a row that already exists, so disable warnings
2789          * about it being unreferenced. */
2790         symbol->strong_ref = true;
2791     }
2792     for (i = 3; i < ctx->argc; i++) {
2793         const struct ovsdb_idl_column *column;
2794         const struct ovsdb_datum *datum;
2795         char *key_string;
2796
2797         /* Special case for obtaining the UUID of a row.  We can't just do this
2798          * through parse_column_key_value() below since it returns a "struct
2799          * ovsdb_idl_column" and the UUID column doesn't have one. */
2800         if (!strcasecmp(ctx->argv[i], "_uuid")
2801             || !strcasecmp(ctx->argv[i], "-uuid")) {
2802             ds_put_format(out, UUID_FMT"\n", UUID_ARGS(&row->uuid));
2803             continue;
2804         }
2805
2806         die_if_error(parse_column_key_value(ctx->argv[i], table,
2807                                             &column, &key_string,
2808                                             NULL, NULL, 0, NULL));
2809
2810         ovsdb_idl_txn_verify(row, column);
2811         datum = ovsdb_idl_read(row, column);
2812         if (key_string) {
2813             union ovsdb_atom key;
2814             unsigned int idx;
2815
2816             if (column->type.value.type == OVSDB_TYPE_VOID) {
2817                 vsctl_fatal("cannot specify key to get for non-map column %s",
2818                             column->name);
2819             }
2820
2821             die_if_error(ovsdb_atom_from_string(&key,
2822                                                 &column->type.key,
2823                                                 key_string, ctx->symtab));
2824
2825             idx = ovsdb_datum_find_key(datum, &key,
2826                                        column->type.key.type);
2827             if (idx == UINT_MAX) {
2828                 if (!if_exists) {
2829                     vsctl_fatal("no key \"%s\" in %s record \"%s\" column %s",
2830                                 key_string, table->class->name, record_id,
2831                                 column->name);
2832                 }
2833             } else {
2834                 ovsdb_atom_to_string(&datum->values[idx],
2835                                      column->type.value.type, out);
2836             }
2837             ovsdb_atom_destroy(&key, column->type.key.type);
2838         } else {
2839             ovsdb_datum_to_string(datum, &column->type, out);
2840         }
2841         ds_put_char(out, '\n');
2842
2843         free(key_string);
2844     }
2845 }
2846
2847 static void
2848 parse_column_names(const char *column_names,
2849                    const struct vsctl_table_class *table,
2850                    const struct ovsdb_idl_column ***columnsp,
2851                    size_t *n_columnsp)
2852 {
2853     const struct ovsdb_idl_column **columns;
2854     size_t n_columns;
2855
2856     if (!column_names) {
2857         size_t i;
2858
2859         n_columns = table->class->n_columns + 1;
2860         columns = xmalloc(n_columns * sizeof *columns);
2861         columns[0] = NULL;
2862         for (i = 0; i < table->class->n_columns; i++) {
2863             columns[i + 1] = &table->class->columns[i];
2864         }
2865     } else {
2866         char *s = xstrdup(column_names);
2867         size_t allocated_columns;
2868         char *save_ptr = NULL;
2869         char *column_name;
2870
2871         columns = NULL;
2872         allocated_columns = n_columns = 0;
2873         for (column_name = strtok_r(s, ", ", &save_ptr); column_name;
2874              column_name = strtok_r(NULL, ", ", &save_ptr)) {
2875             const struct ovsdb_idl_column *column;
2876
2877             if (!strcasecmp(column_name, "_uuid")) {
2878                 column = NULL;
2879             } else {
2880                 die_if_error(get_column(table, column_name, &column));
2881             }
2882             if (n_columns >= allocated_columns) {
2883                 columns = x2nrealloc(columns, &allocated_columns,
2884                                      sizeof *columns);
2885             }
2886             columns[n_columns++] = column;
2887         }
2888         free(s);
2889
2890         if (!n_columns) {
2891             vsctl_fatal("must specify at least one column name");
2892         }
2893     }
2894     *columnsp = columns;
2895     *n_columnsp = n_columns;
2896 }
2897
2898
2899 static void
2900 pre_list_columns(struct vsctl_context *ctx,
2901                  const struct vsctl_table_class *table,
2902                  const char *column_names)
2903 {
2904     const struct ovsdb_idl_column **columns;
2905     size_t n_columns;
2906     size_t i;
2907
2908     parse_column_names(column_names, table, &columns, &n_columns);
2909     for (i = 0; i < n_columns; i++) {
2910         if (columns[i]) {
2911             ovsdb_idl_add_column(ctx->idl, columns[i]);
2912         }
2913     }
2914     free(columns);
2915 }
2916
2917 static void
2918 pre_cmd_list(struct vsctl_context *ctx)
2919 {
2920     const char *column_names = shash_find_data(&ctx->options, "--columns");
2921     const char *table_name = ctx->argv[1];
2922     const struct vsctl_table_class *table;
2923
2924     table = pre_get_table(ctx, table_name);
2925     pre_list_columns(ctx, table, column_names);
2926 }
2927
2928 static struct table *
2929 list_make_table(const struct ovsdb_idl_column **columns, size_t n_columns)
2930 {
2931     struct table *out;
2932     size_t i;
2933
2934     out = xmalloc(sizeof *out);
2935     table_init(out);
2936
2937     for (i = 0; i < n_columns; i++) {
2938         const struct ovsdb_idl_column *column = columns[i];
2939         const char *column_name = column ? column->name : "_uuid";
2940
2941         table_add_column(out, "%s", column_name);
2942     }
2943
2944     return out;
2945 }
2946
2947 static void
2948 list_record(const struct ovsdb_idl_row *row,
2949             const struct ovsdb_idl_column **columns, size_t n_columns,
2950             struct table *out)
2951 {
2952     size_t i;
2953
2954     table_add_row(out);
2955     for (i = 0; i < n_columns; i++) {
2956         const struct ovsdb_idl_column *column = columns[i];
2957         struct cell *cell = table_add_cell(out);
2958
2959         if (!column) {
2960             struct ovsdb_datum datum;
2961             union ovsdb_atom atom;
2962
2963             atom.uuid = row->uuid;
2964
2965             datum.keys = &atom;
2966             datum.values = NULL;
2967             datum.n = 1;
2968
2969             cell->json = ovsdb_datum_to_json(&datum, &ovsdb_type_uuid);
2970             cell->type = &ovsdb_type_uuid;
2971         } else {
2972             const struct ovsdb_datum *datum = ovsdb_idl_read(row, column);
2973
2974             cell->json = ovsdb_datum_to_json(datum, &column->type);
2975             cell->type = &column->type;
2976         }
2977     }
2978 }
2979
2980 static void
2981 cmd_list(struct vsctl_context *ctx)
2982 {
2983     const char *column_names = shash_find_data(&ctx->options, "--columns");
2984     const struct ovsdb_idl_column **columns;
2985     const char *table_name = ctx->argv[1];
2986     const struct vsctl_table_class *table;
2987     struct table *out;
2988     size_t n_columns;
2989     int i;
2990
2991     table = get_table(table_name);
2992     parse_column_names(column_names, table, &columns, &n_columns);
2993     out = ctx->table = list_make_table(columns, n_columns);
2994     if (ctx->argc > 2) {
2995         for (i = 2; i < ctx->argc; i++) {
2996             list_record(must_get_row(ctx, table, ctx->argv[i]),
2997                         columns, n_columns, out);
2998         }
2999     } else {
3000         const struct ovsdb_idl_row *row;
3001
3002         for (row = ovsdb_idl_first_row(ctx->idl, table->class); row != NULL;
3003              row = ovsdb_idl_next_row(row)) {
3004             list_record(row, columns, n_columns, out);
3005         }
3006     }
3007     free(columns);
3008 }
3009
3010 static void
3011 pre_cmd_find(struct vsctl_context *ctx)
3012 {
3013     const char *column_names = shash_find_data(&ctx->options, "--columns");
3014     const char *table_name = ctx->argv[1];
3015     const struct vsctl_table_class *table;
3016     int i;
3017
3018     table = pre_get_table(ctx, table_name);
3019     pre_list_columns(ctx, table, column_names);
3020     for (i = 2; i < ctx->argc; i++) {
3021         pre_parse_column_key_value(ctx, ctx->argv[i], table);
3022     }
3023 }
3024
3025 static void
3026 cmd_find(struct vsctl_context *ctx)
3027 {
3028     const char *column_names = shash_find_data(&ctx->options, "--columns");
3029     const struct ovsdb_idl_column **columns;
3030     const char *table_name = ctx->argv[1];
3031     const struct vsctl_table_class *table;
3032     const struct ovsdb_idl_row *row;
3033     struct table *out;
3034     size_t n_columns;
3035
3036     table = get_table(table_name);
3037     parse_column_names(column_names, table, &columns, &n_columns);
3038     out = ctx->table = list_make_table(columns, n_columns);
3039     for (row = ovsdb_idl_first_row(ctx->idl, table->class); row;
3040          row = ovsdb_idl_next_row(row)) {
3041         int i;
3042
3043         for (i = 2; i < ctx->argc; i++) {
3044             if (!is_condition_satisfied(table, row, ctx->argv[i],
3045                                         ctx->symtab)) {
3046                 goto next_row;
3047             }
3048         }
3049         list_record(row, columns, n_columns, out);
3050
3051     next_row: ;
3052     }
3053     free(columns);
3054 }
3055
3056 static void
3057 pre_cmd_set(struct vsctl_context *ctx)
3058 {
3059     const char *table_name = ctx->argv[1];
3060     const struct vsctl_table_class *table;
3061     int i;
3062
3063     table = pre_get_table(ctx, table_name);
3064     for (i = 3; i < ctx->argc; i++) {
3065         pre_parse_column_key_value(ctx, ctx->argv[i], table);
3066     }
3067 }
3068
3069 static void
3070 set_column(const struct vsctl_table_class *table,
3071            const struct ovsdb_idl_row *row, const char *arg,
3072            struct ovsdb_symbol_table *symtab)
3073 {
3074     const struct ovsdb_idl_column *column;
3075     char *key_string, *value_string;
3076     char *error;
3077
3078     error = parse_column_key_value(arg, table, &column, &key_string,
3079                                    NULL, NULL, 0, &value_string);
3080     die_if_error(error);
3081     if (!value_string) {
3082         vsctl_fatal("%s: missing value", arg);
3083     }
3084
3085     if (key_string) {
3086         union ovsdb_atom key, value;
3087         struct ovsdb_datum datum;
3088
3089         if (column->type.value.type == OVSDB_TYPE_VOID) {
3090             vsctl_fatal("cannot specify key to set for non-map column %s",
3091                         column->name);
3092         }
3093
3094         die_if_error(ovsdb_atom_from_string(&key, &column->type.key,
3095                                             key_string, symtab));
3096         die_if_error(ovsdb_atom_from_string(&value, &column->type.value,
3097                                             value_string, symtab));
3098
3099         ovsdb_datum_init_empty(&datum);
3100         ovsdb_datum_add_unsafe(&datum, &key, &value, &column->type);
3101
3102         ovsdb_atom_destroy(&key, column->type.key.type);
3103         ovsdb_atom_destroy(&value, column->type.value.type);
3104
3105         ovsdb_datum_union(&datum, ovsdb_idl_read(row, column),
3106                           &column->type, false);
3107         ovsdb_idl_txn_write(row, column, &datum);
3108     } else {
3109         struct ovsdb_datum datum;
3110
3111         die_if_error(ovsdb_datum_from_string(&datum, &column->type,
3112                                              value_string, symtab));
3113         ovsdb_idl_txn_write(row, column, &datum);
3114     }
3115
3116     free(key_string);
3117     free(value_string);
3118 }
3119
3120 static void
3121 cmd_set(struct vsctl_context *ctx)
3122 {
3123     const char *table_name = ctx->argv[1];
3124     const char *record_id = ctx->argv[2];
3125     const struct vsctl_table_class *table;
3126     const struct ovsdb_idl_row *row;
3127     int i;
3128
3129     table = get_table(table_name);
3130     row = must_get_row(ctx, table, record_id);
3131     for (i = 3; i < ctx->argc; i++) {
3132         set_column(table, row, ctx->argv[i], ctx->symtab);
3133     }
3134 }
3135
3136 static void
3137 pre_cmd_add(struct vsctl_context *ctx)
3138 {
3139     const char *table_name = ctx->argv[1];
3140     const char *column_name = ctx->argv[3];
3141     const struct vsctl_table_class *table;
3142     const struct ovsdb_idl_column *column;
3143
3144     table = pre_get_table(ctx, table_name);
3145     pre_get_column(ctx, table, column_name, &column);
3146 }
3147
3148 static void
3149 cmd_add(struct vsctl_context *ctx)
3150 {
3151     const char *table_name = ctx->argv[1];
3152     const char *record_id = ctx->argv[2];
3153     const char *column_name = ctx->argv[3];
3154     const struct vsctl_table_class *table;
3155     const struct ovsdb_idl_column *column;
3156     const struct ovsdb_idl_row *row;
3157     const struct ovsdb_type *type;
3158     struct ovsdb_datum old;
3159     int i;
3160
3161     table = get_table(table_name);
3162     row = must_get_row(ctx, table, record_id);
3163     die_if_error(get_column(table, column_name, &column));
3164
3165     type = &column->type;
3166     ovsdb_datum_clone(&old, ovsdb_idl_read(row, column), &column->type);
3167     for (i = 4; i < ctx->argc; i++) {
3168         struct ovsdb_type add_type;
3169         struct ovsdb_datum add;
3170
3171         add_type = *type;
3172         add_type.n_min = 1;
3173         add_type.n_max = UINT_MAX;
3174         die_if_error(ovsdb_datum_from_string(&add, &add_type, ctx->argv[i],
3175                                              ctx->symtab));
3176         ovsdb_datum_union(&old, &add, type, false);
3177         ovsdb_datum_destroy(&add, type);
3178     }
3179     if (old.n > type->n_max) {
3180         vsctl_fatal("\"add\" operation would put %u %s in column %s of "
3181                     "table %s but the maximum number is %u",
3182                     old.n,
3183                     type->value.type == OVSDB_TYPE_VOID ? "values" : "pairs",
3184                     column->name, table->class->name, type->n_max);
3185     }
3186     ovsdb_idl_txn_verify(row, column);
3187     ovsdb_idl_txn_write(row, column, &old);
3188 }
3189
3190 static void
3191 pre_cmd_remove(struct vsctl_context *ctx)
3192 {
3193     const char *table_name = ctx->argv[1];
3194     const char *column_name = ctx->argv[3];
3195     const struct vsctl_table_class *table;
3196     const struct ovsdb_idl_column *column;
3197
3198     table = pre_get_table(ctx, table_name);
3199     pre_get_column(ctx, table, column_name, &column);
3200 }
3201
3202 static void
3203 cmd_remove(struct vsctl_context *ctx)
3204 {
3205     const char *table_name = ctx->argv[1];
3206     const char *record_id = ctx->argv[2];
3207     const char *column_name = ctx->argv[3];
3208     const struct vsctl_table_class *table;
3209     const struct ovsdb_idl_column *column;
3210     const struct ovsdb_idl_row *row;
3211     const struct ovsdb_type *type;
3212     struct ovsdb_datum old;
3213     int i;
3214
3215     table = get_table(table_name);
3216     row = must_get_row(ctx, table, record_id);
3217     die_if_error(get_column(table, column_name, &column));
3218
3219     type = &column->type;
3220     ovsdb_datum_clone(&old, ovsdb_idl_read(row, column), &column->type);
3221     for (i = 4; i < ctx->argc; i++) {
3222         struct ovsdb_type rm_type;
3223         struct ovsdb_datum rm;
3224         char *error;
3225
3226         rm_type = *type;
3227         rm_type.n_min = 1;
3228         rm_type.n_max = UINT_MAX;
3229         error = ovsdb_datum_from_string(&rm, &rm_type,
3230                                         ctx->argv[i], ctx->symtab);
3231         if (error && ovsdb_type_is_map(&rm_type)) {
3232             free(error);
3233             rm_type.value.type = OVSDB_TYPE_VOID;
3234             die_if_error(ovsdb_datum_from_string(&rm, &rm_type,
3235                                                  ctx->argv[i], ctx->symtab));
3236         }
3237         ovsdb_datum_subtract(&old, type, &rm, &rm_type);
3238         ovsdb_datum_destroy(&rm, &rm_type);
3239     }
3240     if (old.n < type->n_min) {
3241         vsctl_fatal("\"remove\" operation would put %u %s in column %s of "
3242                     "table %s but the minimum number is %u",
3243                     old.n,
3244                     type->value.type == OVSDB_TYPE_VOID ? "values" : "pairs",
3245                     column->name, table->class->name, type->n_min);
3246     }
3247     ovsdb_idl_txn_verify(row, column);
3248     ovsdb_idl_txn_write(row, column, &old);
3249 }
3250
3251 static void
3252 pre_cmd_clear(struct vsctl_context *ctx)
3253 {
3254     const char *table_name = ctx->argv[1];
3255     const struct vsctl_table_class *table;
3256     int i;
3257
3258     table = pre_get_table(ctx, table_name);
3259     for (i = 3; i < ctx->argc; i++) {
3260         const struct ovsdb_idl_column *column;
3261
3262         pre_get_column(ctx, table, ctx->argv[i], &column);
3263     }
3264 }
3265
3266 static void
3267 cmd_clear(struct vsctl_context *ctx)
3268 {
3269     const char *table_name = ctx->argv[1];
3270     const char *record_id = ctx->argv[2];
3271     const struct vsctl_table_class *table;
3272     const struct ovsdb_idl_row *row;
3273     int i;
3274
3275     table = get_table(table_name);
3276     row = must_get_row(ctx, table, record_id);
3277     for (i = 3; i < ctx->argc; i++) {
3278         const struct ovsdb_idl_column *column;
3279         const struct ovsdb_type *type;
3280         struct ovsdb_datum datum;
3281
3282         die_if_error(get_column(table, ctx->argv[i], &column));
3283
3284         type = &column->type;
3285         if (type->n_min > 0) {
3286             vsctl_fatal("\"clear\" operation cannot be applied to column %s "
3287                         "of table %s, which is not allowed to be empty",
3288                         column->name, table->class->name);
3289         }
3290
3291         ovsdb_datum_init_empty(&datum);
3292         ovsdb_idl_txn_write(row, column, &datum);
3293     }
3294 }
3295
3296 static void
3297 pre_create(struct vsctl_context *ctx)
3298 {
3299     const char *id = shash_find_data(&ctx->options, "--id");
3300     const char *table_name = ctx->argv[1];
3301     const struct vsctl_table_class *table;
3302
3303     table = get_table(table_name);
3304     if (!id && !table->class->is_root) {
3305         VLOG_WARN("applying \"create\" command to table %s without --id "
3306                   "option will have no effect", table->class->name);
3307     }
3308 }
3309
3310 static void
3311 cmd_create(struct vsctl_context *ctx)
3312 {
3313     const char *id = shash_find_data(&ctx->options, "--id");
3314     const char *table_name = ctx->argv[1];
3315     const struct vsctl_table_class *table = get_table(table_name);
3316     const struct ovsdb_idl_row *row;
3317     const struct uuid *uuid;
3318     int i;
3319
3320     if (id) {
3321         struct ovsdb_symbol *symbol = create_symbol(ctx->symtab, id, NULL);
3322         if (table->class->is_root) {
3323             /* This table is in the root set, meaning that rows created in it
3324              * won't disappear even if they are unreferenced, so disable
3325              * warnings about that by pretending that there is a reference. */
3326             symbol->strong_ref = true;
3327         }
3328         uuid = &symbol->uuid;
3329     } else {
3330         uuid = NULL;
3331     }
3332
3333     row = ovsdb_idl_txn_insert(ctx->txn, table->class, uuid);
3334     for (i = 2; i < ctx->argc; i++) {
3335         set_column(table, row, ctx->argv[i], ctx->symtab);
3336     }
3337     ds_put_format(&ctx->output, UUID_FMT, UUID_ARGS(&row->uuid));
3338 }
3339
3340 /* This function may be used as the 'postprocess' function for commands that
3341  * insert new rows into the database.  It expects that the command's 'run'
3342  * function prints the UUID reported by ovsdb_idl_txn_insert() as the command's
3343  * sole output.  It replaces that output by the row's permanent UUID assigned
3344  * by the database server and appends a new-line.
3345  *
3346  * Currently we use this only for "create", because the higher-level commands
3347  * are supposed to be independent of the actual structure of the vswitch
3348  * configuration. */
3349 static void
3350 post_create(struct vsctl_context *ctx)
3351 {
3352     const struct uuid *real;
3353     struct uuid dummy;
3354
3355     if (!uuid_from_string(&dummy, ds_cstr(&ctx->output))) {
3356         NOT_REACHED();
3357     }
3358     real = ovsdb_idl_txn_get_insert_uuid(ctx->txn, &dummy);
3359     if (real) {
3360         ds_clear(&ctx->output);
3361         ds_put_format(&ctx->output, UUID_FMT, UUID_ARGS(real));
3362     }
3363     ds_put_char(&ctx->output, '\n');
3364 }
3365
3366 static void
3367 pre_cmd_destroy(struct vsctl_context *ctx)
3368 {
3369     const char *table_name = ctx->argv[1];
3370
3371     pre_get_table(ctx, table_name);
3372 }
3373
3374 static void
3375 cmd_destroy(struct vsctl_context *ctx)
3376 {
3377     bool must_exist = !shash_find(&ctx->options, "--if-exists");
3378     const char *table_name = ctx->argv[1];
3379     const struct vsctl_table_class *table;
3380     int i;
3381
3382     table = get_table(table_name);
3383     for (i = 2; i < ctx->argc; i++) {
3384         const struct ovsdb_idl_row *row;
3385
3386         row = (must_exist ? must_get_row : get_row)(ctx, table, ctx->argv[i]);
3387         if (row) {
3388             ovsdb_idl_txn_delete(row);
3389         }
3390     }
3391 }
3392
3393 static bool
3394 is_condition_satisfied(const struct vsctl_table_class *table,
3395                        const struct ovsdb_idl_row *row, const char *arg,
3396                        struct ovsdb_symbol_table *symtab)
3397 {
3398     static const char *operators[] = {
3399         "=", "!=", "<", ">", "<=", ">="
3400     };
3401
3402     const struct ovsdb_idl_column *column;
3403     const struct ovsdb_datum *have_datum;
3404     char *key_string, *value_string;
3405     const char *operator;
3406     unsigned int idx;
3407     char *error;
3408     int cmp = 0;
3409
3410     error = parse_column_key_value(arg, table, &column, &key_string,
3411                                    &operator, operators, ARRAY_SIZE(operators),
3412                                    &value_string);
3413     die_if_error(error);
3414     if (!value_string) {
3415         vsctl_fatal("%s: missing value", arg);
3416     }
3417
3418     have_datum = ovsdb_idl_read(row, column);
3419     if (key_string) {
3420         union ovsdb_atom want_key, want_value;
3421
3422         if (column->type.value.type == OVSDB_TYPE_VOID) {
3423             vsctl_fatal("cannot specify key to check for non-map column %s",
3424                         column->name);
3425         }
3426
3427         die_if_error(ovsdb_atom_from_string(&want_key, &column->type.key,
3428                                             key_string, symtab));
3429         die_if_error(ovsdb_atom_from_string(&want_value, &column->type.value,
3430                                             value_string, symtab));
3431
3432         idx = ovsdb_datum_find_key(have_datum,
3433                                    &want_key, column->type.key.type);
3434         if (idx != UINT_MAX) {
3435             cmp = ovsdb_atom_compare_3way(&have_datum->values[idx],
3436                                           &want_value,
3437                                           column->type.value.type);
3438         }
3439
3440         ovsdb_atom_destroy(&want_key, column->type.key.type);
3441         ovsdb_atom_destroy(&want_value, column->type.value.type);
3442     } else {
3443         struct ovsdb_datum want_datum;
3444
3445         die_if_error(ovsdb_datum_from_string(&want_datum, &column->type,
3446                                              value_string, symtab));
3447         idx = 0;
3448         cmp = ovsdb_datum_compare_3way(have_datum, &want_datum,
3449                                        &column->type);
3450         ovsdb_datum_destroy(&want_datum, &column->type);
3451     }
3452
3453     free(key_string);
3454     free(value_string);
3455
3456     return (idx == UINT_MAX ? false
3457             : !strcmp(operator, "=") ? cmp == 0
3458             : !strcmp(operator, "!=") ? cmp != 0
3459             : !strcmp(operator, "<") ? cmp < 0
3460             : !strcmp(operator, ">") ? cmp > 0
3461             : !strcmp(operator, "<=") ? cmp <= 0
3462             : !strcmp(operator, ">=") ? cmp >= 0
3463             : (abort(), 0));
3464 }
3465
3466 static void
3467 pre_cmd_wait_until(struct vsctl_context *ctx)
3468 {
3469     const char *table_name = ctx->argv[1];
3470     const struct vsctl_table_class *table;
3471     int i;
3472
3473     table = pre_get_table(ctx, table_name);
3474
3475     for (i = 3; i < ctx->argc; i++) {
3476         pre_parse_column_key_value(ctx, ctx->argv[i], table);
3477     }
3478 }
3479
3480 static void
3481 cmd_wait_until(struct vsctl_context *ctx)
3482 {
3483     const char *table_name = ctx->argv[1];
3484     const char *record_id = ctx->argv[2];
3485     const struct vsctl_table_class *table;
3486     const struct ovsdb_idl_row *row;
3487     int i;
3488
3489     table = get_table(table_name);
3490
3491     row = get_row(ctx, table, record_id);
3492     if (!row) {
3493         ctx->try_again = true;
3494         return;
3495     }
3496
3497     for (i = 3; i < ctx->argc; i++) {
3498         if (!is_condition_satisfied(table, row, ctx->argv[i], ctx->symtab)) {
3499             ctx->try_again = true;
3500             return;
3501         }
3502     }
3503 }
3504 \f
3505 static struct json *
3506 where_uuid_equals(const struct uuid *uuid)
3507 {
3508     return
3509         json_array_create_1(
3510             json_array_create_3(
3511                 json_string_create("_uuid"),
3512                 json_string_create("=="),
3513                 json_array_create_2(
3514                     json_string_create("uuid"),
3515                     json_string_create_nocopy(
3516                         xasprintf(UUID_FMT, UUID_ARGS(uuid))))));
3517 }
3518
3519 static void
3520 vsctl_context_init(struct vsctl_context *ctx, struct vsctl_command *command,
3521                    struct ovsdb_idl *idl, struct ovsdb_idl_txn *txn,
3522                    const struct ovsrec_open_vswitch *ovs,
3523                    struct ovsdb_symbol_table *symtab)
3524 {
3525     ctx->argc = command->argc;
3526     ctx->argv = command->argv;
3527     ctx->options = command->options;
3528
3529     ds_swap(&ctx->output, &command->output);
3530     ctx->table = command->table;
3531     ctx->idl = idl;
3532     ctx->txn = txn;
3533     ctx->ovs = ovs;
3534     ctx->symtab = symtab;
3535     ctx->verified_ports = false;
3536
3537     ctx->try_again = false;
3538 }
3539
3540 static void
3541 vsctl_context_done(struct vsctl_context *ctx, struct vsctl_command *command)
3542 {
3543     ds_swap(&ctx->output, &command->output);
3544     command->table = ctx->table;
3545 }
3546
3547 static void
3548 run_prerequisites(struct vsctl_command *commands, size_t n_commands,
3549                   struct ovsdb_idl *idl)
3550 {
3551     struct vsctl_command *c;
3552
3553     ovsdb_idl_add_table(idl, &ovsrec_table_open_vswitch);
3554     if (wait_for_reload) {
3555         ovsdb_idl_add_column(idl, &ovsrec_open_vswitch_col_cur_cfg);
3556     }
3557     for (c = commands; c < &commands[n_commands]; c++) {
3558         if (c->syntax->prerequisites) {
3559             struct vsctl_context ctx;
3560
3561             ds_init(&c->output);
3562             c->table = NULL;
3563
3564             vsctl_context_init(&ctx, c, idl, NULL, NULL, NULL);
3565             (c->syntax->prerequisites)(&ctx);
3566             vsctl_context_done(&ctx, c);
3567
3568             assert(!c->output.string);
3569             assert(!c->table);
3570         }
3571     }
3572 }
3573
3574 static void
3575 do_vsctl(const char *args, struct vsctl_command *commands, size_t n_commands,
3576          struct ovsdb_idl *idl)
3577 {
3578     struct ovsdb_idl_txn *txn;
3579     const struct ovsrec_open_vswitch *ovs;
3580     enum ovsdb_idl_txn_status status;
3581     struct ovsdb_symbol_table *symtab;
3582     struct vsctl_command *c;
3583     struct shash_node *node;
3584     int64_t next_cfg = 0;
3585     char *error = NULL;
3586
3587     txn = the_idl_txn = ovsdb_idl_txn_create(idl);
3588     if (dry_run) {
3589         ovsdb_idl_txn_set_dry_run(txn);
3590     }
3591
3592     ovsdb_idl_txn_add_comment(txn, "ovs-vsctl: %s", args);
3593
3594     ovs = ovsrec_open_vswitch_first(idl);
3595     if (!ovs) {
3596         /* XXX add verification that table is empty */
3597         ovs = ovsrec_open_vswitch_insert(txn);
3598     }
3599
3600     if (wait_for_reload) {
3601         struct json *where = where_uuid_equals(&ovs->header_.uuid);
3602         ovsdb_idl_txn_increment(txn, "Open_vSwitch", "next_cfg", where);
3603         json_destroy(where);
3604     }
3605
3606     symtab = ovsdb_symbol_table_create();
3607     for (c = commands; c < &commands[n_commands]; c++) {
3608         ds_init(&c->output);
3609         c->table = NULL;
3610     }
3611     for (c = commands; c < &commands[n_commands]; c++) {
3612         struct vsctl_context ctx;
3613
3614         vsctl_context_init(&ctx, c, idl, txn, ovs, symtab);
3615         if (c->syntax->run) {
3616             (c->syntax->run)(&ctx);
3617         }
3618         vsctl_context_done(&ctx, c);
3619
3620         if (ctx.try_again) {
3621             goto try_again;
3622         }
3623     }
3624
3625     SHASH_FOR_EACH (node, &symtab->sh) {
3626         struct ovsdb_symbol *symbol = node->data;
3627         if (!symbol->created) {
3628             vsctl_fatal("row id \"%s\" is referenced but never created (e.g. "
3629                         "with \"-- --id=%s create ...\")",
3630                         node->name, node->name);
3631         }
3632         if (!symbol->strong_ref) {
3633             if (!symbol->weak_ref) {
3634                 VLOG_WARN("row id \"%s\" was created but no reference to it "
3635                           "was inserted, so it will not actually appear in "
3636                           "the database", node->name);
3637             } else {
3638                 VLOG_WARN("row id \"%s\" was created but only a weak "
3639                           "reference to it was inserted, so it will not "
3640                           "actually appear in the database", node->name);
3641             }
3642         }
3643     }
3644
3645     status = ovsdb_idl_txn_commit_block(txn);
3646     if (wait_for_reload && status == TXN_SUCCESS) {
3647         next_cfg = ovsdb_idl_txn_get_increment_new_value(txn);
3648     }
3649     if (status == TXN_UNCHANGED || status == TXN_SUCCESS) {
3650         for (c = commands; c < &commands[n_commands]; c++) {
3651             if (c->syntax->postprocess) {
3652                 struct vsctl_context ctx;
3653
3654                 vsctl_context_init(&ctx, c, idl, txn, ovs, symtab);
3655                 (c->syntax->postprocess)(&ctx);
3656                 vsctl_context_done(&ctx, c);
3657             }
3658         }
3659     }
3660     error = xstrdup(ovsdb_idl_txn_get_error(txn));
3661     ovsdb_idl_txn_destroy(txn);
3662     txn = the_idl_txn = NULL;
3663
3664     switch (status) {
3665     case TXN_UNCOMMITTED:
3666     case TXN_INCOMPLETE:
3667         NOT_REACHED();
3668
3669     case TXN_ABORTED:
3670         /* Should not happen--we never call ovsdb_idl_txn_abort(). */
3671         vsctl_fatal("transaction aborted");
3672
3673     case TXN_UNCHANGED:
3674     case TXN_SUCCESS:
3675         break;
3676
3677     case TXN_TRY_AGAIN:
3678         goto try_again;
3679
3680     case TXN_ERROR:
3681         vsctl_fatal("transaction error: %s", error);
3682
3683     case TXN_NOT_LOCKED:
3684         /* Should not happen--we never call ovsdb_idl_set_lock(). */
3685         vsctl_fatal("database not locked");
3686
3687     default:
3688         NOT_REACHED();
3689     }
3690     free(error);
3691
3692     ovsdb_symbol_table_destroy(symtab);
3693
3694     for (c = commands; c < &commands[n_commands]; c++) {
3695         struct ds *ds = &c->output;
3696
3697         if (c->table) {
3698             table_print(c->table, &table_style);
3699         } else if (oneline) {
3700             size_t j;
3701
3702             ds_chomp(ds, '\n');
3703             for (j = 0; j < ds->length; j++) {
3704                 int ch = ds->string[j];
3705                 switch (ch) {
3706                 case '\n':
3707                     fputs("\\n", stdout);
3708                     break;
3709
3710                 case '\\':
3711                     fputs("\\\\", stdout);
3712                     break;
3713
3714                 default:
3715                     putchar(ch);
3716                 }
3717             }
3718             putchar('\n');
3719         } else {
3720             fputs(ds_cstr(ds), stdout);
3721         }
3722         ds_destroy(&c->output);
3723         table_destroy(c->table);
3724         free(c->table);
3725
3726         smap_destroy(&c->options);
3727     }
3728     free(commands);
3729
3730     if (wait_for_reload && status != TXN_UNCHANGED) {
3731         for (;;) {
3732             ovsdb_idl_run(idl);
3733             OVSREC_OPEN_VSWITCH_FOR_EACH (ovs, idl) {
3734                 if (ovs->cur_cfg >= next_cfg) {
3735                     goto done;
3736                 }
3737             }
3738             ovsdb_idl_wait(idl);
3739             poll_block();
3740         }
3741     done: ;
3742     }
3743     ovsdb_idl_destroy(idl);
3744
3745     exit(EXIT_SUCCESS);
3746
3747 try_again:
3748     /* Our transaction needs to be rerun, or a prerequisite was not met.  Free
3749      * resources and return so that the caller can try again. */
3750     if (txn) {
3751         ovsdb_idl_txn_abort(txn);
3752         ovsdb_idl_txn_destroy(txn);
3753     }
3754     ovsdb_symbol_table_destroy(symtab);
3755     for (c = commands; c < &commands[n_commands]; c++) {
3756         ds_destroy(&c->output);
3757         table_destroy(c->table);
3758         free(c->table);
3759     }
3760     free(error);
3761 }
3762
3763 static const struct vsctl_command_syntax all_commands[] = {
3764     /* Open vSwitch commands. */
3765     {"init", 0, 0, NULL, cmd_init, NULL, "", RW},
3766     {"show", 0, 0, pre_cmd_show, cmd_show, NULL, "", RO},
3767
3768     /* Bridge commands. */
3769     {"add-br", 1, 3, pre_get_info, cmd_add_br, NULL, "--may-exist", RW},
3770     {"del-br", 1, 1, pre_get_info, cmd_del_br, NULL, "--if-exists", RW},
3771     {"list-br", 0, 0, pre_get_info, cmd_list_br, NULL, "", RO},
3772     {"br-exists", 1, 1, pre_get_info, cmd_br_exists, NULL, "", RO},
3773     {"br-to-vlan", 1, 1, pre_get_info, cmd_br_to_vlan, NULL, "", RO},
3774     {"br-to-parent", 1, 1, pre_get_info, cmd_br_to_parent, NULL, "", RO},
3775     {"br-set-external-id", 2, 3, pre_cmd_br_set_external_id,
3776      cmd_br_set_external_id, NULL, "", RW},
3777     {"br-get-external-id", 1, 2, pre_cmd_br_get_external_id,
3778      cmd_br_get_external_id, NULL, "", RO},
3779
3780     /* Port commands. */
3781     {"list-ports", 1, 1, pre_get_info, cmd_list_ports, NULL, "", RO},
3782     {"add-port", 2, INT_MAX, pre_get_info, cmd_add_port, NULL, "--may-exist",
3783      RW},
3784     {"add-bond", 4, INT_MAX, pre_get_info, cmd_add_bond, NULL,
3785      "--may-exist,--fake-iface", RW},
3786     {"del-port", 1, 2, pre_get_info, cmd_del_port, NULL,
3787      "--if-exists,--with-iface", RW},
3788     {"port-to-br", 1, 1, pre_get_info, cmd_port_to_br, NULL, "", RO},
3789
3790     /* Interface commands. */
3791     {"list-ifaces", 1, 1, pre_get_info, cmd_list_ifaces, NULL, "", RO},
3792     {"iface-to-br", 1, 1, pre_get_info, cmd_iface_to_br, NULL, "", RO},
3793
3794     /* Controller commands. */
3795     {"get-controller", 1, 1, pre_controller, cmd_get_controller, NULL, "", RO},
3796     {"del-controller", 1, 1, pre_controller, cmd_del_controller, NULL, "", RW},
3797     {"set-controller", 1, INT_MAX, pre_controller, cmd_set_controller, NULL,
3798      "", RW},
3799     {"get-fail-mode", 1, 1, pre_get_info, cmd_get_fail_mode, NULL, "", RO},
3800     {"del-fail-mode", 1, 1, pre_get_info, cmd_del_fail_mode, NULL, "", RW},
3801     {"set-fail-mode", 2, 2, pre_get_info, cmd_set_fail_mode, NULL, "", RW},
3802
3803     /* Manager commands. */
3804     {"get-manager", 0, 0, pre_manager, cmd_get_manager, NULL, "", RO},
3805     {"del-manager", 0, INT_MAX, pre_manager, cmd_del_manager, NULL, "", RW},
3806     {"set-manager", 1, INT_MAX, pre_manager, cmd_set_manager, NULL, "", RW},
3807
3808     /* SSL commands. */
3809     {"get-ssl", 0, 0, pre_cmd_get_ssl, cmd_get_ssl, NULL, "", RO},
3810     {"del-ssl", 0, 0, pre_cmd_del_ssl, cmd_del_ssl, NULL, "", RW},
3811     {"set-ssl", 3, 3, pre_cmd_set_ssl, cmd_set_ssl, NULL, "--bootstrap", RW},
3812
3813     /* Switch commands. */
3814     {"emer-reset", 0, 0, pre_cmd_emer_reset, cmd_emer_reset, NULL, "", RW},
3815
3816     /* Database commands. */
3817     {"comment", 0, INT_MAX, NULL, NULL, NULL, "", RO},
3818     {"get", 2, INT_MAX, pre_cmd_get, cmd_get, NULL, "--if-exists,--id=", RO},
3819     {"list", 1, INT_MAX, pre_cmd_list, cmd_list, NULL, "--columns=", RO},
3820     {"find", 1, INT_MAX, pre_cmd_find, cmd_find, NULL, "--columns=", RO},
3821     {"set", 3, INT_MAX, pre_cmd_set, cmd_set, NULL, "", RW},
3822     {"add", 4, INT_MAX, pre_cmd_add, cmd_add, NULL, "", RW},
3823     {"remove", 4, INT_MAX, pre_cmd_remove, cmd_remove, NULL, "", RW},
3824     {"clear", 3, INT_MAX, pre_cmd_clear, cmd_clear, NULL, "", RW},
3825     {"create", 2, INT_MAX, pre_create, cmd_create, post_create, "--id=", RW},
3826     {"destroy", 1, INT_MAX, pre_cmd_destroy, cmd_destroy, NULL, "--if-exists",
3827      RW},
3828     {"wait-until", 2, INT_MAX, pre_cmd_wait_until, cmd_wait_until, NULL, "",
3829      RO},
3830
3831     {NULL, 0, 0, NULL, NULL, NULL, NULL, RO},
3832 };
3833