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