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