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