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