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